title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Can Pandas run on Google App Engine for Python? | 14,144,867 | 16 | 2013-01-03T18:24:00Z | 14,148,511 | 16 | 2013-01-03T22:47:21Z | [
"python",
"google-app-engine",
"pandas"
] | Can the [pandas](http://pandas.pydata.org/) data analysis module run on Google App Engine?
My first inclination is no: the web page states "critical code paths **compiled to C**". So since this is not a purely python package, you cannot simply copy a directory or ZIP file into your app engine project.
Is it possible ... | As of today, Google App Engine Python 2.7 runtime [doesn't currently allow](https://developers.google.com/appengine/docs/python/runtime#Pure_Python) running arbitrary C extensions.
But it does allow [inclusion](https://developers.google.com/appengine/docs/python/config/appconfig#Configuring_Libraries) of [third party ... |
file.tell() inconsistency | 14,145,082 | 25 | 2013-01-03T18:39:14Z | 14,145,118 | 42 | 2013-01-03T18:41:31Z | [
"python",
"python-2.7",
"buffering"
] | Does anybody happen to know why when you iterate over a file this way:
## Input:
```
f = open('test.txt', 'r')
for line in f:
print "f.tell(): ",f.tell()
```
## Output:
```
f.tell(): 8192
f.tell(): 8192
f.tell(): 8192
f.tell(): 8192
```
I consistently get the wrong file index from tell(), however, if I use rea... | Using open files as an iterator uses a read-ahead buffer to increase efficiency. As a result, the file pointer advances in large steps across the file as you loop over the lines.
From the [File Objects](http://docs.python.org/2/library/stdtypes.html#file.next) documentation:
> In order to make a for loop the most eff... |
file.tell() inconsistency | 14,145,082 | 25 | 2013-01-03T18:39:14Z | 14,145,157 | 10 | 2013-01-03T18:44:12Z | [
"python",
"python-2.7",
"buffering"
] | Does anybody happen to know why when you iterate over a file this way:
## Input:
```
f = open('test.txt', 'r')
for line in f:
print "f.tell(): ",f.tell()
```
## Output:
```
f.tell(): 8192
f.tell(): 8192
f.tell(): 8192
f.tell(): 8192
```
I consistently get the wrong file index from tell(), however, if I use rea... | The answer lies in the following part of Python 2.7 source code (`fileobject.c`):
```
#define READAHEAD_BUFSIZE 8192
static PyObject *
file_iternext(PyFileObject *f)
{
PyStringObject* l;
if (f->f_fp == NULL)
return err_closed();
if (!f->readable)
return err_mode("reading");
l = reada... |
cron job doesn't output to nohup.out | 14,145,250 | 6 | 2013-01-03T18:51:44Z | 14,146,575 | 9 | 2013-01-03T20:20:29Z | [
"python",
"bash",
"ubuntu",
"cron",
"crontab"
] | i have **start.sh** bash script that is running though **CRON JOB** on ubuntu server
**start.sh** contains bellow mentioned lines of code
path of **start.sh** is `/home/ubuntu/folder1/folder2/start.sh`
```
#!/bin/bash
crawlers(){
nohup scrapy crawl first &
nohup scrapy crawl 2nd &
wait $!
nohup scra... | Why are you using `nohup`? `nohup` is a command that tells the running terminal to ignore the hangup signal. `cron`, however, has no hangup signal, because it is not linked to a terminal session.
In this case, instead of:
```
nohup scrapy crawl first &
```
You probably want:
```
scrapy crawl first > first.txt &
```... |
Why does Python let you instantiate local variables as global from inside a function? | 14,146,106 | 2 | 2013-01-03T19:50:00Z | 14,146,142 | 8 | 2013-01-03T19:52:14Z | [
"python",
"scope",
"global-variables"
] | Why does the below work in Python, without declaring **a** in the global scope first?
```
def setA():
global a
a = 5
def printA():
print a
setA()
printA()
```
It seems to me that this is the correct way to do it:
```
a = None
def setA():
global a
a = 5
def printA():
print a
setA()
printA()... | Basically for the same reason that `a = 5` works to create a new local variable: when you assign to a variable, Python doesn't care whether it exists already or not. The `global` statement simply means "any uses of the following name in this scope are now considered to be operating in global scope".
You can do `a = 5`... |
python: recurcive list processing changes original list | 14,147,175 | 8 | 2013-01-03T21:01:11Z | 14,147,200 | 9 | 2013-01-03T21:03:14Z | [
"python",
"list",
"recursion"
] | What I'm trying to do is recursively process a list. I'm new to python so when all the code was written and sent to be executed I faced a strange problem: the list returns changed after calling the recursive function. To test this I wrote that:
```
def recur(n):
n.append(len(n))
print '>',n
if n[-1]<5: rec... | All the recursive invocations of your function operate on the same list. You need to make a copy:
```
def recur(n):
n.append(len(n))
print '>',n
if n[-1]<5: recur(n[:]) # <<<< Note the [:]
print '<',n
```
There are some good explanations in the answers to [Python: How do I pass a variable by referenc... |
nargout in Python | 14,147,675 | 12 | 2013-01-03T21:37:00Z | 14,147,740 | 7 | 2013-01-03T21:42:04Z | [
"python",
"multiple-variable-return"
] | Does Python have any equivalent of nargout in MATLAB? I find nargout a very neat approach if we want to keep the number of return parameters flexible. Is there a way I can find out how many output parameters have been requested? Something like the following pseudo-python-code:
```
def var_returns_func(a):
"""
a is... | The function can't know what is going to be done with the return value, so it can't know how many are needed. What you could do is pass `nargout` as an argument to your function and use that to decide what to return:
```
def f(a, nargout=1):
if nargout == 1:
return "one value"
elif nargout == 2:
... |
why does python require __init__.py to treat directories as containing packages? | 14,147,990 | 2 | 2013-01-03T22:03:20Z | 14,148,016 | 7 | 2013-01-03T22:05:35Z | [
"python"
] | While going through 6.4 Packages section of [python manual](http://docs.python.org/2/tutorial/modules.html) I came across the following line:
> The `__init__.py` files are required to make Python treat the directories
> as containing packages; this is done to prevent directories with a
> common name, such as string, f... | Lets say you had a project that contained a directory called `math` that contained some numerical data. If no `__init__.py` were required, then when you did `import math`, it would try to import that directory instead of the real `math` module. But since your directory just contained data and not actual Python code, th... |
Using function names as variables in python | 14,148,643 | 2 | 2013-01-03T22:58:50Z | 14,148,654 | 12 | 2013-01-03T22:59:56Z | [
"python"
] | I had an interesting (potentially stupid) idea: What happens if I use a built-in function name as a variable to assign some object (say integer). Here's what I tried:
```
>>> a = [1,2,3,4]
>>> len(a)
4
>>> len = 1
>>> len(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'int' obj... | Technically you can get it back from `__builtin__`
```
from __builtin__ import len
```
But please don't name stuff `len`, it makes sensible programmers angry.
Okay, for a start don't name your variable after the builtins, secondly if you want to respect other functions then respect namespaces for example
```
import... |
Using function names as variables in python | 14,148,643 | 2 | 2013-01-03T22:58:50Z | 14,148,709 | 17 | 2013-01-03T23:04:13Z | [
"python"
] | I had an interesting (potentially stupid) idea: What happens if I use a built-in function name as a variable to assign some object (say integer). Here's what I tried:
```
>>> a = [1,2,3,4]
>>> len(a)
4
>>> len = 1
>>> len(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'int' obj... | Use `del len`:
```
>>> a=[1,2,3,4]
>>> len=15
>>> len(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del len
>>> len(a)
4
```
From [docs.python.org](http://docs.python.org/2/reference/simple_stmts.html#del):
> Deletion of a name removes the bin... |
IncompleteRead using httplib | 14,149,100 | 19 | 2013-01-03T23:43:56Z | 14,206,036 | 23 | 2013-01-07T23:41:46Z | [
"python",
"feedparser",
"httplib"
] | I have been having a persistent problem getting an rss feed from a particular website. I wound up writing a rather ugly procedure to perform this function, but I am curious why this happens and whether any higher level interfaces handle this problem properly. This problem isn't really a show stopper, since I don't need... | At the end of the day, all of the other modules (`feedparser`, `mechanize`, and `urllib2`) call `httplib` which is where the exception is being thrown.
Now, first things first, I also downloaded this with wget and the resulting file was 1854 bytes. Next, I tried with `urllib2`:
```
>>> import urllib2
>>> url = 'http:... |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 14,150,397 | 15 | 2013-01-04T02:46:17Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | for windows; set your proxy in command prompt as
`set HTTP_PROXY=domain\username:password@myproxy:myproxyport`
example:
`set http_proxy=IND\namit.kewat:xl123456@192.168.180.150:8880` |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 14,188,155 | 29 | 2013-01-07T00:02:28Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | To setup CNTLM for windows, follow this [article](http://stormpoopersmith.com/2012/03/20/using-applications-behind-a-corporate-proxy/). For Ubuntu, read [my blog post](http://annelagang.blogspot.com/2012/11/installing-gems-in-ubuntu-1204-using.html).
**Edit:**
Basically, to use CNTLM in any platform, you need to setu... |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 16,357,159 | 34 | 2013-05-03T10:50:07Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | Under Windows dont forget to set
```
SET HTTPS_PROXY=<proxyHost>:<proxyPort>
```
what I needed to set for
```
pip install pep8
``` |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 16,788,430 | 10 | 2013-05-28T09:24:36Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | Under our security policy **I may not use https** with pypi, SSL-inspection rewrites certificates, it breaks the built-in security of pip for www.python.org. The man in the middle is the network-admin.
So **I need to use plain http**. To do so I need to override the system proxy as well as the default pypi:
```
bin/p... |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 19,962,913 | 116 | 2013-11-13T19:44:27Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | Under Ubuntu:
I could not get the proxy option to work as advertised - so following command did *not* work:
> sudo pip --proxy <http://web-proxy.mydomain.com> install somepackage
But exporting the https\_proxy env variable (note its https\_proxy not http\_proxy) did the trick:
> export https\_proxy=<http://web-prox... |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 20,986,910 | 7 | 2014-01-08T04:15:37Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | ## Phone as mobile hotspot/USB tethering
If I have much trouble finding a way through the corporate proxy, I connect to the web through my phone (wireless hotspot if I have wifi, USB tether if not) and do a quick `pip install`.
Might not work for all setups, but should get most people by in a pinch. |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 22,229,387 | 20 | 2014-03-06T15:51:22Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | You can continue to use pip over HTTPS by adding your corporation's root certificate to the cacert.pem file in your site-packages/pip folder. Then configure pip to use your proxy by adding the following lines to ~/pip/pip.conf (or ~\pip\pip.ini if you're on Windows):
```
[global]
proxy = [user:passwd@]proxy.server:por... |
Using pip behind a proxy | 14,149,422 | 109 | 2013-01-04T00:22:17Z | 33,611,028 | 12 | 2015-11-09T14:12:03Z | [
"python",
"proxy",
"pip"
] | I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious.
One of the answers from [this post](http://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy) suggested using [CNTLM](http://cntlm.sourceforge.net/). I installed a... | I was not working to me. I used https for works:
```
pip install --proxy=https://user@mydomain:port somepackage
```
In order to update, add -U. |
Choosing a function randomly | 14,150,561 | 3 | 2013-01-04T03:10:43Z | 14,150,578 | 12 | 2013-01-04T03:12:57Z | [
"python",
"python-2.7"
] | Hello fellow stack overflow users. I was wondering if there is a way to choose a function randomly?
example :
```
from random import choice
random_function_selector = [foo(), foobar(), fudge()]
print choice(random_function_selector)
def foo() :
# some code follows.
```
I have been thinking for about 20 minutes... | ```
from random import choice
random_function_selector = [foo, foobar, fudge]
print choice(random_function_selector)()
```
Python functions are first-class objects: you can refer to them by name without calling them, and then invoke them later.
In your original code, you were invoking all three, then choosing random... |
Converting two lists to a list of dictionaries in Python | 14,150,797 | 2 | 2013-01-04T03:45:28Z | 14,150,816 | 7 | 2013-01-04T03:47:59Z | [
"python",
"list",
"dictionary",
"python-2.7"
] | I have two lists for example like this:
```
L = [1, 2]
S = ['B', 'C']
```
How can I get them to be combined into a dictionary like this:
```
X = {'B': 1, 'C': 2}
```
The lists will always be the same length, but can have any amount of items. | It's a one-liner:
```
dict(zip(S, L))
``` |
can one python script run both with python 2.x and python 3.x | 14,152,548 | 4 | 2013-01-04T06:55:53Z | 14,152,646 | 10 | 2013-01-04T07:02:21Z | [
"python",
"python-3.x"
] | i have thousands of servers(linux), some only has python 2.x and some only has python 3.x, i want to write one script check.py can run on all servers just as $./check.py without use $python check.py or $python3 check.py, is there any way to do this?
my question is how the script check.py find the Interpreter no matter... | Many scripts can run on both 2.x and 3.x. (I've got a bunch I work on on a daily basis, and I've converted various open source libraries from 2.x-only to dual-version.)
A few things make it much easier:
* Require 2.7, or at least 2.6+, for 2.x users. Otherwise, for example, you cannot raise and exceptions with parame... |
Call Python script from bash with argument | 14,155,669 | 9 | 2013-01-04T10:48:28Z | 14,155,701 | 13 | 2013-01-04T10:50:37Z | [
"python",
"linux",
"bash",
"shell",
"debian"
] | I know that I can run a python script from my bash script using the following:
```
python python_script.py
```
But what about if I wanted to pass a variable / argument to my python script from my bash script. How can I do that?
Basically bash will work out a filename and then python will upload it, but I need to sen... | Use
```
python python_script.py filename
```
and in your Python script
```
import sys
print sys.argv[1]
``` |
Call Python script from bash with argument | 14,155,669 | 9 | 2013-01-04T10:48:28Z | 14,155,784 | 8 | 2013-01-04T10:55:36Z | [
"python",
"linux",
"bash",
"shell",
"debian"
] | I know that I can run a python script from my bash script using the following:
```
python python_script.py
```
But what about if I wanted to pass a variable / argument to my python script from my bash script. How can I do that?
Basically bash will work out a filename and then python will upload it, but I need to sen... | Beside [`sys.argv`](http://docs.python.org/3.0/library/sys.html#sys.argv), also take a look at the [argparse](http://docs.python.org/dev/library/argparse.html) module, which helps define options and arguments for scripts.
> The argparse module makes it easy to write user-friendly command-line interfaces. |
Call Python script from bash with argument | 14,155,669 | 9 | 2013-01-04T10:48:28Z | 32,750,302 | 9 | 2015-09-23T22:07:07Z | [
"python",
"linux",
"bash",
"shell",
"debian"
] | I know that I can run a python script from my bash script using the following:
```
python python_script.py
```
But what about if I wanted to pass a variable / argument to my python script from my bash script. How can I do that?
Basically bash will work out a filename and then python will upload it, but I need to sen... | To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance
```
> python python_script.py var1 var2
```
To access these variables within python you will need
```
import sys
print sys.argv[0] # prints python_script.py
print sys.argv[1] # prints var1
pri... |
Fetching tweets with hashtag from Twitter using Python | 14,156,625 | 6 | 2013-01-04T11:49:01Z | 14,177,040 | 14 | 2013-01-05T22:21:57Z | [
"python",
"twitter",
"twython"
] | How do we find or fetch tweets on the basis of hash tag. i.e. I want to find tweets regarding on a certain subject? Is it possible in Python using Twython?
Thanks | **EDIT**
My original solution using Twython's hooks for the Search API appears to be no longer valid because Twitter now wants users authenticated for using Search. To do an authenticated search via Twython, just supply your Twitter authentication credentials when you initialize the Twython object. Below, I'm pasting a... |
Python: skip comment lines marked with # in csv.DictReader | 14,158,868 | 33 | 2013-01-04T14:20:30Z | 14,158,869 | 44 | 2013-01-04T14:20:30Z | [
"python",
"csv",
"comments"
] | Processing CSV files with [csv.DictReader](http://docs.python.org/2/library/csv.html#csv.DictReader) is great - but I have CSV files with comment lines in (indicated by a hash at the start of a line), for example:
```
# step size=1.61853
val0,val1,val2,hybridisation,temp,smattr
0.206895,0.797923,0.202077,0.631199,0.36... | Actually this works nicely with `filter`:
```
import csv
fp = open('samples.csv')
rdr = csv.DictReader(filter(lambda row: row[0]!='#', fp))
for row in rdr:
print(row)
fp.close()
``` |
Python: suggestion how to improve to write in streaming text file in Python | 14,158,880 | 3 | 2013-01-04T14:20:57Z | 14,158,991 | 8 | 2013-01-04T14:28:17Z | [
"python",
"performance",
"optimization",
"coding-style"
] | I am studying how to write in [streaming strings as files in python](http://docs.python.org/2/library/io.html).
normally i use an expression as
```
myfile = open("test.txt", w)
for line in mydata:
... myfile.write(line + '\n')
myfile.close()
```
Python creates a text file in the directory and save the values chu... | File I/O in python is already buffered. The [`open()` function](http://docs.python.org/2/library/functions.html#open) lets you determine to what extend writing is buffered:
> The optional *`buffering`* argument specifies the fileâs desired buffer size: `0` means unbuffered, `1` means line buffered, any other positiv... |
Python monkey patching | 14,158,947 | 8 | 2013-01-04T14:25:27Z | 14,159,081 | 11 | 2013-01-04T14:34:28Z | [
"python",
"monkeypatching"
] | I need to monkeypatch requests' Response class (version 1.0.4, current as of this question), to add additional methods.
I have this code:
```
import requests
class Response(requests.models.Response):
def hmm(self):
return 'ok'
requests.models.Response = Response
r = requests.get('http://bbc.co.uk')
pr... | You'd be better off just adding your function directly to the class:
```
def hmm(self):
return 'ok'
requests.models.Response.hmm = hmm
```
This works just fine:
```
>>> import requests
>>> def hmm(self):
... return 'ok'
...
>>> requests.models.Response.hmm = hmm
>>> r = requests.get('http://bbc.co.uk')
>>> ... |
pip install a local git repository | 14,159,482 | 14 | 2013-01-04T14:56:42Z | 17,577,904 | 35 | 2013-07-10T18:11:37Z | [
"python",
"git",
"pip"
] | I can't find the correct way to install a local directory as a python package using pip.
```
(venv) C:\(...)>pip install . --no-index
Ignoring indexes: http://pypi.python.org/simple/
Unpacking c:\users\fsantos\desktop\biskates.com\biskates\forks\django-pipeline
Running setup.py egg_info for package from file:///(...... | I can also just use:
```
cd your-local-repo
pip install -e .
```
or
```
python setup.py install develop
``` |
pip install a local git repository | 14,159,482 | 14 | 2013-01-04T14:56:42Z | 27,134,362 | 26 | 2014-11-25T18:47:10Z | [
"python",
"git",
"pip"
] | I can't find the correct way to install a local directory as a python package using pip.
```
(venv) C:\(...)>pip install . --no-index
Ignoring indexes: http://pypi.python.org/simple/
Unpacking c:\users\fsantos\desktop\biskates.com\biskates\forks\django-pipeline
Running setup.py egg_info for package from file:///(...... | If you're working in a venv, you can do this:
env/bin/pip install git+file:///path/to/your/git/repo
Or with a branch:
env/bin/pip install git+file:///path/to/your/git/repo@mybranch |
How to make field in OpenERP required only for specific workflow state? | 14,160,068 | 7 | 2013-01-04T15:33:20Z | 14,161,207 | 9 | 2013-01-04T16:44:37Z | [
"python",
"postgresql",
"openerp"
] | In my OpenERP installation I have the following field, which wasn't required before, but I changed the required argument to True.
```
'fiscal_position': fields.many2one(
'account.fiscal.position',
'Fiscal Position',
required=True,
readonly=True,
states={'draft':[('readonly',False)]}
),
```
In ... | To make a field required only in some states, leave it as not required in the Model, and in the form view set the conditions on which the field will be required:
```
<field
name="fiscal_position"
attrs="{'required':[('state','in',['pending','open'])]}"
/>
``` |
Jinja2: TemplateSyntaxError: Encountered unknown tag | 14,160,414 | 3 | 2013-01-04T15:54:55Z | 14,161,689 | 15 | 2013-01-04T17:15:50Z | [
"python",
"highcharts",
"flask",
"jinja2"
] | "I am using Flask,Jinja2,higHighcharts"
Example (Python/Flask):
```
@app.route("/column/")
def column():
data=[{"data": [49.9, 54.4], "name": "Tokyo"}, {"data": [42, 30.4], "name": "AC"}]
return render_template('column.html', data=data)
```
Example(html,Jinja2,highcharts),my code is Wrong, and how to change ... | Replace
```
series: {% data %}
```
with
```
series: {{ data }}
```
`{{ variable }}` is used when you want to use a variable passed from the python script to the template. |
Python - Sorting elements in a list of lists | 14,161,827 | 5 | 2013-01-04T17:25:01Z | 14,161,882 | 8 | 2013-01-04T17:28:20Z | [
"python",
"list",
"sorting"
] | Apologies if this has been answered elsewhere; I've tried searching, but haven't found anything that answers my question (or perhaps I have, but didn't understand it)...
I'm fairly new to Python (v2.6.2) and have a list of lists containing floating point values which looks something like the following (except the full... | This is going to be painful, but using default python you have 2 options:
* decorate the 1st and 2nd lists with `enumerate()`, then sort these using the index to refer to values from the 3rd list:
```
cat_sorted = [
[e for i, e in sorted(enumerate(cat[0]), key=lambda p: cat[2][p[0]])],
[e for i, e in ... |
How to get the values from a NumPy array using multiple indices | 14,162,026 | 5 | 2013-01-04T17:37:35Z | 14,162,121 | 12 | 2013-01-04T17:44:11Z | [
"python",
"numpy",
"scipy"
] | I have a NumPy array that looks like this:
```
arr = [100.10, 200.42, 4.14, 89.00, 34.55, 1.12]
```
How can I get multiple values from this array by index:
For example, how can I get the values at the index positions 1, 4, and 5?
I was trying something like this, which is incorrect:
```
arr[1, 4, 5]
``` | Try like this:
```
>>> arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
>>> arr[[1,4,5]]
array([ 200.42, 34.55, 1.12])
```
And for multidimensional arrays:
```
>>> arr = np.arange(9).reshape(3,3)
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> arr[[0, 1, 1], [1, 0, 2]]
array([1, 3, ... |
JSON "POST" to Flask View doesn't work | 14,162,821 | 13 | 2013-01-04T18:32:38Z | 14,163,162 | 13 | 2013-01-04T18:57:18Z | [
"jquery",
"python",
"json",
"post",
"flask"
] | I want to send some JSON via POST to my Flask View.
here is my code
js:
```
$.post('/blog/add/ajax',
{ "title": "hallo", "article": "test" },
function(data) {
console.log(data.title);
console.log(data.article);
},
"json"
);
```
py:
```
@app.route('/blog/add/ajax', methods=['POST', 'GET'])
def add_b... | Ok I got a solution:
```
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/blog/add/ajax",
data: JSON.stringify({title: 'hallo', article: 'test'}),
success: function (data) {
console.log(data.title);
console.log(data.article);
},
dataType: "json"
});
```
This works fo... |
Convert list of datestrings to datetime very slow with Python strptime | 14,163,399 | 5 | 2013-01-04T19:13:40Z | 14,163,523 | 13 | 2013-01-04T19:23:01Z | [
"python",
"numpy"
] | I have data files containing lists of strings representing ISO formatted dates. Currently, I am reading them in using:
```
mydates = [ datetime.datetime.strptime(timdata[x], "%Y-%m-%dT%H:%M:%S") for x in range(len(timedata)) ]
```
This looks quite straightforward, but is ridiculously slow when operating on huge lists... | Here is a way to do it about 3x faster.
The original version:
```
In [23]: %timeit datetime.datetime.strptime("2013-01-01T01:23:45", "%Y-%m-%dT%H:%M:%S")
10000 loops, best of 3: 21.8 us per loop
```
The faster version:
```
In [24]: p = re.compile('[-T:]')
In [26]: %timeit datetime.datetime(*map(int, p.split("2013-... |
Convert list of datestrings to datetime very slow with Python strptime | 14,163,399 | 5 | 2013-01-04T19:13:40Z | 14,166,888 | 7 | 2013-01-04T23:48:16Z | [
"python",
"numpy"
] | I have data files containing lists of strings representing ISO formatted dates. Currently, I am reading them in using:
```
mydates = [ datetime.datetime.strptime(timdata[x], "%Y-%m-%dT%H:%M:%S") for x in range(len(timedata)) ]
```
This looks quite straightforward, but is ridiculously slow when operating on huge lists... | Indexing / slicing seems to be faster than the regex used by @NPE:
```
In [47]: def with_indexing(dstr):
....: return datetime.datetime(*map(int, [dstr[:4], dstr[5:7], dstr[8:10],
....: dstr[11:13], dstr[14:16], dstr[17:]]))
In [48]: p = re.compil... |
Python and Django OperationalError (2006, 'MySQL server has gone away') | 14,163,429 | 16 | 2013-01-04T19:16:02Z | 14,268,418 | 25 | 2013-01-10T22:26:47Z | [
"python",
"mysql",
"django",
"nginx",
"django-middleware"
] | Original: I have recently started getting MySQL OperationalErrors from some of my old code and cannot seem to trace back the problem. Since it was working before, I thought it may have been a software update that broke something. I am using python 2.7 with django runfcgi with nginx. Here is my original code:
**views.p... | As per the [MySQL documentation](http://dev.mysql.com/doc/refman/5.0/en/gone-away.html), your error message is raised when the client can't send a question to the server, most likely because the server itself has closed the connection. In the most common case the server will close an idle connection after a (default) o... |
Python and Django OperationalError (2006, 'MySQL server has gone away') | 14,163,429 | 16 | 2013-01-04T19:16:02Z | 17,798,683 | 29 | 2013-07-22T22:40:05Z | [
"python",
"mysql",
"django",
"nginx",
"django-middleware"
] | Original: I have recently started getting MySQL OperationalErrors from some of my old code and cannot seem to trace back the problem. Since it was working before, I thought it may have been a software update that broke something. I am using python 2.7 with django runfcgi with nginx. Here is my original code:
**views.p... | Sometimes if you see "OperationalError: (2006, 'MySQL server has gone away')", it is because you are issuing a query that is too large. This can happen, for instance, if you're storing your sessions in MySQL, and you're trying to put something really big in the session. To fix the problem, you need to increase the valu... |
Is there anything like Python export? | 14,163,532 | 5 | 2013-01-04T19:23:49Z | 14,164,287 | 7 | 2013-01-04T20:17:20Z | [
"python",
"python-module"
] | We use all the time python's import mechanism to import modules and variables and other stuff..but, is there anything that works as export? like:
we import stuff from a module:
```
from abc import *
```
so can we export like?:
```
to xyz export *
```
or
export a,b,c to program.py
I know this question isn't a typi... | First, import the module you want to export stuff into, so you have a reference to it. Then assign the things you want to export as attributes of the module:
```
# to xyz export a, b, c
import xyz
xyz.a = a
xyz.b = b
xyz.c = c
```
To do a wildcard export, you can use a loop:
```
# to xyz export *
exports = [(k, v) f... |
how can set headers (user-agent), retrieve a web page, capture redirects and accept cookies? | 14,164,985 | 2 | 2013-01-04T21:07:31Z | 14,165,123 | 8 | 2013-01-04T21:17:38Z | [
"python",
"python-3.x",
"urllib"
] | ```
import urllib.request
url="http://espn.com"
f = urllib.request.urlopen(url)
contents = f.read().decode('latin-1')
q = f.geturl()
print(q)
```
This code will return `http://espn.go.com/`, which is what I want -- a redirect web site URL. After looking at the Python documentation, googling, etc., I can't figure out h... | There *is* a better module, it's called [`requests`](http://python-requests.org/):
```
import requests
session = requests.Session()
session.headers['User-Agent'] = 'My-requests-agent/0.1'
resp = session.get(url)
contents = resp.text # If the server said it's latin 1, this'll be unicode (ready decoded)
print(resp.ur... |
Can I read the browser url using selenium webdriver? | 14,166,572 | 6 | 2013-01-04T23:13:30Z | 14,166,631 | 15 | 2013-01-04T23:19:27Z | [
"python",
"selenium",
"beautifulsoup",
"selenium-webdriver"
] | I am using python2.7 with `beautiful Soup4 and Selenium webdriver`. Now in my webautomation script i will open the link or URL and get into the home page. Now I need to click onto some `anchor Labels` to navigate through other pages.I did till now. now when i will be going to a new page, I need to get the new `URL` fro... | You get `current_url` attribute on the driver:
```
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.current_url
``` |
beautifulSoup html csv | 14,167,352 | 6 | 2013-01-05T00:54:45Z | 14,167,916 | 15 | 2013-01-05T02:22:20Z | [
"python",
"csv",
"python-2.7",
"beautifulsoup"
] | Good evening, I have used BeautifulSoup to extract some data from a website as follows:
```
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
soup = BeautifulSoup(urlopen('http://www.fsa.gov.uk/about/media/facts/fines/2002'))
table = soup.findAll('table', attrs={ "class" : "table-horizontal-line"})... | Here is a basic thing you can try. This makes the assumption that the `headers` are all in the `<th>` tags, and that all subsequent data is in the `<td>` tags. This works in the single case you provided, but I'm sure adjustments will be necessary if other cases :) The general idea is that once you find your `table` (he... |
python/flask/Jinja2 and Json | 14,168,539 | 8 | 2013-01-05T04:19:55Z | 14,168,553 | 16 | 2013-01-05T04:23:20Z | [
"python",
"json",
"highcharts",
"flask",
"jinja2"
] | "I am using Flask,Jinja2,higHighcharts"
Example (Python/Flask):
```
@app.route("/column/")
def column():
data=[{"data": [49.9, 54.4], "name": "Tokyo"}, {"data": [42, 30.4], "name": "AC"}]
return render_template('column.html', data=data)
```
my templates
```
$(document).ready(function() {
chart1 = new ... | Mark your data as *safe* with [`Markup`](http://flask.pocoo.org/docs/api/#flask.Markup):
> Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped.
Or change `{{ data }}` to `{{ data|tojson|safe }}`. |
Generating all unique pair permutations | 14,169,122 | 6 | 2013-01-05T05:58:27Z | 14,169,142 | 7 | 2013-01-05T06:00:43Z | [
"python",
"combinatorics",
"itertools"
] | I need to generate all possible pairings, but with the constraint that a particular pairing only occurs once in the results. So for example:
```
import itertools
for perm in itertools.permutations(range(9)):
print zip(perm[::2], perm[1::2])
```
generates all possible two-paired permutations; here's a small subse... | Pass the list to `set` to get make sure each tuple only exists once.
```
>>> from itertools import permutations
>>> set( [ zip( perm[::2], perm[1::2] ) for perm in permutations( range( 9 ) ) ] )
set([(7, 3), (4, 7), (1, 3), (4, 8), (5, 6), (2, 8), (8, 0), (3, 2), (2, 1), (6, 2), (1, 6), (5, 1), (3, 7), (2, 5), (8, 5),... |
How to use multiprocessing with class instances in Python? | 14,169,550 | 13 | 2013-01-05T07:10:17Z | 14,169,781 | 7 | 2013-01-05T07:44:33Z | [
"python",
"multiprocessing",
"decorator"
] | I am trying to create a class than can run a separate process to go do some work that takes a long time, launch a bunch of these from a main module and then wait for them all to finish. I want to launch the processes once and then keep feeding them things to do rather than creating and destroying processes. For example... | Instead of attempting to send a method itself (which is impractical), try sending a *name* of a method to execute.
Provided that each worker runs the same code, it's a matter of a simple `getattr(self, task_name)`.
I'd pass tuples `(task_name, task_args)`, where `task_args` were a dict to be directly fed to the task ... |
How to use multiprocessing with class instances in Python? | 14,169,550 | 13 | 2013-01-05T07:10:17Z | 14,179,779 | 13 | 2013-01-06T06:03:54Z | [
"python",
"multiprocessing",
"decorator"
] | I am trying to create a class than can run a separate process to go do some work that takes a long time, launch a bunch of these from a main module and then wait for them all to finish. I want to launch the processes once and then keep feeding them things to do rather than creating and destroying processes. For example... | So, the problem was that I was assuming that Python was doing some sort of magic that is somehow different from the way that C++/fork() works. I somehow thought that Python only copied the class, not the whole program into a separate process. I seriously wasted days trying to get this to work because all of the talk ab... |
Get Absolute URL in Django when using Class Based Views | 14,170,473 | 4 | 2013-01-05T09:34:08Z | 14,171,325 | 15 | 2013-01-05T11:29:11Z | [
"python",
"django"
] | Hello I am migrating my app to use class based views instead of function based views. In my old code I was able to get the absolute URL of an object related to a function view this way:
```
class Category(models.Model):
name = models.CharField(max_length=100,unique=True)
slug = models.SlugField(unique=True)
... | You should always give your URLs a name, and refer to that:
```
url(r'/category/(?P<slug>\w+)/$', CategoryView.as_view(), name='category_view'),
```
Now:
```
@models.permalink
def get_absolute_url(self):
return ('category_view', (), {'slug': self.slug})
```
Note I've used the permalink decorator, which does the... |
lxml truncates text that contains 'less than' character | 14,171,035 | 4 | 2013-01-05T10:52:34Z | 14,171,433 | 11 | 2013-01-05T11:43:54Z | [
"python",
"html-parsing",
"lxml"
] | ```
>>> s = '<div> < 20 </div>'
>>> import lxml.html
>>> tree = lxml.html.fromstring(s)
>>> lxml.etree.tostring(tree)
'<div> </div>'
```
Does anybody know any workaround for this? | Your HTML input is broken; that `<` left angle bracket should have been encoded to `<` instead. From the [`lxml` documentation](http://lxml.de/parsing.html) on parsing broken HTML:
> The support for parsing broken HTML depends entirely on libxml2's recovery algorithm. It is not the fault of lxml if you find documen... |
what $ ,^ and * symbols are doing in python 2.7 and BS4 | 14,171,790 | 3 | 2013-01-05T12:28:52Z | 14,171,846 | 7 | 2013-01-05T12:34:57Z | [
"python",
"python-2.7",
"beautifulsoup"
] | In the [Selenium Doc](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors) they have used `^`, `$` and `*` previous to the `=` operators the in the below code: But none of them are explained why such **special symbols**
```
soup.select('a[href="http://example.com/elsie"]')
# [<a class="sister" href="ht... | Those are [substring matching attribute selectors adapted from CSS 3](http://www.w3.org/TR/css3-selectors/#attribute-substrings):
* `=` matches only if the given value is *equal* to the elementâs attribute value.
* `^=` matches only if the given value is *a prefix* of the elementâs attribute value.
* `$=` matches ... |
WARNING: IPython History requires SQLite, your history will not be saved | 14,173,271 | 5 | 2013-01-05T15:33:05Z | 14,176,406 | 7 | 2013-01-05T21:06:05Z | [
"python",
"sqlite3",
"ipython",
"pysqlite"
] | Hi I'm using Ubuntu release 12.10 (quantal) 32-bit with Linux Kernel 3.5.0-21-generic. I'm trying to get IPython's History to work. I've set it up using pythonbrew and a virtual environment. In there I use pip to install IPython. Currently, when I start up IPython in a terminal I get:
```
WARNING: IPython History requ... | > I've also read in a few places that I may have to rebuild Python.
This is correct. SQLite is part of the standard library,
and is built when you compile Python. There are a few 'optional' parts
of the standard library, which Python will simply skip (with minimal warning, unfortunately)
if the dependencies are missin... |
WARNING: IPython History requires SQLite, your history will not be saved | 14,173,271 | 5 | 2013-01-05T15:33:05Z | 14,179,352 | 7 | 2013-01-06T04:39:40Z | [
"python",
"sqlite3",
"ipython",
"pysqlite"
] | Hi I'm using Ubuntu release 12.10 (quantal) 32-bit with Linux Kernel 3.5.0-21-generic. I'm trying to get IPython's History to work. I've set it up using pythonbrew and a virtual environment. In there I use pip to install IPython. Currently, when I start up IPython in a terminal I get:
```
WARNING: IPython History requ... | Thanks to minrk for pointing me in the right direction. All I had to do was rebuild python. I've outlined the steps below for those that are using pythonbrew. Notice that I already installed the `libsqlite3-dev` package up in the question section.
First, with the proper version of python and virtual environment loaded... |
use string.translate in Python to transliterate Cyrillic? | 14,173,421 | 5 | 2013-01-05T15:49:29Z | 14,173,535 | 8 | 2013-01-05T16:01:04Z | [
"python",
"transliteration"
] | I'm getting `UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-51: ordinal not in range(128)` exception trying to use `string.maketrans` in `Python`. I'm kinda discouraged with this kind of error in following code ([gist](https://gist.github.com/4462092)):
```
# -*- coding: utf-8 -*-
import stri... | [translate](http://docs.python.org/2/library/stdtypes.html#str.translate) behaves differently when used with unicode strings. Instead of a `maketrans` table, you have to provide a dictionary `ord(search)->ord(replace)`:
```
symbols = (u"абвгдеÑжзийклмнопÑÑÑÑÑÑ
ÑÑÑÑÑÑÑÑÑÑÐÐÐÐÐÐÐÐ... |
use string.translate in Python to transliterate Cyrillic? | 14,173,421 | 5 | 2013-01-05T15:49:29Z | 17,587,364 | 12 | 2013-07-11T07:22:41Z | [
"python",
"transliteration"
] | I'm getting `UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-51: ordinal not in range(128)` exception trying to use `string.maketrans` in `Python`. I'm kinda discouraged with this kind of error in following code ([gist](https://gist.github.com/4462092)):
```
# -*- coding: utf-8 -*-
import stri... | You can use transliterate package (<https://pypi.python.org/pypi/transliterate>)
Example #1:
```
from transliterate import translit
print translit("Lorem ipsum dolor sit amet", "ru")
# ÐоÑем ипÑÑм Ð´Ð¾Ð»Ð¾Ñ ÑÐ¸Ñ Ð°Ð¼ÐµÑ
```
Example #2:
```
print translit(u"ÐоÑем ипÑÑм Ð´Ð¾Ð»Ð¾Ñ ÑÐ¸Ñ Ð°Ð¼Ð... |
Why does Python's multiprocessing module import __main__ when starting a new process on Windows? | 14,175,348 | 7 | 2013-01-05T19:13:17Z | 14,175,401 | 15 | 2013-01-05T19:18:16Z | [
"python",
"windows",
"python-2.7",
"multiprocessing"
] | I am playing around with a library for my beginner students, and I'm using the multiprocessing module in Python. I ran into this problem: [importing and using a module that uses multiprocessing without causing infinite loop on Windows](http://stackoverflow.com/questions/11367835/importing-and-using-a-module-that-uses-m... | Windows doesn't have `fork`, so there's no way to make a new process just like the existing one. So the child process has to run your code again, but now you need a way to distinguish between the parent process and the child process, and `__main__` is it.
This is covered in the docs here: <http://docs.python.org/2/lib... |
List only files in a directory? | 14,176,166 | 8 | 2013-01-05T20:36:44Z | 14,176,179 | 14 | 2013-01-05T20:38:16Z | [
"python"
] | Is there a way to list the files (not directories) in a directory with Python? I know I could use `os.listdir` and a loop of `os.path.isfile()`s, but if there's something simpler (like a function `os.path.listfilesindir` or something), it would probably be better. | This is [a simple generator expression](http://www.youtube.com/watch?v=pShL9DCSIUw):
```
files = (file for file in os.listdir(path)
if os.path.isfile(os.path.join(path, file)))
for file in files: # You could shorten this to one line, but it runs on a bit.
...
```
Or you could make a generator function i... |
Can't Install PIL 1.7 | 14,177,000 | 5 | 2013-01-05T22:16:58Z | 15,802,648 | 12 | 2013-04-04T04:40:36Z | [
"python",
"python-imaging-library"
] | I have python 2.7.3 and I want to install PIL 1.7.
I downloaded "PIL-1.1.7.win32-py2.7" and try to install it but it shows me an error messege that it can't find python 2.7 in the registry.
> "python version 2.7 requried, which wasn't found in the registry".
I double check and I'm sure that I have python 2.7.3.
w... | As the message says, PIL installer can't find registry keys, this because python installer put values in 32 bit OS version path "HKEY\_LOCAL\_MACHINE\SOFTWARE\Python\PythonCore\2.7" but for 64 bit OS version it should be set in "HKEY\_LOCAL\_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7".
Easy fix is to copy and ... |
Perform simple math on regular expression output? (Python) | 14,177,592 | 6 | 2013-01-05T23:31:58Z | 14,177,673 | 11 | 2013-01-05T23:43:40Z | [
"python",
"regex"
] | Is it possible to perform simple math on the output from Python regular expressions?
I have a large file where I need to divide numbers following a `")"` by 100. For instance, I would convert the following line containing `)75` and `)2`:
```
((words:0.23)75:0.55(morewords:0.1)2:0.55);
```
to `)0.75` and `)0.02`:
``... | You can do it by providing a function as the replacement:
```
s = "((words:0.23)75:0.55(morewords:0.1)2:0.55);"
s = re.sub("\)(\d+)", lambda m: ")" + str(float(m.groups()[0]) / 100), s)
print s
# ((words:0.23)0.75:0.55(morewords:0.1)0.02:0.55);
```
Incidentally, if you wanted to do it using [BioPython's Newick tree... |
How does perspective transformation work in PIL? | 14,177,744 | 20 | 2013-01-05T23:54:29Z | 14,178,717 | 36 | 2013-01-06T02:35:35Z | [
"python",
"python-imaging-library",
"perspective"
] | PIL's transform-function has a perspective-mode which requires an 8-tupel of data but I can't figure out how to convert let's say a right tilt of 30 degrees to that tupel.
Can anyone explain it?
Here's the documentation to it: <http://effbot.org/imagingbook/image.htm> | To apply a perspective transformation you first have to know four points in a plane A that will be mapped to four points in a plane B. With those points, you can derive the homographic transform. By doing this, you obtain your 8 coefficients and the transformation can take place.
The site <http://xenia.media.mit.edu/~... |
Numpy cross-product on rectangular grid | 14,177,989 | 8 | 2013-01-06T00:27:29Z | 14,178,079 | 8 | 2013-01-06T00:40:12Z | [
"python",
"numpy"
] | I have two numpy arrays holding 2d vectors:
```
import numpy as np
a = np.array([[ 0.999875, 0.015836],
[ 0.997443, 0.071463],
[ 0.686554, 0.727078],
[ 0.93322 , 0.359305]])
b = np.array([[ 0.7219 , 0.691997],
[ 0.313656, 0.949537],
[ 0.5079... | I thought a bit more on this.
```
>>> a
array([[ 0.999875, 0.015836],
[ 0.997443, 0.071463],
[ 0.686554, 0.727078],
[ 0.93322 , 0.359305]])
>>> b
array([[ 0.7219 , 0.691997],
[ 0.313656, 0.949537],
[ 0.507926, 0.861401],
[ 0.818131, 0.575031],
[ 0.117956, 0.99... |
Python pandas, Plotting options for multiple lines | 14,178,194 | 12 | 2013-01-06T00:58:33Z | 14,179,954 | 20 | 2013-01-06T06:35:53Z | [
"python",
"plot",
"pandas"
] | I want to plot multiple lines from a pandas dataframe and setting different options for each line. I would like to do something like
```
testdataframe=pd.DataFrame(np.arange(12).reshape(4,3))
testdataframe.plot(style=['s-','o-','^-'],color=['b','r','y'],linewidth=[2,1,1])
```
This will raise some error messages:
* l... | You're so close!
You can specify the colors in the styles list:
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
testdataframe = pd.DataFrame(np.arange(12).reshape(4,3), columns=['A', 'B', 'C'])
styles = ['bs-','ro-','y^-']
linewidths = [2, 1, 4]
fig, ax = plt.subplots()
for col, style, lw ... |
Python Encrypting with PyCrypto AES | 14,179,784 | 8 | 2013-01-06T06:05:03Z | 14,205,319 | 33 | 2013-01-07T22:36:51Z | [
"python",
"pycrypto"
] | I just found pycrypto today, and I've been working on my AES encryption class. Unfortunately it only half-works. self.h.md5 outputs md5 hash in hex format, and is 32byte.
This is the output. It seems to decrypt the message, but it puts random characters after decryption, in this case \n\n\n... I think I have a problem ... | To be honest, the characters *"\n\n\n\n\n\n\n\n\n\n"* don't look that random to me. ;-)
You are using AES in CBC mode. That requires length of plaintext and ciphertext to be always a multiple of 16 bytes. With the code you show, you should actually see an exception being raised when `data` passed to `encrypt()` does n... |
How to install python packages without root privileges? | 14,179,941 | 22 | 2013-01-06T06:33:47Z | 14,179,974 | 10 | 2013-01-06T06:39:11Z | [
"python",
"numpy",
"installation",
"scipy"
] | I am using `numpy` /Â `scipy` / `pynest` to do some research computing on Mac OS X. For performance, we rent a 400-node cluster (with Linux) from our university so that the tasks could be done parallel. The problem is that we are NOT allowed to install any extra packages on the cluster (no `sudo` or any installation to... | You could create a virtual environment through the [virtualenv](http://pypi.python.org/pypi/virtualenv) package.
This creates a folder (say `venv`) with a new copy of the Python executable and a new `site-packages` directory, into which you can "install" any number of packages without needing any kind of administrativ... |
How to install python packages without root privileges? | 14,179,941 | 22 | 2013-01-06T06:33:47Z | 14,183,151 | 29 | 2013-01-06T14:39:32Z | [
"python",
"numpy",
"installation",
"scipy"
] | I am using `numpy` /Â `scipy` / `pynest` to do some research computing on Mac OS X. For performance, we rent a 400-node cluster (with Linux) from our university so that the tasks could be done parallel. The problem is that we are NOT allowed to install any extra packages on the cluster (no `sudo` or any installation to... | You don't need root privileges to install packages *in your home directory*. You can do that with a command such as
```
pip install --user numpy
```
or from source
```
python setup.py install --user
```
See <http://stackoverflow.com/a/7143496/284795>
---
The first alternative is much more convenient, so if the se... |
sum each value in a list of tuples | 14,180,866 | 13 | 2013-01-06T09:32:43Z | 14,180,875 | 34 | 2013-01-06T09:33:53Z | [
"python",
"performance",
"list",
"python-2.7",
"list-comprehension"
] | I have a list of tuples similar to this:
```
l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
```
I want to create a simple one-liner that will give me the following result:
```
r = (25, 20) or r = [25, 20] # don't care if tuple or list.
```
Which would be like doing the following:
```
r = [0, 0]
for t in l:
r[0]+=t... | Use `zip()` and `sum()`:
```
In [1]: l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
In [2]: [sum(x) for x in zip(*l)]
Out[2]: [25, 20]
```
or:
```
In [4]: map(sum, zip(*l))
Out[4]: [25, 20]
```
`timeit` results:
```
In [16]: l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]*1000
In [17]: %timeit [sum(x) for x in zip(*l... |
curled brackets in .format | 14,182,129 | 2 | 2013-01-06T12:32:46Z | 14,182,140 | 8 | 2013-01-06T12:34:04Z | [
"python",
"string",
"format"
] | I want to print the following
```
\printCodeFromFile[5]{7}{myfile.tex}
```
which I construct with the following code
```
outputStr = "\\printCodeFromFile[{startline}]{{endline}}{{name}}".format(startline=lineStart, endline=lineEnd, name=filename)
```
That unfortunately comes out as
```
\printCodeFromFile[5]{endli... | Double the curly braces that you want to keep:
```
outputStr = "\\printCodeFromFile[{startline}{{{endline}}}{{{name}}}]".format(startline=lineStart, endline=lineEnd, name=filename)
```
Now you have doubled braces (`{{` and `}}`) surrounding the replacement pattern (`{endline}` and `{name}`). |
Matching multiple regex patterns with the alternation operator? | 14,182,339 | 4 | 2013-01-06T12:55:00Z | 14,182,389 | 7 | 2013-01-06T13:00:29Z | [
"python",
"regex",
"regex-alternation"
] | I ran into a small problem using Python Regex.
Suppose this is the input:
```
(zyx)bc
```
What I'm trying to achieve is obtain whatever is between parentheses as a single match, and any char outside as an individual match. The desired result would be along the lines of:
```
['zyx','b','c']
```
The order of matches... | From the documentation of `re.findall`:
> If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.
While your regexp is matching the string three times, the `(.*?)` group is empty for the second two matches. If you want the output... |
Python regex: Multiple matches in one line (using findall()) | 14,182,430 | 3 | 2013-01-06T13:05:00Z | 14,182,516 | 11 | 2013-01-06T13:17:34Z | [
"python",
"regex"
] | I'm looking for these "tags" inside text: `{t d="var1"}var2{/t}` or `{t d="varA"}varB{/t}`
There can be more attributes, only "d" is mandatory: `{t d="var1" foo="bar"}var2{/t}`
My problem is - if there are more tags on one line, just one result is returned, not all of them. What is returned (from test string below):
`... | Your wildcards are greedy. Change them from `.*` to `.*?` so they'll be non-greedy:
```
re_pattern = '''
\{t[ ]{1} # start tag name
d=" # "d" attribute
([a-zA-Z0-9]*) # "d" attribute content
".*?\} # end of "d" attribute
(.+?) # tag content
... |
run a process to /dev/null in python | 14,182,434 | 2 | 2013-01-06T13:05:07Z | 14,182,473 | 7 | 2013-01-06T13:09:33Z | [
"python",
"linux"
] | How do I run the following in Python?
```
/some/path/and/exec arg > /dev/null
```
I got this:
```
call(["/some/path/and/exec","arg"])
```
How do I insert the output of the `exec` process to `/dev/null` and keep the print output of my python process as usual? As in, don't redirect everything to stdout? | For Python 3.3 and later, just use [`subprocess.DEVNULL`](http://docs.python.org/3/library/subprocess.html#subprocess.DEVNULL):
```
call(["/some/path/and/exec","arg"], stdout=DEVNULL, stderr=DEVNULL)
```
Note that this redirects both `stdout` and `stderr`. If you only wanted to redirect `stdout` (as your `sh` line im... |
In python's generators - what is the difference between raise StopIteration and return statement? | 14,183,803 | 12 | 2013-01-06T15:52:10Z | 14,183,847 | 21 | 2013-01-06T15:56:44Z | [
"python",
"generator",
"stopiteration"
] | I'm curious about the difference between using `raise StopIteration` and `return` statement in generators.
For example - is there any difference between those two functions?
```
def my_generator0(n):
for i in range(n):
yield i
if i >= 5:
return
def my_generator1(n):
for i in range... | There's no need to explicitly raise `StopIteration` as that's what a bare `return` statement does for a generator function - so yes they're the same. But no, just using `return` is more Pythonic.
From: <http://docs.python.org/2/reference/simple_stmts.html#the-return-statement> (valid to Python 3.2)
> In a generator f... |
Python - How to check Booleans inside a for loop? | 14,184,563 | 2 | 2013-01-06T17:10:06Z | 14,184,582 | 8 | 2013-01-06T17:11:30Z | [
"python",
"for-loop"
] | I'm without clues on how to do this. I've a list:
```
list_something = [5, 6, 8]
```
And I've a method is\_valid()
```
def is_valid(number):
return type(number) is int
```
How can I check at once if the 3 numbers are all Integers inside a for loop?
```
for item in list_something:
```
At the end of the for loo... | You can use `all` and `map`:
```
all_list_something = all(map(is_valid, list_something))
```
Using `itertools.imap` would allow this to short-circuit (meaning that if the first element is invalid, it never checks the rest):
```
import itertools
all_list_something = all(itertools.imap(is_valid, list_something))
``` |
Python - How to check Booleans inside a for loop? | 14,184,563 | 2 | 2013-01-06T17:10:06Z | 14,184,604 | 10 | 2013-01-06T17:13:20Z | [
"python",
"for-loop"
] | I'm without clues on how to do this. I've a list:
```
list_something = [5, 6, 8]
```
And I've a method is\_valid()
```
def is_valid(number):
return type(number) is int
```
How can I check at once if the 3 numbers are all Integers inside a for loop?
```
for item in list_something:
```
At the end of the for loo... | A generator comprehension can improve readability over a map for some.
```
all_list_something = all(is_valid(x) for x in list_something)
``` |
How to work with interactively-defined classes in IPython.parallel? | 14,184,621 | 6 | 2013-01-06T17:15:03Z | 14,186,621 | 7 | 2013-01-06T20:52:25Z | [
"python",
"parallel-processing",
"ipython",
"ipython-notebook"
] | ## Context
In an interactive prototyping development on the notebook connected to a cluster, I would like to define a class that is both available in the client `__main__` session and interactively update on the cluster engine nodes to be able to move instances of that class around by passing such instances a argument... | Thanks for the detailed question (and pinging me on Twitter).
First, maybe it should be considered a bug that you can't just push classes,
because the simple solution should be
```
rc[:]['MyClass'] = MyClass
```
but pickling interactively defined classes results only in a reference (`'\x80\x02c__main__\nMyClass\nq\x... |
django test app error - Got an error creating the test database: permission denied to create database | 14,186,055 | 68 | 2013-01-06T19:51:21Z | 14,186,439 | 140 | 2013-01-06T20:31:49Z | [
"python",
"sql",
"django",
"postgresql",
"django-testing"
] | When I try to test any app with command (I noticed it when I tried to deploy myproject using fabric, which uses this command):
```
python manage.py test appname
```
I get this error:
```
Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database
Type ... | When Django runs the test suite, it creates a new database, in your case test\_finance. The postgres user with username `django` does not have permission to create a database, hence the error message.
When you run syncdb, Django does not try to create the finance database, so you don't get any errors.
You can add the... |
Instantiate subclass from superclass | 14,186,073 | 2 | 2013-01-06T19:53:09Z | 14,186,182 | 7 | 2013-01-06T20:04:52Z | [
"python"
] | I need to instantiate a subclass from the superclass.
```
class Superclass(object):
@staticmethod
def get_instance():
#This should return an instance of subclass1 or subclass2
class Subclass1(Superclass):
pass
class Subclass2(Superclass):
pass
```
I want to write:
```
Subclass1.get_instance(... | use `@classmethod` instead of `@staticmethod` :
```
class Superclass(object):
@classmethod
def get_instance(cls):
#This should return an instance of subclass1 or subclass2
return cls()
class Subclass1(Superclass):
pass
class Subclass2(Superclass):
pass
``` |
In Python, is epoch time returned by time() always measured from Jan 1, 1970? | 14,186,179 | 8 | 2013-01-06T20:04:36Z | 14,186,233 | 10 | 2013-01-06T20:09:45Z | [
"python",
"time",
"epoch"
] | Is the epoch start time in Python independent of the platform (i.e. always 1/1/1970)?
Or is it platform dependent?
I want to serialize datetimes (with second accuracy) on various machines running Python, and be able to read them back on different platforms, possibly also using different programming languages (than Py... | [The documentation](http://docs.python.org/2/library/time.html) says:
> To find out what the epoch is, look at `gmtime(0)`.
I would interpret this to mean that no particular epoch is guaranteed.
See also [this Python-Dev thread](http://grokbase.com/t/python/python-dev/086gxjdb5a/epoch-and-platform). That seems to co... |
flask-wtf selectField choices not valid | 14,186,412 | 2 | 2013-01-06T20:27:20Z | 14,190,908 | 7 | 2013-01-07T06:21:27Z | [
"python",
"dictionary",
"flask",
"wtforms"
] | I made a SelectField like this:
```
# constants.py
QUESTION_LIST = {}
QUESTION_LIST['QuestionOne'] = { 'disagree-strong': "Strongly Disagree", 'agree-strong': "Strongly Agree" }
#forms.py
from constants import *
typeone = SelectField('QuestionOne',
choices=QUESTION_LIST['QuestionOne'].iteritems(),
descr... | Maybe the problem is that your keys in dict are a strings. I had this issue before, so maybe something like this would help:
```
typeone = SelectField("Question1", coerce=str, choices=QUESTION_LIST['QuestionOne'])
```
This `coerce` thingie helped. What happens I think that all POST data is unicode and by default `coe... |
"Undefined variable : main" in pydev/python | 14,186,485 | 3 | 2013-01-06T20:37:08Z | 14,186,492 | 9 | 2013-01-06T20:37:49Z | [
"python",
"pydev",
"main"
] | I made a file named "Main" in pydev and inside it wrote:
```
if __name__ =='__Main__':
main()
def main():
print("jargon")
```
It says my call to main() under the if statement contains an undefined variable and won't compile. Why does it do this? | Python code is executed top-to-bottom. You need to move your `main()` definition above the `if __name__ == '__main__'` block. The way you have it, at the time that you try to call `main()`, the function does not yet exist. |
Why is collections.Counter much slower than ''.count? | 14,186,533 | 6 | 2013-01-06T20:42:24Z | 14,186,593 | 7 | 2013-01-06T20:49:42Z | [
"python",
"performance",
"counter"
] | I have a simple task: To count how many times every letter occurs in a string. I've used a `Counter()` for it, but on one forum I saw information that using `dict()` / `Counter()` is much slower than using `string.count()` for every letter. I thought that it would interate through the string only once, and the `string.... | The `Counter` class inherits from `dict`, while `string.count` is the following C-implementation (CPython 3.3):
```
/* stringlib: count implementation */
#ifndef STRINGLIB_FASTSEARCH_H
#error must include "stringlib/fastsearch.h" before including this module
#endif
Py_LOCAL_INLINE(Py_ssize_t)
STRINGLIB(count)(const... |
What is the best way to write a python iterator based on a generator | 14,187,261 | 3 | 2013-01-06T22:01:36Z | 14,187,299 | 8 | 2013-01-06T22:05:23Z | [
"python",
"iterator",
"generator"
] | I've been looking for a good way to write a Python iterator that is based on a generator. I've found many tutorials on the topic of iterators and many on generators and the yield statement, but nothing that combines the two. I've built a small example that works and wondered if there is a better way to do this.
```
cl... | The iterator protocol consists of two parts. The `__iter__` method is the most important one, it is expected to return the iterator when you use `iter()` on an object.
Just replace the body of `__iter__` with `myGenerator`; no need to raise `StopIteration` either:
```
class myIterator:
def __init__(self, n):
... |
Python3: check if method is static | 14,187,973 | 5 | 2013-01-06T23:34:59Z | 14,188,192 | 8 | 2013-01-07T00:08:11Z | [
"python",
"static",
"static-methods",
"introspection"
] | Simmilar question (related with Python2: [Python: check if method is static](http://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 th... | ```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
``` |
Get multiple request params of the same name | 14,188,451 | 13 | 2013-01-07T00:48:42Z | 14,188,496 | 23 | 2013-01-07T00:56:01Z | [
"python",
"flask"
] | My problem is that with the given code:
```
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def hello():
return str(request.values.get("param", "None"))
app.run(debug=True)
```
and I visit:
```
http://localhost:5000/?param=a¶m=bbb
```
I should expect an output of ['a', 'bbb'] excep... | You can use `getlist`, which is similar to Django's `getList` but for some reason isn't mentioned in the Flask documentation:
```
return str(request.args.getlist('param'))
```
The result is:
```
[u'a', u'bbb']
```
Use `request.args` if the param is in the query string (as in the question), `request.form` if the val... |
How to get PyCharm to display unicode data in its console? | 14,188,655 | 4 | 2013-01-07T01:21:21Z | 14,500,785 | 7 | 2013-01-24T11:54:27Z | [
"python",
"unicode",
"utf-8",
"ide",
"pycharm"
] | I have switched over to PyCharm and have had a blast using it. I code for projects that use languages other than English (i.e. Hebrew and Arabic) and need to debug encodings once in a while. For some reason, PyCharm will not display Unicode characters in its debug console.
I have set the IDE encoding to UTF-8 but it d... | You need to change the **console font** to the one which contains the required Unicode glyphs:
 |
How to get PyCharm to display unicode data in its console? | 14,188,655 | 4 | 2013-01-07T01:21:21Z | 28,823,671 | 7 | 2015-03-03T03:38:39Z | [
"python",
"unicode",
"utf-8",
"ide",
"pycharm"
] | I have switched over to PyCharm and have had a blast using it. I code for projects that use languages other than English (i.e. Hebrew and Arabic) and need to debug encodings once in a while. For some reason, PyCharm will not display Unicode characters in its debug console.
I have set the IDE encoding to UTF-8 but it d... | The accepted answer is no longer correct. Of the default fonts, none of them make a difference. I just spent awhile going through this same problem and the best solution is to modify your .bash\_profile (or .zshrc) and include the line:
```
export PYTHONIOENCODING=UTF-8
```
In theory, you could also add this to your ... |
Numpy: Beginner nditer | 14,188,807 | 5 | 2013-01-07T01:44:22Z | 14,189,430 | 10 | 2013-01-07T03:22:59Z | [
"python",
"numpy",
"iteration"
] | I am trying to learn [nditer](http://docs.scipy.org/doc/numpy-dev/reference/arrays.nditer.html) for possible use in speeding up my application. Here, i try to make a facetious reshape program that will take a size 20 array and reshape it to a 5x4 array:
```
myArray = np.arange(20)
def fi_by_fo_100(array):
offset =... | It really helps to break things down by printing out what's going on along the way.
First, let's replace your whole loop with this:
```
i = 0
while not it.finished:
i += 1
print i
```
It'll print 20, not 5. That's because you're doing a 5x4 iteration, not 5x1.
So, why is this even close to working? Well, let's ... |
python topN max heap, use heapq or self implement? | 14,189,540 | 5 | 2013-01-07T03:37:48Z | 14,189,741 | 16 | 2013-01-07T04:07:12Z | [
"python",
"heap"
] | there's heapq in python, for general usage.
i want recording topN(0~20) for 10e7 records.
if use heapq, should use '-' to translate max to min; and recording a min number of bottom, to call heapq.heappushpop()
should i use heapq or self implement a heap(maybe buggy or less efficient)?
```
#update
import heapq
class... | The only problem with `heapq` is that it doesn't provide a `key` function like everything else in the stdlib does. (If you're curious why, Raymond Hettinger explains in [this email](http://code.activestate.com/lists/python-list/162387/). He's right that `heapq` couldn't provide the same interface as other sort function... |
Reset a columns MultiIndex levels | 14,189,695 | 12 | 2013-01-07T03:59:30Z | 14,189,912 | 11 | 2013-01-07T04:32:47Z | [
"python",
"pandas",
"dataframe"
] | Is there a shorter way of dropping a column MultiIndex level (in my case, `basic_amt`) except transposing it twice?
```
In [704]: test
Out[704]:
basic_amt
Faculty NSW QLD VIC All
All 1 1 2 4
Full Time 0 1 0 1
Part Time 1 0 ... | How about simply reassigning `df.columns`:
```
levels = df.columns.levels
labels = df.columns.labels
df.columns = levels[1][labels[1]]
```
For example:
```
import pandas as pd
columns = pd.MultiIndex.from_arrays([['basic_amt']*4,
['NSW','QLD','VIC','All']])
index = pd.Index(['Al... |
Separate mixture of gaussians in Python | 14,189,937 | 6 | 2013-01-07T04:36:20Z | 14,191,407 | 8 | 2013-01-07T07:08:48Z | [
"python",
"statistics",
"normal-distribution"
] | There is a result of some physical experiment, witch is represented as histogram `[i, amount_of(i)]`. I suppose that result can be estimated by a mixture of 4..6 gaussian functions.
Is there a package in Python wich gets the histogram at input and returns mean and variance for each gaussian in sum?
Original data, for... | This is a [mixture of gaussians](http://en.wikipedia.org/wiki/Mixture_model), and can be estimated using an [expectation maximization](http://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm) approach (basically, it finds the centers and means of the distribution at the same time as it is estimating how... |
How to convert datetime.timedelta to minutes, hours in Python? | 14,190,045 | 19 | 2013-01-07T04:48:07Z | 14,190,143 | 46 | 2013-01-07T05:02:08Z | [
"python",
"django"
] | I get a start\_date like this:
```
from django.utils.timezone import utc
import datetime
start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
duration = end_date - start_date
```
I get output like this:
```
datetime.timedelta(0, 5, 41038)
```
How do ... | There's no built-in formatter for `timedelta` objects, but it's pretty easy to do it yourself:
```
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
```
Or, equivalently, if you're in Python 2.7+ or 3.2+:
```
seconds = duration... |
How to convert datetime.timedelta to minutes, hours in Python? | 14,190,045 | 19 | 2013-01-07T04:48:07Z | 14,190,162 | 9 | 2013-01-07T05:04:27Z | [
"python",
"django"
] | I get a start\_date like this:
```
from django.utils.timezone import utc
import datetime
start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
duration = end_date - start_date
```
I get output like this:
```
datetime.timedelta(0, 5, 41038)
```
How do ... | A `datetime.timedelta` corresponds to the *difference* between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).
If you want to convert a `timedelta` into hours and... |
merge querysets in django | 14,190,140 | 5 | 2013-01-07T05:02:02Z | 14,190,202 | 9 | 2013-01-07T05:08:45Z | [
"python",
"django",
"merge",
"django-queryset"
] | I have in `models.py`:
```
class Game(models.Model):
players1 = models.ManyToManyField(Player, related_name='games1')
players2 = models.ManyToManyField(Player, related_name='games2')
def get_all_players(self):
return list(itertools.chain(self.players1.all(), self.players2.all()))
```
How can I wr... | This should do the trick:
```
# On the top of the file:
from django.db.models import Q
# Game instance method:
def get_all_players(self):
return Player.objects.filter(Q(games1__pk=self.pk) | Q(games2__pk=self.pk))
```
`Q` is described in details here: [Complex lookups with Q objects](https://docs.djangoproject.c... |
How to calculate difference between two dates in weeks in python | 14,191,832 | 7 | 2013-01-07T07:43:55Z | 14,191,912 | 18 | 2013-01-07T07:52:40Z | [
"python",
"datetime"
] | I'm trying to calculate the difference between two dates in "weeks of year". I can get the datetime object and get the days etc but not week numbers. I can't, of course, subtract dates because weekends can't be ensured with that.
I tried getting the week number using `d1.isocalendar()[1]` and subtracting `d2.isocalend... | You may want to refer the Python CookBook (2005 edition) Recipe 3.3. The following code snippet is from the cookbook, does what you require.
```
from dateutil import rrule
import datetime
def weeks_between(start_date, end_date):
weeks = rrule.rrule(rrule.WEEKLY, dtstart=start_date, until=end_date)
return weeks... |
How to calculate difference between two dates in weeks in python | 14,191,832 | 7 | 2013-01-07T07:43:55Z | 14,191,915 | 19 | 2013-01-07T07:53:06Z | [
"python",
"datetime"
] | I'm trying to calculate the difference between two dates in "weeks of year". I can get the datetime object and get the days etc but not week numbers. I can't, of course, subtract dates because weekends can't be ensured with that.
I tried getting the week number using `d1.isocalendar()[1]` and subtracting `d2.isocalend... | How about calculating the difference in weeks between the **Mondays** within weeks of respective dates? In the following code, `monday1` is the Monday on or before `d1` (the same week):
```
from datetime import datetime, timedelta
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday... |
Understanding pandas dataframe indexing | 14,192,741 | 9 | 2013-01-07T09:03:57Z | 14,193,170 | 11 | 2013-01-07T09:32:27Z | [
"python",
"pandas"
] | Summary:
This doesn't work:
```
df[df.key==1]['D'] = 1
```
but this does:
```
df.D[df.key==1] = 1
```
Why?
Reproduction:
```
In [1]: import pandas as pd
In [2]: from numpy.random import randn
In [4]: df = pd.DataFrame(randn(6,3),columns=list('ABC'))
In [5]: df
Out[5]:
A B C
0 1.4381... | The pandas documentation says:
> Returning a view versus a copy
>
> The rules about when a view on the data is returned are entirely
> dependent on NumPy. Whenever an array of labels or a boolean vector
> are involved in the indexing operation, the result will be a copy.
> With single label / scalar indexing and slici... |
Are Python sets mutable? | 14,193,438 | 7 | 2013-01-07T09:51:39Z | 14,193,473 | 21 | 2013-01-07T09:53:46Z | [
"python",
"set"
] | Are sets in Python mutable?
---
In other words, if I do this:
```
x = set([1, 2, 3])
y = x
y |= set([4, 5, 6])
```
Are `x` and `y` still pointing to the same object, or was a new set created and assigned to `y`? | ```
>>>> x = set([1, 2, 3])
>>>> y = x
>>>>
>>>> y |= set([4, 5, 6])
>>>> print x
set([1, 2, 3, 4, 5, 6])
>>>> print y
set([1, 2, 3, 4, 5, 6])
```
Conclusion: sets are mutable. |
ImportError: No module named django.core.wsgi for uwsgi | 14,194,859 | 9 | 2013-01-07T11:19:56Z | 27,568,998 | 7 | 2014-12-19T15:25:41Z | [
"python",
"django",
"uwsgi"
] | I'm using uwsgi for my Django(version =1.4) project, but there's an error if I run
```
uwsgi --ini django.ini
```
```
from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
```
but I could import django.core.wsgi as follows:
```
>>> import django.core.wsgi
```
the djang... | The error `ImportError: No module named django.core.wsgi` generally arises when uwsgi tries reading the wsgi.py file, and comes to the line:
```
from django.core.wsgi import get_wsgi_application
```
It can't find this these modules because Django is not installed, or if it is installed, it is not in PYTHONPATH.
If y... |
Fetchall returning only one column in Python? | 14,194,969 | 3 | 2013-01-07T11:28:02Z | 14,194,986 | 11 | 2013-01-07T11:29:10Z | [
"python",
"mysql-python"
] | I have a a code like this:
```
db = MySQLdb.connect(user='root', db='galaxy', passwd='devil', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT username, password FROM galaxy_user')
names = [row[0] for row in cursor.fetchall()]
passw = [password[1] for password in cursor.fetchall()]
db.close()
```
The pro... | After each `cursor.execute` you can use `cursor.fetchall` only once. It "exhausts" the cursor, gets all its data and then it cannot be "read" again.
With the following code you read all data at the same time:
```
db = MySQLdb.connect(user='root', db='galaxy', passwd='devil', host='localhost')
cursor = db.cursor()
cur... |
python tuples and lists. A tuple that refuses to convert | 14,195,885 | 5 | 2013-01-07T12:24:07Z | 14,195,911 | 11 | 2013-01-07T12:25:30Z | [
"python",
"list",
"python-2.7",
"tuples",
"iterable-unpacking"
] | I need to know WHY this fails:
```
class ConfigurationError(Exception):
def __init__(self, *args):
super(ConfigurationError, self).__init__(self, args)
self.args = list(args)
# Do some formatting on the message string stored in self.args[0]
self.args[0]=self.__prettyfi(self.args[0]... | `Exception.args` is a [descriptor](http://docs.python.org/2/reference/datamodel.html#implementing-descriptors); it hooks [`__set__`](http://docs.python.org/2/reference/datamodel.html#object.__set__) to turn *anything* you assign to `self.args` into a tuple.
So, as soon as you assign your list to `self.args`, the descr... |
Which function is invoked when the save button is clicked in OpenERP6.1 | 14,197,116 | 3 | 2013-01-07T13:37:13Z | 14,201,057 | 7 | 2013-01-07T17:33:19Z | [
"python",
"openerp"
] | Which function is invoked when the save button(marked red in the attached screenshot) is clicked in OpenERP6.1?
Thanks in advance!!! | To elaborate a bit on DReispt's answer, your screenshot seems to highlight the save button of an editable [One2Many](http://doc.openerp.com/v6.1/developer/03_modules_2.html#relational-types) line, within a One2Many field of an existing record form. One2Many lines are treated as *sub-records* of their parent record, so ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.