title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python code that should error from asyncio.wait and be caught in a try clause is not being caught | 23,164,701 | 5 | 2014-04-19T01:21:28Z | 23,458,465 | 7 | 2014-05-04T16:09:04Z | [
"python",
"try-catch",
"python-asyncio"
] | so I have an event loop which will `run_until_complete` my `accept_connection` method
```
@asyncio.coroutine
def accept_connection(self):
assert self.server_socket is not None
while True:
client, addr = yield from self.loop.sock_accept(self.server_socket)
asyncio.async(self.handle_connection(c... | You need to use the returned values from `asyncio.wait()`:
```
import asyncio
class Error(Exception):
pass
@asyncio.coroutine
def main():
try:
done, pending = yield from asyncio.wait([raise_exception()], timeout=1)
assert not pending
future, = done # unpack a set of length one
... |
Python: case where x==y and x.__eq__y() return different things. Why? | 23,165,946 | 7 | 2014-04-19T04:46:32Z | 23,166,032 | 9 | 2014-04-19T04:56:44Z | [
"python",
"object",
"inheritance",
"superclass"
] | I'm taking my first computing science course, and we just learned about class implementation and inheritance. In particular, we just covered method overriding and how classes we define inherit from the `object` superclass by default. As one of my examples trying out this particular case of inheritance, I used the follo... | The `==` operator is equivalent to the `eq` function, which will internally call the `__eq__` method of the left operand if it exists to try to determine equality. This is not the *only* thing it will do, and if `__eq__` does not exist, as is the case here, it will do other checks, such as checking whether the two are ... |
How to JSON serialize __dict__ of a Django model? | 23,169,890 | 5 | 2014-04-19T12:09:01Z | 23,169,930 | 8 | 2014-04-19T12:14:13Z | [
"python",
"json",
"django",
"dictionary",
"django-1.7"
] | I want to serialize the values of a single model in Django. Because I want to use `get()`, [`values()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values) is not available. However, I read [on Google Groups](https://groups.google.com/d/msg/django-users/Jxjdf2LAmXo/hcruIi... | [`model_to_dict()`](https://github.com/django/django/blob/master/django/forms/models.py#L112) is what you need:
```
from django.forms.models import model_to_dict
data = model_to_dict(model)
data['logo'] = data['logo'].url
return HttpResponse(json.dumps(data), content_type='application/json')
```
By specifying `field... |
Sending a POST request with Angularjs and get parameters in a Flask backend | 23,172,265 | 3 | 2014-04-19T16:04:19Z | 23,172,266 | 7 | 2014-04-19T16:04:19Z | [
"python",
"angularjs",
"flask"
] | I have this code in AngularJS:
```
myApp.controller('LoginCtrl', function($scope, $http){
$scope.formData = {};
$scope.doLogin = function(url, pass){
$http({
url: url,
method: "POST",
data: $.param($scope.formData)
}).success(function(data) {
console.log(data)
});
}
});
```
... | **UPDATE**
After have a lot of problems with this, I solve using another Stackoverflow answer. So, I got this code:
**ANGULARJS**
```
$scope.doLogin = function(url, pass){
$http({
url: url,
method: "POST",
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify(data)
}).... |
lxml runtime error: Reason: Incompatible library version: etree.so requires version 12.0.0 or later, but libxml2.2.dylib provides version 10.0.0 | 23,172,384 | 19 | 2014-04-19T16:15:07Z | 26,289,928 | 28 | 2014-10-10T00:09:28Z | [
"python",
"amazon",
"lxml",
"osx-mavericks"
] | I have a perplexing problem.
I have used mac version 10.9, anaconda 3.4.1, python 2.7.6.
Developing web application with python-amazon-product-api. i have overcome an obstacle about installing lxml, referencing [clang error: unknown argument: '-mno-fused-madd' (python package installation failure)](http://stackoverflo... | Force a reinstall of `lxml`:
`$ conda install -f lxml`
First tried `conda update lxml` to no effect.
Note that forcing a reinstall may have unforeseen consequences. |
lxml runtime error: Reason: Incompatible library version: etree.so requires version 12.0.0 or later, but libxml2.2.dylib provides version 10.0.0 | 23,172,384 | 19 | 2014-04-19T16:15:07Z | 31,607,751 | 32 | 2015-07-24T10:09:28Z | [
"python",
"amazon",
"lxml",
"osx-mavericks"
] | I have a perplexing problem.
I have used mac version 10.9, anaconda 3.4.1, python 2.7.6.
Developing web application with python-amazon-product-api. i have overcome an obstacle about installing lxml, referencing [clang error: unknown argument: '-mno-fused-madd' (python package installation failure)](http://stackoverflo... | This worked for me:
```
brew install libxml2
brew install libxslt
brew link libxml2 --force
brew link libxslt --force
``` |
Converting a string to a tuple in python | 23,173,916 | 2 | 2014-04-19T18:36:59Z | 23,173,934 | 7 | 2014-04-19T18:38:31Z | [
"python",
"string",
"tuples"
] | Okay, I have this string
```
tc='(107, 189)'
```
and I need it to be a tuple, so I can call each number one at a time.
```
print(tc[0]) #needs to output 107
```
Thank you in advance! | All you need is `ast.literal_eval`:
```
>>> from ast import literal_eval
>>> tc = '(107, 189)'
>>> tc = literal_eval(tc)
>>> tc
(107, 189)
>>> type(tc)
<class 'tuple'>
>>> tc[0]
107
>>> type(tc[0])
<class 'int'>
>>>
```
From the [docs](https://docs.python.org/3/library/ast.html#ast.literal_eval):
> `ast.literal_eval... |
TypeError - Translate takes one argument.(2 given) Python | 23,175,809 | 14 | 2014-04-19T21:32:28Z | 23,306,505 | 39 | 2014-04-26T04:05:36Z | [
"python",
"nltk",
"typeerror"
] | I have the following code
```
import nltk, os, json, csv, string, cPickle
from scipy.stats import scoreatpercentile
lmtzr = nltk.stem.wordnet.WordNetLemmatizer()
def sanitize(wordList):
answer = [word.translate(None, string.punctuation) for word in wordList]
answer = [lmtzr.lemmatize(word.lower()) for word in answ... | I suspect your issue has to do with the differences between `str.translate` and `unicode.translate` (these are also the differences between `str.translate` on Python 2 versus Python 3). I suspect your original code is being sent `unicode` instances while your test code is using regular 8-bit `str` instances.
I don't s... |
no module named ecdsa with Paramiko | 23,176,231 | 4 | 2014-04-19T22:19:08Z | 23,177,224 | 10 | 2014-04-20T00:45:45Z | [
"python",
"paramiko",
"ecdsa"
] | I keep coming up with the error `no module named ecdsa` when I run a program with Paramiko. I have installed it using pip, and it says that it *has* installed, but when I run the program again, it comes up with the error again!
What can I do? I'm using Linux, by the way. | Make sure you have `ecdsa` module installed in your linux system. Go to prompt, and try running the following commands:
```
mamun@bobolink:~$ python
Python 2.7.5+ (default, Feb 27 2014, 19:37:08)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from e... |
python object() takes no parameters error | 23,176,597 | 5 | 2014-04-19T23:07:04Z | 23,183,022 | 15 | 2014-04-20T13:29:56Z | [
"python"
] | I can't believe this is actually a problem, but I've been trying to debug this error and I've gotten nowhere. I'm sure I'm missing something really simple because this seems so silly.
```
import Experiences, Places, Countries
class Experience(object):
def make_place(self, place):
addr = place["address"]
... | You've mixed tabs and spaces. `__init__` is actually defined nested inside another method, so your class doesn't have an `__init__` method, and it calls `object.__init__` instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.
This is ... |
ImportError: No module named _io in ubuntu 14.04 | 23,176,697 | 42 | 2014-04-19T23:21:03Z | 23,176,749 | 41 | 2014-04-19T23:27:47Z | [
"python",
"linux",
"ubuntu",
"pip"
] | I just fresh installed ubuntu 14.04LTS and i am trying to use pip but i am getting the following traceback:
```
(nlmanagement)psychok7@Ultrabook:~/code/work/nlmanagement$ pip freeze
Traceback (most recent call last):
File "/home/psychok7/code/work/venv/nlmanagement/bin/pip", line 9, in <module>
load_entry_point(... | Your virtualenv became corrupt due to diffs in the Python system lib.
Best choice is to reinstall your virtualenv:
```
$ deactivate
$ rmvirtualenv nlmanagement
$ mkvirtualenv nlmanagement
$ pip install -r requirements.txt
``` |
ImportError: No module named _io in ubuntu 14.04 | 23,176,697 | 42 | 2014-04-19T23:21:03Z | 23,430,316 | 19 | 2014-05-02T14:18:09Z | [
"python",
"linux",
"ubuntu",
"pip"
] | I just fresh installed ubuntu 14.04LTS and i am trying to use pip but i am getting the following traceback:
```
(nlmanagement)psychok7@Ultrabook:~/code/work/nlmanagement$ pip freeze
Traceback (most recent call last):
File "/home/psychok7/code/work/venv/nlmanagement/bin/pip", line 9, in <module>
load_entry_point(... | You don't need to delete the virtual environment.
Just follow these steps.
1. Let's say your virtual environment name is "mydev" and you are using `virtualenvwrapper`, do
```
cd $WORKON_HOME
virtualenv mydev
```
The above command just upgrades the link to the python executable without losing any pack... |
ImportError: No module named _io in ubuntu 14.04 | 23,176,697 | 42 | 2014-04-19T23:21:03Z | 24,191,303 | 44 | 2014-06-12T18:19:18Z | [
"python",
"linux",
"ubuntu",
"pip"
] | I just fresh installed ubuntu 14.04LTS and i am trying to use pip but i am getting the following traceback:
```
(nlmanagement)psychok7@Ultrabook:~/code/work/nlmanagement$ pip freeze
Traceback (most recent call last):
File "/home/psychok7/code/work/venv/nlmanagement/bin/pip", line 9, in <module>
load_entry_point(... | I had the same problem. This happened in Ubuntu - 14.04 and Virtual environment's Python version - 2.7.3
After spending a day in debugging, posting my answer here, hope it helps for future visitors.
Found that `io.py` is invoking `_io` module. I think `_io` module is internal to interpreter so, replacing `python` bin... |
Python 3: Making a str object callable | 23,177,308 | 3 | 2014-04-20T01:01:28Z | 23,177,341 | 10 | 2014-04-20T01:08:16Z | [
"python",
"string",
"object",
"callable"
] | I have a Python program that takes user input. I store user input a string variable called "userInput". I want to be able to call the string the user entered...
```
userInput = input("Enter a command: ")
userInput()
```
From this, I get the error: TypeError: 'str' object is not callable
Currently, I have the program... | A better method might be to use a dict:
```
def command1():
pass
def command2():
pass
commands = {
'command1': command1,
'command2': command2
}
user_input = input("Enter a command: ")
if user_input in commands:
func = commands[user_input]
func()
# You could also shorten this to:
# c... |
Python: Checking if a 'Dictionary' is empty doesn't seem to work | 23,177,439 | 82 | 2014-04-20T01:29:19Z | 23,177,452 | 171 | 2014-04-20T01:31:06Z | [
"python",
"dictionary"
] | I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays **ONLINE** without anything except of display the message. Any ideas why ?
```
def isEmpty(self, dictionary):
for element in dictionary:
if element:
return True
return False
def onMessage(... | Empty dictionaries [evaluate to `False`](https://docs.python.org/2/library/stdtypes.html#truth-value-testing) in Python:
```
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
```
Thus, your `isEmpty` function is unnecessary. All you need to do is:
```
def onMessage(self, socket, message):
if not self.users:
... |
Python: Checking if a 'Dictionary' is empty doesn't seem to work | 23,177,439 | 82 | 2014-04-20T01:29:19Z | 23,178,451 | 35 | 2014-04-20T04:29:12Z | [
"python",
"dictionary"
] | I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays **ONLINE** without anything except of display the message. Any ideas why ?
```
def isEmpty(self, dictionary):
for element in dictionary:
if element:
return True
return False
def onMessage(... | Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.
```
test_dict = {}
if not test_dict:
print "Dict is Empty"
if not bool(test_dict):
print "Dict is Empty"
if len(test_dict) == 0:
print "Dict is Empty"
``` |
Switch Python Version for Vim & Syntastic | 23,177,561 | 9 | 2014-04-20T01:51:06Z | 25,637,352 | 10 | 2014-09-03T06:08:30Z | [
"python",
"vim",
"syntastic"
] | Is it possible to change the python version used by syntastic for syntax checking?
As the Issue <https://github.com/scrooloose/syntastic/issues/385> indicates I could use virtual-env. But is it also possible just with syntastic or vim commands? | From the [Syntastic repository README](https://github.com/scrooloose/syntastic):
> ### Q. The python checker complains about syntactically valid Python 3 constructs...
>
> A. Configure the python checker to call a Python 3 interpreter rather than Python 2, e.g:
>
> `let g:syntastic_python_python_exec = '/path/to/pytho... |
Getting min and max Date's from a pandas dataframe | 23,178,129 | 6 | 2014-04-20T03:32:13Z | 23,178,185 | 11 | 2014-04-20T03:43:59Z | [
"python",
"datetime",
"pandas"
] | How do I get the min and max Date's from a dataframes major axis?
```
value
Date
2014-03-13 10000.000
2014-03-21 2000.000
2014-03-27 2000.000
2014-03-17 200.000
2014-03-17 5.000
2014-03-17 70.000
2014-03-21 200.000
2014-03-27 5.000
... | 'Date' is your index so you want to do,
```
print df.index.min()
print df.index.max()
2014-03-13 00:00:00
2014-03-31 00:00:00
``` |
Multiple monitors with Kivy | 23,178,570 | 3 | 2014-04-20T04:53:45Z | 23,179,572 | 7 | 2014-04-20T07:23:14Z | [
"python",
"user-interface",
"kivy"
] | I'm looking at using Kivy to create a program that needs to display a window on each monitor, is there a way to accomplish this? I'd also prefer not to have a single window spanning across.
If not, is there another (good looking, windows/linux) GUI toolkit that can accomplish this? | You can have two separate windows running two separate kivy apps controlling/communicating with each other via osc/twisted/... However one "App" instance is only limited to one App window for that process. It can launch another process(subprocess.popen) which has a new window though. |
Debugging Python Fatal Error: GC Object already Tracked | 23,178,606 | 7 | 2014-04-20T05:00:18Z | 23,705,373 | 7 | 2014-05-16T22:20:50Z | [
"python",
"crash",
"garbage-collection"
] | My python code has been crashing with error 'GC Object already Tracked' . Trying to figure out the best approach to debug this crashes.
OS : Linux.
* Is there a proper way to debug this issue.
There were couple of suggestions in the following article.
[Python memory debugging with GDB](http://stackoverflow.com/quest... | Found out the reason for this issue in my scenario (not necessarily the only reason for the GC object crash).
I used the GDB and Core dumps to debug this issue.
I have Python and C Extension Code (in shared object).
Python code registers a Callback routine with C Extension code.
In a certain workflow a thread from C E... |
Install pysqlite in virtualenv with python3 support | 23,181,197 | 2 | 2014-04-20T10:50:43Z | 23,414,147 | 8 | 2014-05-01T18:34:28Z | [
"python",
"sqlite",
"python-3.x",
"pip",
"virtualenv"
] | I've created virtualenv with:
```
mkvirtualenv -p /usr/bin/python3.4 django
```
After, I tried install pysqlite:
```
pip install pysqlite
```
But I got:
```
Downloading/unpacking pysqlite
Downloading pysqlite-2.6.3.tar.gz (76kB): 76kB downloaded
Running setup.py (path:/home/sigo/.virtualenvs/django/build/pysql... | There is no public version of pysqlite for Python 3.x. For Python 3.x, the sqlite3 module in the standard library is the most up-to date version of pysqlite there is. |
use python list comprehension to update dictionary value | 23,181,774 | 5 | 2014-04-20T12:04:58Z | 23,181,835 | 9 | 2014-04-20T12:12:47Z | [
"python",
"dictionary"
] | I have a list of dictionaries and would like to update the value for key 'price' with 0 if key price value is equal to ''
```
data=[a['price']=0 for a in data if a['price']=='']
```
Is it possible to do something like that? I have tried also with
```
a.update({'price':0})
```
but did not work as well... | Assignments are statements, and statements are not usable inside list comprehensions. Just use a normal for-loop:
```
data = ...
for a in data:
if a['price'] == '':
a['price'] = 0
```
And for the sake of completeness, you can also use this abomination (but that doesn't mean you should):
```
data = ...
[... |
Find a maximum of a list without constructing the list | 23,183,009 | 3 | 2014-04-20T13:28:10Z | 23,183,019 | 7 | 2014-04-20T13:29:32Z | [
"python"
] | I've been playing around with Python for making one-line solutions for some competition problems, and I've run into the following issue. My solution can be written as `max([f(k) for k in range(n)])` (where `f(k)` is some simple expression), which looks great, but when `n` is large it ends up constructing a list before ... | [`max()`](https://docs.python.org/3/library/functions.html#max) takes a [generator](https://docs.python.org/3/tutorial/classes.html#generators) also:
```
max(f(k) for k in range(n))
```
This saves you from having to build the entire list.
Thanks to @DanielRoseman for pointing out that in Python 2.x you should be usi... |
How can a plug-in enhance Anki's JavaScript? | 23,183,105 | 11 | 2014-04-20T13:40:04Z | 23,310,521 | 8 | 2014-04-26T11:57:40Z | [
"javascript",
"python",
"pyqt",
"anki"
] | Anki enables cards to use JavaScript. For example, a card can contain something like:
```
<script>
//JavaScript code here
</script>
```
and the JavaScript code will be executed when the card is shown.
In order to allow more flexibility by enabling such scripts to interact with the Anki back-end (for example in order... | Having read the [post](http://pysnippet.blogspot.de/2010/01/calling-python-from-javascript-in-pyqts.html) linked to by @Louis, and discussed the issue with some colleagues, and messed around trying various things out, I've finally managed to come up with a solution:
The idea can be summarised in these two key points (... |
Why is loading SQLAlchemy objects via the ORM 5-8x slower than rows via a raw MySQLdb cursor? | 23,185,319 | 7 | 2014-04-20T17:14:17Z | 25,534,166 | 32 | 2014-08-27T18:07:12Z | [
"python",
"mysql",
"performance",
"orm",
"sqlalchemy"
] | I noticed that SQLAlchemy was slow fetching (and ORMing) some data, which was rather fast to fetch using bare bone SQL. First off, I created a database with a million records:
```
mysql> use foo
mysql> describe Foo;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+... | Here is the SQLAlchemy version of your MySQL script that performs in four seconds, compared to three for MySQLdb:
```
from sqlalchemy import Integer, Column, create_engine, MetaData, Table
import datetime
metadata = MetaData()
foo = Table(
'foo', metadata,
Column('id', Integer, primary_key=True),
Column(... |
Installing gmpy on OSX - mpc.h not found | 23,187,801 | 5 | 2014-04-20T21:31:43Z | 27,663,446 | 16 | 2014-12-27T00:53:10Z | [
"python",
"clang",
"gmp",
"mpc"
] | I have `brew install`ed `mpc`and `gmp` , but when I try to `pip install gmpy2` I get a compile error on the line
```
#include "mpc.h"
```
so for some reason `clang` is having trouble finding the `mpc` library. I'm not sure what I should do at this point. | For OSX with homebrew users - I tried to do the usual dance with
```
brew install mpc
brew install mpfr
```
and then
```
python setup.py --prefix=/usr/local/Cellar
```
but got the error, that 'mpc.h' could not be found. True enough, there is no mpc.h file to be found. The solution is, to use
```
brew install libmp... |
Maximum allowed value for a numpy data type | 23,189,506 | 8 | 2014-04-21T01:28:22Z | 23,189,557 | 12 | 2014-04-21T01:33:48Z | [
"python",
"numpy"
] | I am working with numpy arrays of a range of data types (uint8, uint16, int16, etc.). I would like to be able to check whether a number can be represented within the limits of an array for a given datatype. I am imagining something that looks like:
```
>>> im.dtype
dtype('uint16')
>>> dtype_max(im.dtype)
65535
>>> dty... | ```
min_value = np.iinfo(im.dtype).min
max_value = np.iinfo(im.dtype).max
```
docs:
* [np.iinfo](http://docs.scipy.org/doc/numpy/reference/generated/numpy.iinfo.html#numpy-iinfo) (machine limits for integer types)
* [np.finfo](http://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html#numpy-finfo) (machine ... |
What is the meaning of "<" for Python dictionaries? | 23,192,163 | 16 | 2014-04-21T06:35:36Z | 23,192,213 | 15 | 2014-04-21T06:39:30Z | [
"python",
"python-2.7",
"python-internals"
] | I've noticed that Python lets me do this:
```
>>> {1: "foo"} < {2: "bar"}
True
```
It lets me do the same thing for lists, deques, etc. What are the semantics of `<` when applied to dictionaries in Python?
In general where can I find out the semantics of `<` for any given type of collection? In most cases it seems n... | Quoting from [comparison](https://docs.python.org/2/reference/expressions.html#not-in) docs,
### Tuples and Lists
> Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same ty... |
How to convert string to uppercase / lowercase in Jinja2? | 23,195,321 | 16 | 2014-04-21T10:16:15Z | 23,195,355 | 21 | 2014-04-21T10:17:39Z | [
"python",
"jinja2",
"jinja"
] | I am trying to convert to upper case a string in a Jinja template I am working on.
In the [template documentation](http://jinja.pocoo.org/docs/templates/), I read:
```
upper(s)
Convert a value to uppercase.
```
So I wrote this code:
```
{% if student.departament == "Academy" %}
Academy
{% elif upper(studen... | Filters are used with the [`|filter` syntax](http://jinja.pocoo.org/docs/templates/#filters):
```
{% elif student.department|upper != "MATHS DEPARTMENT" %}
Maths department
{% endif %}
```
or you can use the [`str.upper()` method](https://docs.python.org/2/library/stdtypes.html#str.upper):
```
{% elif student.... |
How do you shift Pandas DataFrame with a multiindex? | 23,198,053 | 8 | 2014-04-21T13:05:45Z | 23,198,160 | 14 | 2014-04-21T13:11:18Z | [
"python",
"pandas"
] | With the following DataFrame, how can I shift the "beyer" column based on the index without having Pandas assign the shifted value to a different index value?
```
line_date line_race beyer
horse
Last Gunfighter 2013-09-28 10 99
Last Gunfighter 2... | Use `groupby/shift` to apply the shift to each group individually: (Thanks to Jeff for pointing out this simplification.)
```
In [60]: df['beyer_shifted'] = df.groupby(level=0)['beyer'].shift(1); df
Out[61]:
line_date line_race beyer beyer_shifted
Last Gunfighter 2013-09-28 10 99 ... |
Detect and exclude outliers in Pandas dataframe | 23,199,796 | 26 | 2014-04-21T14:51:37Z | 23,200,666 | 38 | 2014-04-21T15:44:04Z | [
"python",
"pandas",
"filtering",
"dataframe",
"outliers"
] | I have a pandas dataframe with few columns.
Now I know that certain rows are outliers based on a certain column value.
For instance columns - 'Vol' has all values around 12.xx and one value which is 4000
Now I would like to exclude those rows that have Vol Column like this.
So essentially I need to put a filter suc... | Use `boolean` indexing as you would do in `numpy.array`
```
df=pd.DataFrame({'Data':np.random.normal(size=200)}) #example dataset of normally distributed data.
df[np.abs(df.Data-df.Data.mean())<=(3*df.Data.std())] #keep only the ones that are within +3 to -3 standard deviations in the column 'Data'.
df[~(np.abs(df.D... |
Detect and exclude outliers in Pandas dataframe | 23,199,796 | 26 | 2014-04-21T14:51:37Z | 23,202,269 | 32 | 2014-04-21T17:20:35Z | [
"python",
"pandas",
"filtering",
"dataframe",
"outliers"
] | I have a pandas dataframe with few columns.
Now I know that certain rows are outliers based on a certain column value.
For instance columns - 'Vol' has all values around 12.xx and one value which is 4000
Now I would like to exclude those rows that have Vol Column like this.
So essentially I need to put a filter suc... | If you have multiple columns in your dataframe and would like to remove all rows that have outliers in at least one column, the following expression would do that in one shot.
```
df = pd.DataFrame(np.random.randn(100, 3))
from scipy import stats
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]
``` |
Detect and exclude outliers in Pandas dataframe | 23,199,796 | 26 | 2014-04-21T14:51:37Z | 31,502,974 | 8 | 2015-07-19T15:44:23Z | [
"python",
"pandas",
"filtering",
"dataframe",
"outliers"
] | I have a pandas dataframe with few columns.
Now I know that certain rows are outliers based on a certain column value.
For instance columns - 'Vol' has all values around 12.xx and one value which is 4000
Now I would like to exclude those rows that have Vol Column like this.
So essentially I need to put a filter suc... | This answer is similar to that provided by @tanemaki, but uses a `lambda` expression instead of `scipy stats`.
```
df = pd.DataFrame(np.random.randn(100, 3), columns=list('ABC'))
df[df.apply(lambda x: np.abs(x - x.mean()) / x.std() < 3).all(axis=1)]
```
To filter the DataFrame where only ONE column (e.g. 'B') is wit... |
How to clone or copy a set in Python? | 23,200,969 | 7 | 2014-04-21T16:01:59Z | 23,200,970 | 15 | 2014-04-21T16:01:59Z | [
"python",
"set",
"clone",
"shallow-copy"
] | For copying a list: `shallow_copy_of_list = old_list[:]`.
For copying a dict: `shallow_copy_of_dict = dict(old_dict)`.
But for a `set`, I was worried that a similar thing wouldn't work, because saying `new_set = set(old_set)` would give a set of a set?
But it does work. So I'm posting the question and answer here fo... | Both of these will give a duplicate of a set:
```
shallow_copy_of_set = set(old_set)
```
Or:
```
shallow_copy_of_set = old_set.copy() #Which is more readable.
```
The reason that the first way above **doesn't** give a set of a set, is that the proper syntax for that would be `set([old_set])`. Which wouldn't work, b... |
manage.py flag to force unattended command? | 23,202,805 | 2 | 2014-04-21T17:53:14Z | 23,202,846 | 7 | 2014-04-21T17:55:14Z | [
"python",
"django",
"django-manage.py"
] | I am reading this tutorial: [Installing and Configuring Graphite and Statsd on an Ubuntu 12.04 VPS](https://www.digitalocean.com/community/articles/installing-and-configuring-graphite-and-statsd-on-an-ubuntu-12-04-vps)
and I am working to automatize everything is possible then there is one step of this tutorial that i... | You can use [the `--noinput` argument](https://docs.djangoproject.com/en/1.6/ref/django-admin/#django-admin-option---noinput) to disable those prompts for [the `syncdb` command](https://docs.djangoproject.com/en/1.6/ref/django-admin/#django-admin-syncdb).
> `--noinput`
>
> Use the `--noinput` option to suppress all us... |
python flask ImmutableMultiDict | 23,205,577 | 7 | 2014-04-21T20:36:48Z | 23,210,451 | 26 | 2014-04-22T04:35:31Z | [
"python",
"forms",
"flask"
] | this is mycode
```
@user_bp.route('/band', methods=['GET', 'POST'])
def band_details():
from include.form.User import Banddetails
form = Banddetails()
if request.method == 'POST' and form.validate_on_submit():
pippo = request.args.getlist('name[]')
print 'sei passato di qui' + str(len... | If you are using an HTTP POST method you need to retrieve parameters like this:
```
pippo = request.form.getlist('name[]')
```
If you use HTTP GET method, do it like this:
```
pippo = request.args.getlist('name[]')
```
Check the docs [here](http://flask.pocoo.org/docs/api/#incoming-request-data). |
sqlalchemy : executing raw sql with parameter bindings | 23,206,562 | 18 | 2014-04-21T21:44:48Z | 23,206,636 | 19 | 2014-04-21T21:50:56Z | [
"python",
"sqlalchemy",
"database-migration",
"flask-sqlalchemy",
"alembic"
] | I'm trying to run this simple raw sql statement with parameters with SQLALchemy (within an alembic script) :
```
from alembic import op
t = {"code": "123", "description": "one two three"}
op.execute("insert into field_tags (id, field_id, code, description) "+
"values (1,'zasz', :code ,:description')",... | You need to get the [`connection`](http://docs.sqlalchemy.org/en/rel_0_9/core/connections.html) object, call [`execute()`](http://docs.sqlalchemy.org/en/rel_0_9/core/connections.html#sqlalchemy.engine.Engine.execute) on it and pass query parameters as keyword arguments:
```
from alembic import op
from sqlalchemy.sql i... |
Check if current thread is main thread, in Python | 23,206,787 | 11 | 2014-04-21T22:02:51Z | 23,207,116 | 18 | 2014-04-21T22:28:09Z | [
"python",
"multithreading"
] | This has been answered for [Android](http://stackoverflow.com/questions/11411022/how-to-check-if-current-thread-is-not-main-thread), [Objective C](http://stackoverflow.com/questions/3546539/check-whether-or-not-the-current-thread-is-the-main-thread) and [C++](http://stackoverflow.com/questions/20530218/check-if-current... | The problem with `threading.current_thread().name == 'MainThread'` is that one can always do:
```
threading.current_thread().name = 'MyName'
assert threading.current_thread().name == 'MainThread' # will fail
```
Perhaps the following is more solid:
```
threading.current_thread().__class__.__name__ == '_MainThread'
`... |
Django's prefetch_related for count only | 23,210,254 | 6 | 2014-04-22T04:15:04Z | 23,210,490 | 8 | 2014-04-22T04:39:07Z | [
"python",
"django",
"django-orm"
] | I have a situation something like this (the actual code is bound up in a template, and omitted for brevity).
```
threads = Thread.objects.all()
for thread in threads:
print(thread.comments.count())
print(thread.upvotes.count())
```
I've managed to considerably reduce the total number of queries using Django's... | You're right, it's wasteful to fetch all that data from the database if all you want to do is get the count. I suggest annotation:
```
threads = (Thread.objects.annotate(Count('comments', distinct=True))
annotate(Count('upvotes', distinct=True)))
for thread in threads:
print(thread.commen... |
Advanced slicing with tuple using *args | 23,211,183 | 2 | 2014-04-22T05:35:37Z | 23,211,220 | 7 | 2014-04-22T05:38:41Z | [
"python",
"slice"
] | According to [Create a slice using a tuple](http://stackoverflow.com/questions/7071264/create-a-slice-using-a-tuple), you can do it handy way:
```
>>> a = range(20)
>>> b = (5, 12)
>>> a[slice(*b)]
[5, 6, 7, 8, 9, 10, 11]
```
But what I need is advanced ones:
```
a[5:]
a[:12]
a[:]
a[-1]
a[-2:]
a[:-2]
a[::-1]
```
Ho... | For options that you want to omit, replace it with `None`. Generally, if any option is omitted, it default to `None`.
So option like `slice(None, None, None)` is equivalent to `a[::]`. Also remember the `start` and `step` arguments default to `None`.
For. ex.
```
a[5:] -> b=(5,None,None)
a[:12] -> b=(None,12)
a[:] ... |
Permission Denied To Write To My Temporary File | 23,212,435 | 8 | 2014-04-22T06:49:53Z | 23,212,515 | 13 | 2014-04-22T06:53:29Z | [
"python",
"temporary-files"
] | I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module `tempfile` to create a temporary file.
But when I go to write that temporary file I get an error `Permission Denied`. Am I not allowed to write to temporary files?! Am I doing something wrong? If I want to... | `NamedTemporaryFile` actually *creates* the file for you, there's no need for you to open it for write.
In fact, the [Python docs](https://docs.python.org/2/library/tempfile.html) state:
> Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platform... |
Celery with RabbitMQ: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' | 23,215,311 | 30 | 2014-04-22T09:15:30Z | 23,217,379 | 22 | 2014-04-22T10:50:07Z | [
"python",
"celery"
] | I'm running the [First Steps with Celery Tutorial](http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html).
We define the following task:
```
from celery import Celery
app = Celery('tasks', broker='amqp://guest@localhost//')
@app.task
def add(x, y):
return x + y
```
Then call it:
... | Just keep reading tutorial. It will be explained in [Keep Results](http://celery.readthedocs.org/en/latest/getting-started/first-steps-with-celery.html#keeping-results) chapter.
To start Celery you need to provide just broker parameter, which is required to send messages about tasks. If you want to retrieve informatio... |
Celery with RabbitMQ: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' | 23,215,311 | 30 | 2014-04-22T09:15:30Z | 25,743,929 | 15 | 2014-09-09T11:50:32Z | [
"python",
"celery"
] | I'm running the [First Steps with Celery Tutorial](http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html).
We define the following task:
```
from celery import Celery
app = Celery('tasks', broker='amqp://guest@localhost//')
@app.task
def add(x, y):
return x + y
```
Then call it:
... | I suggest having a look at:
<http://www.cnblogs.com/fangwenyu/p/3625830.html>
There you will see that
instead of
```
app = Celery('tasks', broker='amqp://guest@localhost//')
```
you should be writing
```
app = Celery('tasks', backend='amqp', broker='amqp://guest@localhost//')
```
This is it. |
Unable to perform collectstatic | 23,215,581 | 21 | 2014-04-22T09:27:12Z | 23,215,675 | 7 | 2014-04-22T09:31:49Z | [
"python",
"django",
"django-staticfiles"
] | I am new to django ! When i use the command `python manage.py collectstatic` i get this error
```
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
```
But i can successfully run the server .
My static files declarations are ... | You must have to give path in STATIC\_ROOT in settings.py where all your static files are collected as for example:-
```
STATIC_ROOT = "app-root/repo/wsgi/static"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets', 'app-root/repo/wsgi/openshift/static'),
)
``` |
Unable to perform collectstatic | 23,215,581 | 21 | 2014-04-22T09:27:12Z | 23,215,679 | 36 | 2014-04-22T09:32:03Z | [
"python",
"django",
"django-staticfiles"
] | I am new to django ! When i use the command `python manage.py collectstatic` i get this error
```
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
```
But i can successfully run the server .
My static files declarations are ... | Try this,
```
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
```
Look at <https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-STATIC_ROOT> |
Why can I encrypt data with one DES key and successfully decrypt with another? | 23,216,138 | 6 | 2014-04-22T09:53:56Z | 23,216,778 | 7 | 2014-04-22T10:21:28Z | [
"python",
"cryptography",
"des",
"encryption-symmetric",
"pycrypto"
] | I tried to implement DES algorithm using pyDes and Crypto.Cipher.DES modules. I found a problem that when I encrypt with `82514145` key and then decrypt the cipher with `93505044` I can retrieve the decrypted text. I found 256 keys behaving like this. This is violation of cryptography. My code is as follows:
```
f... | DES keys are only 56 bits long, but they are expanded to 64 bits thanks to parity bits. The eighth bit of each byte should be set to ensure [odd parity](http://en.wikipedia.org/wiki/Parity_bit).
Many crypto libraries ignore parity bits, which means there are many ways to represent the same 56-bit key in a 64-bit key s... |
Python - make string equal length | 23,216,512 | 5 | 2014-04-22T10:09:36Z | 23,216,558 | 8 | 2014-04-22T10:11:35Z | [
"python",
"string"
] | I have a RNA sequence of varying length. Max length of the sequence is 22. Some sequences are shorter. So if a sequence is shorter then add "0" to the end of the line till the length becomes 22.
How to do it in python?
this is my input
AAGAUGUGGAAAAAUUGGAAUC
CAGUGGUUUUAUGGUAG
CUCUAGAGGGUUUCUG
UUCAUUCGGC
and my ex... | Use [`str.ljust`](https://docs.python.org/2/library/stdtypes.html#str.ljust) method:
```
>>> s = 'foobar'
>>> s.ljust(22, '0')
'foobar0000000000000000'
``` |
wrapping class method in try / except using decorator | 23,218,974 | 4 | 2014-04-22T12:03:40Z | 23,219,015 | 7 | 2014-04-22T12:05:22Z | [
"python",
"python-2.7",
"decorator"
] | I have a general purpose function that sends info about exceptions to an application log.
I use the exception\_handler function from within methods in classes. The app log handler that is passed into and called by the exception\_handler creates a json string that is what actually gets sent to the logfile. This all work... | Such a decorator would simply be:
```
def handle_exceptions(f):
def wrapper(*args, **kw):
try:
return f(*args, **kw)
except Exception:
self = args[0]
exception_handler(self.log, True)
return wrapper
```
This decorator simply calls the wrapped function inside... |
Python Equality Check Difference | 23,220,141 | 34 | 2014-04-22T12:50:48Z | 23,220,264 | 37 | 2014-04-22T12:55:04Z | [
"python"
] | Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :
```
if a == 5 and b == 5:
# do something
```
But a few days ago, I just involuntarily wrote a similar condition check as :
```
if a == b and b == 5:
# do something
```
which made me think, is... | Since they are *basically* equivalent, you could also consider the way you read/think about the code:
```
if a == 5 and b == 5:
# do something
```
can be *read* as "if `a` equals `5` and `b` equals `5`, then do ...". You have to *think/conclude*, that then also `a` will be equal to `b`.
This is opposite to the nex... |
Python Equality Check Difference | 23,220,141 | 34 | 2014-04-22T12:50:48Z | 23,220,328 | 14 | 2014-04-22T12:57:52Z | [
"python"
] | Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :
```
if a == 5 and b == 5:
# do something
```
But a few days ago, I just involuntarily wrote a similar condition check as :
```
if a == b and b == 5:
# do something
```
which made me think, is... | As far as integers are concerned, there is no difference, in terms of sheer performance, between the first two comparisons.
The third comparison is different, though; since a little more **fiddling with the stack** gets involved. Indeed, the code
```
import dis
def comparison_1(a, b):
if a == 5 and b == 5:
... |
Python Equality Check Difference | 23,220,141 | 34 | 2014-04-22T12:50:48Z | 23,220,462 | 19 | 2014-04-22T13:03:27Z | [
"python"
] | Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :
```
if a == 5 and b == 5:
# do something
```
But a few days ago, I just involuntarily wrote a similar condition check as :
```
if a == b and b == 5:
# do something
```
which made me think, is... | If you have more variables to test, using `all` might be slightly more readable:
```
if all(i==5 for i in [a,b,c,d]):
# do something
``` |
Storing a list of strings to a HDF5 Dataset from Python | 23,220,513 | 10 | 2014-04-22T13:05:34Z | 23,223,417 | 9 | 2014-04-22T15:09:29Z | [
"python",
"hdf5",
"h5py"
] | I am trying to store a variable length list of string to a HDF5 Dataset. The code for this is
```
import h5py
h5File=h5py.File('xxx.h5','w')
strList=['asas','asas','asas']
h5File.create_dataset('xxx',(len(strList),1),'S10',strList)
h5File.flush()
h5File.Close()
```
I am getting an error stating that "TypeError: No... | You're reading in Unicode strings, but specifying your datatype as ASCII. According to [the h5py wiki](https://github.com/h5py/h5py/wiki/Unicode-Manifesto#creating-datasets-from-input-python-data), h5py does not currently support this conversion.
You'll need to encode the strings in a format h5py handles:
```
asciiLi... |
Does range() really create lists? | 23,221,025 | 44 | 2014-04-22T13:27:27Z | 23,221,045 | 91 | 2014-04-22T13:28:20Z | [
"python",
"range"
] | Both my professor and [this guy](http://www.secnetix.de/olli/Python/lambda_functions.hawk) claim that `range` creates a list of values.
> "Note: The range function simply returns a list containing the numbers
> from x to y-1. For example, range(5, 10) returns the list [5, 6, 7, 8,
> 9]."
I believe this is to be inacc... | In Python 2.x, [`range`](https://docs.python.org/2/library/functions.html#range) returns a list, but in Python 3.x [`range`](https://docs.python.org/3/library/functions.html#func-range) returns an immutable sequence, of type [`range`](https://docs.python.org/3/library/stdtypes.html#range).
**Python 2.x:**
```
>>> typ... |
Does range() really create lists? | 23,221,025 | 44 | 2014-04-22T13:27:27Z | 23,221,054 | 7 | 2014-04-22T13:28:43Z | [
"python",
"range"
] | Both my professor and [this guy](http://www.secnetix.de/olli/Python/lambda_functions.hawk) claim that `range` creates a list of values.
> "Note: The range function simply returns a list containing the numbers
> from x to y-1. For example, range(5, 10) returns the list [5, 6, 7, 8,
> 9]."
I believe this is to be inacc... | **It depends.**
In python-2.x, `range` actually creates a list (which is also a sequence) whereas `xrange` creates an `xrange` object that can be used to iterate through the values.
On the other hand, in python-3.x, `range` creates an iterable (or more specifically, a sequence) |
No distributions at all found for some package | 23,222,104 | 11 | 2014-04-22T14:14:15Z | 23,223,408 | 7 | 2014-04-22T15:09:09Z | [
"python",
"django"
] | **error when installing some package but its actualy existing example django-ajax-filtered-fields==0.5**
> Downloading/unpacking django-ajax-filtered-fields==0.5 (from -r
> requirements.example.pip (line 13)) **Could not find any downloads
> that satisfy the requirement** django-ajax-filtered-fields==0.5(from
> -r req... | I got the solution ,Try with **--allow-unverified**
> syntax: **pip install packagename=version --allow-unverified packagename**
Some package condains insecure and unverifiable files. it will not download to the system . and it can be solved by using this method **--allow-unverified**. it will allow the installation.... |
django nginx static files 404 | 23,226,357 | 11 | 2014-04-22T17:29:06Z | 25,123,835 | 10 | 2014-08-04T17:00:01Z | [
"python",
"django",
"nginx",
"django-deployment"
] | Here are my settings :
```
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = '/home/django-projects/tshirtnation/staticfiles'
```
Here's my nginx configuration:
```
server {
server_name 77.241.197.95;
access_log off;
location /static/ {
alias /... | I encountered the same problem and was able to fix my nginx configuration by removing the trailing `/` from the `/static/` location.
```
location /static { # "/static" NOT "/static/"
# ...
}
``` |
Django Custom View Decorators | 23,228,126 | 7 | 2014-04-22T19:05:45Z | 23,228,231 | 10 | 2014-04-22T19:11:43Z | [
"python",
"django",
"decorator",
"python-decorators"
] | Alright I have a method called no\_m in the user class and i've not written a decorator before, but basically I need to redirect the user to another URL if they pass this. I have created a file called decorators.py in a dir called accounts and i'm guessing the decorator is imported correctly, however I cannot get it to... | You're missing a step in the decorator, or rather you have a step confused. It's the *outer* function that must return the inner function (`_wrapped_view_func`), and it must *always* do so: that's what takes the place of the original function when it is called.
I'm not sure what the except clause is there for. Apart f... |
How do you find the IQR in Numpy? | 23,228,244 | 23 | 2014-04-22T19:12:43Z | 23,229,224 | 39 | 2014-04-22T20:10:26Z | [
"python",
"numpy"
] | Is there a baked-in Numpy/Scipy function to find the interquartile range? I can do it pretty easily myself, but `mean()` exists which is basically `sum/len`...
```
def IQR(dist):
return np.percentile(dist, 75) - np.percentile(dist, 25)
``` | `np.percentile` takes multiple percentile arguments, and you are slightly better off doing:
```
q75, q25 = np.percentile(x, [75 ,25])
iqr = q75 - q25
```
or
```
iqr = np.subtract(*np.percentile(x, [75, 25]))
```
than making two calls to `percentile`:
```
In [8]: x = np.random.rand(1e6)
In [9]: %timeit q75, q25 = ... |
Selenium Webdriver: execute_script can't execute custom methods and external javascript files | 23,228,247 | 5 | 2014-04-22T19:12:55Z | 23,231,689 | 9 | 2014-04-22T22:48:05Z | [
"javascript",
"python",
"selenium",
"webdriver"
] | I'm working with Selenium and Python and I'm trying to do two things:
* Import an external javascript file and execute a method defined there
* Define methods on a string and call them after evaluating
This is the output for the first case:
test.js
```
function hello(){
document.body.innerHTML = "testing";
}
```
... | I can get your first case to work if I create an empty html file and issue:
```
f = webdriver.Firefox()
f.get("file://path/to/empty.html")
```
After this, the JavaScript you've shown will execute without issue. When I try the code you've shown in the question, Firefox does not give me an error but Chrome says: "Not a... |
"if", and "elif" chain versus a plain "if" chain | 23,230,044 | 2 | 2014-04-22T20:57:18Z | 23,230,067 | 16 | 2014-04-22T20:58:23Z | [
"python",
"if-statement"
] | I was wondering, why is using `elif` necessary when you could just do this?
```
if True:
...
if False:
...
...
``` | You'd use `elif` when you want to ensure that only *one* branch is picked:
```
foo = 'bar'
spam = 'eggs'
if foo == 'bar':
# do this
elif spam == 'eggs':
# won't do this.
```
Compare this with:
```
foo = 'bar'
spam = 'eggs'
if foo == 'bar':
# do this
if spam == 'eggs':
# *and* do this.
```
With jus... |
Having problems accessing port 5000 in Vagrant | 23,230,599 | 6 | 2014-04-22T21:31:22Z | 23,230,821 | 8 | 2014-04-22T21:47:13Z | [
"python",
"networking",
"flask",
"vagrant",
"vagrantfile"
] | I am trying to teach myself Flask in a Vagrant environment. I understand that Flask runs a server on port 5000 by default. In my Vagrantfile I have:
```
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :forwarded_port, guest: 5000, host: 5000
```
I have a simple tutorial Flask app:
```
from... | You possibly need to get Flask to serve on an externally-visible URL: see [the docs](http://flask.pocoo.org/docs/quickstart/#public-server) |
Having problems accessing port 5000 in Vagrant | 23,230,599 | 6 | 2014-04-22T21:31:22Z | 26,075,543 | 8 | 2014-09-27T14:13:49Z | [
"python",
"networking",
"flask",
"vagrant",
"vagrantfile"
] | I am trying to teach myself Flask in a Vagrant environment. I understand that Flask runs a server on port 5000 by default. In my Vagrantfile I have:
```
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :forwarded_port, guest: 5000, host: 5000
```
I have a simple tutorial Flask app:
```
from... | If you are accessing from Chrome in your desktop, you are technically accessing from a different computer (hence you need to place `host='0.0.0.0'` as argument to `app.run()` to tell the guest OS to accept connections from all public (external) IPs.
This is what worked for me (for both `127.0.0.1:5000/hello` and `loca... |
Convert Pandas dataframe to csv string | 23,231,605 | 6 | 2014-04-22T22:41:57Z | 23,231,758 | 11 | 2014-04-22T22:53:48Z | [
"python",
"pandas"
] | Here is an example of what I am trying to get:
I have:
```
import pandas as pd
df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
```
My goal is:
```
',A,B\n0,0,1\n1,1,6\n'
```
I can achieve this with lazy and horrible:
```
df.to_csv('temp.csv') # create unnecessary file
body = open('temp.csv').read()
```
Also `to... | ```
In [10]: df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
In [11]: import StringIO
In [12]: s = StringIO.StringIO()
In [13]: df.to_csv(s)
In [14]: s.getvalue()
Out[14]: ',A,B\n0,0,1\n1,1,6\n'
``` |
Convert Pandas dataframe to csv string | 23,231,605 | 6 | 2014-04-22T22:41:57Z | 27,768,189 | 10 | 2015-01-04T17:20:00Z | [
"python",
"pandas"
] | Here is an example of what I am trying to get:
I have:
```
import pandas as pd
df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
```
My goal is:
```
',A,B\n0,0,1\n1,1,6\n'
```
I can achieve this with lazy and horrible:
```
df.to_csv('temp.csv') # create unnecessary file
body = open('temp.csv').read()
```
Also `to... | The simplest way is just to not input any filename, in this case a string is returned:
```
>>> df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
>>> df.to_csv()
',A,B\n0,0,1\n1,1,6\n'
``` |
Boxplot stratified by column in python pandas | 23,232,989 | 5 | 2014-04-23T01:02:00Z | 23,233,196 | 7 | 2014-04-23T01:24:26Z | [
"python",
"matplotlib",
"pandas",
"boxplot"
] | I would like to draw a boxplot for the following pandas dataframe:
```
> p1.head(10)
N0_YLDF MAT
0 1.29 13.67
1 2.32 10.67
2 6.24 11.29
3 5.34 21.29
4 6.35 41.67
5 5.35 91.67
6 9.32 21.52
7 6.32 31.52
8 3.33 13.52
9 4.56 44.52
```
I want the boxplots to be of t... | Pandas has the `cut` and `qcut` functions to make stratifying variables like this easy:
```
# Just asking for split into 4 equal groups (i.e. quartiles) here,
# but you can split on custom quantiles by passing in an array
p1['MAT_quartiles'] = pd.qcut(p1['MAT'], 4, labels=['0-25%', '25-50%', '50-75%', '75-100%'])
p1.b... |
Broken references in Virtualenvs | 23,233,252 | 39 | 2014-04-23T01:30:09Z | 25,947,333 | 74 | 2014-09-20T09:31:03Z | [
"python",
"osx",
"virtualenv",
"homebrew"
] | I recently installed a bunch of dotfiles on my Mac along with some other applications (I changed to iTerm instead of Terminal, and Sublime as my default text editor) but ever since, all my virtual environments have stopped working, although their folders inside .virtualenvs are still there and they give the following e... | I found the solution to the problem [here](http://wirtel.be/posts/en/2014/07/29/fix_virtualenv_python_brew/), so all credit goes to the author.
The gist is that when you create a virtualenv, many symlinks are created to the Homebrew installed Python.
Here is one example:
```
$ ls -la ~/.virtualenvs/my-virtual-env
..... |
Setting numpoints in matplotlib legend does not work | 23,233,290 | 8 | 2014-04-23T01:35:08Z | 23,233,368 | 9 | 2014-04-23T01:43:43Z | [
"python",
"matplotlib",
"legend"
] | I am trying to have a single data point on a plot legend by following the suggestions [here](http://stackoverflow.com/questions/6146778/matplotlib-legend-markers-only-once) and it does not seem to work:
```
from pylab import scatter
import pylab
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.gca()
ax.sca... | For scatterplots, use the [scatterpoints](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend) parameter:
```
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(1, 2, c='blue', marker='x')
ax.scatter(2, 3, c='red', marker='o')
ax.legend(('1', '2'), loc=2, scatterpoints=1)
plt.show()
``... |
Get Authenticated user from token in Django Rest Framework | 23,235,544 | 8 | 2014-04-23T05:32:38Z | 23,239,026 | 7 | 2014-04-23T08:38:32Z | [
"python",
"django",
"angularjs",
"api",
"django-rest-framework"
] | I am new in Django and I have managed to build a small API using DRF. I have my angular.js client end posting user auth details and DRF returns a token which looks like this:
```
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
```
Based on the [tutorial](http://www.django-rest-framework.org/api-guide/authent... | Keeping in mind that I am also new to Angular and DRF...
If you are already receiving the token, then on the angularjs side, you need to be including the token in the headers of your subsequent requests. Perhaps like this abbreviated code from the authentication request:
```
$http({auth request code here}).then(funct... |
Create object from class in separate file | 23,238,352 | 3 | 2014-04-23T08:03:01Z | 23,238,374 | 9 | 2014-04-23T08:04:17Z | [
"python",
"class",
"object",
"package"
] | I have done several tutorials on Python and I know how to define classes, but I don't know how to use them. For example I create the following **file** (car.py):
```
class Car(object):
condition = 'New'
def __init__(self,brand,model,color):
self.brand = brand
self.model = model
self.col... | In your `Mercedes.py`, you should import the `car.py` file as follows (as long as the two files are in the *same directory*):
```
import car
```
Then you can do:
```
Mercedes = car.Car('Mercedes', 'S Class', 'Red') #note the necessary 'car.'
```
Alternatively, you could do
```
from car import Car
Mercedes = Car(... |
Why `.` in PEP 0263 regex? | 23,239,588 | 4 | 2014-04-23T09:03:33Z | 23,239,617 | 7 | 2014-04-23T09:05:33Z | [
"python",
"regex",
"syntax",
"pep"
] | In [PEP 0263](http://legacy.python.org/dev/peps/pep-0263/) the format for defining the encoding of a Python file is defined as:
```
coding[:=]\s*([-\w.]+)
```
Why is there a `.` in the regex, or alternatively, why is there `-` and `\w`? So far as I understand, the `.` matches any character except a newline, so either... | When you use `.` and `-` in character classes, they both behave differently. In character classes, `.` has no special meaning and will be treated as dot only, where as `-` can be used to specify ranges like `a-zA-Z0-9`.
Since we don't use `-` to represent a range in this case, both `.` and `-` will be matching themsel... |
Confused about the proper order of try and with in Python | 23,240,650 | 5 | 2014-04-23T09:46:40Z | 23,240,692 | 8 | 2014-04-23T09:48:36Z | [
"python",
"try-catch",
"with-statement",
"contextmanager"
] | I read here that it is recommended to use `with open(filename)` instead of using the pair `open(filename)` and `filename.close()` (at least for basic tasks) and that it is also better to use `try`.
Q1: If my understanding is correct, what would be the proper order ?
```
try:
with open(filename) as f:
do somethi... | Keep your `try` / `except` statement as close to the source of the exception as possible.
If you are not catching `IOError`s, put it inside the `with` statement. On the other hand, if it is an exception that `open()` throws, put it *around* the `with` statement.
If the `with` statement is longer or you don't want to ... |
Why is python's word in words iterating on letters instead of words? | 23,243,948 | 4 | 2014-04-23T12:14:36Z | 23,243,973 | 8 | 2014-04-23T12:15:26Z | [
"python"
] | When I enter the following code:
```
def word_feats(words):
return dict([(word, True) for word in words])
print(word_feats("I love this sandwich."))
```
I get the output in letters instead of words
```
{'a': True, ' ': True, 'c': True, 'e': True, 'd': True, 'I': True, 'h': True, 'l': True, 'o': True, 'n': True, ... | You need to explicitly *split* the string on whitespace:
```
def word_feats(words):
return dict([(word, True) for word in words.split()])
```
This uses [`str.split()`](https://docs.python.org/3/library/stdtypes.html#str.split) without arguments, splitting on arbitrary-width whitespace (including tabs and line sep... |
Set LD_LIBRARY_PATH before importing in python | 23,244,418 | 13 | 2014-04-23T12:33:48Z | 23,244,452 | 7 | 2014-04-23T12:35:09Z | [
"python",
"import",
"environment-variables",
"sys"
] | Python uses the `PYTHONPATH` environment-variable to determine in which folders it should look for modules.
You can play around with it by modifying `sys.path`, which works nicely for pure Python-Modules.
But when a module uses shared object files or static libraries, it looks for those in `LD_LIBRARY_PATH` (on linux),... | I would use:
```
import os
os.environ['LD_LIBRARY_PATH'] = os.getcwd() # or whatever path you want
```
This sets the `LD_LIBRARY_PATH` environment variable for the duration/lifetime of the execution of the current process only.
**EDIT:** it looks like this needs to be set before starting Python: [Changing LD\_LIBR... |
Python - if x not in any of a, b, c | 23,246,474 | 2 | 2014-04-23T13:52:27Z | 23,246,500 | 10 | 2014-04-23T13:53:30Z | [
"python",
"if-statement"
] | In a program I am writing at the moment I need to do the following:
```
if (x not in a) and (x not in b) and (x not in c):
```
which, of course, is very tedious, especially when a, b, and c all have much longer names.
Is there a built-in function that can do this:
```
if x is_in_one_of(a, b, c):
```
I know how I c... | You can do that as:
```
if all(x not in i for i in (a,b,c)):
```
The `all` above will only evaluate to `True` if x is not in any of a,b, or c
Or in other words:
```
if not any(x in i for i in (a,b,c)):
``` |
Python: Cast time module as string | 23,247,983 | 3 | 2014-04-23T14:53:13Z | 23,248,045 | 7 | 2014-04-23T14:56:05Z | [
"python",
"time"
] | I have a string in a piece of python code which I want to add a time stamp too. However, when I try to cast the timestamp to a string I get the data type, rather than a string representation of the timestamp.
The code looks like this,
```
timeStamp = "TIME-" + str(time)
print timeStamp
>>> Time-<module 'time' (built... | You imported just the `time` module and turned *that* into a string; you need to call the [`time.time()` *function*](https://docs.python.org/2/library/time.html#time.time):
```
timeStamp = "TIME-" + str(time.time())
``` |
Cannot find reference 'xxx' in __init__.py - Python / Pycharm | 23,248,017 | 14 | 2014-04-23T14:55:00Z | 23,839,976 | 19 | 2014-05-24T00:07:55Z | [
"python",
"reference",
"coding-style",
"pycharm"
] | I have a project in Pycharm organized as follows:
```
-- Sources
|--__init__.py
|--Calculators
|--__init__.py
|--Filters.py
|--Controllers
|--__init__.py
|--FiltersController.py
|--Viewers
|--__init__.py
|--DataVisualization.py
|--Models
|--__init__.py
|--... | This is a bug in pycharm. PyCharm seems to be expecting the referenced module to be included in an `__all__ = []` statement.
For proper coding etiquette, should you include the `__all__` statement from your modules? ..this is actually the question we hear young Spock answering while he was being tested, to which he re... |
FIll between two vertical lines in matplotlib | 23,248,435 | 19 | 2014-04-23T15:10:55Z | 23,248,784 | 36 | 2014-04-23T15:24:44Z | [
"python",
"matplotlib"
] | I went through the [examples](http://matplotlib.org/examples/pylab_examples/fill_between_demo.html) in the `matplotlib` documentation, but it wasn't clear to me how I can make a plot that fills the area between two specific vertical lines.
For example, say I want to create a plot between `x=0.2` and `x=4` (for the ful... | It sounds like you want [`axvspan`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axvspan), rather than one of the fill between functions. The differences is that `axvspan` (and [`axhspan`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axhspan)) will fill up the entire y (or x) extent of the... |
Python3 rounding to nearest even | 23,248,489 | 13 | 2014-04-23T15:12:38Z | 23,248,569 | 23 | 2014-04-23T15:16:23Z | [
"python",
"python-3.x",
"floating-point",
"rounding"
] | Python3.4 rounds to the nearest even (in the tie-breaker case).
```
>>> round(1.5)
2
>>> round(2.5)
2
```
But it only seems to do this when rounding to an integer.
```
>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9
```
In the final example above, I would have expected 2.8 as the answer when rounding to the nearest e... | Floating point numbers are only *approximations*; 2.85 cannot be represented *exactly*:
```
>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'
```
It is slightly *over* 2.85.
0.5 and 0.75 *can* be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).
The `round... |
Joining of strings in a list | 23,249,269 | 3 | 2014-04-23T15:43:55Z | 23,249,445 | 8 | 2014-04-23T15:51:50Z | [
"python",
"list"
] | I have a list in python:
```
A = ['5', 'C', '1.0', '2.0', '3.0', 'C', '2.1', '1.0', '2.4', 'C', '5.4', '2.4', '2.6', 'C', '2.3', '1.2', '5.2']
```
I want to join `A` in a a way where output looks like:
```
5\n
C 1.0 2.0 3.0\n
C 2.1 1.0 2.4\n
C 5.4 2.4 2.6\n
C 2.3 1.2 5.2
```
`''.join(A)` joins every string together... | You can loop through, or just do something like this:
```
' '.join(A).replace(' C', '\nC')
```
The space in the replace string is really important to prevent a leading empty line if the first char is a 'C', and to prevent trailing whitespace in other places. (Thanks @aruisdante) |
ImportError: No module named rest_framework.authtoken | 23,251,141 | 9 | 2014-04-23T17:19:59Z | 23,251,308 | 8 | 2014-04-23T17:28:41Z | [
"python",
"django",
"django-rest-framework"
] | I'm using django rest-framework's, (DRF), token authentication in my project to create tokens when a user is created. Everything works great until I add this line from the DRF docs:
```
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
```
to create an endpoint that returns the token for a... | Check out the last response [here](https://groups.google.com/forum/#!topic/django-rest-framework/7OKXjcViC38). Instead of including the whole view as a string, import 'obtain\_auth\_token' first and then just refer to that.
```
from rest_framework.authtoken.views import obtain_auth_token
...
url(r'^api-token-auth/', ... |
Overloading __dict__() on python class | 23,252,370 | 13 | 2014-04-23T18:26:05Z | 23,252,443 | 15 | 2014-04-23T18:30:00Z | [
"python",
"class"
] | I have a class where I want to get the object back as a dictionary, so I implemented this in the `__dict__()`. Is this correct?
I figured once I did that, I could then use the `dict` (custom object), and get back the object as a dictionary, but that does not work.
Should you overload `__dict__()`? How can you make it... | `__dict__` is *not* a special method on Python objects. Instead, it is used for the attribute dictionary. `dict()` never uses it.
Instead, you could support *iteration*; when `dict()` is passed an [iterable](https://docs.python.org/2/glossary.html#term-iterable) that produces key-value pairs, a new dictionary object w... |
Overloading __dict__() on python class | 23,252,370 | 13 | 2014-04-23T18:26:05Z | 23,252,537 | 8 | 2014-04-23T18:35:05Z | [
"python",
"class"
] | I have a class where I want to get the object back as a dictionary, so I implemented this in the `__dict__()`. Is this correct?
I figured once I did that, I could then use the `dict` (custom object), and get back the object as a dictionary, but that does not work.
Should you overload `__dict__()`? How can you make it... | No. `__dict__` is a method used for introspection - it returns object attributes. What you want is a brand new method, call it `as_dict`, for example - that's the convention. The thing to understand here is that `dict` objects don't need to be necessarily created with `dict` constructor. |
I get an Error 400: Bad Request on custom Heroku domain, but works fine on foo.herokuapp.com | 23,252,733 | 6 | 2014-04-23T18:45:52Z | 27,402,083 | 7 | 2014-12-10T13:20:28Z | [
"python",
"django",
"http",
"heroku"
] | I've just pushed a Django project up to Heroku. It works fine at <http://rtd-staging.herokuapp.com/rtd2015/>, but for some reason I get a 400 error: Bad Request when I visit it using: <http://staging.researchthroughdesign.org/rtd2015/>
I know that the CNAME was setup correctly because during the process of pushing up ... | You have to set your website domain as an allowed host. Place this in your `settings.py`:
```
ALLOWED_HOSTS = [".herokuapp.com", ".researchthroughdesign.org"]
``` |
Numpy, the array doesn't have its own data? | 23,253,144 | 7 | 2014-04-23T19:09:15Z | 23,253,578 | 8 | 2014-04-23T19:32:30Z | [
"python",
"numpy"
] | I tried to use `resize` on an array in this way:
```
a = np.array([1,2,3,4,5,6], dtype=np.uint8)
a.resize(4,2)
print a
```
and the output is Ok!(I meant that there was no error). But when I run this code:
```
a = np.array([1,2,3,4,5,6], dtype=np.uint8).reshape(2,3)
a.resize(4,2)
print a
```
it gave rise to an error... | Lets start with the following:
```
>>> a = np.array([1,2,3,4,5,6], dtype=np.uint8)
>>> b = a.reshape(2,3)
>>> b[0,0] = 5
>>> a
array([5, 2, 3, 4, 5, 6], dtype=uint8)
```
I can see here that array `b` is not its own array, but simply a view of `a` (just another way to understand the "OWNDATA" flag). To put it simply b... |
How to input 2 integers in one line in Python? | 23,253,863 | 5 | 2014-04-23T19:47:06Z | 23,253,889 | 14 | 2014-04-23T19:48:40Z | [
"python",
"python-3.x",
"input",
"line"
] | I wonder if it is possible to input two or more integer numbers in one line of standard input. In `C`/`C++` it's easy:
`C++`:
```
#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
return 0;
}
```
`C`:
```
#include <stdio.h>
void main() {
int a, b;
scanf("%d%d", &a, &b);
}
```
In `P... | Split the entered text on whitespace:
```
a, b = map(int, input().split())
```
Demo:
```
>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5
``` |
Install django1.7 with Python 3.4 using virtualenv | 23,256,054 | 9 | 2014-04-23T22:02:09Z | 23,256,141 | 23 | 2014-04-23T22:09:08Z | [
"python",
"django",
"python-2.7",
"python-3.4"
] | I have hit a bit of a brick wall regarding the set up of django 1.7 using a virtualenv configured to Python 3.4.
I have created a Python 3.4 virtualenv using:
```
sudo virtualenv --no-site-packages -p /usr/bin/python3.4 venv
```
I have then activated the env using:
```
source venv/bin/activate
```
Once in the acti... | `sudo` is unnecessary when creating a virtualenv and when installing with pip inside a virtualenv. Try the following instead:
`$ virtualenv -p /usr/bin/python3.4 venv`
`$ source venv/bin/activate`
(At this point, you can check that your virtualenv is active and using python 3.4 with `which python`, which should prin... |
importing pyspark in python shell | 23,256,536 | 44 | 2014-04-23T22:40:14Z | 23,567,670 | 22 | 2014-05-09T14:51:24Z | [
"python",
"apache-spark"
] | *This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue. (See <http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736>)*
I have Spark installed properly on my machine and am able to run python programs with the pyspark modules w... | Turns out that the pyspark bin is LOADING python and automatically loading the correct library paths. Check out $SPARK\_HOME/bin/pyspark :
```
# Add the PySpark classes to the Python path:
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
```
I added this line to my .bashrc file and the modules are now correctly foun... |
importing pyspark in python shell | 23,256,536 | 44 | 2014-04-23T22:40:14Z | 27,312,524 | 25 | 2014-12-05T09:23:01Z | [
"python",
"apache-spark"
] | *This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue. (See <http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736>)*
I have Spark installed properly on my machine and am able to run python programs with the pyspark modules w... | If it prints such error:
> ImportError: No module named py4j.java\_gateway
Please add $SPARK\_HOME/python/build to PYTHONPATH:
```
export SPARK_HOME=/Users/pzhang/apps/spark-1.1.0-bin-hadoop2.4
export PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/build:$PYTHONPATH
``` |
importing pyspark in python shell | 23,256,536 | 44 | 2014-04-23T22:40:14Z | 28,305,078 | 12 | 2015-02-03T17:29:03Z | [
"python",
"apache-spark"
] | *This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue. (See <http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736>)*
I have Spark installed properly on my machine and am able to run python programs with the pyspark modules w... | On Mac, I use Homebrew to install Spark (formula "apache-spark"). Then, I set the PYTHONPATH this way so the Python import works:
```
export SPARK_HOME=/usr/local/Cellar/apache-spark/1.2.0
export PYTHONPATH=$SPARK_HOME/libexec/python:$SPARK_HOME/libexec/python/build:$PYTHONPATH
```
Replace the "1.2.0" with the actual... |
importing pyspark in python shell | 23,256,536 | 44 | 2014-04-23T22:40:14Z | 33,273,451 | 8 | 2015-10-22T04:33:55Z | [
"python",
"apache-spark"
] | *This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue. (See <http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736>)*
I have Spark installed properly on my machine and am able to run python programs with the pyspark modules w... | dont run your py file as: `python filename.py`
instead use: `spark-submit filename.py` |
importing pyspark in python shell | 23,256,536 | 44 | 2014-04-23T22:40:14Z | 33,513,655 | 11 | 2015-11-04T04:22:35Z | [
"python",
"apache-spark"
] | *This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue. (See <http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736>)*
I have Spark installed properly on my machine and am able to run python programs with the pyspark modules w... | By exporting the SPARK path and the Py4j path, it started to work:
```
export SPARK_HOME=/usr/local/Cellar/apache-spark/1.5.1
export PYTHONPATH=$SPARK_HOME/libexec/python:$SPARK_HOME/libexec/python/build:$PYTHONPATH
PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.8.2.1-src.zip:$PYTHONPATH
export PYTHONPATH=$SPARK_HOME/pytho... |
Python3.4 on Sublime Text 3 | 23,257,984 | 13 | 2014-04-24T01:06:36Z | 23,258,314 | 22 | 2014-04-24T01:43:01Z | [
"python",
"python-3.x",
"sublimetext2",
"sublimetext",
"sublimetext3"
] | I followed these steps to get Python 3 on Sublime Text 3
Select the menu Tools > Build > New Build System and enter the following:
```
{
"cmd": ["python3", "$file"]
, "selector": "source.python"
, "file_regex": "file \"(...*?)\", line ([0-9]+)"
}
```
After that, saved it to the following (Mac-specific) directory: ~/... | You need to provide the full path to python3, since Sublime Text does not read your `~/.bash_profile` file. Open up Terminal, type `which python3`, and use that full path:
```
{
"cmd": ["path/to/python3", "$file"],
"selector": "source.python",
"file_regex": "file \"(...*?)\", line ([0-9]+)"
}
``` |
Python3.4 on Sublime Text 3 | 23,257,984 | 13 | 2014-04-24T01:06:36Z | 31,988,138 | 7 | 2015-08-13T12:22:25Z | [
"python",
"python-3.x",
"sublimetext2",
"sublimetext",
"sublimetext3"
] | I followed these steps to get Python 3 on Sublime Text 3
Select the menu Tools > Build > New Build System and enter the following:
```
{
"cmd": ["python3", "$file"]
, "selector": "source.python"
, "file_regex": "file \"(...*?)\", line ([0-9]+)"
}
```
After that, saved it to the following (Mac-specific) directory: ~/... | This is the snippet that I've been using. It's a slight variation to Andrew's solution, such that python3 is dynamically located by consulting the environment's PATH setting (*as is similarly done inside of a python source file; e.g.*: '**#! /usr/bin/env python3**'). It also uses "*shell\_cmd*" instead of "*cmd*", whic... |
How does Python 2.7.3 hash strings used to seed random number generators? | 23,260,975 | 8 | 2014-04-24T06:02:45Z | 23,332,550 | 8 | 2014-04-28T04:33:28Z | [
"python",
"python-2.7",
"random"
] | In 64 bit Python 2.7.6 this is True, however in 32 bit Python 2.7.3 it is False:
```
random.Random(hash("a")).random() == random.Random("a").random()
```
So how does Python 2.7.3 hash strings used to seed random number generators? | it's because on 32bit `hash("a")` is a negative number (because of platform long type size) and the random modules behaves differently.
The random module seed() function:
* passing int or long it will use `PyNumber_Absolute()` that is `abs()`
* passing an object (a string) it will use `PyLong_FromUnsignedLong((unsign... |
How to specify C++11 with distutils? | 23,261,320 | 8 | 2014-04-24T06:23:51Z | 23,261,706 | 7 | 2014-04-24T06:46:44Z | [
"python",
"c++11",
"distutils"
] | I have a module that needs to be compiled with C++11. On GCC and Clang, that means a `std=c++11` switch, or `std=c++0x` on older compilers.
Python is not compiled with this switch so Distutils doesn't include it when compiling modules.
What is the preferred way to compile C++11 code with distutils? | You can use the `extra_compile_args` parameter of `distutils.core.Extension`:
```
ext = Extension('foo', sources=[....],
libraries=[....],
extra_compile_args=['-std=c++11'],
....)
```
Note that this is completely platform dependent. It won't even work on some older ver... |
How to extract 128x128 icon bitmap data from EXE in python | 23,263,599 | 6 | 2014-04-24T08:23:17Z | 23,390,460 | 8 | 2014-04-30T14:10:25Z | [
"python",
"bitmap",
"pywin32"
] | I'm trying to extract icons from .exe files in windows using win32gui. I found the functionalities ExtractIconEx() and ExtractIcon().
I am able to get Icons of size 32x32 or 16x16 only from the above functionalities. the following link only answers way to extract 32x32 images.
[How to extract 32x32 icon bitmap data fr... | I've made some researches and also post it. If you would like just see the result code (I hope it's exactly what you ask) you could find it after the "horizontal rule" below.
First I tried to use the next code to determine what icon sizes stored in the resources of the file:
```
# Using LoadLibrary (rather than Creat... |
Exclude URLs from Django REST Swagger | 23,263,696 | 4 | 2014-04-24T08:28:35Z | 23,264,206 | 9 | 2014-04-24T08:54:15Z | [
"python",
"django",
"rest",
"swagger"
] | I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (<https://github.com/marcgibbons/django-rest-swagger>) doesn't really tell me much. There is the "exclude\_namespaces" part of SWAGGER\_SETTINGS in settings.py, but there is no re... | the namespaces to exclude are the one defined in your urls.py.
So for example, in your case:
urls.py:
```
internal_apis = patterns('',
url(r'^/api/jobs/status/',...),
url(r'^/api/jobs/parameters/',...),
)
urlpatterns = urlpatterns + patterns('',
... |
Python 3.x BaseHTTPServer or http.server | 23,264,569 | 14 | 2014-04-24T09:10:52Z | 26,652,985 | 19 | 2014-10-30T12:27:50Z | [
"python",
"basehttpserver"
] | I am trying to make a BaseHTTPServer program. I prefer to use Python 3.3 or 3.2 for it. I find the doc hard to understand regarding what to import but tried changing the import from:
```
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
```
to:
```
from http.server import BaseHTTPRequestHandler,HTTPServer... | Your program in python 3.xx does work right out of the box - except for one minor problem. The issue is not in your code but the place where you are writing these lines:
```
self.wfile.write("Hello World !")
```
You are trying to write "string" in there, but bytes should go there. So you need to convert your string t... |
Why can a dictionary be unpacked as a tuple? | 23,268,615 | 61 | 2014-04-24T12:15:44Z | 23,268,666 | 63 | 2014-04-24T12:18:20Z | [
"python",
"python-2.7",
"dictionary",
"iterable-unpacking"
] | Today, I saw one statement which didn't throw an exception. Can anyone explain the theory behind it?
```
>>> x, y = {'a': 2, 'b': 5}
>>> x
'a'
>>> y
'b'
``` | In Python, every [iterable](https://docs.python.org/2/glossary.html#iterable) can be unpacked1:
```
>>> x,y,z = [1, 2, 3] # A list
>>> x,y,z
(1, 2, 3)
>>> x,y,z = 1, 2, 3 # A tuple
>>> x,y,z
(1, 2, 3)
>>> x,y,z = {1:'a', 2:'b', 3:'c'} # A dictionary
>>> x,y,z
(1, 2, 3)
>>> x,y,z = (a for a in (1, 2, 3)) # A genera... |
Why can a dictionary be unpacked as a tuple? | 23,268,615 | 61 | 2014-04-24T12:15:44Z | 23,268,674 | 19 | 2014-04-24T12:18:39Z | [
"python",
"python-2.7",
"dictionary",
"iterable-unpacking"
] | Today, I saw one statement which didn't throw an exception. Can anyone explain the theory behind it?
```
>>> x, y = {'a': 2, 'b': 5}
>>> x
'a'
>>> y
'b'
``` | Iterating a `dict` iterates over the keys. Since your dict literal has exactly two keys, you can unpack it into a 2-tuple.
This is probably not a good practice in general, since dicts are unordered and `x == 'b'` and `y == 'a'` would be a prefectly legal outcome of that code. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.