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 |
|---|---|---|---|---|---|---|---|---|---|
Numpy dot product very slow using ints | 11,856,293 | 12 | 2012-08-08T01:05:16Z | 11,856,623 | 7 | 2012-08-08T01:55:31Z | [
"python",
"floating-point",
"numpy",
"int",
"dot-product"
] | sorry for so many questions. I am running Mac OSX 10.6 on Intel core 2 Duo. I am running some benchmarks for my research and I have run into another thing that baffles me.
If I run
`python -mtimeit -s 'import numpy as np; a = np.random.randn(1e3,1e3)' 'np.dot(a,a)'`
I get the following output: `10 loops, best of 3: ... | Using int vs float data types causes different code paths to be executed:
The stack trace for float looks like this:
```
(gdb) backtr
#0 0x007865a0 in dgemm_ () from /usr/lib/libblas.so.3gf
#1 0x007559d5 in cblas_dgemm () from /usr/lib/libblas.so.3gf
#2 0x00744108 in dotblas_matrixproduct (__NPY_UNUSED_TAGGEDdummy... |
Numpy dot product very slow using ints | 11,856,293 | 12 | 2012-08-08T01:05:16Z | 11,856,667 | 11 | 2012-08-08T02:00:59Z | [
"python",
"floating-point",
"numpy",
"int",
"dot-product"
] | sorry for so many questions. I am running Mac OSX 10.6 on Intel core 2 Duo. I am running some benchmarks for my research and I have run into another thing that baffles me.
If I run
`python -mtimeit -s 'import numpy as np; a = np.random.randn(1e3,1e3)' 'np.dot(a,a)'`
I get the following output: `10 loops, best of 3: ... | very interesting, I was curious to see how it was implemented so I did:
```
>>> import inspect
>>> import numpy as np
>>> inspect.getmodule(np.dot)
<module 'numpy.core._dotblas' from '/Library/Python/2.6/site-packages/numpy-1.6.1-py2.6-macosx-10.6-universal.egg/numpy/core/_dotblas.so'>
>>>
```
So it looks like its us... |
Numpy `ValueError: operands could not be broadcast together with shape ...` | 11,856,493 | 15 | 2012-08-08T01:34:55Z | 11,856,572 | 13 | 2012-08-08T01:48:40Z | [
"python",
"arrays",
"numpy",
"numpy-broadcasting"
] | Im using python 2.7 and am attempting a forcasting on some random data from 1.00000000 to 3.0000000008. There are approx 196 items in my array and I get the error
```
ValueError: operands could not be broadcast together with shape (2) (50)
```
I do not seem to be able to resolve this issue on my own. Any help or link... | If `X` and `beta` do not have the same shape as the second term in the rhs of your last line (i.e. `nsample`), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the [numpy broadcasting rules](http://docs.scipy.org/doc/numpy/user/ba... |
Start IDLE with python 3 on Linux (python 2.7 installed alongside) | 11,856,802 | 7 | 2012-08-08T02:20:44Z | 14,132,374 | 7 | 2013-01-03T02:46:22Z | [
"python",
"python-3.2",
"python-idle"
] | I initially had python 2.7, which often comes bundled with the OS (currently using Linux Mint 12). I wanted to try python 3, so I installed it alongside python 2. All fine there, I can run both versions in terminal by calling either `python` or `python3`. However, there seems to be no way to start IDLE with python 3. I... | Just type sudo apt-get install idle3 in your terminal and idle for your version of python 3 previously installed will be installed.
Then both are compatible. You run the 2.7 idle from your terminal by just typing idle. And you run the idle 3 version by just typing idle3 in the terminal. That worked for me. |
How do I render jinja2 output to a file in Python instead of a Browser | 11,857,530 | 37 | 2012-08-08T04:06:41Z | 11,857,610 | 71 | 2012-08-08T04:20:53Z | [
"python",
"django",
"jinja2"
] | I have a jinja2 template (.html file) that I want to render (replace the tokens with values from my py file). Instead of sending the rendered result to a browser, however, I want to write it to a new .html file. I would imagine the solution would also be similar for a django template.
How can I do this? | How about something like this?
```
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('test.html')
output_from_parsed_template = template.render(foo='Hello World!')
print output_from_parsed_template
# to save the results
with open("my_n... |
Verifying that os.remove has worked | 11,858,454 | 4 | 2012-08-08T05:56:27Z | 11,858,496 | 9 | 2012-08-08T06:00:22Z | [
"python"
] | To [delete a file in Python](http://stackoverflow.com/questions/1995373/deleting-files-in-python), I'm using [os.remove](http://docs.python.org/library/os#os.remove).
The docs (linked) don't give any indication of any exceptions except for [OSError](http://docs.python.org/library/exceptions.html#exceptions.OSError):
... | `OSError` exceptions have an `errno` attribute which you can use together with the `errno` module to get more information about what type of OS error occurred. See [the documentation for OSError](http://docs.python.org/library/exceptions.html#exceptions.OSError). |
Pandas: Combine string and int columns | 11,858,472 | 34 | 2012-08-08T05:57:33Z | 11,858,532 | 64 | 2012-08-08T06:03:51Z | [
"python",
"numpy",
"dataframe",
"pandas"
] | I have a following DataFrame:
```
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
```
It looks like this:
```
bar foo
0 1 a
1 2 b
2 3 c
```
Now I want to have something like:
```
bar
0 1 is a
1 2 is b
2 3 is c
```
How can I achieve this?
I tried the fol... | `df['bar'] = df.bar.map(str) + " is " + df.foo`. |
Pandas: Combine string and int columns | 11,858,472 | 34 | 2012-08-08T05:57:33Z | 11,874,590 | 25 | 2012-08-08T23:15:47Z | [
"python",
"numpy",
"dataframe",
"pandas"
] | I have a following DataFrame:
```
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
```
It looks like this:
```
bar foo
0 1 a
1 2 b
2 3 c
```
Now I want to have something like:
```
bar
0 1 is a
1 2 is b
2 3 is c
```
How can I achieve this?
I tried the fol... | The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
```
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
```
It's longer tha... |
IndentationError from comment in python | 11,860,064 | 3 | 2012-08-08T07:53:15Z | 11,860,085 | 9 | 2012-08-08T07:55:18Z | [
"python",
"comments",
"indentation"
] | How come python reacts to indentations of a comment?
```
def foo():
"""
Random comment
"""
return True
```
works, but:
```
def foo():
"""
Random comment
"""
return True
```
doesn't work, throwing an IndentationError.
Seems weird to me since comments shouldn't be nothing more then comments. And ... | The tripple-quoted string is not a comment; it is the docstring of the method. You can access it with `foo.__doc__` later, for example, or have it formatted for you with `help(foo)`. Tripple-quoting (`"""` or `'''`) is a python-specific method of specifying a [string literal](http://docs.python.org/reference/lexical_an... |
Flask how do you use sqlalchemy declaratively with init_db()? | 11,860,804 | 5 | 2012-08-08T08:42:24Z | 11,869,775 | 7 | 2012-08-08T17:17:17Z | [
"python",
"sqlalchemy",
"flask"
] | this is my database.py
```
engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = session.query_property()
def init_db():
# import all modules here that might define models so that
# they... | When you create a SQLite database in memory it is only accessible to the particular thread that created it - change `create_engine('sqlite:///:memory:')` to `create_engine('sqlite:////some/file/path/db.sqlite'` and your tables will exist.
As to why you are seeing the tables created twice - Flask in debug mode by defau... |
string.decode() vs. unicode(string) | 11,861,551 | 9 | 2012-08-08T09:29:06Z | 11,861,660 | 8 | 2012-08-08T09:35:52Z | [
"python",
"string",
"unicode",
"decode"
] | ```
myString = 'éÃÄÅáé'
```
I need to decode this string to unicode.
Is there any difference between folowing usages and between these two methods in general?
```
myString.decode(encoding='UTF-8', errors='ignore')
```
and
```
unicode(myString, encoding='UTF-8', errors='ignore')
``` | The `unicode` constructor can take other types apart from strings:
```
>>> unicode(10)
u'10'
```
For the bytestring case, however, the two forms are mostly equivalent. Some encoding options are not valid for the `unicode` constructor as they do not result in unicode output, but are valid for the `.decode` method of b... |
Importing Orange returns "ImportError: no module named orange" | 11,861,698 | 4 | 2012-08-08T09:37:38Z | 11,861,954 | 7 | 2012-08-08T09:52:57Z | [
"python",
"linux",
"ubuntu",
"orange"
] | I'd like to use the Orange package for [scientific analysis](http://orange.biolab.si/) . Installation on `x86_64 Ubuntu 12.04`, with `Python 2.7.3`, went well, using `sudo easy_install orange`. However, the package doesn't seem to be available for direct use:
```
11:30:43 leon@t410i:~$ python
Python 2.7.3 (default, Ap... | The semantics for importing Orange have changed around version 2.5. If using code written with a previous version, some changes must be made, see <http://orange.biolab.si/blog/2011/12/20/orange-25-code-conversion/>. Critically, one needs to replace:
```
import orange
```
with:
```
import Orange
```
(note the capita... |
fabric API direct call in python | 11,861,802 | 8 | 2012-08-08T09:43:42Z | 11,862,034 | 21 | 2012-08-08T09:56:40Z | [
"python",
"fabric"
] | i remember fabric API can be called directly in py script
but forgot where to start
anybody give a clue? | Yes, you can call it, for example:
```
from fabric.api import run
from fabric.tasks import execute
def do_something():
run("echo $RANDOM")
if __name__ == "__main__":
execute(do_something, hosts=["username@host"])
``` |
SciPy/Python install on Ubuntu | 11,863,775 | 28 | 2012-08-08T11:43:23Z | 11,864,996 | 26 | 2012-08-08T12:55:43Z | [
"python",
"ubuntu",
"numpy",
"python-2.7",
"scipy"
] | I'm currently following the tutorial *[Installing the SciPy Stack](http://www.scipy.org/Installing_SciPy/Linux)* to install [SciPy](http://en.wikipedia.org/wiki/SciPy) on Ubuntu 12.04 (Precise Pangolin) (I can't use `apt-get install` because I need a recent version).
However, I get errors when I do the following comma... | My usual work flow is to use a [`virtualenv`](http://www.virtualenv.org/en/latest/index.html) to have a Python distribution with up-to-date packages.
Within this environment you can than install and update all packages you need with [`pip`](http://www.pip-installer.org/en/latest/index.html) and without any `sudo` call... |
SciPy/Python install on Ubuntu | 11,863,775 | 28 | 2012-08-08T11:43:23Z | 22,336,915 | 14 | 2014-03-11T21:23:20Z | [
"python",
"ubuntu",
"numpy",
"python-2.7",
"scipy"
] | I'm currently following the tutorial *[Installing the SciPy Stack](http://www.scipy.org/Installing_SciPy/Linux)* to install [SciPy](http://en.wikipedia.org/wiki/SciPy) on Ubuntu 12.04 (Precise Pangolin) (I can't use `apt-get install` because I need a recent version).
However, I get errors when I do the following comma... | Had the same problem. The following worked for me:
```
sudo apt-get install libblas-dev
sudo apt-get install liblapack-dev
sudo apt-get install gfortran
``` |
Sending Hex data | 11,865,490 | 3 | 2012-08-08T13:21:14Z | 11,865,616 | 7 | 2012-08-08T13:28:59Z | [
"python",
"python-3.x"
] | I am working with some hardware that can be controlled via hex commands. I already have some snippets of Python code I use for telnet control of other devices that use ASCII commands.
How do I go about sending hex commands? For instance, how would I modify `skt.send('some ascii command\r')` with hex value, and what's ... | In Python 2, use string literals:
```
skt.send('\x12\r')
```
In Python 3, use bytes literals or [`bytes.fromhex`](http://docs.python.org/dev/library/stdtypes.html#bytes.fromhex):
```
skt.send(b'\x12\r')
skt.send(bytes.fromhex('12 0d'))
```
In either case, the [`bytearray`](http://docs.python.org/dev/library/functio... |
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128) | 11,865,582 | 4 | 2012-08-08T13:26:45Z | 11,865,599 | 10 | 2012-08-08T13:28:02Z | [
"python",
"pyqt",
"ascii",
"encode"
] | Î've tried all the solution that I could find, but nothing seems to work:
```
teext = str(self.tableWidget.item(row, col).text())
```
I'm writing in greek by the way... | Clearly, `self.tableWidget.item().text()` returns Unicode, and you need to use the `decode` method instead:
```
self.tableWidget.item(row, col).text().encode('utf8')
```
You really want to review the [Python Unicode HOWTO](http://docs.python.org/howto/unicode.html) to fully appreciate the difference between a unicode... |
Handling a timeout error in python sockets | 11,865,685 | 14 | 2012-08-08T13:33:10Z | 11,865,993 | 12 | 2012-08-08T13:50:16Z | [
"python",
"sockets",
"exception"
] | I am trying to figure out how to use the try and except to handle a socket timeout.
```
from socket import *
def main():
client_socket = socket(AF_INET,SOCK_DGRAM)
client_socket.settimeout(1)
server_host = 'localhost'
server_port = 1234
while(True):
client_socket.sendto('Message',(server_h... | ```
from foo import *
```
adds all the names without leading underscores (or only the names defined in the modules `__all__` attribute) in `foo` into your current module.
In the above code with `from socket import *` you just want to catch `timeout` as you've pulled `timeout` into your current namespace.
`from socke... |
Heroku logs for Django projects missing errors | 11,866,322 | 10 | 2012-08-08T14:09:23Z | 11,879,545 | 9 | 2012-08-09T08:33:34Z | [
"python",
"django",
"logging",
"heroku"
] | I'm running a simple Django project on Heroku. It works, but if I get a server error it doesn't give me any details in the logs. This makes errors incredibly hard to deal with.
Now I've set up a staging server and it has the same problem - the pages are failing and I don't get any feedback as to why.
$ heroku logs
.... | Looks like it was simply a problem caused by an expectation that Django under Heroku would work like Rails. Silly me.
For anyone else suffering this problem when moving from one framework/language to another:
* When debug is off, Django uses the standard Python logger to handle errors in the code.
* There is a defaul... |
How to maintain state in Python without classes? | 11,866,419 | 11 | 2012-08-08T14:14:04Z | 11,866,711 | 10 | 2012-08-08T14:27:33Z | [
"python",
"closures",
"state"
] | Are there `pythonic` ways to maintain state (for purposes of optimisation, for example) without going fully object-oriented?
To illustrate my question better, here's an example of a pattern I use frequently in JavaScript:
```
var someFunc = (function () {
var foo = some_expensive_initialization_operation();
r... | You can also accomplish this with default arguments:
```
def try_match(m, re_match=re.compile(r'sldkjlsdjf').match):
return re_match(m)
```
since default arguments are only evaluated once, at module import time.
Or even simpler:
```
try_match = lambda m, re_match=re.compile(r'sldkjlsdjf').match: re_match(m)
```... |
How to maintain state in Python without classes? | 11,866,419 | 11 | 2012-08-08T14:14:04Z | 11,866,713 | 10 | 2012-08-08T14:27:35Z | [
"python",
"closures",
"state"
] | Are there `pythonic` ways to maintain state (for purposes of optimisation, for example) without going fully object-oriented?
To illustrate my question better, here's an example of a pattern I use frequently in JavaScript:
```
var someFunc = (function () {
var foo = some_expensive_initialization_operation();
r... | You can define closure in Python in the same way you define a closure in JavaScript.
```
def get_matcher():
compiled_regex = compile_my_regex()
def try_match(m)
return compiled_regex.match(m)
return try_match
```
However, in Python 2.x closures are read-only (you cannot re-assign to `compiled_re... |
How do I decode unicode one line at a time in Python 2.7? | 11,866,566 | 5 | 2012-08-08T14:20:38Z | 11,866,709 | 7 | 2012-08-08T14:27:27Z | [
"python",
"python-2.7",
"file-io",
"unicode",
"generator"
] | The correct way to load unicode text from Python 2.7 is something like:
```
content = open('filename').read().decode('encoding'):
for line in content.splitlines():
process(line)
```
(**Update**: No it isn't. See the answers.)
However, if the file is very large, I might want to read, decode and process it one lin... | How about trying somethng like:
```
for line in codecs.open("filename", "rt", "utf32"):
print line
```
I think this should work.
The `codecs` module should do the translation for you. |
How to prevent errno 32 broken pipe? | 11,866,792 | 57 | 2012-08-08T14:31:26Z | 11,866,962 | 47 | 2012-08-08T14:40:08Z | [
"python",
"broken-pipe"
] | Currently I am using an app built in python. When I run it in personal computer, it works without problems.
However, when I move it into a production server. It keeps showing me the error attached as below:.
I've done some research and I got the reason that the end user browser stops the connection while the server i... | Your server process has received a `SIGPIPE` writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using `close` function).
In a C... |
finding binomial co-effecient modulo prime number,Interview street challenge | 11,867,162 | 3 | 2012-08-08T14:49:15Z | 11,909,694 | 13 | 2012-08-10T21:46:13Z | [
"python",
"algorithm",
"primes",
"largenumber",
"binomial-coefficients"
] | I have done a lot of work on this but couldnt find the answer for larger test cases
# Problem statement
In mathematics, binomial coefficients are a family of positive integers that occur as coefficients in the binomial theorem. C(n,k) denotes the number of ways of choosing k objects from n different objects.
However... | You can look at it from the other end: How many `nCr` are *not* divisible by `p`? There's a rather simple formula for that.
### Preliminaries:
The binomial coefficient `nCr` is given by
```
nCr = n! / (r! * (n-r)!)
```
so the multiplicity `v_p(nCr)` of `p` in `nCr` - the exponent of `p` in the prime factorisation o... |
(Z3Py) checking all solutions for equation | 11,867,611 | 10 | 2012-08-08T15:10:28Z | 11,869,410 | 12 | 2012-08-08T16:53:07Z | [
"python",
"z3",
"z3py"
] | In Z3Py, how can I check if equation for given constraints have only one solution?
If more than one solution, how can I enumerate them? | You can do that by adding a new constraint that blocks the model returned by Z3.
For example, suppose that in the model returned by Z3 we have that `x = 0` and `y = 1`. Then, we can block this model by adding the constraint `Or(x != 0, y != 1)`.
The following script does the trick.
You can try it online at: <http://ris... |
Python (List Comprehension): Returning two (or more) items for each item | 11,868,964 | 35 | 2012-08-08T16:27:53Z | 11,868,996 | 31 | 2012-08-08T16:29:44Z | [
"python",
"list-comprehension"
] | **Is it possible to return 2 (or more) items for each item in a list comprehension?**
What I want (example):
```
[f(x), g(x) for x in range(n)]
```
should return `[f(0), g(0), f(1), g(1), ..., f(n-1), g(n-1)]`
So, something to replace this block of code:
```
result = list()
for x in range(n):
result.add(f(x))
... | ```
>>> from itertools import chain
>>> f = lambda x: x + 2
>>> g = lambda x: x ** 2
>>> list(chain.from_iterable((f(x), g(x)) for x in range(3)))
[2, 0, 3, 1, 4, 4]
```
Timings:
```
from timeit import timeit
f = lambda x: x + 2
g = lambda x: x ** 2
def fg(x):
yield f(x)
yield g(x)
print timeit(stmt='list(... |
Python (List Comprehension): Returning two (or more) items for each item | 11,868,964 | 35 | 2012-08-08T16:27:53Z | 11,869,360 | 39 | 2012-08-08T16:50:19Z | [
"python",
"list-comprehension"
] | **Is it possible to return 2 (or more) items for each item in a list comprehension?**
What I want (example):
```
[f(x), g(x) for x in range(n)]
```
should return `[f(0), g(0), f(1), g(1), ..., f(n-1), g(n-1)]`
So, something to replace this block of code:
```
result = list()
for x in range(n):
result.add(f(x))
... | Double list comprehension:
```
[f(x) for x in range(5) for f in (f1,f2)]
```
Demo:
```
>>> f1 = lambda x: x
>>> f2 = lambda x: 10*x
>>> [f(x) for x in range(5) for f in (f1,f2)]
[0, 0, 1, 10, 2, 20, 3, 30, 4, 40]
``` |
How to I return JSON in flask python fetched from another url to the browser? | 11,870,396 | 5 | 2012-08-08T17:59:14Z | 11,870,499 | 10 | 2012-08-08T18:06:00Z | [
"python",
"flask"
] | I want to use flask to return JSON to the brower with or without simplejson (with appropriate headers) here is what I have so far for my flask application:
```
@app.route('/')
def hello_world():
QUERY_URL="http://someappserver:9902/myjsonservlet"
result = simplejson.load(urllib.urlopen(QUERY_URL))
return r... | ```
import requests
r = requests.get(QUERY_URL)
return r.json
#normal return
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
```
jsonify is available in flask. Here is the [docs](http://flask.pocoo.org/docs/api/#flask.json.jsonify) |
Binary selection process | 11,870,785 | 9 | 2012-08-08T18:24:50Z | 11,871,032 | 10 | 2012-08-08T18:41:19Z | [
"python",
"c",
"algorithm",
"binary-search"
] | I have been working on what seems to be a simple task that is driving me nuts. So if you fancy a programming challenge ... read on.
I want to be able to take a number range e.g. [1:20] and print the values using a mechanism similar to a binary serach algorithm. So, print first the lowest value (in this case 1) and the... | Here is some Python code producing similar output to your example:
```
def f(low, high):
ranges = collections.deque([(low, high)])
while ranges:
low, high = ranges.popleft()
mid = (low + high) // 2
yield mid
if low < mid:
ranges.append((low, mid))
if mid + 1 ... |
Python: "TypeError: __str__ returned non-string" but still prints to output? | 11,871,221 | 19 | 2012-08-08T18:53:02Z | 11,871,233 | 39 | 2012-08-08T18:54:04Z | [
"python"
] | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | Method [\_\_str\_\_](http://docs.python.org/reference/datamodel.html#object.__str__) should return string, not print.
```
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
``` |
Python: "TypeError: __str__ returned non-string" but still prints to output? | 11,871,221 | 19 | 2012-08-08T18:53:02Z | 28,462,069 | 10 | 2015-02-11T18:46:43Z | [
"python"
] | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | You can also surround the output with str(). I had this same problem because my model had the following (as a simplified example):
```
def __str__(self):
return self.pressid
```
Where pressid was an IntegerField type object. Django (and python in general) expects a string for a **str** function, so returning an i... |
Python iteration over non-sequence | 11,871,593 | 8 | 2012-08-08T19:16:57Z | 11,871,666 | 8 | 2012-08-08T19:21:28Z | [
"python"
] | I have this piece of code which creates a note and adds to the notebook. When I run this I get a Iteration over non-sequence error.
```
import datetime
class Note:
def __init__(self, memo, tags):
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
def __str__(self)... | Notes is an instance of `NoteBook`. To iterate over such an object, it needs an [`__iter__` method](http://docs.python.org/reference/datamodel.html#object.__iter__):
```
class NoteBook:
def __iter__(self):
return iter(self.notes)
```
PS. It is a [PEP8](http://www.python.org/dev/peps/pep-0008/) recommenda... |
Python iteration over non-sequence | 11,871,593 | 8 | 2012-08-08T19:16:57Z | 11,871,671 | 7 | 2012-08-08T19:21:54Z | [
"python"
] | I have this piece of code which creates a note and adds to the notebook. When I run this I get a Iteration over non-sequence error.
```
import datetime
class Note:
def __init__(self, memo, tags):
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
def __str__(self)... | You are trying to iterate over the object itself, which is returning the error. You want to iterate over the list inside the object, in this case `Notes.notes` (which is somewhat confusing naming, you may want to distinguish the internal list by using another name for the instance of the notebook object).
```
for note... |
How to pass Django request object in user_passes_test decorator callable function | 11,872,560 | 11 | 2012-08-08T20:22:49Z | 11,872,933 | 11 | 2012-08-08T20:48:37Z | [
"python",
"django",
"django-views",
"django-authentication"
] | I am using Django user\_passes\_test decorator to check the User Permission.
```
@user_passes_test(lambda u: has_add_permission(u, "project"))
def create_project(request):
......
```
I am calling a callback function has\_add\_permission which takes two arguments User and a String. I would like to pass the request obj... | No, you cannot pass request to `user_passes_test`. To understand why and how it works, just head over to the [source](https://github.com/django/django/blob/1.3.1/django/contrib/auth/decorators.py):
```
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for v... |
Global variable declaration Python | 11,872,808 | 5 | 2012-08-08T20:39:39Z | 11,872,886 | 9 | 2012-08-08T20:45:18Z | [
"python",
"global-variables"
] | I have the below piece of code that creates a note and adds to a notebook.
My question is more related to the global variable `last_id`. When I declare it as class variable i.e. inside Class Note, I get the following error but when I declare outside the class, my code works fine.
Here are my clarifications:
1. Why d... | When you write
```
global last_id
```
Inside your function, you are not creating a new global variable. What you are doing is saying "instead of creating a new local variable and associating it to the name `last_id`, instead associate that name to a pre-existing variable in the enclosing scope that has the name `last... |
Global variable declaration Python | 11,872,808 | 5 | 2012-08-08T20:39:39Z | 11,872,916 | 9 | 2012-08-08T20:47:09Z | [
"python",
"global-variables"
] | I have the below piece of code that creates a note and adds to a notebook.
My question is more related to the global variable `last_id`. When I declare it as class variable i.e. inside Class Note, I get the following error but when I declare outside the class, my code works fine.
Here are my clarifications:
1. Why d... | python is a bit more explicit about where attributes come from than other object oriented languages; you can have a class level counter, like so:
```
from itertools import count
class Foo(object):
last_id = count()
def __init__(self):
self.id = self.last_id.next()
```
you must refer to `last_id` as ... |
sampling random floats on a range in numpy | 11,873,741 | 11 | 2012-08-08T21:52:06Z | 11,873,796 | 23 | 2012-08-08T21:56:14Z | [
"python",
"numpy",
"scipy"
] | How can I sample random floats on an interval [a, b] in numpy? Not just integers, but any real numbers. For example,
`random_float(5, 10)`
would return random numbers between `[5, 10]`. thanks. | The [uniform distribution](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform) would probably do what you are asking.
```
np.random.uniform(5,10) # A single value
np.random.uniform(5,10,[2,3]) # A 2x3 array
``` |
flask-sqlalchemy - PostgreSQL - Define specific schema for table? | 11,873,959 | 8 | 2012-08-08T22:11:35Z | 11,875,775 | 13 | 2012-08-09T02:03:12Z | [
"python",
"flask",
"flask-sqlalchemy"
] | I want to define a specific schema for a 'model' using flask-sqlalchemy. When you create a table object in sqlalchemy itself it has a parameter to pass for schema name.
How do I do this in flask-sqlalchemy? | When you define your model class use:
```
__table_args__ = {"schema":"schema_name"}
```
maybe it will save someone else some hunting. |
Combine Two LIsts in Unique Way in Python | 11,874,669 | 7 | 2012-08-08T23:24:13Z | 11,874,819 | 23 | 2012-08-08T23:42:38Z | [
"python",
"list"
] | I am working on Project Euler problem 5 and am using the following:
```
def findLCM(k):
start=time.time()
primes=[2,3,5,7,11,13,17,19,23]
factors=[]
for factor in range(2,k):
if factor in primes:
factors.append(factor)
else:
factorization=[]
while factor!=1:
for prime in pri... | The terminology is "union of [multisets](http://en.wikipedia.org/wiki/Multiset)".
It is implemented in Python using *[collections.Counter](http://docs.python.org/library/collections.html#counter-objects)*:
```
>>> from collections import Counter
>>> combined = Counter([2, 3, 5]) | Counter([2, 2, 3])
>>> list(combined... |
real-time plotting in while loop with matplotlib | 11,874,767 | 58 | 2012-08-08T23:36:04Z | 11,874,882 | 28 | 2012-08-08T23:48:57Z | [
"python",
"matplotlib",
"while-loop"
] | I am trying to plot some data from a camera in real time using OpenCV. However the real-time plotting (using matplotlib) doesn't seem to be working.
I've isolated the problem into this simple example:
```
fig=plt.figure()
plt.axis([0,1000,0,1])
i=0
x=list()
y=list()
while i <1000:
temp_y=np.random.random()
... | `show` is probably not the best choice for this. What I would do is use `pyplot.draw()` instead. You also might want to include a small time delay (e.g., `time.sleep(0.05)`) in the loop so that you can see the plots happening. If I make these changes to your example it works for me and I see each point appearing one at... |
real-time plotting in while loop with matplotlib | 11,874,767 | 58 | 2012-08-08T23:36:04Z | 15,720,891 | 101 | 2013-03-30T16:37:14Z | [
"python",
"matplotlib",
"while-loop"
] | I am trying to plot some data from a camera in real time using OpenCV. However the real-time plotting (using matplotlib) doesn't seem to be working.
I've isolated the problem into this simple example:
```
fig=plt.figure()
plt.axis([0,1000,0,1])
i=0
x=list()
y=list()
while i <1000:
temp_y=np.random.random()
... | Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):
```
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0, 10, 0, 1])
plt.ion()
for i in range(10):
y = np.random.random()
plt.scatter(i, y)
plt.pause(0.05)
while True:
plt.pause... |
real-time plotting in while loop with matplotlib | 11,874,767 | 58 | 2012-08-08T23:36:04Z | 15,724,978 | 34 | 2013-03-31T00:17:21Z | [
"python",
"matplotlib",
"while-loop"
] | I am trying to plot some data from a camera in real time using OpenCV. However the real-time plotting (using matplotlib) doesn't seem to be working.
I've isolated the problem into this simple example:
```
fig=plt.figure()
plt.axis([0,1000,0,1])
i=0
x=list()
y=list()
while i <1000:
temp_y=np.random.random()
... | If you're interested in realtime plotting, I'd recommend looking into [matplotlib's animation API](http://www.scipy.org/Cookbook/Matplotlib/Animations#head-3d51654b8306b1585664e7fe060a60fc76e5aa08). In particular, using `blit` to avoid redrawing the background on every frame can give you substantial speed gains (~10x):... |
real-time plotting in while loop with matplotlib | 11,874,767 | 58 | 2012-08-08T23:36:04Z | 24,228,275 | 16 | 2014-06-15T09:33:01Z | [
"python",
"matplotlib",
"while-loop"
] | I am trying to plot some data from a camera in real time using OpenCV. However the real-time plotting (using matplotlib) doesn't seem to be working.
I've isolated the problem into this simple example:
```
fig=plt.figure()
plt.axis([0,1000,0,1])
i=0
x=list()
y=list()
while i <1000:
temp_y=np.random.random()
... | None of the methods worked for me.
But I have found this
[Real time matplotlib plot is not working while still in a loop](http://stackoverflow.com/questions/19766100/real-time-matplotlib-plot-is-not-working-while-still-in-a-loop)
All you need is to add
```
plt.pause(0.0001)
```
and than you could see the new plot.
... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 11,875,813 | 132 | 2012-08-09T02:07:57Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:
<http://api.mongodb.org/python/1.10.1/api/bson/json_util.html>
Example usage (serialization):
```
from bson import json_util
import json
json.dumps(anObject, default=json_util.de... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 11,875,834 | 92 | 2012-08-09T02:10:55Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | Convert the date to a string
```
sample['somedate'] = str( datetime.now() )
``` |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 15,823,348 | 66 | 2013-04-04T23:15:58Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | For others who do not need or want to use the pymongo library for this.. you can achieve datetime JSON conversion easily with this small snippet:
```
def default(obj):
"""Default JSON serializer."""
import calendar, datetime
if isinstance(obj, datetime.datetime):
if obj.utcoffset() is not None:
... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 16,353,080 | 7 | 2013-05-03T06:38:32Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | Here is my solution:
```
# -*- coding: utf-8 -*-
import json
class DatetimeEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super(DatetimeEncoder, obj).default(obj)
except TypeError:
return str(obj)
```
Then you can use it like that:
```
json.dumps(dictionn... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 17,959,535 | 11 | 2013-07-31T00:07:54Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | My solution (with less verbosity, I think):
```
def default(o):
if type(o) is datetime.date or type(o) is datetime.datetime:
return o.isoformat()
def jsondumps(o):
return json.dumps(o, default=default)
```
Then use `jsondumps` instead of `json.dumps`. It will print:
```
>>> jsondumps({'today': datet... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 18,006,338 | 20 | 2013-08-01T23:27:38Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | I have an application with a similar issue; my approach was to JSONize the datetime value as a 6-item list (year, month, day, hour, minutes, seconds); you could go to microseconds as a 7-item list, but I had no need to:
```
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj,... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 22,238,613 | 148 | 2014-03-06T23:46:17Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | Building on other answers, a simple solution based on a specific serializer that just converts datetime.datetime objects to strings.
```
from datetime import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
serial = o... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 27,058,505 | 54 | 2014-11-21T09:52:44Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | I have just encountered this problem and my solution is to subclass `json.JSONEncoder`:
```
from datetime import datetime
import json
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return json.JSONEncoder.default(self, o... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 32,225,623 | 7 | 2015-08-26T11:38:06Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | This Q repeats time and time again - a simple way to patch the json module such that serialization would support datetime.
```
import json
import datetime
json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None)
```
Than use json serialization as you always do - t... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 34,303,655 | 8 | 2015-12-16T03:53:51Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | Here is a simple solution to over come "datetime not JSON serializable"
problem.
```
enco = lambda obj: (
obj.isoformat()
if isinstance(obj, datetime.datetime)
or isinstance(obj, datetime.date)
else None
)
json.dumps({'date': datetime.datetime.now()}, default=enco)
```
**Output:->** {"date": "2015-12... |
How to overcome "datetime.datetime not JSON serializable" in python? | 11,875,770 | 215 | 2012-08-09T02:02:51Z | 36,142,844 | 18 | 2016-03-21T22:29:26Z | [
"python",
"json"
] | I have a basic dict as follows:
```
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
```
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do such that my dictionary sample can overcome the error a... | My quick & dirty JSON dump that eats dates and everything:
```
json.dumps(my_dictionary, indent=4, sort_keys=True, default=lambda x:str(x))
``` |
Python (3.2.3) If Or Statement Syntax Error | 11,876,338 | 2 | 2012-08-09T03:23:33Z | 11,876,346 | 8 | 2012-08-09T03:24:48Z | [
"python",
"syntax",
"if-statement",
"conditional"
] | Thanks for reading this. I'm trying to do [this lab from programarcadegames.com](http://programarcadegames.com/index.php?chapter=lab_create_a_quiz#section_24) where you have to write a quiz. I finished my first question and got a syntax error. Here's the code:
```
print ("This is a quiz.")
x=0
questionOne=input("First... | You are missing a closing parenthesis on the previous line (the line with `input`). |
Python, Press Any Key To Exit | 11,876,618 | 10 | 2012-08-09T04:00:48Z | 11,876,639 | 7 | 2012-08-09T04:03:43Z | [
"python",
"key",
"any"
] | So, as the title says, I want a proper code to close my python script.
So far, I've used `input('Press Any Key To Exit')`, but what that does, is generate a error.
I would like a code that just closes your script without using a error.
Does anyone have a idea? Google gives me the input option, but I don't want that
It... | Have you tried `raw_input()`? It could be that you are getting a syntax error by using `input()` on python 2.x, which will try to `eval` whatever it gets. |
Python, Press Any Key To Exit | 11,876,618 | 10 | 2012-08-09T04:00:48Z | 11,877,177 | 10 | 2012-08-09T05:13:47Z | [
"python",
"key",
"any"
] | So, as the title says, I want a proper code to close my python script.
So far, I've used `input('Press Any Key To Exit')`, but what that does, is generate a error.
I would like a code that just closes your script without using a error.
Does anyone have a idea? Google gives me the input option, but I don't want that
It... | If you are on windows then the cmd `pause` command should work, although it reads 'press any key to continue'
```
import os
os.system('pause')
```
The linux alternative is `read`, a good description can be found [here](http://stackoverflow.com/questions/92802/what-is-the-linux-equivalent-to-dos-pause) |
serializing and deserializing lambdas | 11,878,300 | 12 | 2012-08-09T07:02:44Z | 11,878,430 | 15 | 2012-08-09T07:12:51Z | [
"python",
"lambda",
"pickle"
] | I would like to serialize on machine A and deserialize on machine B a python lambda. There are a couple of obvious problems with that:
* the pickle module does not serialize or deserialize code. It only serializes the names of classes/methods/functions
* some of the answers I found with google suggest the use of the l... | Surprisingly, checking whether a lambda will work without its associated closure is actually fairly easy. According to the [data model documentation](http://docs.python.org/release/2.6.2/reference/datamodel.html), you can just check the `func_closure` attribute:
```
>>> def get_lambdas():
... bar = 42
... retu... |
String.maketrans for English and Persian numbers | 11,879,025 | 3 | 2012-08-09T07:56:56Z | 11,883,061 | 9 | 2012-08-09T12:04:40Z | [
"python",
"python-2.7",
"python-unicode"
] | I have a function like this:
```
persian_numbers = 'Û±Û²Û³Û´ÛµÛ¶Û·Û¸Û¹Û°'
english_numbers = '1234567890'
arabic_numbers = '١٢٣٤٥٦٧٨٩٠'
english_trans = string.maketrans(english_numbers, persian_numbers)
arabic_trans = string.maketrans(arabic_numbers, persian_numbers)
text.translate(english_trans)
text... | Unicode objects can interpret these digits (arabic and persian) as actual digits -
no need to translate them by using character substitution.
**EDIT -**
I came out with a way to make your replacement using Python2 regular expressions:
```
# coding: utf-8
import re
# Attention: while the characters for the strings b... |
How to write inline if statement for print? | 11,880,430 | 149 | 2012-08-09T09:31:48Z | 11,880,445 | 50 | 2012-08-09T09:32:50Z | [
"python",
"if-statement",
"inline"
] | I need to print some stuff only when a boolean variable is set to `True`. So, after looking at [this](http://stackoverflow.com/questions/1319214/shorter-more-pythonic-way-of-writing-an-if-statements), I tried with a simple example:
```
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b... | Inline if-else *EXPRESSION* must always contain else clause, e.g:
```
a = 1 if b else 0
```
If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands):
```
a = 1 if b else a
```
This piece of code leaves **a** unchanged when b turns to be False. |
How to write inline if statement for print? | 11,880,430 | 149 | 2012-08-09T09:31:48Z | 11,880,478 | 9 | 2012-08-09T09:34:08Z | [
"python",
"if-statement",
"inline"
] | I need to print some stuff only when a boolean variable is set to `True`. So, after looking at [this](http://stackoverflow.com/questions/1319214/shorter-more-pythonic-way-of-writing-an-if-statements), I tried with a simple example:
```
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b... | The 'else' statement is mandatory. You can do stuff like this :
```
>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>>
```
**EDIT:**
Or, depending of your needs, you may try:
```
>>> if b: print(a)
``` |
How to write inline if statement for print? | 11,880,430 | 149 | 2012-08-09T09:31:48Z | 11,880,682 | 306 | 2012-08-09T09:47:28Z | [
"python",
"if-statement",
"inline"
] | I need to print some stuff only when a boolean variable is set to `True`. So, after looking at [this](http://stackoverflow.com/questions/1319214/shorter-more-pythonic-way-of-writing-an-if-statements), I tried with a simple example:
```
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b... | Python does **not** have a trailing `if` **statement**.
There are two kinds of `if` in Python:
1. `if` statement:
```
if condition: statement
if condition:
block
```
2. `if` **expression** (introduced in Python 2.5)
```
expression_if_true if condition else expression_if_false
```
And no... |
How to write inline if statement for print? | 11,880,430 | 149 | 2012-08-09T09:31:48Z | 30,004,980 | 7 | 2015-05-02T16:54:46Z | [
"python",
"if-statement",
"inline"
] | I need to print some stuff only when a boolean variable is set to `True`. So, after looking at [this](http://stackoverflow.com/questions/1319214/shorter-more-pythonic-way-of-writing-an-if-statements), I tried with a simple example:
```
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b... | Since 2.5 you can use [equivalent of Câs â?:â](https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator) [ternary conditional operator](http://stackoverflow.com/q/394809/55075) and the syntax is:
```
[on_true] if [expression] else [on_false]
```
So your example is fine, bu... |
Slice Pandas DataFrame by Row | 11,881,165 | 18 | 2012-08-09T10:15:27Z | 11,882,354 | 26 | 2012-08-09T11:26:08Z | [
"python",
"pandas",
"slice"
] | I am working with survey data loaded from an h5-file as `hdf = pandas.HDFStore('Survey.h5')` through the pandas package. Within this DataFrame, all rows are the results of a single survey, whereas the columns are the answers for all questions within a single survey.
I am aiming to reduce this dataset to a smaller `Dat... | ```
In [36]: df
Out[36]:
A B C D
a 0 2 6 0
b 6 1 5 2
c 0 2 6 0
d 9 3 2 2
In [37]: rows
Out[37]: ['a', 'c']
In [38]: df.drop(rows)
Out[38]:
A B C D
b 6 1 5 2
d 9 3 2 2
In [39]: df[~((df.A == 0) & (df.B == 2) & (df.C == 6) & (df.D == 0))]
Out[39]:
A B C D
b 6 1 5 2
d 9 3... |
call function with a dynamic list of arguments in python | 11,881,700 | 5 | 2012-08-09T10:47:47Z | 11,881,810 | 9 | 2012-08-09T10:53:26Z | [
"python",
"web.py"
] | I need to call a function that handles a list of arguments that can have default values:
example code:
```
web.input(name=None, age=None, desc=None, alert=None, country=None, lang=None)
```
How can I call web.input like this using a list or dictionary? I'm stuck at:
```
getattr(web, 'input').__call__()
``` | find [here](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) the relevant documentation
```
web.input(*list)
web.input(**kwargs)
``` |
matplotlib: disregard outliers when plotting | 11,882,393 | 7 | 2012-08-09T11:28:33Z | 11,886,564 | 21 | 2012-08-09T15:16:03Z | [
"python",
"plot",
"matplotlib",
"percentile",
"outliers"
] | I'm plotting some data from various tests. Sometimes in a test I happen to have one outlier (say 0.1), while all other values are three orders of magnitude smaller.
With matplotlib, I plot against the range `[0, max_data_value]`
How can I just zoom into my data and not display outliers, which would mess up the x-axis... | There's no single "best" test for an outlier. Ideally, you should incorporate a-priori information (e.g. "This parameter shouldn't be over x because of blah...").
Most tests for outliers use the median absolute deviation, rather than the 95th percentile or some other variance-based measurement. Otherwise, the variance... |
Celery dynamic queue creation and routing | 11,882,826 | 7 | 2012-08-09T11:52:17Z | 11,992,185 | 11 | 2012-08-16T17:08:20Z | [
"python",
"rabbitmq",
"celery"
] | I'm trying to call a task and create a queue for that task if it doesn't exist then immediately insert to that queue the called task. I have the following code:
```
@task
def greet(name):
return "Hello %s!" % name
def run():
result = greet.delay(args=['marc'], queue='greet.1',
routing_key='greet.1')
... | When you do the following:
```
task.apply_async(queue='foo', routing_key='foobar')
```
Then Celery will take default values from the 'foo' queue in CELERY\_QUEUES,
or if it does not exist then automatically create it using (queue=foo, exchange=foo, routing\_key=foo)
So if 'foo' does not exist in CELERY\_QUEUES you w... |
Python: bytearray vs array | 11,882,988 | 22 | 2012-08-09T12:00:40Z | 11,883,097 | 11 | 2012-08-09T12:06:59Z | [
"python",
"bytearray"
] | What is the difference between `array.array('B')` and `bytearray`?
```
from array import array
a = array('B', 'abc')
b = bytearray('abc')
a[0] = 100
b[0] = 'd'
print a
print b
```
Are there any memory or speed differences? What is the preferred use case of each one? | `bytearray` is the successor of Python 2.x's `string` type. It's basically the built-in byte array type. Unlike the original `string` type, it's mutable.
The `array` module, on the other hand, was created to create binary data structures to communicate with the outside world (for example, to read/write binary file for... |
Python - list of function/argument tuples | 11,883,319 | 5 | 2012-08-09T12:20:32Z | 11,883,385 | 8 | 2012-08-09T12:23:42Z | [
"python",
"list",
"function",
"arguments",
"tuples"
] | ```
def f1(n): #accepts one argument
pass
def f2(): #accepts no arguments
pass
FUNCTION_LIST = [(f1,(2)), #each list entry is a tuple containing a function object and a tuple of arguments
(f1,(6)),
(f2,())]
for f, arg in FUNCTION_LIST:
f(arg)
```
The third time round in... | Your comment in this code snippet shows a misconception relevant in this context:
```
FUNCTION_LIST = [(f1,(2)), #each list entry is a tuple containing a function object and a tuple of arguments
(f1,(6)),
(f2,())]
```
The expressions `(2)` and `(6)` are not tuples â they are intege... |
Detect file creation with watchdog | 11,883,336 | 7 | 2012-08-09T12:21:30Z | 11,886,361 | 8 | 2012-08-09T15:04:53Z | [
"python",
"multithreading",
"exit-code",
"termination",
"watchdog"
] | I am trying to detect when a file with a given name is created in a directory. I am doing it thanks to [watchdog](http://pypi.python.org/pypi/watchdog/). The creation is correctly detected but I don't know how to terminate the application properly once the detection is done.
My piece of code is the following:
```
#!/... | Finally, after taking a look at the watchdog implementation, it is not necessary to call `unschedule_all` before `stop`, this is done automatically. Removing the line containing this method call fixes the issue and the application is running perfectly. |
python csv unicode 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) | 11,884,190 | 20 | 2012-08-09T13:09:18Z | 11,884,299 | 46 | 2012-08-09T13:14:47Z | [
"python",
"csv"
] | I have copied this script from [python web site][1] This is another question but now problem with encoding:
```
import sqlite3
import csv
import codecs
import cStringIO
import sys
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, en... | > Then I converted all integers to string,
You converted both integers *and* strings to *byte strings*. For strings this will use the default character encoding which happens to be ASCII, and this fails when you have non-ASCII characters. You want `unicode` instead of `str`.
```
self.writer.writerow([unicode(s).encod... |
Python Coverting scrambled alphabet | 11,884,419 | 2 | 2012-08-09T13:20:51Z | 11,884,443 | 8 | 2012-08-09T13:22:30Z | [
"python"
] | I am trying to figure out a homework problem. I have all the code written except one part. I need to take an input of a scrambled alphabet and covert it to the A-Z alphabet. I think I need to change these to integers. Any idea how to take a scrambled input and changed it to integers?
Any help is appreciated. Thanks
*... | Since this is a homework question, I only hint you at the functions you could use to easily implement this: Take a look at [`string.maketrans()`](http://docs.python.org/library/string.html#string.maketrans) and [`str.translate()`](http://docs.python.org/library/stdtypes.html#str.translate). |
how to shade points in scatter based on colormap in matplotlib? | 11,885,060 | 16 | 2012-08-09T13:55:06Z | 11,886,242 | 12 | 2012-08-09T14:58:04Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | I'm trying to shade points in a scatter plot based on a set of values (from 0 to 1) picked from one of the already defined color maps, like Blues or Reds. I tried this:
```
import matplotlib
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
fig = plt.figure()
mymap = plt.get_cmap("Reds")
x = [8.4... | [As per the documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.scatter), you want the `c` keyword argument instead of `color`. (I agree that this is a bit confusing, but the "c" and "s" terminology is inherited from matlab, in this case.)
E.g.
```
import numpy as np
import matplotl... |
how to shade points in scatter based on colormap in matplotlib? | 11,885,060 | 16 | 2012-08-09T13:55:06Z | 11,916,309 | 15 | 2012-08-11T17:54:53Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | I'm trying to shade points in a scatter plot based on a set of values (from 0 to 1) picked from one of the already defined color maps, like Blues or Reds. I tried this:
```
import matplotlib
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
fig = plt.figure()
mymap = plt.get_cmap("Reds")
x = [8.4... | If you really want to do this (what you describe in your edit), you have to "pull" the colors from your colormap (I have commented all changes I made to your code):
```
import numpy as np
import matplotlib.pyplot as plt
# plt.subplots instead of plt.subplot
# create a figure and two subplots side by side, they share... |
how to shade points in scatter based on colormap in matplotlib? | 11,885,060 | 16 | 2012-08-09T13:55:06Z | 11,978,238 | 7 | 2012-08-15T22:26:51Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | I'm trying to shade points in a scatter plot based on a set of values (from 0 to 1) picked from one of the already defined color maps, like Blues or Reds. I tried this:
```
import matplotlib
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
fig = plt.figure()
mymap = plt.get_cmap("Reds")
x = [8.4... | How about:
```
import matplotlib.pyplot as plt
import numpy as np
reds = plt.get_cmap("Reds")
x = np.linspace(0, 10, 10)
y = np.log(x)
# color by value given a cmap
plt.subplot(121)
plt.scatter(x, y, c=x, s=100, cmap=reds)
# color by value, and add a legend for each
plt.subplot(122)
norm = plt.normalize()
norm.au... |
Is there any difference between `if bool(x)` and `if x` in Python? | 11,885,382 | 8 | 2012-08-09T14:12:27Z | 11,885,410 | 13 | 2012-08-09T14:14:16Z | [
"python"
] | I've come across some code that reads:
```
if bool(x):
doSomething
```
I think that the following would do the same job:
```
if x:
doSomething
```
[The reference](http://docs.python.org/reference/compound_stmts.html#the-if-statement) says that it evaluates the suite if the test expression
> is found to be ... | Objects are implicitly converted to bool type when they are placed in an if statement. So, for most purposes, there's no difference between `x` and `bool(x)` in an `if` statement. However, you will incur extra overhead if you call `bool()` because you are making a function call. Here's a quick test to demonstrate this:... |
Is there any difference between `if bool(x)` and `if x` in Python? | 11,885,382 | 8 | 2012-08-09T14:12:27Z | 11,885,567 | 7 | 2012-08-09T14:22:55Z | [
"python"
] | I've come across some code that reads:
```
if bool(x):
doSomething
```
I think that the following would do the same job:
```
if x:
doSomething
```
[The reference](http://docs.python.org/reference/compound_stmts.html#the-if-statement) says that it evaluates the suite if the test expression
> is found to be ... | `if` will use `__nonzero__()` if available, as does `bool()` when testing a value for truth. So **yes**, the behaviour is equivalent.
From the documentation:
> In the context of Boolean operations, and also when expressions are
> used by control flow statements, the following values are interpreted
> as false: False,... |
Numpy transpose not giving expected result | 11,885,503 | 9 | 2012-08-09T14:19:34Z | 11,885,581 | 11 | 2012-08-09T14:23:45Z | [
"python",
"numpy",
"scipy"
] | I am trying a very basic example in Python scipy module for transpose method but is not giving expected result. I am using Ipython with pylab mode.
```
a = array([1,2,3]
print a.shape
>> (3,)
b = a.transpose()
print b.shape
>> (3,)
```
If i print the contents of arrays "a" and "b", they are similar.
Expectation is :... | NumPy's `transpose()` effectively reverses the shape of an array. If the array is one-dimensional, this means it has no effect.
In NumPy, the arrays
```
array([1, 2, 3])
```
and
```
array([1,
2,
3])
```
are actually the same â they only differ in whitespace. What you probably want are the correspon... |
Numpy transpose not giving expected result | 11,885,503 | 9 | 2012-08-09T14:19:34Z | 11,885,718 | 20 | 2012-08-09T14:31:09Z | [
"python",
"numpy",
"scipy"
] | I am trying a very basic example in Python scipy module for transpose method but is not giving expected result. I am using Ipython with pylab mode.
```
a = array([1,2,3]
print a.shape
>> (3,)
b = a.transpose()
print b.shape
>> (3,)
```
If i print the contents of arrays "a" and "b", they are similar.
Expectation is :... | Transpose is a noop for one-dimensional arrays.
Add new axis and transpose:
```
>>> a[None].T
array([[1],
[2],
[3]])
>>> np.newaxis is None
True
```
Or reshape:
```
>>> a.reshape(a.shape+(1,))
array([[1],
[2],
[3]])
```
Or as @Sven Marnach suggested in comments, add new axis at the end:... |
cv2.kmeans usage in Python | 11,885,751 | 4 | 2012-08-09T14:32:39Z | 11,931,668 | 13 | 2012-08-13T09:40:25Z | [
"python",
"opencv"
] | I am considering to use OpenCV's Kmeans implementation since it says to be faster...
Now I am using package cv2 and function kmeans,
I can not understand the parameters' description in their reference:
```
Python: cv2.kmeans(data, K, criteria, attempts, flags[, bestLabels[, centers]]) â retval, bestLabels, centers... | the documentation on this function is almost impossible to find. I wrote the following Python code in a bit of a hurry, but it works on my machine. It generates two multi-variate Gaussian Distributions with different means and then classifies them using cv2.kmeans(). You may refer to [this blog post](http://www.aishack... |
Why must "exec" (and not "eval") be used for Python import statements? | 11,886,540 | 11 | 2012-08-09T15:14:36Z | 11,886,582 | 16 | 2012-08-09T15:17:40Z | [
"python",
"eval",
"jython"
] | I'm trying to run a snippet of Python from within Java, using Jython. If I use an exec statement to import, everything works.
```
PythonInterpreter pi = new PythonInterpreter();
pi.exec("import re");
PythonObject o = pi.eval("re.match('abc', 'abc123')"); // returns a MatchObject
o = pi.eval("re.match('abc', 'def123')"... | The problem is that **eval** *evaluates expressions* and *returns some result*, while **exec** *executes statements* in some context. import is a statement, while re.match() is an expression. |
How to add carriage return in python? | 11,887,291 | 2 | 2012-08-09T15:56:32Z | 11,887,341 | 9 | 2012-08-09T15:58:59Z | [
"python",
"jinja2"
] | I have a simpl example:
```
test = """test
dsdssd
dsdssd
"""
def html_doc(args):
return Environment().from_string(test).render(args)
print html_doc({ })
```
How to add "carriage return" (\r) in the end of each string ? | ```
test = str.replace(test, '\n', '\r\n')
```
**EDIT:** Python [automatically tries to take care of newlines](http://docs.python.org/whatsnew/2.3.html#pep-278-universal-newline-support) for reading and writing files, but I assume because the question is tagged as jinja2 that this string isn't being written to a file. |
Compare version strings | 11,887,762 | 74 | 2012-08-09T16:22:50Z | 11,887,825 | 40 | 2012-08-09T16:26:40Z | [
"python",
"version",
"string-comparison"
] | I am walking a directory that contains eggs to add those eggs to the `sys.path`. If there are two versions of the same .egg in the directory, I want to add only the latest one.
I have a regular expression `r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$` to extract the name and version from the filename. The prob... | ```
def versiontuple(v):
return tuple(map(int, (v.split("."))))
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
False
``` |
Compare version strings | 11,887,762 | 74 | 2012-08-09T16:22:50Z | 11,887,885 | 102 | 2012-08-09T16:30:03Z | [
"python",
"version",
"string-comparison"
] | I am walking a directory that contains eggs to add those eggs to the `sys.path`. If there are two versions of the same .egg in the directory, I want to add only the latest one.
I have a regular expression `r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$` to extract the name and version from the filename. The prob... | Use [`distutils.version`](http://docs.python.org/distutils/apiref.html#module-distutils.version) or [`packaging.version.parse`](https://packaging.pypa.io/en/latest/version/#packaging.version.parse).
```
>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
Tru... |
Compare version strings | 11,887,762 | 74 | 2012-08-09T16:22:50Z | 21,065,570 | 39 | 2014-01-11T17:36:50Z | [
"python",
"version",
"string-comparison"
] | I am walking a directory that contains eggs to add those eggs to the `sys.path`. If there are two versions of the same .egg in the directory, I want to add only the latest one.
I have a regular expression `r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$` to extract the name and version from the filename. The prob... | setuptools defines `parse_version()`. This implements [PEP 0440 -- Version Identification](https://www.python.org/dev/peps/pep-0440/) and is also able to parse versions that don't follow the PEP. This function is used by `easy_install` and [`pip`](https://github.com/pypa/pip/blob/fc5746a34cc39d5bb890bad079896d42e61008e... |
Should PostgreSQL connections be pooled in a Python web app, or create a new connection per request? | 11,889,104 | 7 | 2012-08-09T17:48:32Z | 11,889,157 | 9 | 2012-08-09T17:51:43Z | [
"python",
"postgresql",
"web-applications",
"flask",
"psycopg2"
] | I'm building a web app in Python (using Flask). I do not intend to use SQLAlchemy or similar ORM system, rather I'm going to use Psycopg2 directly.
Should I open a new database connection (and subsequently close it) for each new request? Or should I use something to pool these connections? | PgBouncer is pretty neat and transparent to the application and server.
We have been using PgBouncer in production for 2 years without a single issue. It's a pretty awesome PostgreSQL connection pooler.
<http://wiki.postgresql.org/wiki/PgBouncer> |
Is this is an efficient and pythonic way to see if any item in an iterable is true for a certain attribute? | 11,889,134 | 5 | 2012-08-09T17:50:26Z | 11,889,154 | 12 | 2012-08-09T17:51:38Z | [
"python"
] | Say you have an iterable sequence of `thing` objects called `things`. Each `thing` has a method `is_whatever()` that returns True if it fulfills the "whatever" criteria. I want to efficiently find out if any item in `things` is whatever.
This is what I'm doing now:
```
any_item_is_whatever = True in (item.is_whatever... | You should use the built-in function `any()`:
```
any_item_is_whatever = any(item.is_whatever() for item in items)
``` |
Converting data to missing in pandas | 11,889,474 | 10 | 2012-08-09T18:12:21Z | 11,889,488 | 8 | 2012-08-09T18:13:34Z | [
"python",
"numpy",
"pandas"
] | I have a DataFrame with a mix of 0's and other numbers. I would like to convert the 0's to missing.
For example, I am looking for the command that would convert
```
In [618]: a=DataFrame(data=[[1,2],[0,1],[1,2],[0,0]])
In [619]: a
Out[619]:
0 1
0 1 2
1 0 1
2 1 2
3 0 0
```
to
```
In [619]: a
Out[619]: ... | Just do `from numpy import nan`. (You will have to convert your DataTable to float type, because you can't use `NaN` in integer arrays.) |
Making custom containers work with **kwargs (how does Python expand the args?) | 11,890,066 | 14 | 2012-08-09T18:53:06Z | 11,890,526 | 9 | 2012-08-09T19:23:34Z | [
"python"
] | I have a custom container class in Python 2.7, and everything works as expected *except* if I pass try to expand an instance as `**kwargs` for a function:
```
cm = ChainableMap({'a': 1})
cm['b'] = 2
assert cm == {'a': 1, 'b': 2} # Is fine
def check_kwargs(**kwargs):
assert kwargs == {'a': 1, 'b': 2}
check_kwargs(**... | When creating a keyword argument dictionary, the behavior is the same as passing your object into the `dict()` initializer, which results in the dict `{'b': 2}` for your `cm` object:
```
>>> cm = ChainableMap({'a': 1})
>>> cm['b'] = 2
>>> dict(cm)
{'b': 2}
```
A more detailed explanation of why this is the case is be... |
Is there an equivalent of the Python range function in MATLAB? | 11,890,437 | 6 | 2012-08-09T19:17:11Z | 11,890,470 | 11 | 2012-08-09T19:19:56Z | [
"python",
"matlab"
] | Is there an equivalent MATLAB function for the `range()` function in Python?
I'd really like to be able to type something like `range(-10, 11, 5)` and get back `[-10, -5, 0, 5, 10]` instead of having to write out the entire range by hand. | Yes, there is the `:` operator. The command `-10:5:11` would produce the vector `[-10, -5, 0, 5, 10];` |
Find all references to an object in python | 11,891,755 | 10 | 2012-08-09T20:51:33Z | 11,891,904 | 9 | 2012-08-09T21:02:28Z | [
"python",
"django",
"memory-leaks",
"garbage-collection"
] | **What is a good way to find all of the references to an object in python?**
The reason I ask is that it looks like we have a "memory leak". We are uploading image files to the server from a web browser. Each time we do this, the memory usage goes up on the server goes up proportionately to the size of the file that w... | Python's standard library has `gc` module containing garbage collector API. One of the function you possible want to have is
```
gc.get_objects()
```
This function returns list of all objects currently tracked by garbage collector. The next step is to analyze it.
If you know the object you want to track you can use ... |
gunicorn import error on heroku | 11,892,277 | 11 | 2012-08-09T21:34:11Z | 27,941,408 | 7 | 2015-01-14T11:04:58Z | [
"python",
"heroku",
"flask",
"wsgi",
"gunicorn"
] | I cannot run gunicorn on heroku with simple flask app
the application is really simple, this app.py
```
app = Flask(__name__)
@app.route("/")
def say_hello(url):
return "Hello"
if __name__ == "__main__":
port = int(os.environ.get('PORT', 8888))
app.run(host='0.0.0.0',port=port)
```
the app works fine t... | In my case, I got this error by having a `gunicorn.py` file in my top level folder. This clashed with the installed gunicorn library on Heroku.
So my run command that caused the problem was:
```
gunicorn -c gunicorn.py myapp:main
```
Raising the following error:
```
Traceback (most recent call last):
File "/app/.... |
Filtering a list based on a second list | 11,892,337 | 2 | 2012-08-09T21:38:26Z | 11,892,365 | 7 | 2012-08-09T21:40:14Z | [
"python"
] | Here is what is probably a simple question, but I wasn't able to find a straightforward answer for on my own.
Given two lists, one with only a list of ids, the other with all data, including some ids that we don't care about:
`all_data = [['abc', 123], ['cde', 234], ['fgh', 345]]`
`ids = ['abc', 'fgh']`
what i... | Use a list comprehension where the conditional checks for membership in a set:
```
>>> all_data = [['abc', 123], ['cde', 234], ['fgh', 345]]
>>> ids = ['abc', 'fgh']
>>> id_set = set(ids)
>>> [s for s in all_data if s[0] in id_set]
[['abc', 123], ['fgh', 345]]
``` |
Filtering a list based on a second list | 11,892,337 | 2 | 2012-08-09T21:38:26Z | 11,892,371 | 7 | 2012-08-09T21:40:41Z | [
"python"
] | Here is what is probably a simple question, but I wasn't able to find a straightforward answer for on my own.
Given two lists, one with only a list of ids, the other with all data, including some ids that we don't care about:
`all_data = [['abc', 123], ['cde', 234], ['fgh', 345]]`
`ids = ['abc', 'fgh']`
what i... | Edited after the comment, I meant to use a set.
As Raymond suggests in his answer use a list comprehension :) with a set for ids.
```
all_data = [['abc', 123], ['cde', 234], ['fgh', 345]]
ids = set(['abc', 'fgh'])
filtered_data = [x for x in all_data if x[0] in ids]
``` |
Matlab vs Python: Reshape | 11,892,358 | 13 | 2012-08-09T21:39:54Z | 11,893,174 | 17 | 2012-08-09T22:54:32Z | [
"python",
"matlab",
"matrix",
"numpy",
"scipy"
] | So I found [this](http://www.scipy.org/NumPy_for_Matlab_Users/#line-206):
> When converting MATLAB code it might be necessary to first reshape a
> matrix to a linear sequence, perform some indexing operations and then
> reshape back. As reshape (usually) produces views onto the same
> storage, it should be possible to... | Example:
### MATLAB:
```
>> mafs = [(1:16)' (17:32)']
mafs =
1 17
2 18
3 19
4 20
5 21
6 22
7 23
8 24
9 25
10 26
11 27
12 28
13 29
14 30
15 31
16 32
>> reshape(mafs,[4 4 2])
ans(:,:,1) =
1 ... |
Already installed pyzmq but still getting "ImportError: No module named zmq" | 11,892,497 | 7 | 2012-08-09T21:51:28Z | 11,892,665 | 13 | 2012-08-09T22:06:02Z | [
"python",
"ipython"
] | I am trying to get ipython notebook run.
I already installed pyzmq.
Do you know why it's still giving this error? | The only reason you would be seeing that error (having manually installed pyzmq) is if pyzmq was installed to a different pythonpath than where ipython is running from.
If you followed the install instructions, you should have no problems:
```
easy_install ipython pyzmq tornado
# or
pip install ipython pyzmq tornado
... |
Python StringIO and compatibility with `with' statement (context manager) | 11,892,623 | 24 | 2012-08-09T22:02:29Z | 11,892,712 | 36 | 2012-08-09T22:10:49Z | [
"python",
"with-statement",
"contextmanager"
] | I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below.
What I want to do is not have to write to disk with some content that I generate in order to use this legacy function, so I though I could use StringIO to creat... | A `StringIO` instance *is* an open file already. The `open` command, on the other hand, only takes filenames, to return an open file. A `StringIO` instance is not suitable as a filename.
Also, you don't need to close a `StringIO` instance, so there is no need to use it as a context manager either.
If all your legacy ... |
How to "log in" to a website using Python's Requests module? | 11,892,729 | 31 | 2012-08-09T22:12:14Z | 11,892,838 | 11 | 2012-08-09T22:21:48Z | [
"python",
"python-requests",
"pyquery"
] | I am trying to post a request to log in to a website using the Requests module in Python but its not really working. I'm new to this...so I can't figure out if I should make my Username and Password cookies or some type of HTTP authorization thing I found (??).
```
from pyquery import PyQuery
import requests
url = 'h... | ## If the information you want is on the page you are directed to immediately after login...
Lets call your `ck` variable `payload` instead, like in the [python-requests](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) docs:
```
payload = {'inUserName': 'USERNAME/EMAIL', 'in... |
How to "log in" to a website using Python's Requests module? | 11,892,729 | 31 | 2012-08-09T22:12:14Z | 17,633,072 | 94 | 2013-07-13T18:32:18Z | [
"python",
"python-requests",
"pyquery"
] | I am trying to post a request to log in to a website using the Requests module in Python but its not really working. I'm new to this...so I can't figure out if I should make my Username and Password cookies or some type of HTTP authorization thing I found (??).
```
from pyquery import PyQuery
import requests
url = 'h... | I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:
Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the use... |
How to "log in" to a website using Python's Requests module? | 11,892,729 | 31 | 2012-08-09T22:12:14Z | 28,628,617 | 13 | 2015-02-20T12:07:52Z | [
"python",
"python-requests",
"pyquery"
] | I am trying to post a request to log in to a website using the Requests module in Python but its not really working. I'm new to this...so I can't figure out if I should make my Username and Password cookies or some type of HTTP authorization thing I found (??).
```
from pyquery import PyQuery
import requests
url = 'h... | Let me try to make it simple, suppose URL of the site is <http://example.com/> and let's suppose you need to sign up by filling username and password, so we go to the login page say <http://example.com/login.php> now and view it's source code and search for the action URL it will be in form tag something like
```
<fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.