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 |
|---|---|---|---|---|---|---|---|---|---|
How can I attach a pyplot function to a figure instance? | 14,254,379 | 10 | 2013-01-10T09:19:06Z | 14,261,698 | 15 | 2013-01-10T15:46:17Z | [
"python",
"numpy",
"matplotlib"
] | Previously, I had a problem with the [interference between multiple Matplotlib figures](http://stackoverflow.com/questions/7673444/avoid-interference-between-multiple-matplotlib-figures-on-the-web). Finally i got tracked that to an issue that some pyplot functions do not attach to their figure instance but can be rende... | As a bit of explanation of what is going on here, `matplotlib` has two semi-independent interfaces; the state machine and the OO interface.
The state machine code is designed for working in an interactive shell (and mimics matlab's interface). It does this by wrapping the OO interface in a set of commands that keep tr... |
Catching DoesNotExist exception in a custom manager in Django | 14,255,125 | 28 | 2013-01-10T09:59:33Z | 14,261,163 | 50 | 2013-01-10T15:18:48Z | [
"python",
"django",
"exception",
"django-custom-manager"
] | I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:
```
class TaskManager(models.Manager):
def task_depend_tree(self, *args, **kwargs):
if "id" in kwargs:
try:
tas... | Try either using `ObjectDoesNotExist` instead of `DoesNotExist` or possibly `self.DoesNotExist`. If all else fails, just try and catch a vanilla `Exception` and evaluate it to see it's type().
`from django.core.exceptions import ObjectDoesNotExist` |
Catching DoesNotExist exception in a custom manager in Django | 14,255,125 | 28 | 2013-01-10T09:59:33Z | 23,460,817 | 7 | 2014-05-04T19:46:48Z | [
"python",
"django",
"exception",
"django-custom-manager"
] | I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:
```
class TaskManager(models.Manager):
def task_depend_tree(self, *args, **kwargs):
if "id" in kwargs:
try:
tas... | As panchicore suggested, `self.model` is the way to go.
```
class TaskManager(models.Manager):
def task_depend_tree(self, *args, **kwargs):
if "id" in kwargs:
try:
task = self.get(id=kwargs["id"])
except self.model.DoesNotExist:
raise Http404
``` |
How to check if an RSS feed has been updated in Python? | 14,256,745 | 10 | 2013-01-10T11:20:11Z | 14,256,849 | 9 | 2013-01-10T11:25:26Z | [
"python",
"rss",
"feedparser"
] | I am using the feedparser library in Python to get the various details from an RSS feed. Suppose I have pulled out 25 headlines titles from an RSS feed of a news channel. After an hour I run the feedparser command again to get the latest list of the titles of the 25 new headlines. The list might or not be updated the s... | Each feed item has an identifier, in `item.id`. Track those, together with their `.updated` (or `.updated_parsed`) entry, to check for new items.
So, see if you already have seen the item (via `item.id`) or if it has been updated since the last time you checked (via `item.updated` or `item.updated_parsed`).
Do make s... |
Expand multiple selection to all suggestions (boxes,hints) in Sublime Text 2 | 14,256,830 | 12 | 2013-01-10T11:24:14Z | 14,361,623 | 12 | 2013-01-16T15:15:50Z | [
"python",
"plugins",
"editor",
"selection",
"sublimetext2"
] | I am wondering if there already exists a way to expand selection to all areas suggested by Sublime Text 2 boxes, so one does not have to keep pressing `Ctrl`-`D` and sometimes `Ctrl`-`K`-`D` as shown in [Skip Ctrl+D selection in Sublime Text 2](http://stackoverflow.com/questions/11548308/skip-ctrld-selection-in-sublime... | You can click before or after any '2' and then select all 2's with `Atl`+`F3` on Windows and Linux or `Ctrl`+`â`+`G` on OS X. |
Expand multiple selection to all suggestions (boxes,hints) in Sublime Text 2 | 14,256,830 | 12 | 2013-01-10T11:24:14Z | 14,427,145 | 7 | 2013-01-20T17:26:52Z | [
"python",
"plugins",
"editor",
"selection",
"sublimetext2"
] | I am wondering if there already exists a way to expand selection to all areas suggested by Sublime Text 2 boxes, so one does not have to keep pressing `Ctrl`-`D` and sometimes `Ctrl`-`K`-`D` as shown in [Skip Ctrl+D selection in Sublime Text 2](http://stackoverflow.com/questions/11548308/skip-ctrld-selection-in-sublime... | I did the following, for such cases:
Put an entry in `Key bindings - User`:
```
{ "keys": ["alt+s"], "command": "toggle_in_selection", "context":
[
{ "key": "setting.is_widget", "operator": "equal", "operand": true }
]
},
```
Note: you can choose another key combination.
Then, select the text you wa... |
Skip the headers when editing a csv file using Python | 14,257,373 | 58 | 2013-01-10T11:54:38Z | 14,257,599 | 106 | 2013-01-10T12:07:53Z | [
"python",
"python-2.7",
"csv"
] | I am using below referred code to edit a csv using Python. Functions called in the code form upper part of the code.
Problem: I want the below referred code to start editing the csv from 2nd row, I want it to exclude 1st row which contains headers. Right now it is applying the functions on 1st row only and my header r... | Your `reader` variable is an iterable, by looping over it you retrieve the rows.
To make it skip one item before your loop, simply call [`next(reader, None)`](http://docs.python.org/2/library/functions.html#next) and ignore the return value.
You can also simplify your code a little; use the opened files as context ma... |
Skip the headers when editing a csv file using Python | 14,257,373 | 58 | 2013-01-10T11:54:38Z | 29,156,926 | 19 | 2015-03-19T23:37:41Z | [
"python",
"python-2.7",
"csv"
] | I am using below referred code to edit a csv using Python. Functions called in the code form upper part of the code.
Problem: I want the below referred code to start editing the csv from 2nd row, I want it to exclude 1st row which contains headers. Right now it is applying the functions on 1st row only and my header r... | Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.
Given "foo.csv" as follows:
```
FirstColumn,SecondColumn
asdf,1234
qwer,5678
```
Use DictReader like this:
```
import csv
with open('foo.csv') as f:
reader = csv.DictReader(f, delimite... |
Python BeautifulSoup: wildcard attribute/id search | 14,257,717 | 11 | 2013-01-10T12:14:57Z | 14,257,743 | 18 | 2013-01-10T12:16:20Z | [
"python",
"beautifulsoup"
] | I have this:
```
dates = soup.findAll("div", {"id" : "date"})
```
However, I need id to be a wildcard search since the `id` can be `date_1`, `date_2` etc. | You can provide a callable as a filter:
```
dates = soup.findAll("div", {"id" : lambda L: L and L.startswith('date')})
```
Or as @DSM points out
```
dates = soup.findAll("div", {"id" : re.compile('date.*')})
```
as BeautifulSoup will recognise a RegExp object and call its `.match()` method. |
Python: significance of -u option? | 14,258,500 | 4 | 2013-01-10T12:58:32Z | 14,258,511 | 9 | 2013-01-10T12:59:12Z | [
"python"
] | I am noticed in some python code that -u is used to start the python interpreter.
I looked at the man page for python but I could not get much out of it. Please give me some examples. | From `python --help`:
> ```
> -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
> see man page for details on internal buffering relating to '-u'
> ```
The manpage states:
> ```
> -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put std... |
Most Pythonic Way to Build Dictionary From Single List | 14,258,984 | 8 | 2013-01-10T13:25:59Z | 14,259,007 | 25 | 2013-01-10T13:26:57Z | [
"python",
"list",
"dictionary"
] | I have a list of day names (typically Monday-Saturday, though special cases apply) that I want to create a dictionary out of. I want to initialize the value of each day to zero.
If I had a list of zeroes the same length of the list of days, this would be a simple use case of `zip()`. However, a list of zeroes is a was... | Use the [`.fromkeys()` class method](http://docs.python.org/2/library/stdtypes.html#dict.fromkeys):
```
dayDict = dict.fromkeys(weekList, 0)
```
It builds a dictionary using the elements from the first argument (a sequence) as the keys, and the second argument (which defaults to `None`) as the value for all entries.
... |
Most Pythonic Way to Build Dictionary From Single List | 14,258,984 | 8 | 2013-01-10T13:25:59Z | 14,259,052 | 16 | 2013-01-10T13:29:15Z | [
"python",
"list",
"dictionary"
] | I have a list of day names (typically Monday-Saturday, though special cases apply) that I want to create a dictionary out of. I want to initialize the value of each day to zero.
If I had a list of zeroes the same length of the list of days, this would be a simple use case of `zip()`. However, a list of zeroes is a was... | Apart from `dict.fromkeys` you can also use `dict-comprehension`,
but `fromkeys()` is faster than dict comprehensions:
```
In [27]: lis = ['a', 'b', 'c', 'd']
In [28]: dic = {x: 0 for x in lis}
In [29]: dic
Out[29]: {'a': 0, 'b': 0, 'c': 0, 'd': 0}
```
For 2.6 and earlier:
```
In [30]: dic = dict((x, 0) for x in l... |
python querying wikipedia performance | 14,259,685 | 4 | 2013-01-10T14:03:34Z | 14,260,013 | 8 | 2013-01-10T14:21:21Z | [
"python",
"wikipedia"
] | I need to query wikipedia for just one very particular purpose, that is to to get the text for a given url. To be a little more precise:
I have about 14.000 wikipedia urls of the english corpus and I need to get the text, or at least the introduction of each of these urls. My further processing will be in python, so t... | Some thoughts:
> I have about 14.000 wikipedia urls of the english corpus and I need to get the text, or at least the introduction of each of these urls.
>
> 1 - get the xml dump and parse directly via python
There are currently 4,140,640 articles in the English Wikipedia. You're interested in 14,000 articles or abou... |
Unittesting cherrypy webapp | 14,260,101 | 9 | 2013-01-10T14:25:25Z | 14,261,070 | 17 | 2013-01-10T15:13:57Z | [
"python",
"unit-testing",
"cherrypy"
] | I recently had to rewrite our rest api, and made the switch from Flask to Cherrypy (mostly due to Python 3 compatibility). But now I'm stuck trying to write my unit tests, Flask has a really nifty built-in test client, that you can use to sent fake requests to your application (without starting a server.) I can't find ... | As far as I know, CherryPy doesn't indeed provide a facility for this type of testing (no running server). But it's fairly easy to do it nonetheless (though it relies on some of the internals of CherryPy).
Here's a simple showcase:
```
from StringIO import StringIO
import unittest
import urllib
import cherrypy
loca... |
How python-Levenshtein.ratio is computed | 14,260,126 | 12 | 2013-01-10T14:26:40Z | 14,260,774 | 13 | 2013-01-10T15:00:04Z | [
"python",
"levenshtein-distance"
] | According to the `python-Levenshtein.ratio` source:
<https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L722>
it's computed as `(lensum - ldist) / lensum`. This works for
```
distance('ab', 'a') = 1
ratio('ab', 'a') = 0.666666
```
However, it seems to break with
```
distance('ab', 'ac') = 1
r... | **Levenshtein distance** for `'ab'` and `'ac'` as below:

so alignment is:
```
a c
a b
```
Alignment length = 2
number of mismatch = 1
`Levenshtein Distance` is `1` because only one substitutions is required to transfer `ac` into `ab` (or reverse)
Distance ratio =... |
How python-Levenshtein.ratio is computed | 14,260,126 | 12 | 2013-01-10T14:26:40Z | 14,296,743 | 10 | 2013-01-12T18:46:02Z | [
"python",
"levenshtein-distance"
] | According to the `python-Levenshtein.ratio` source:
<https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L722>
it's computed as `(lensum - ldist) / lensum`. This works for
```
distance('ab', 'a') = 1
ratio('ab', 'a') = 0.666666
```
However, it seems to break with
```
distance('ab', 'ac') = 1
r... | By looking more carefully at the C code, I found that this apparent contradiction is due to the fact that `ratio` treats the "replace" edit operation differently than the other operations (i.e. with a cost of 2), whereas `distance` treats them all the same with a cost of 1.
This can be seen in the calls to the interna... |
Python: How to count how many lines in a file are the same | 14,260,406 | 4 | 2013-01-10T14:41:19Z | 14,260,441 | 12 | 2013-01-10T14:42:50Z | [
"python",
"file",
"count",
"comparison"
] | I have a text document in the format of:
```
-1+1
-1-1
+1+1
-1-1
+1-1
...
```
I want to have a program that counts how many lines have -1+1 lines and +1-1 lines. The program would then just need to return the value of how many lines are like this.
I have written the code:
```
f1 = open("results.txt", "r")
fileOne = ... | Use [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) instead:
```
import collections
with open('results.txt') as infile:
counts = collections.Counter(l.strip() for l in infile)
for line, count in counts.most_common():
print line, count
```
Most of all, remove whi... |
Python: How to count how many lines in a file are the same | 14,260,406 | 4 | 2013-01-10T14:41:19Z | 14,260,445 | 8 | 2013-01-10T14:43:07Z | [
"python",
"file",
"count",
"comparison"
] | I have a text document in the format of:
```
-1+1
-1-1
+1+1
-1-1
+1-1
...
```
I want to have a program that counts how many lines have -1+1 lines and +1-1 lines. The program would then just need to return the value of how many lines are like this.
I have written the code:
```
f1 = open("results.txt", "r")
fileOne = ... | The `.readlines()` leaves the `\n` in the lines, that's why they don't match. |
How to randomly generate decreasing numbers in Python? | 14,260,923 | 4 | 2013-01-10T15:06:50Z | 14,260,955 | 10 | 2013-01-10T15:08:36Z | [
"python",
"random",
"python-2.7",
"numbers"
] | I'm wondering if there's a way to generate decreasing numbers within a certain range?
I want to program to keep outputting until it reaches 0, and the highest number in the range must be positive.
For example, if the range is (0, 100), this could be a possible output:
96
57
43
23
9
0
Sorry for the confusion from my o... | I would generate a list of n random numbers then sort them highest to lowest. |
How do I write a function that returns another function? | 14,261,474 | 10 | 2013-01-10T15:34:44Z | 14,271,106 | 37 | 2013-01-11T03:17:45Z | [
"python",
"function",
"functional-programming",
"currying"
] | In Python, I'd like to write a function `make_cylinder_volume(r)` which returns another function. That returned function should be callable with a parameter `h`, and return the volume of a cylinder with height `h` and radius `r`.
I know how to return *values* from functions in Python, but how do I return *another func... | Try this, using Python:
```
import math
def make_cylinder_volume_func(r):
def volume(h):
return math.pi * r * r * h
return volume
```
Use it like this, for example with `radius=10` and `height=5`:
```
volume_radius_10 = make_cylinder_volume_func(10)
volume_radius_10(5)
=> 1570.7963267948967
```
Noti... |
How do I install the yaml package for Python? | 14,261,614 | 109 | 2013-01-10T15:42:03Z | 14,261,615 | 52 | 2013-01-10T15:42:03Z | [
"python",
"python-2.7",
"yaml",
"pip",
"pyyaml"
] | I have a Python program that uses YAML. I attempted to install it on a new server using `pip install yaml` and it returns the following:
```
$ sudo pip install yaml
Downloading/unpacking yaml
Could not find any downloads that satisfy the requirement yaml
No distributions at all found for yaml
Storing complete log in... | `pip install pyyaml`
If you don't have pip, run `easy_install pip` to install pip, which is the go-to package installer - [Why use pip over easy\_install?](http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install). If you prefer to stick with easy\_install, then `easy_install pyyaml` |
How do I install the yaml package for Python? | 14,261,614 | 109 | 2013-01-10T15:42:03Z | 14,262,462 | 183 | 2013-01-10T16:21:59Z | [
"python",
"python-2.7",
"yaml",
"pip",
"pyyaml"
] | I have a Python program that uses YAML. I attempted to install it on a new server using `pip install yaml` and it returns the following:
```
$ sudo pip install yaml
Downloading/unpacking yaml
Could not find any downloads that satisfy the requirement yaml
No distributions at all found for yaml
Storing complete log in... | You could try the search feature in pip,
```
$ pip search yaml
```
which looks for packages in PyPI with yaml in the short description. That reveals various packages, including PyYaml, yamltools, and PySyck, among others (Note that [PySyck docs](http://pyyaml.org/wiki/PySyck) recommend using PyYaml, since syck is out... |
How do I install the yaml package for Python? | 14,261,614 | 109 | 2013-01-10T15:42:03Z | 21,317,961 | 28 | 2014-01-23T19:49:22Z | [
"python",
"python-2.7",
"yaml",
"pip",
"pyyaml"
] | I have a Python program that uses YAML. I attempted to install it on a new server using `pip install yaml` and it returns the following:
```
$ sudo pip install yaml
Downloading/unpacking yaml
Could not find any downloads that satisfy the requirement yaml
No distributions at all found for yaml
Storing complete log in... | For MacOSX (mavericks), the following seems to work:
```
brew install libyaml
sudo python -m easy_install pyyaml
``` |
How to get the list with the higher sum of its elements | 14,262,112 | 2 | 2013-01-10T16:06:20Z | 14,262,184 | 7 | 2013-01-10T16:09:21Z | [
"python"
] | I was wondering if anyone could help me with a Python problem I have. I have four lists, each list holds floats (decimals). I'm adding all the floats that each list contains. The part I'm stuck on is I want to know which of the four list has a higher sum. I know I could use if statements but does anyone know a more of ... | use `max()`:
```
>>> max(foodmart,nike,gas_station,toy_store, key=sum)
>>> [42.2, 69.99]
```
`help()` on `max`:
> max(iterable[, key=func]) -> value
>
> max(a, b, c, ...[, key=func]) ->
> value
>
> With a single iterable argument, return its largest item. With two or
> more arguments, return the largest argument. |
loop through a certain type of file in a folder (python) | 14,262,405 | 6 | 2013-01-10T16:19:26Z | 14,262,451 | 10 | 2013-01-10T16:21:31Z | [
"python"
] | I'm trying to loop through only the csv files in a folder that contains many kinds of files and many folders, I just want it to list all of the .csv files in this folder.
Here's what I mean:
```
import os, sys
path = "path/to/dir"
dirs = os.listdir(path)
for file in dirs:
if file == '*.csv':
print file
... | Python provides [`glob`](http://docs.python.org/2/library/glob.html) which should do this
```
>>> import glob
>>> glob.glob('/path/to/dir/*.csv')
```
> Return a possibly-empty list of path names that match pathname, which
> must be a string containing a path specification. pathname can be
> either absolute (like /usr... |
loop through a certain type of file in a folder (python) | 14,262,405 | 6 | 2013-01-10T16:19:26Z | 14,262,502 | 13 | 2013-01-10T16:23:28Z | [
"python"
] | I'm trying to loop through only the csv files in a folder that contains many kinds of files and many folders, I just want it to list all of the .csv files in this folder.
Here's what I mean:
```
import os, sys
path = "path/to/dir"
dirs = os.listdir(path)
for file in dirs:
if file == '*.csv':
print file
... | Use the glob module: <http://docs.python.org/2/library/glob.html>
```
import glob
path = "path/to/dir/*.csv"
for fname in glob.glob(path):
print(fname)
``` |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 14,268,804 | 276 | 2013-01-10T22:57:22Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | I routinely use tens of gigabytes of data in just this fashion
e.g. I have tables on disk that I read via queries, create data and append back.
It's worth reading [the docs](http://pandas-docs.github.io/pandas-docs-travis/io.html#hdf5-pytables) and [late in this thread](https://groups.google.com/forum/m/?fromgroups#!t... |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 14,287,518 | 32 | 2013-01-11T22:11:52Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | This is the case for pymongo. I have also prototyped using sql server, sqlite, HDF, ORM (SQLAlchemy) in python. First and foremost pymongo is a document based DB, so each person would be a document (`dict` of attributes). Many people form a collection and you can have many collections (people, stock market, income).
p... |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 15,558,350 | 27 | 2013-03-21T21:19:30Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | I spotted this a little late, but I work with a similar problem (mortgage prepayment models). My solution has been to skip the pandas HDFStore layer and use straight pytables. I save each column as an individual HDF5 array in my final file.
My basic workflow is to first get a CSV file from the database. I gzip it, so ... |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 19,739,768 | 29 | 2013-11-02T07:14:07Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | If your datasets are between 1 and 20GB, you should get a workstation with 48GB of RAM. Then Pandas can hold the entire dataset in RAM. I know its not the answer you're looking for here, but doing scientific computing on a notebook with 4GB of RAM isn't reasonable. |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 20,690,383 | 46 | 2013-12-19T19:46:48Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | I think the answers above are missing a simple approach that I've found very useful.
When I have a file that is too large to load in memory, I break up the file into multiple smaller files (either by row or cols)
Example: In case of 30 days worth of trading data of ~30GB size, I break it into a file per day of ~1GB s... |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 27,282,644 | 31 | 2014-12-03T22:09:40Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | I know this is an old thread but I think the [Blaze](https://github.com/ContinuumIO/blaze) library is worth checking out. It's built for these types of situations.
**From the docs:**
Blaze extends the usability of NumPy and Pandas to distributed and out-of-core computing. Blaze provides an interface similar to that o... |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 29,910,919 | 7 | 2015-04-28T05:22:21Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | One more variation
Many of the operations done in pandas can also be done as a db query (sql, mongo)
Using a RDBMS or mongodb allows you to perform some of the aggregations in the DB Query (which is optimized for large data, and uses cache and indexes efficiently)
Later, you can perform post processing using pandas.... |
"Large data" work flows using pandas | 14,262,433 | 417 | 2013-01-10T16:20:32Z | 36,188,131 | 14 | 2016-03-23T20:30:53Z | [
"python",
"mongodb",
"pandas",
"large-data",
"hdf5"
] | I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I c... | There is now, two years after the question, an 'out-of-core' pandas equivalent: [dask](http://dask.pydata.org/en/latest/). It is excellent! Though it does not support all of pandas functionality, you can get really far with it. |
Numpy: Get random set of rows from 2D array | 14,262,654 | 34 | 2013-01-10T16:30:47Z | 14,262,743 | 36 | 2013-01-10T16:35:09Z | [
"python",
"numpy"
] | I have a very large 2D array which looks something like this:
```
a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
```
Using numpy, is there an easy way to get a new 2D array with e.g. 2 random rows from the initial array a (without replacement)?
e.g.
```
b=
[[a4, b4, c4],
[a99, b99, c99]]
``` | ```
>>> A=np.random.randint(5,size=(10,3))
>>> A
array([[1, 3, 0],
[3, 2, 0],
[0, 2, 1],
[1, 1, 4],
[3, 2, 2],
[0, 1, 0],
[1, 3, 1],
[0, 4, 1],
[2, 4, 2],
[3, 3, 1]])
>>> B=np.random.randint(10,size=2)
>>> B
array([7, 6])
>>> A[B,:]
array([[0, 4, 1],
... |
Numpy: Get random set of rows from 2D array | 14,262,654 | 34 | 2013-01-10T16:30:47Z | 27,815,343 | 11 | 2015-01-07T08:37:04Z | [
"python",
"numpy"
] | I have a very large 2D array which looks something like this:
```
a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
```
Using numpy, is there an easy way to get a new 2D array with e.g. 2 random rows from the initial array a (without replacement)?
e.g.
```
b=
[[a4, b4, c4],
[a99, b99, c99]]
``` | This is an old post, but this is what works best for me:
```
A[np.random.choice(A.shape[0], num_rows_2_sample)]
``` |
Numpy: Get random set of rows from 2D array | 14,262,654 | 34 | 2013-01-10T16:30:47Z | 31,794,767 | 10 | 2015-08-03T18:58:14Z | [
"python",
"numpy"
] | I have a very large 2D array which looks something like this:
```
a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
```
Using numpy, is there an easy way to get a new 2D array with e.g. 2 random rows from the initial array a (without replacement)?
e.g.
```
b=
[[a4, b4, c4],
[a99, b99, c99]]
``` | Another option is to create a random mask if you just want to down-sample your data by a certain factor. Say I want to down-sample to 25% of my original data set, which is currently held in the array `data_arr`:
```
# generate random boolean mask the length of data
# use p 0.75 for False and 0.25 for True
mask = numpy... |
Why am I suddenly getting "OperationalError: no such table"? | 14,262,771 | 5 | 2013-01-10T16:36:19Z | 14,262,955 | 8 | 2013-01-10T16:45:03Z | [
"python",
"sqlite",
"sqlite3"
] | I am trying to do various things with my database. I've connected and pulled data out and out data in, successfully, no problems. I've been debugging other issues, and then suddenly I can no longer get anything from my database table - I'm getting "OperationalError: no such table: article".
I'm really stumped here - t... | did you moved your code to another place?
because sqlite store the database into a file, when you call connect, if a file with the name `'mydatabase'` exist, it will be loaded, otherwise. a new fresh database file will be created automatically.
search for your old file with name `'mydatabase'` and put it within your ... |
Best practices for Python if-elif-elif-elif when dispatching requests | 14,263,427 | 6 | 2013-01-10T17:12:18Z | 14,263,486 | 13 | 2013-01-10T17:15:39Z | [
"python",
"if-statement",
"dispatch"
] | I have 5 sets of request's categories defined as python dicts, for example:
```
category1 = {'type1', 'type2', 'type3'}
category2 = {'type4', 'type5'}
category3 = {'type6', 'type7', 'type8', 'type9'}
category4 = {'type10', 'type11'}
category5 = {'type12', 'type13', 'type14'}
```
And I need to handle requests using th... | If `request_type` can be present in more than one category, you could use a tuple to loop through them in priority order:
```
categories = (
(category1, dispatch1method),
(category2, dispatch2method),
(category3, dispatch3method),
(category4, dispatch4method),
(category5, dispatch5method),
)
next... |
Only add to a dict if a condition is met | 14,263,872 | 12 | 2013-01-10T17:34:39Z | 14,263,905 | 14 | 2013-01-10T17:36:16Z | [
"python",
"variables",
"dictionary",
"urllib"
] | I am using `urllib.urlencode` to build web POST parameters, however there are a few values I only want to be added if a value other than `None` exists for them.
```
apple = 'green'
orange = 'orange'
params = urllib.urlencode({
'apple': apple,
'orange': orange
})
```
That works fine, however if I make the `ora... | You'll have to add the key separately, after the creating the initial `dict`:
```
params = {'apple': apple}
if orange is not None:
params['orange'] = orange
params = urllib.urlencode(params)
```
Python has no syntax to define a key as conditional; you could use a dict comprehension if you already had everything i... |
Only add to a dict if a condition is met | 14,263,872 | 12 | 2013-01-10T17:34:39Z | 14,264,150 | 14 | 2013-01-10T17:51:53Z | [
"python",
"variables",
"dictionary",
"urllib"
] | I am using `urllib.urlencode` to build web POST parameters, however there are a few values I only want to be added if a value other than `None` exists for them.
```
apple = 'green'
orange = 'orange'
params = urllib.urlencode({
'apple': apple,
'orange': orange
})
```
That works fine, however if I make the `ora... | To piggyback on sqreept's answer, here's a subclass of `dict` that behaves as desired:
```
class DictNoNone(dict):
def __setitem__(self, key, value):
if key in self or value is not None:
dict.__setitem__(self, key, value)
d = DictNoNone()
d["foo"] = None
assert "foo" not in d
```
This will a... |
python - beautifulsoup - TypeError: sequence item 0: expected string, Tag found | 14,264,102 | 2 | 2013-01-10T17:48:25Z | 14,264,141 | 8 | 2013-01-10T17:51:01Z | [
"python",
"beautifulsoup"
] | I'm using beautifulsoup to extract images and links from a html string. It all works perfectly fine, however with some links that have a tag in the link contents it is throwing an error.
Example Link:
```
<a href="http://www.example.com"><strong>Link Text</strong></a>
```
Python Code:
```
soup = BeautifulSoup(conte... | To grab just the text content of a tag, the [`element.get_text()` method](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text) lets you grab (stripped) text from the current element including tags:
```
print link.get_text(' ', strip=True)
```
The first argument is used to join all text elements, and sittin... |
syntax error on nonlocal statement in Python | 14,264,313 | 5 | 2013-01-10T18:00:58Z | 14,264,325 | 13 | 2013-01-10T18:01:43Z | [
"python",
"syntax-error",
"python-nonlocal"
] | I would like to test the example of the use of the nonlocal statement specified in the answer on [this](http://stackoverflow.com/questions/1261875/python-nonlocal-statement) question:
```
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
```... | `nonlocal` only works in Python 3; it is a [new addition to the language](http://docs.python.org/3/reference/simple_stmts.html#nonlocal).
In Python 2 it'll raise a syntax error; python sees `nonlocal` as part of an expression instead of a statement.
This specific example works just fine when you actually use the corr... |
Why does [].append() not work in python? | 14,265,589 | 8 | 2013-01-10T19:17:21Z | 14,265,608 | 12 | 2013-01-10T19:18:48Z | [
"python"
] | Why does this work -
```
a = []
a.append(4)
print a
```
But this does not -
```
print [].append(4)
```
The output in second case is `None`. Can you explain the output? | The `append` method has no return value. It changes the list in place, and since you do not assign the `[]` to any variable, it's simply "lost in space"
```
class FluentList(list):
def append(self, value):
super(FluentList,self).append(value)
return self
def extend(self, iterable):
sup... |
iterate over individual bytes in python3 | 14,267,452 | 12 | 2013-01-10T21:20:01Z | 14,267,935 | 12 | 2013-01-10T21:53:00Z | [
"python",
"python-3.x"
] | when iterating over a bytes object in python 3, one gets the individual bytes as ints:
```
>>> [b for b in b'123']
[49, 50, 51]
```
how to get 1-length bytes objects instead?
the following is possible, but not very obvious for the reader and most likely performs bad:
```
>>> [bytes([b]) for b in b'123']
[b'1', b'2'... | If you are concerned about performance of this code and an int as a byte is not suitable interface in your case then you should probably reconsider data structures that you use e.g., use `str` objects instead.
You could slice the bytes object to get 1-length bytes objects:
```
L = [bytes_obj[i:i+1] for i in range(len... |
How can I find the smallest power of 2 greater than n in Python | 14,267,555 | 2 | 2013-01-10T21:26:42Z | 14,267,825 | 14 | 2013-01-10T21:44:57Z | [
"python",
"python-2.7"
] | What is the simplest way to find the smallest power of 2 greater than a given n in python?
For example the smallest power of 2 greater than 6 is 8 | Since the OP apparently posted this just to give his own solution which he believes is faster than other ways to do it, let's test it:
```
import collections
import math
import timeit
def power_bit_length(x):
return 2**(x-1).bit_length()
def shift_bit_length(x):
return 1<<(x-1).bit_length()
def power_log(x)... |
Python list.remove() skips next element in list | 14,267,722 | 3 | 2013-01-10T21:37:14Z | 14,267,755 | 10 | 2013-01-10T21:39:41Z | [
"python"
] | Python, but not programming, newbie here. I'm programming with lists and have run into an interesting problem.
```
width = 2
height = 2
# Traverse the board
def traverse(x, y):
# The four possible directions
squares = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
print squares
# Remove impossible ... | The statement `for square in squares` just visits each item in the list in order: `squares[0]`, then `squares[1]`, then `squares[2]`, and so on until it runs out of squares.
Removing `squares[0]` shifts all the other items in the list to the left one slot; the original `squares[1]` is now `squares[0]`, so the for loop... |
Most efficient way to calculate pairwise similarity of 250k lists | 14,268,053 | 8 | 2013-01-10T22:00:23Z | 14,270,445 | 7 | 2013-01-11T01:55:54Z | [
"python",
"matrix"
] | I have 250,000 lists containing an average of 100 strings each, stored across 10 dictionaries. I need to calculate the pairwise similarity of all lists (the similarity metric isn't relevant here; but, briefly, it involves taking the intersection of the two lists and normalizing the result by some constant).
The code I... | Do you just want the most efficient way to determine the distance between any two points in your data?
Or do you actually need this *m x m* distance matrix that stores all pair-wise similarity values for all rows in your data?
Usually it's far more efficient to persist your data in some metric space,
using a data str... |
Why do casting rules differ between computers in python? | 14,269,164 | 16 | 2013-01-10T23:28:08Z | 14,270,230 | 15 | 2013-01-11T01:26:24Z | [
"python",
"osx",
"numpy"
] | I am running python 2.7 on my Mac, and I'm working on a group coding project with other people using Ubuntu. Every once and a while, code they write won't work on my computer due to casting rule errors:
```
273 # Apply column averages to image
--> 274 img[:middle] *= (bg[0]/np.tile(topCol, (middle,1)))
... | [This thread](http://mail.scipy.org/pipermail/numpy-discussion/2012-September/063915.html) suggests that your `numpy` is newer than the version your colleagues are using (please check using `numpy.version.version`). In the 1.7.0 development branch, it seems they've changed the implicit casting rule to the more strict `... |
The right way to find the size of text in wxPython | 14,269,880 | 3 | 2013-01-11T00:42:26Z | 14,269,981 | 7 | 2013-01-11T00:55:29Z | [
"python",
"wxpython",
"size",
"wxtextctrl"
] | I have an application I am developing in wxPython. Part of the application creates a large number of TextCtrls in a grid in order to enter four-letter codes for each day of the week for an arbitrarily large list of people.
I've managed to make it work, but I'm having to do something kludgy. Specifically, I haven't fou... | Create a wx.Font instance with the face, size, etc.; create a wx.DC; then call dc.GetTextExtent("a text string") on that to get the width and height needed to display that string. Set your row height and column width in the grid accordingly.
Something like:
```
font = wx.Font(...)
dc = wx.DC()
dc.SetFont(font)
w,h = ... |
Using yield with multiple ndb.get_multi_async | 14,269,894 | 8 | 2013-01-11T00:45:01Z | 14,314,031 | 10 | 2013-01-14T06:13:36Z | [
"python",
"google-app-engine",
"asynchronous",
"app-engine-ndb"
] | I am trying to improve efficiency of my current query from appengine datastore. Currently, I am using a synchronous method:
```
class Hospital(ndb.Model):
name = ndb.StringProperty()
buildings= ndb.KeyProperty(kind=Building,repeated=True)
class Building(ndb.Model):
name = ndb.StringProperty()
r... | using the given structures above, it is possible, and was confirmed that you can solve this with a set of tasklets. It is a **SIGNIFICANT** speed up over the iterative method.
```
@ndb.tasklet
def get_bed_info(bed_key):
bed_info = {}
bed = yield bed_key.get_async()
format and store bed information into bed... |
python matplotlib multiple bars | 14,270,391 | 16 | 2013-01-11T01:48:40Z | 14,270,539 | 10 | 2013-01-11T02:06:16Z | [
"python",
"matplotlib"
] | How to plot multiple bars in matplotlib, when i tried to call the bar function multiple times, they overlap and as seen the below figure the highest value red can be seen only.
How can I plot the multiple bars with dates on the x axes?
So far, i tried this:
```
import matplotlib.pyplot as plt
import datetime
x... | The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).
```
import numpy as np
imp... |
python matplotlib multiple bars | 14,270,391 | 16 | 2013-01-11T01:48:40Z | 14,270,596 | 19 | 2013-01-11T02:12:49Z | [
"python",
"matplotlib"
] | How to plot multiple bars in matplotlib, when i tried to call the bar function multiple times, they overlap and as seen the below figure the highest value red can be seen only.
How can I plot the multiple bars with dates on the x axes?
So far, i tried this:
```
import matplotlib.pyplot as plt
import datetime
x... | ```
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
x = [datetime.datetime(2011, 1, 4, 0, 0),
datetime.datetime(2011, 1, 5, 0, 0),
datetime.datetime(2011, 1, 6, 0, 0)]
x = date2num(x)
y = [4, 9, 2]
z=[1,2,3]
k=[11,12,13]
ax = plt.subplot(111)
ax.bar(x-0.2, y,width=0.2,... |
Get file size using python-requests, while only getting the header | 14,270,698 | 20 | 2013-01-11T02:27:19Z | 14,270,756 | 33 | 2013-01-11T02:32:49Z | [
"python",
"python-requests"
] | I have looked at the requests documentation, but I can't seem to find anything. How do I only request the header, so I can assess filesize? | Send a [HEAD request](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods):
```
>>> import requests
>>> response = requests.head('http://example.com')
>>> response.headers
{'connection': 'close',
'content-encoding': 'gzip',
'content-length': '606',
'content-type': 'text/html; charset=UTF-8'... |
Scrapy error "No module named cmdline" | 14,270,889 | 3 | 2013-01-11T02:50:01Z | 14,274,235 | 7 | 2013-01-11T08:25:57Z | [
"python",
"scrapy"
] | I've some problem with Scrapy on my mac, I checked many website to find an answer but I didn't find any good one.
Here's my error :
```
Traceback (most recent call last):
File "scrapy-ctl.py", line 6, in <module>
from scrapy.command.cmdline import execute
ImportError: No module named cmdline
```
I actually ... | It took a while to work out and involved searching the [scrapy github repository](https://github.com/scrapy/scrapy), but the [cmdline](https://github.com/scrapy/scrapy/blob/d788ba8a44e0538188872977a8705c1209a09194/scrapy/cmdline.py) module has moved. Instead of your current import, try this:
```
from scrapy.cmdline im... |
Beginner Python: Reading and writing to the same file | 14,271,216 | 12 | 2013-01-11T03:31:50Z | 14,271,376 | 14 | 2013-01-11T03:49:10Z | [
"python",
"io"
] | Started Python a week ago and I have some questions to ask about reading and writing to the same files. I've gone through some tutorials online but I am still confused about it. I can understand simple read and write files.
```
openFile = open("filepath", "r")
readFile = openFile.read()
print readFile
openFile = ope... | **Updated Response**:
This seems like a bug specific to Windows - <http://bugs.python.org/issue1521491>.
Quoting from the workaround explained at <http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html>
> the effect of mixing reads with writes on a file open for update is
> entirely undefined unle... |
calling rsync from python subprocess.call | 14,272,582 | 9 | 2013-01-11T06:01:33Z | 14,282,824 | 13 | 2013-01-11T16:50:17Z | [
"python",
"arguments",
"call",
"subprocess",
"rsync"
] | I'm trying to execute rsync over ssh from a subprocess in a python script to copy images from one server to another. I have a function defined as:
```
def rsyncBookContent(bookIds, serverEnv):
bookPaths = ""
if len(bookIds) > 1:
bookPaths = "{" + ",".join(("book_"+str(x)) for x in bookIds) + "}"
el... | Figured out my issues. My problems were the result of my misunderstanding of how the subprocess.call function executes and bash's expansion of lists inside curly braces.
When I was issuing the rsync command in a bash shell with subdirectories in curly braces, bash was really expanding that into multiple arguments whic... |
Which method should I use for accessing files and why? | 14,274,679 | 2 | 2013-01-11T08:59:32Z | 14,274,804 | 10 | 2013-01-11T09:08:30Z | [
"python",
"file"
] | I am in python and there is a lot of ways to access files.
***Method 1:***
```
fp = open("hello.txt", "w")
fp.write("No no no");
fp.close()
fp = open("hello.txt", "r")
print fp.read()
fp.close()
```
***Method 2:***
```
open("hello.txt", "w").write("hello world!")
print open("hello.txt", "r").read()
```
***Method ... | You should use the third method.
There is a common pattern in programming where to use some object you have set it up, run your code, and tear it down again. File handles are one example of this: you have to open the file, run your code, *and then close the file*. This last is not optional -- it's important for the op... |
Execute Twisted reactor.run() in a thread? | 14,274,916 | 4 | 2013-01-11T09:15:45Z | 14,282,640 | 13 | 2013-01-11T16:39:11Z | [
"python",
"cocoa",
"ubuntu",
"twisted"
] | I'm trying to make a Python library to use the Ubutu One API from Objective-C. Here is my source code:
<https://github.com/JoseExposito/U1-Finder-Plugin/blob/master/U1FinderLib/U1FinderLib.py>
I need to make many calls to the API, for this reason I need to have my reactor running once instead of run it and stop it, li... | Rather than running the reactor in a thread, you should use a reactor which integrates with the application you want to use it in.
For example, perhaps you want to use the [CoreFoundation reactor](http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html#auto14) (since your application uses Obj-C and... |
Python: remove odd number from a list | 14,275,118 | 5 | 2013-01-11T09:29:31Z | 14,275,269 | 8 | 2013-01-11T09:37:35Z | [
"python"
] | I wrote a function to remove odd number from a list, like that:
```
def remove_odd(l):
for i in l:
if i % 2 != 0:
l.remove(i)
print l
return l
remove_odd([4,5,4])
remove_odd([4,5,4,7,9,11])
remove_odd([4,5,4,7,9,11,12,13])
```
It returns:
```
[4, 4]
[4, 4, 9]
[4, 4, 9, 12]
```
-> wr... | Your function is working in another way than you would expect. The `for` loop takes first element, than second etc., so when you remove one element, others change their positions and can be skipped by it (and that happens in your case) when they are preceded by another odd number.
If you insist on using `.remove()` me... |
How to run celery as a daemon in production? | 14,275,821 | 10 | 2013-01-11T10:09:37Z | 14,276,580 | 14 | 2013-01-11T10:52:26Z | [
"python",
"django",
"celery"
] | i created a celeryd file in /etc/defaults/ from the code here:
<https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd>
Now when I want to run celeryd as a daemon and do this: sudo /etc/init.d/celerdy it says command not found. Where am I going wrong? | I am not sure what you are doing here but these are the steps to run celery as a daemon.
1. The file that you have referred in the link
<https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd>
needs to be copied in your `/etc/init.d` folder with the name
`celeryd`
2. Then you need to create a ... |
How to run celery as a daemon in production? | 14,275,821 | 10 | 2013-01-11T10:09:37Z | 16,470,913 | 9 | 2013-05-09T20:52:31Z | [
"python",
"django",
"celery"
] | i created a celeryd file in /etc/defaults/ from the code here:
<https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd>
Now when I want to run celeryd as a daemon and do this: sudo /etc/init.d/celerdy it says command not found. Where am I going wrong? | I found this link extremely usefull: [How to write an Ubuntu Upstart job for Celery (django-celery) in a virtualenv](http://stackoverflow.com/questions/10250682/how-to-write-an-ubuntu-upstart-job-for-celery-django-celery-in-a-virtualenv?rq=1)
tweaking it a bit.. I have a celery worker running using this script:
(usin... |
How to run celery as a daemon in production? | 14,275,821 | 10 | 2013-01-11T10:09:37Z | 16,470,997 | 7 | 2013-05-09T20:57:37Z | [
"python",
"django",
"celery"
] | i created a celeryd file in /etc/defaults/ from the code here:
<https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd>
Now when I want to run celeryd as a daemon and do this: sudo /etc/init.d/celerdy it says command not found. Where am I going wrong? | I generally use [supervisor](http://supervisord.org/) (plus [django-supervisor)](https://github.com/rfk/django-supervisor) for this purpose. That way, you don't need to figure out how to daemonize each process in your application (of which you have at least a webserver hosting django, plus celery, plus realistically wh... |
Creating random binary files | 14,275,975 | 11 | 2013-01-11T10:18:12Z | 14,276,423 | 23 | 2013-01-11T10:43:35Z | [
"python",
"random"
] | I'm trying to use python to create a random binary file. This is what I've got already:
```
f = open(filename,'wb')
for i in xrange(size_kb):
for ii in xrange(1024/4):
f.write(struct.pack("=I",random.randint(0,sys.maxint*2+1)))
f.close()
```
But it's terribly slow (0.82 seconds for size\_kb=1024 on my 3.... | IMHO - the following is completely redundant:
```
f.write(struct.pack("=I",random.randint(0,sys.maxint*2+1)))
```
There's absolutely no need to use `struct.pack`, just do something like:
```
import os
with open('output_file', 'wb') as fout:
fout.write(os.urandom(1024)) # replace 1024 with size_kb if not unreaso... |
HTML templating using Jinja2 - Lost | 14,276,829 | 4 | 2013-01-11T11:05:44Z | 18,380,147 | 7 | 2013-08-22T12:15:36Z | [
"python",
"html",
"templates",
"jinja2"
] | I am trying to create a html template in python using Jinja2. I have a templates folder with my 'template.html' but I don't know how to deal with environments or package loaders.
I installed Jinja2 using easy\_python and ran the following script.
```
from jinja2 import Environment, PackageLoader
env = Environment(loa... | I solved this problem using the following code:
```
env = Environment(loader=PackageLoader('scriptname',
templatesPath))
```
where this code is into the file `scriptname.py`.
I am not sure if my answer is relevant but I was wondering that perhaps someone may find this answer... |
Why is it possible to mix python indentation | 14,276,849 | 2 | 2013-01-11T11:07:03Z | 14,276,915 | 7 | 2013-01-11T11:10:34Z | [
"python",
"indentation"
] | I could not believe, but it is possible to mix tabs and spaces in python code:
```
if __name__ == '__main__':
for a in range(3): # indented with 4 spaces
print(a) # indented with 4 spaces and one tab
```
What is the reason behind this?
Tested on:
* Python 3.3.0 (CPython)
* Python 2.7.3 (CPython)
... | This is one of many myths about Python indentation.
What Python actually does, is look at relative indentation between lines, rather than fixed amounts.
* When indentation increases between lines, it considers it the start of a block and pushes the new indentation level on a stack.
* When indentation decreases, it po... |
Redirect back in Flask | 14,277,067 | 6 | 2013-01-11T11:18:44Z | 14,279,967 | 14 | 2013-01-11T14:15:43Z | [
"python",
"redirect",
"flask"
] | I have a DB Table called Item. Item has a `status` attribute, that can be either of
```
new
todo
doing
done
```
On my website I have two views showing tables of Item.
* View 1 shows **all** Items (with a status column).
* View 2 **only** shows Items with the status `todo`.
Depending on the Item status, there are ce... | I'm using the helper function which is recommended here: <http://flask.pocoo.org/docs/reqcontext/>
```
def redirect_url(default='index'):
return request.args.get('next') or \
request.referrer or \
url_for(default)
```
Use it in in the view
```
def some_view():
# some action
return r... |
How can I add textures to my bars and wedges? | 14,279,344 | 6 | 2013-01-11T13:37:40Z | 14,279,510 | 10 | 2013-01-11T13:48:45Z | [
"python",
"matplotlib"
] | I'm drawing several bar and pie charts using [`matplotlib.pyplot.bar()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar) and [`matplotlib.pyplot.pie()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie). In both functions, I can change the colors of the bars and wedges.
However, I need ... | With `bar()`, you can directly use hatches (with some backends): <http://matplotlib.org/examples/pylab_examples/hatch_demo.html>:

It works by adding the `hatch` argument to your call to `bar()`.
---
As for `pie()`, it does not have a `hatch` keyword. You c... |
How can I add textures to my bars and wedges? | 14,279,344 | 6 | 2013-01-11T13:37:40Z | 14,279,608 | 8 | 2013-01-11T13:55:38Z | [
"python",
"matplotlib"
] | I'm drawing several bar and pie charts using [`matplotlib.pyplot.bar()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar) and [`matplotlib.pyplot.pie()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie). In both functions, I can change the colors of the bars and wedges.
However, I need ... | ```
import matplotlib.pyplot as plt
fig = plt.figure()
patterns = [ "/" , "\\" , "|" , "-" , "+" , "x", "o", "O", ".", "*" ]
ax1 = fig.add_subplot(111)
for i in range(len(patterns)):
ax1.bar(i, 3, color='red', edgecolor='black', hatch=patterns[i])
plt.show()
```

for k, v in zip(key, data):
d[k].append(v)
print [(k, ' '.join(v)) for k, v in d.items()]
```
Output:
```
[('1', 'a'), ('3', 'd'), ('2', 'b c')]
```
And how to get new lists:
```
newkey, newvalue = d.keys(), [' '.join(v) for v in d.values()]
```
... |
world map without rivers with matplotlib / Basemap? | 14,280,312 | 14 | 2013-01-11T14:34:06Z | 14,282,100 | 7 | 2013-01-11T16:11:27Z | [
"python",
"matplotlib",
"maps",
"geography",
"matplotlib-basemap"
] | Would there be a way to plot the borders of the continents with Basemap (or without Basemap, if there is some other way), without those annoying rivers coming along? Especially that piece of Kongo River, not even reaching the ocean, is disturbing.
EDIT: I intend to further plot data over the map, like in the [Basemap ... | For reasons like this i often avoid Basemap alltogether and read the shapefile in with OGR and convert them to a Matplotlib artist myself. Which is alot more work but also gives alot more flexibility.
Basemap has some very neat features like converting the coordinates of input data to your 'working projection'.
If yo... |
Pylint False Positive E1101: Instance of 'Popen' has no 'poll' member | 14,280,372 | 7 | 2013-01-11T14:38:13Z | 14,280,373 | 7 | 2013-01-11T14:38:13Z | [
"python",
"static-analysis",
"abstract-syntax-tree",
"pylint"
] | Pylint is returning lots of false positives for the subprocess module:
```
E1101:184,7:resetboard: Instance of 'Popen' has no 'poll' member
E1101:188,4:resetboard: Instance of 'Popen' has no 'terminate' member
# etc.
```
How can I fix this? | This bug has been identified in the `logilab-astng` package:
<http://www.logilab.org/ticket/46273>
They have created a new side project called `pylint-brain` which will be a set of plugins and get included in `logilab-astng`. In the meantime, you can clone or download the latest code from here: <https://bitbucket.org/... |
Bulbflow: difference between neo4jserver Graph and neo4jserver Neo4jclient | 14,281,251 | 6 | 2013-01-11T15:25:00Z | 15,358,024 | 13 | 2013-03-12T09:55:10Z | [
"python",
"neo4j",
"cypher",
"bulbs",
"tinkerpop"
] | I am now trying to learn how to connect to Neo4j server and run Cypher queries on it using Bulbflow from Python. And the thing I do not understand is the difference between two possibilities to connect to the neo4j server:
1) [Graph](http://bulbflow.com/quickstart/#graph)
```
from bulbs.neo4jserver import Graph
g = G... | [Bulbs](http://bulbflow.com) supports three different graph database servers -- [Neo4j Server](http://www.neo4j.org/), [Rexster](http://www.tinkerpop.com/), and now [Titan](http://thinkaurelius.github.com/titan/).
Code specific to each backend server is contained within its own Python package (directory). You should s... |
Call a python unittest from another script and export all the error messages | 14,282,783 | 4 | 2013-01-11T16:48:24Z | 14,282,837 | 9 | 2013-01-11T16:50:55Z | [
"python",
"unit-testing"
] | Sorry for the basic question. I have used unittest method to check my models in one script. Now, my question is how do I call this script from another file and save testing results. Below is my code sample:
```
**model_test.py**
import unittest
import model_eq #script has models
class modelOutputTest(unittest.TestCa... | You need to use a `test runner`
> test runner
> A test runner is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.
```
from unittest.case i... |
How to increase node spacing for networkx.spring_layout | 14,283,341 | 6 | 2013-01-11T17:19:50Z | 17,290,356 | 11 | 2013-06-25T06:16:53Z | [
"python",
"graph",
"networkx",
"graph-drawing"
] | Drawing a clique graph with
```
import networkx as nx
....
nx.draw(G, layout=nx.spring_layout(G))
```
produces the following picture:

Obviously, the spacing between the nodes (e.g., the edge length) needs to be increased. I've googled this and foun... | Alright, my answer is too late for this question. But the solution to this problem lies in the NetworkX version 1.8 which is yet to be released, but is available via git hub.
Do the following to increase the distance between nodes:
```
pos = nx.spring_layout(G,k=0.15,iterations=20)
# k controls the distance b... |
Python: What is the difference between these two import statements? | 14,284,141 | 4 | 2013-01-11T18:10:47Z | 14,284,188 | 9 | 2013-01-11T18:13:22Z | [
"python",
"import",
"tuples"
] | They both functionally looks same to me. Are there any differences and advantages of using one over another?
```
>>> from datetime import datetime, timedelta
>>> from datetime import (datetime, timedelta)
``` | If you wrap the imports in parens, you don't have to use a backslash for line continuation if you put a line break in the import statement, which is the preferred style. Functionally, they are identical, and if on one line, leaving out the parens is cleaner. |
Python: What is the difference between these two import statements? | 14,284,141 | 4 | 2013-01-11T18:10:47Z | 14,284,196 | 7 | 2013-01-11T18:13:43Z | [
"python",
"import",
"tuples"
] | They both functionally looks same to me. Are there any differences and advantages of using one over another?
```
>>> from datetime import datetime, timedelta
>>> from datetime import (datetime, timedelta)
``` | Both of them are same:
```
In [17]: import dis
In [18]: def func1():
....: from datetime import datetime, timedelta
....:
In [19]: def func2():
....: from datetime import (datetime, timedelta)
....:
In [20]: dis.dis(func1)
2 0 LOAD_CONST 1 (-1)
3... |
Why doesn't Python recognize my utf-8 encoded source file? | 14,284,269 | 6 | 2013-01-11T18:18:46Z | 14,284,404 | 14 | 2013-01-11T18:26:53Z | [
"python",
"python-3.x",
"encoding",
"utf-8"
] | Here is a little tmp.py with a non ASCII character:
```
if __name__ == "__main__":
s = 'Ã'
print(s)
```
Running it I get the following error:
```
Traceback (most recent call last):
File ".\tmp.py", line 3, in <module>
print(s)
File "C:\Python32\lib\encodings\cp866.py", line 19, in encode
return ... | The encoding your [terminal is using](http://en.wikipedia.org/wiki/Code_page_866) doesn't support that character:
```
>>> '\xdf'.encode('cp866')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/cp866.py"... |
Stopping threads spawned by BaseHTTPServer using ThreadingMixin | 14,284,936 | 4 | 2013-01-11T19:02:50Z | 14,285,036 | 7 | 2013-01-11T19:10:50Z | [
"python",
"multithreading",
"python-2.7",
"basehttpserver"
] | I have read on here on [this post](http://stackoverflow.com/a/2398283/1291411) that using `ThreadingMixin` (from the `SocketServer` module), you are able to create a threaded server with `BaseHTTPServer`. I have tried it, and it *does* work. However, how can I stop active threads spawned by the server (for example, dur... | The simplest solution is to just use `daemon_threads`. The short version is: just set this to True, and don't worry about it; when you quit, any threads still working will stop automatically.
As the [`ThreadingMixIn` docs](http://docs.python.org/2/library/socketserver.html) say:
> When inheriting from ThreadingMixIn ... |
How do I refactor 100s of Class Methods in Python? | 14,287,935 | 9 | 2013-01-11T22:50:00Z | 14,287,995 | 11 | 2013-01-11T22:55:09Z | [
"python"
] | I am working on some legacy code (created by someone in love with spaghetti code) that has over 150 getters and over 150 setters. The getters look like this:
```
def GetLoadFee(self):
r_str = ""
if len(self._LoadFee) > 20:
r_str = self._LoadFee[:20]
else:
r_str = self._LoadFee.strip()
r... | ```
def make_generic_getter(name, maxlen):
def getter(self):
value = getattr(self, name)
r_str = ""
if len(value) > maxlen:
r_str = value[:maxlen]
else:
r_str = value.strip()
return r_str.strip()
return getter
```
Now, you can do this:
```
class ... |
Interact with other programs using Python | 14,288,177 | 12 | 2013-01-11T23:13:18Z | 14,288,361 | 16 | 2013-01-11T23:32:24Z | [
"python",
"automation",
"concept"
] | I'm having the idea of writing a program using Python which shall find a lyric of a song whose name I provided. I think the whole process should boil down to couple of things below. These are what I want the program to do when I run it:
* prompt me to enter a name of a song
* copy that name
* open a web browser (googl... | If what you're really looking into is a good excuse to teach yourself how to interact with other apps, this may not be the best one. Web browsers are messy, the timing is going to be unpredictable, etc. So, you've taken on a very hard taskâand one that would be very easy if you did it the usual way (talk to the serve... |
Interact with other programs using Python | 14,288,177 | 12 | 2013-01-11T23:13:18Z | 14,304,493 | 12 | 2013-01-13T14:35:54Z | [
"python",
"automation",
"concept"
] | I'm having the idea of writing a program using Python which shall find a lyric of a song whose name I provided. I think the whole process should boil down to couple of things below. These are what I want the program to do when I run it:
* prompt me to enter a name of a song
* copy that name
* open a web browser (googl... | The following script uses [Automa](http://www.getautoma.com "Automa") to do exactly what you want (tested on Word 2010):
```
def find_lyrics():
print 'Please minimize all other open windows, then enter the song:'
song = raw_input()
start("Google Chrome")
# Disable Google's autocompletion and set the la... |
Interact with other programs using Python | 14,288,177 | 12 | 2013-01-11T23:13:18Z | 14,338,006 | 8 | 2013-01-15T12:42:48Z | [
"python",
"automation",
"concept"
] | I'm having the idea of writing a program using Python which shall find a lyric of a song whose name I provided. I think the whole process should boil down to couple of things below. These are what I want the program to do when I run it:
* prompt me to enter a name of a song
* copy that name
* open a web browser (googl... | Here's an implementation in Python of [@Matteo Italia's comment](http://stackoverflow.com/questions/14288177/interact-with-other-programs-using-python/14338006#comment19842264_14288177):
> You are approaching the problem from a "user perspective" when you
> should approach it from a "programmer perspective"; you don't... |
Python: unicode in system commands | 14,288,379 | 3 | 2013-01-11T23:34:35Z | 14,288,946 | 10 | 2013-01-12T00:39:39Z | [
"python",
"unicode",
"encoding"
] | Suppose I have a mysterious unicode string in Python (2.7) that I want to feed to a command line program such as imagemagick (or really just get it *out* of Python in any way). The strings might be:
* Adolfo López Mateos
* StanisÅawa Walasiewicz
* Hermann Göring
So in Python I might make a little command like this... | Use [subprocess.call](http://docs.python.org/2/library/subprocess.html#subprocess.call) instead:
```
>>> s = u'Hermann Göring'
>>> import subprocess
>>> subprocess.call(['echo', s])
Hermann Göring
0
``` |
Not understanding why this won't sum up properly | 14,289,215 | 7 | 2013-01-12T01:20:39Z | 14,289,226 | 13 | 2013-01-12T01:22:10Z | [
"python"
] | ```
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(grades):
sum = 0
for i in grades:
sum += grades[i]
print(grades_sum(grades))
```
That's my code and I'm trying to understand why I'm getting an out of index traceback. | You don't need to do `grade[i]` because you're already referencing the elements in the list - all you need to do it replace that with a plain old `i`
However, there is already a builtin function for this - `sum`
```
print(sum(grades))
``` |
Not understanding why this won't sum up properly | 14,289,215 | 7 | 2013-01-12T01:20:39Z | 14,289,227 | 14 | 2013-01-12T01:22:13Z | [
"python"
] | ```
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(grades):
sum = 0
for i in grades:
sum += grades[i]
print(grades_sum(grades))
```
That's my code and I'm trying to understand why I'm getting an out of index traceback. | Iterating over a list will return the item in the list, not the index of the item. The correct code as you have written it would look like this:
```
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
```
Of course as others have answered this can be done much more ... |
How to use mmap in python when the whole file is too big | 14,289,421 | 9 | 2013-01-12T01:59:30Z | 14,289,444 | 16 | 2013-01-12T02:04:25Z | [
"python"
] | I have a python script which read a file line by line and look if each line matches a regular expression.
I would like to improve the performance of that script by using memory map the file before I search. I have looked into mmap example: <http://docs.python.org/2/library/mmap.html>
My question is how can I mmap a f... | First, the memory of your machine is irrelevant. It's the size of your process's [*address space*](http://en.wikipedia.org/wiki/Virtual_address_space) that's relevant. With a 32-bit Python, this will be somewhere under 4GB. With a 64-bit Python, it will be more than enough.
The reason for this is that [`mmap`](http://... |
Django: When To Use QuerySet None | 14,289,887 | 7 | 2013-01-12T03:22:19Z | 14,289,938 | 8 | 2013-01-12T03:30:17Z | [
"python",
"django"
] | Just came across this in the [django docs](https://docs.djangoproject.com/en/dev/ref/models/querysets/#none)
> Calling none() will create a queryset that never returns any objects
> and no query will be executed when accessing the results. A qs.none()
> queryset is an instance of EmptyQuerySet.
I build a lot of CRUD ... | Usually in instances where you need to provide a `QuerySet`, but there isn't one to provide - such as calling a method or to give to a template.
The advantage is if you *know* there is going to be no result (or don't want a result) and you still *need* one, `none()` will not hit the database.
For a non-realistic exam... |
Safely Using JSON with html inside of the JSON in Django Templates | 14,290,517 | 8 | 2013-01-12T05:21:05Z | 14,290,542 | 11 | 2013-01-12T05:25:00Z | [
"javascript",
"python",
"html",
"django"
] | How do you safely render JSON data in a django webapp?
On the server in django I generate JSON data and then render that JSON data in a django template. The JSON occasionally contains snippets of html. Most of the time, that's fine, however if the `</script>` tag is inside the JSON data when it is rendered, it destroy... | **Safely insert the JSON as a string, and then call JSON.parse on it**
Use [escapejs](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs) instead of safe. It is designed for outputting to JavaScript.
```
var the_json = '{{my_json|escapejs}}';
```
To get a JavaScript object you then need to call `... |
argument of type 'type' is not iterable | 14,292,292 | 4 | 2013-01-12T10:08:24Z | 14,292,311 | 9 | 2013-01-12T10:11:33Z | [
"python",
"django",
"django-templates",
"typeerror"
] | I have written this simple method that seems to be working fine in the terminal, but everytime I fire it up in the browser, I get: argument of type 'type' is not iterable.
```
def get_main(request):
t = get_template('main.html')
p = urllib2.urlopen("http://www.caltech.edu/news/rss.xml")
x = minidom.parseS... | You return `HttpResponse` without calling it; it's a class and thus not iterable.
Perhaps you meant to return `html` in the response?
```
return HttpResponse(html)
``` |
DAG(directed acyclic graph) dynamic job scheduler | 14,292,636 | 13 | 2013-01-12T10:55:57Z | 23,382,472 | 12 | 2014-04-30T07:48:35Z | [
"python",
"scheduling",
"etl",
"directed-acyclic-graphs",
"oozie"
] | I need to manage a large workflow of ETL tasks, which execution depends on time, data availability or an external event. Some jobs may fail during execution of the workflow and the system should have the ability to restart a failed workflow branch without waiting for whole workflow to finish execution.
Are there any f... | 1) You can give [dagobah](https://github.com/thieman/dagobah) a try, as described on its github page: Dagobah is a simple dependency-based job scheduler written in Python. Dagobah allows you to schedule periodic jobs using Cron syntax. Each job then kicks off a series of tasks (subprocesses) in an order defined by a de... |
Restarting thread in python. Why needs the instance to be recreated? | 14,293,368 | 7 | 2013-01-12T12:35:56Z | 14,293,432 | 9 | 2013-01-12T12:43:57Z | [
"python",
"multithreading"
] | Imagine the following classes:
```
Class Object(threading.Thread):
// some initialisation blabla
def run(self):
while True:
// do something
sleep(1)
class Checker():
def check_if_thread_is_alive(self):
o = Object()
o.start()
while True:
if not o.is_alive():
o.start()
... | The reason why threading.Thread is implemented that way is to keep correspondence between a thread object and operating system's thread. In major OSs threads can not be restarted, but you may create another thread **with another thread id**.
If recreation is a problem, there is no need to inherit your class from threa... |
What is the pythonic way to loop through two arrays at the same time? | 14,293,869 | 9 | 2013-01-12T13:40:54Z | 14,293,895 | 7 | 2013-01-12T13:44:43Z | [
"python"
] | If I have two arrays, of the same length - say `a` and `b`
`a = [4,6,2,6,7,3,6,7,2,5]`
`b = [6,4,6,3,2,7,8,5,3,5]`
normally, I would do this like so:
```
for i in range(len(a)):
print a[i] + b[i]
```
rather than something like this:
```
i=0
for number in a:
print number + b[i]
i += 1
```
because I pr... | A possible solution is using `zip`, as you mentioned yourself, but slightly differently than how you wrote it in the question:
```
for x, y in zip(a, b):
print x, y
```
Notice that the length of the list of tuples returned by `zip()` will be equal to the minimum between the lengths of `a` and `b`. This impacts wh... |
What is the pythonic way to loop through two arrays at the same time? | 14,293,869 | 9 | 2013-01-12T13:40:54Z | 14,293,953 | 11 | 2013-01-12T13:51:08Z | [
"python"
] | If I have two arrays, of the same length - say `a` and `b`
`a = [4,6,2,6,7,3,6,7,2,5]`
`b = [6,4,6,3,2,7,8,5,3,5]`
normally, I would do this like so:
```
for i in range(len(a)):
print a[i] + b[i]
```
rather than something like this:
```
i=0
for number in a:
print number + b[i]
i += 1
```
because I pr... | If the lists `a` and `b` are short, use [zip](http://docs.python.org/2/library/functions.html#zip) (as @Vincenzo Pii showed):
```
for x, y in zip(a, b):
print(x + y)
```
If the lists `a` and `b` are long, then use [itertools.izip](http://docs.python.org/2/library/itertools.html#itertools.izip) to save memory:
``... |
Extract information from Gmail with Python | 14,294,057 | 2 | 2013-01-12T14:04:10Z | 14,294,059 | 13 | 2013-01-12T14:04:10Z | [
"python",
"gmail",
"extract",
"imaplib"
] | I have come through solutions to **extract useful information from selected received emails in Gmail mailbox**.
Aim in this example is to fetch all mails sent from a newsletter providing monthly prices for petroleum. You can freely subscribe to such a newsletter on EIA website. All such newsletter arrive in same folde... | Python `email` library will help.
```
import email, getpass, imaplib, os, re
import matplotlib.pyplot as plt
```
This directory is where you will save attachments
```
detach_dir = "F:\OTHERS\CS\PYTHONPROJECTS"
```
Your script then asks user (or yourself) for account features
```
user = raw_input("Enter your GMail... |
Which setup is more efficient? Flask with pypy, or Flask with gevent? | 14,294,643 | 14 | 2013-01-12T15:10:33Z | 20,390,688 | 12 | 2013-12-05T03:12:20Z | [
"python",
"performance",
"gevent",
"pypy"
] | Both 'pypy' and 'gevent' are supposed to provide high performance. Pypy is supposedly faster than CPython, while gevent is based on co-routines and greenlets, which supposedly makes for a faster web server.
However, they're not compatible with each other.
I'm wondering which setup is more efficient (in terms of speed... | The short answer is: It's *faster* with PyPy, and it has *higher concurrency* with gevent.
It is possible to use gevent and PyPy simultaneously (we do this at PubNub for multiple projects) although it can be tricky. Starting with PyPy 2.2, a few patches are required to gevent on their socket implementation. We have an... |
What tools are available to auto-produce documentation for a REST API written in Flask? | 14,295,322 | 15 | 2013-01-12T16:24:48Z | 14,295,815 | 12 | 2013-01-12T17:19:12Z | [
"python",
"rest",
"documentation",
"flask"
] | I'm looking for a quick way to auto produce REST API docs from a Flask REST API I've written. Does anyone know of tools that can do this and how I would markup the code? | I would recommend you [Sphinx](http://sphinx-doc.org/), you add your documentation as `__doc__` and the `autodoc` module of Sphinx will generate the docs for you ([docs.python.org](http://docs.python.org/3/) also uses Sphinx). The Markup is `reST`, similiar to `Markdown`.
e.g.:
```
@app.route('/download/<int:id>')
de... |
What tools are available to auto-produce documentation for a REST API written in Flask? | 14,295,322 | 15 | 2013-01-12T16:24:48Z | 26,975,392 | 10 | 2014-11-17T14:55:09Z | [
"python",
"rest",
"documentation",
"flask"
] | I'm looking for a quick way to auto produce REST API docs from a Flask REST API I've written. Does anyone know of tools that can do this and how I would markup the code? | I really like [Swagger](https://helloreverb.com/developers/swagger) because it allows to generate an API documentation by just adding a few decorators and comments into your code. There is a [Flask Swagger](https://github.com/rantav/flask-restful-swagger) available.
```
from flask import Flask
from flask.ext.restful i... |
Convert string into datetime.time object | 14,295,673 | 24 | 2013-01-12T17:06:45Z | 14,295,709 | 46 | 2013-01-12T17:09:22Z | [
"python",
"time",
"python-datetime"
] | Given the `string` in this format `"HH:MM"`, for example `"03:55"`, that represents *3 hours and 55 minutes*.
I want to convert it to `datetime.time` object for easier manipulation. What would be the easiest way to do that? | Use [`datetime.datetime.strptime()`](http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime) and call [`.time()`](http://docs.python.org/2/library/datetime.html#datetime.datetime.time) on the result:
```
>>> datetime.datetime.strptime('03:55', '%H:%M').time()
datetime.time(3, 55)
```
The first argu... |
Convert string into datetime.time object | 14,295,673 | 24 | 2013-01-12T17:06:45Z | 14,295,726 | 7 | 2013-01-12T17:10:46Z | [
"python",
"time",
"python-datetime"
] | Given the `string` in this format `"HH:MM"`, for example `"03:55"`, that represents *3 hours and 55 minutes*.
I want to convert it to `datetime.time` object for easier manipulation. What would be the easiest way to do that? | ```
>>> datetime.time(*map(int, '03:55'.split(':')))
datetime.time(3, 55)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.