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 |
|---|---|---|---|---|---|---|---|---|---|
making matplotlib graphs look like R by default? | 14,349,055 | 49 | 2013-01-15T23:45:53Z | 14,349,766 | 39 | 2013-01-16T00:57:14Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | Is there a way to make `matplotlib` behave identically to R, or almost like R, in terms of plotting defaults? For example R treats its axes pretty differently from `matplotlib`. The following histogram

has "floating axes" with outward ticks, such that... | ### Edit 1 year later:
With `seaborn`, the example below becomes:
```
import numpy as np
import matplotlib.pyplot as plt
import seaborn
seaborn.set(style='ticks')
# Data to be represented
X = np.random.randn(256)
# Actual plotting
fig = plt.figure(figsize=(8,6), dpi=72, facecolor="white")
axes = plt.subplot(111)
hei... |
making matplotlib graphs look like R by default? | 14,349,055 | 49 | 2013-01-15T23:45:53Z | 14,351,567 | 27 | 2013-01-16T04:49:32Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | Is there a way to make `matplotlib` behave identically to R, or almost like R, in terms of plotting defaults? For example R treats its axes pretty differently from `matplotlib`. The following histogram

has "floating axes" with outward ticks, such that... | #
#
#
#
#
#
EDIT 10/14/2013:
For information, ggplot has now been implemented for python (built on matplotlib).
See this [blog](http://blog.yhathq.com/posts/ggplot-for-python.html) or go directly to the [github page](https://github.com/yhat/ggplot) of the project for more information and examples.
#
#
#
#
#
#
To my... |
making matplotlib graphs look like R by default? | 14,349,055 | 49 | 2013-01-15T23:45:53Z | 21,221,138 | 27 | 2014-01-19T18:56:42Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | Is there a way to make `matplotlib` behave identically to R, or almost like R, in terms of plotting defaults? For example R treats its axes pretty differently from `matplotlib`. The following histogram

has "floating axes" with outward ticks, such that... | matplotlib >= 1.4 suports [styles](https://github.com/matplotlib/matplotlib/blob/master/doc/users/style_sheets.rst) (and ggplot-style is build in):
```
In [1]: import matplotlib as mpl
In [2]: import matplotlib.pyplot as plt
In [3]: import numpy as np
In [4]: mpl.style.available
Out[4]: [u'dark_background', u'grays... |
python argparse - either both optional arguments or else neither one | 14,350,343 | 11 | 2013-01-16T02:10:35Z | 14,350,426 | 7 | 2013-01-16T02:21:27Z | [
"python",
"command-line-arguments",
"argparse"
] | I have a program that uses a default name and password. I'm using argparse to allow the user to specify command line options, and I would like to enable the user to provide the program with a different name and password to use. So I have the following:
```
parser.add_argument(
'-n',
'--name',
help='the log... | I believe that the best way to handle this is to post-process the returned namespace. The reason that `argparse` doesn't support this is because it parses arguments 1 at a time. It's easy for `argparse` to check to see if something was already parsed (which is why mutually-exclusive arguments work), but it isn't easy t... |
is there antialiasing method for python PIL | 14,350,645 | 6 | 2013-01-16T02:51:22Z | 14,351,890 | 10 | 2013-01-16T05:26:09Z | [
"python",
"python-imaging-library",
"antialiasing"
] | For line and ellipse in PIL, images are rough.
I found antialiasing only in resize and thumbnail.
Is there any way to do antialiasing when drawing a line or ellipse? | The only way to do it natively is with supersampling. Render your image at a multiple of the size you require, then `resize` it with `filter=Image.ANTIALIAS`. |
Define a route for url ending with integer in python | 14,350,920 | 4 | 2013-01-16T03:28:42Z | 14,351,078 | 8 | 2013-01-16T03:50:59Z | [
"python",
"flask",
"routes"
] | Here is a portion of my python code:
```
@app.route("/<int:param>/")
def go_to(param):
return param
```
The above function routes a url such as `www.example.com/12` to this function.
How can I declare a parameter rule to redirect urls ending with integers, such as `www.example.com/and/boy/12`, to this function?
... | You will need `Werkzeug routing`.
*Complete code:*
```
from flask import Flask
from werkzeug.routing import BaseConverter
app = Flask(__name__)
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex =... |
Define a route for url ending with integer in python | 14,350,920 | 4 | 2013-01-16T03:28:42Z | 14,351,196 | 7 | 2013-01-16T04:05:34Z | [
"python",
"flask",
"routes"
] | Here is a portion of my python code:
```
@app.route("/<int:param>/")
def go_to(param):
return param
```
The above function routes a url such as `www.example.com/12` to this function.
How can I declare a parameter rule to redirect urls ending with integers, such as `www.example.com/and/boy/12`, to this function?
... | You just need to add "and/boy" to your parameter:
```
@app.route("/and/boy/<int:param>/")
def go_to(param):
return param
``` |
Techniques for working with large Numpy arrays? | 14,351,255 | 14 | 2013-01-16T04:12:57Z | 14,352,093 | 12 | 2013-01-16T05:47:34Z | [
"python",
"arrays",
"optimization",
"memory-management",
"numpy"
] | There are times when you have to perform many intermediate operations on one, or more, large Numpy arrays. This can quickly result in `MemoryError`s. In my research so far, U have found that Pickling (Pickle, CPickle, Pytables, etc.) and `gc.collect()` are ways to mitigate this. I was wondering if there are any other t... | I feel your pain... You sometimes end up storing several times the size of your array in values you will later discard. When processing one item in your array at a time, this is irrelevant, but can kill you when vectorizing.
I'll use an example from work for illustration purposes. I recently coded the algorithm descri... |
How to repair a clobbered method of a Python object? | 14,352,610 | 4 | 2013-01-16T06:36:21Z | 14,352,659 | 7 | 2013-01-16T06:41:00Z | [
"python",
"object",
"methods"
] | In an interactive Python session, I sometimes do dumb things like
```
plot.ylimits = (0,100)
```
where plot is an instance of some Plot class, and ylimits is a method for it. I should have tapped in this:
```
plot.ylimits(0,100)
```
The way Python works, the plot object now has a new member named ylimits which hold... | A simple way is to do `del plot.ylimits`. In general, methods are defined on the class, not the instance. Python just looks attributes up every time you try to access them, and when it doesn't find them on the instance, it goes to the class. When you did `plot.ylimits=(0,100)`, you created a new instance attribute, so ... |
compare if an element exists in two lists | 14,352,621 | 6 | 2013-01-16T06:37:23Z | 14,352,657 | 8 | 2013-01-16T06:40:35Z | [
"python",
"list"
] | What would be the easiest and the most elegant way of checking if an element exists in two given lists. For Example, i have two lists as follows ?
```
>>>a, b = ['a', 'b', 'g', 'r'], ['e', 'g', 'l', 1, 'w']
```
Now in the above given lists i want to check if there is any element that exists in both lists. Currently i... | check elements of `a` and `b` with this:
```
set(a).intersection(b)
```
example:
```
In [44]: nk=set(a).intersection(b)
In [45]: for x in a:
...: if x in nk:
...: print x, 'present in b'
...: else:
...: print x, 'absent in b'
...:
a absent in b
b absent in b
g pr... |
How to find shortest path in a weighted graph using networkx? | 14,353,743 | 6 | 2013-01-16T08:03:22Z | 14,354,670 | 7 | 2013-01-16T09:08:38Z | [
"python",
"python-2.7",
"networkx"
] | I'm using the `networkx` package in `Python 2.7 Enthought distribution` to calculate shortest paths between a network of seaports. It's working fine to calculate the distance using `dijkstra_path_length`, but I also need to know what route it has found using `dijkstra_path` (as an aside, I think it should be faster to ... | Experimenting a bit, it appears that `nx.dijkstra_path` raises a misleading exception when the origin and destination nodes are the same:
```
>>> import networkx as nx
>>> g = nx.Graph()
>>> g.add_edge('a', 'b', distance=0.3)
>>> g.add_edge('a', 'c', distance=0.7)
>>> nx.dijkstra_path_length(g, 'b', 'c', 'distance')
1... |
Add scrolling to a platformer in pygame | 14,354,171 | 22 | 2013-01-16T08:37:09Z | 14,357,169 | 65 | 2013-01-16T11:19:42Z | [
"python",
"scroll",
"pygame"
] | Ok so I included the code for my project below, I'm just doing some experimenting with pygame on making a platformer. I'm trying to figure out how to do some very simple scrolling that follows the player, so the player is the center of the camera and it bounces/follows him. Can anyone help me?
```
import pygame
from p... | You need to apply an *offset* to the position of your entities when drawing them. Let's call that *offset* a `camera`, since this is the effect we want to achieve with this.
First of all, we can't (and should not) use the `draw` function of the sprite group, since the sprites don't need to know that their position (`r... |
Plot periodic trajectories | 14,357,104 | 4 | 2013-01-16T11:16:30Z | 14,358,909 | 10 | 2013-01-16T12:50:27Z | [
"python",
"numpy",
"matplotlib"
] | I have some data of a particle moving in a corridor with closed boundary conditions.
Plotting the trajectory leads to a zig-zag-trajectory.

I would like to know how to hinder `plot()` from connecting the points, where the particle comes back to the st... | I'd go a different approach. First, I'd determine the jump points not by looking at the sign of the derivative, as probably the movement might go up or down, or even have some periodicity in it. I'd look at those points with the biggest derivative.
Second, an elegant approach to have breaks in a plot line is to mask o... |
Finding consecutive segments in a pandas data frame | 14,358,567 | 7 | 2013-01-16T12:31:42Z | 14,359,211 | 7 | 2013-01-16T13:07:53Z | [
"python",
"pandas"
] | I have a pandas.DataFrame with measurements taken at consecutive points in time. Along with each measurement the system under observation had a distinct state at each point in time. Hence, the DataFrame also contains a column with the state of the system at each measurement. State changes are much slower than the measu... | You could use np.diff() to test where a segment starts/ends and iterate over those results. Its a very simple solution, so probably not the most performent one.
```
a = np.array([3,3,3,3,3,4,4,4,4,4,1,1,1,1,4,4,12,12,12])
prev = 0
splits = np.append(np.where(np.diff(a) != 0)[0],len(a)+1)+1
for split in splits:
p... |
Finding consecutive segments in a pandas data frame | 14,358,567 | 7 | 2013-01-16T12:31:42Z | 14,360,423 | 14 | 2013-01-16T14:16:30Z | [
"python",
"pandas"
] | I have a pandas.DataFrame with measurements taken at consecutive points in time. Along with each measurement the system under observation had a distinct state at each point in time. Hence, the DataFrame also contains a column with the state of the system at each measurement. State changes are much slower than the measu... | One-liner:
```
df.reset_index().groupby('A')['index'].apply(lambda x: np.array(x))
```
Code for example:
```
In [1]: import numpy as np
In [2]: from pandas import *
In [3]: df = DataFrame([3]*4+[4]*4+[1]*4, columns=['A'])
In [4]: df
Out[4]:
A
0 3
1 3
2 3
3 3
4 4
5 4
6 4
7 4
8 1
9 1
10 1
11... |
How to use "import" in python? | 14,359,191 | 3 | 2013-01-16T13:06:50Z | 14,359,254 | 12 | 2013-01-16T13:10:19Z | [
"python",
"syntax",
"scikit-learn",
"python-import"
] | If I use `from sklearn import *` or `from skleanr import datasets`, then I can use datasets in the following way: `iris = datasets.load_iris()`.
However, `import sklearn` and `import sklearn as sk` do not work as I expect. For example I cannot use `sklearn.datasets.import_iris()` or `sk.datasets.import_iris()`. Do I m... | No, you are not misinterpreting it. It's the package structure of this particular project.
When you import `sklearn`, you import a special python file `__init__.py` in a directory `sklearn`, that has *inside* of it another package called `datasets`. But if `sklearn` itself doesn't import the nested package into it's `... |
Reading YAML in python | 14,359,557 | 21 | 2013-01-16T13:27:51Z | 14,404,103 | 37 | 2013-01-18T17:14:58Z | [
"python",
"yaml",
"pyyaml"
] | I have a yaml file that looks like
```
---
level_1: "test"
level_2: 'NetApp, SOFS, ZFS Creation'
request: 341570
---
level_1: "test"
level_2: 'NetApp, SOFS, ZFS Creation'
request: 341569
---
level_1: "test"
level_2: 'NetApp, SOFS, ZFS Creation'
request: 341568
```
I am able to read this correctly in Perl using YAML b... | The yaml documents are separated by `---`, and if any stream (e.g. a file) contains more than one document then you should use the `yaml.load_all` function rather than `yaml.load`. The code:
```
import yaml
stream = open("test", "r")
docs = yaml.load_all(stream)
for doc in docs:
for k,v in doc.items():
pr... |
How would you implement a divisor function? | 14,359,936 | 3 | 2013-01-16T13:49:30Z | 14,361,083 | 8 | 2013-01-16T14:50:23Z | [
"python",
"math",
"numbers"
] | The [divisor function](http://en.wikipedia.org/wiki/Divisor_function) is the sum of divisors of a natural number.
Making a little research I found [this](http://mathschallenge.net/index.php?section=faq&ref=number/sum_of_divisors) to be a very good method if you want to find the divisor function of a given natural numb... | When computing the sum of divisors, you need the factorization of *n* in the form *p1**k1* *p2**k2* ... â that is, you need the exponent of each prime in the factorization. At the moment you are doing this by computing a flat list of prime factors, and then calling `count` to work out the exponent. This is a waste of... |
getting file path from command line argument in python | 14,360,389 | 2 | 2013-01-16T14:14:25Z | 14,360,405 | 9 | 2013-01-16T14:15:33Z | [
"python"
] | Can anyone guide me how can I get file path if we pass file from command line argument and extract file also. In case we also need to check if the file exist into particular directory
```
python.py /home/abhishek/test.txt
```
get file path and check test.txt exist into abhishek folder.
I know it may be very easy but... | ```
import os
import sys
fn = sys.argv[1]
if os.path.exists(fn):
print os.path.basename(fn)
# file exists
``` |
what's the biggest difference between dir and __dict__ in python | 14,361,256 | 37 | 2013-01-16T14:58:45Z | 14,361,362 | 64 | 2013-01-16T15:03:12Z | [
"python",
"introspection"
] | ```
class C(object):
def f(self):
print self.__dict__
print dir(self)
c = C()
c.f()
```
output:
```
{}
['__class__', '__delattr__','f',....]
```
why there is not a 'f' in self.\_\_dict\_\_ | ## `dir()` does much more than look up `__dict__`
First of all, `dir()` is a API method that knows how to use attributes like `__dict__` to look up attributes of an object.
Not all objects have a `__dict__` attribute though. For example, if you were to add a [`__slots__` attribute](http://docs.python.org/2/reference/... |
Using scikit-learn DecisionTreeClassifier to cluster | 14,361,798 | 4 | 2013-01-16T15:23:46Z | 14,362,468 | 8 | 2013-01-16T15:57:27Z | [
"python",
"machine-learning",
"scikit-learn"
] | When using sklearn.tree.DecisionTreeClassifier, the classifier has methods for predicting probability and class.
Is there a way to use the same tree for clustering: for a given input vector x, simply tell which leaf x belongs to? | I found the answer to my own question - leaving it here as reference for the next time someone looks for it:
```
import numpy as np
import sklearn.tree
clf = sklearn.tree.DecisionTreeClassifier()
clf.fit(X,y)
clf.tree_.apply(np.asfortranarray(X.astype(sklearn.tree._tree.DTYPE)))
``` |
Django dev server error: image not found | 14,363,522 | 2 | 2013-01-16T16:51:10Z | 14,389,181 | 18 | 2013-01-17T22:18:25Z | [
"python",
"django"
] | I get the following error trying to run the Django development server. I'm using OS X 10.8. I also using virtualenv system install package.
```
(django-env)Glyns-iMac:Ares Glyn$ sudo python manage.py runserver
dyld: DYLD_ environment variables being ignored because main executable (/usr/bin/sudo) is setuid or setgid
T... | Resolved:
Adding a couple of symbolic links fix this issue for me.
```
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql
``` |
Python Pandas - Deleting multiple series from a data frame in one command | 14,363,640 | 11 | 2013-01-16T16:57:30Z | 14,363,721 | 27 | 2013-01-16T17:01:31Z | [
"python",
"pandas"
] | In short ... I have a Python Pandas data frame that is read in from an Excel file using 'read\_table'. I would like to keep a handful of the series from the data, and purge the rest. I know that I can just delete what I don't want one-by-one using 'del data['SeriesName']', but what I'd rather do is specify what to keep... | You can use the `DataFrame` `drop` function to remove columns. You have to pass the `axis=1` option for it to work on columns and not rows. Note that it returns a copy so you have to assign the result to a new `DataFrame`:
```
In [1]: from pandas import *
In [2]: df = DataFrame(dict(x=[0,0,1,0,1], y=[1,0,1,1,0], z=[0... |
Python Pandas - Deleting multiple series from a data frame in one command | 14,363,640 | 11 | 2013-01-16T16:57:30Z | 14,363,758 | 11 | 2013-01-16T17:03:39Z | [
"python",
"pandas"
] | In short ... I have a Python Pandas data frame that is read in from an Excel file using 'read\_table'. I would like to keep a handful of the series from the data, and purge the rest. I know that I can just delete what I don't want one-by-one using 'del data['SeriesName']', but what I'd rather do is specify what to keep... | Basically the same as Zelazny7's answer -- just specifying what to keep:
```
In [68]: df
Out[68]:
x y z
0 0 1 0
1 0 0 0
2 1 1 1
3 0 1 0
4 1 0 1
In [70]: df = df[['x','z']]
In [71]: df
Out[71]:
x z
0 0 0
1 0 0
2 1 1
3 0 ... |
counting n-gram frequency in python nltk | 14,364,762 | 12 | 2013-01-16T18:00:23Z | 14,413,194 | 18 | 2013-01-19T10:05:38Z | [
"python",
"nltk",
"n-gram"
] | I have the following code. I know that I can use `apply_freq_filter` function to filter out collocations that are less than a frequency count. However, I don't know how to get the frequencies of all the n-gram tuples (in my case bi-gram) in a document, before I decide what frequency to set for filtering. As you can see... | NLTK comes with its own `bigrams generator`, as well as a convenient `FreqDist()` function.
```
f = open('a_text_file')
raw = f.read()
tokens = nltk.word_tokenize(raw)
#Create your bigrams
bgs = nltk.bigrams(tokens)
#compute frequency distribution for all the bigrams in the text
fdist = nltk.FreqDist(bgs)
for k,v i... |
counting n-gram frequency in python nltk | 14,364,762 | 12 | 2013-01-16T18:00:23Z | 14,431,290 | 8 | 2013-01-21T01:22:09Z | [
"python",
"nltk",
"n-gram"
] | I have the following code. I know that I can use `apply_freq_filter` function to filter out collocations that are less than a frequency count. However, I don't know how to get the frequencies of all the n-gram tuples (in my case bi-gram) in a document, before I decide what frequency to set for filtering. As you can see... | The `finder.ngram_fd.viewitems()` function works |
Python POST binary data | 14,365,027 | 18 | 2013-01-16T18:17:28Z | 14,448,953 | 23 | 2013-01-21T23:17:58Z | [
"python",
"rest",
"post",
"urllib2",
"redmine"
] | I am writing some code to interface with redmine and I need to upload some files as part of the process, but I am not sure how to do a POST request from python containing a binary file.
I am trying to mimic the commands [here](http://www.redmine.org/projects/redmine/wiki/Rest_api_with_curl):
```
curl --data-binary "@... | Basically what you do is correct. Looking at redmine docs you linked to, it seems that suffix after the dot in the url denotes type of posted data (.json for JSON, .xml for XML), which agrees with the response you get - `Processing by AttachmentsController#upload as XML`. I guess maybe there's a bug in docs and to post... |
numpy 3D-image array to 2D | 14,365,029 | 5 | 2013-01-16T18:17:34Z | 14,365,086 | 8 | 2013-01-16T18:21:42Z | [
"python",
"arrays",
"image",
"numpy",
"slice"
] | I have a **3D-numpy** array of a gray image, which looks something like this:
```
[[[120,120,120],[67,67,67]]...]
```
Obviously I have every R G and B the same because it is a gray image - this is redundent.
I want to get a new 2D array which looks like:
```
[[120,67]...]
```
Which means to take every pixel's array... | If the shape of your `ndarray` is (M, N, 3), then you can get an (M, N) gray-scale image like this:
```
>>> gray = img[:,:,0]
``` |
read csv file and return data.frame in Python | 14,365,542 | 26 | 2013-01-16T18:50:15Z | 14,365,647 | 57 | 2013-01-16T18:56:20Z | [
"python",
"csv",
"pandas"
] | I have a CSV file, `"value.txt"` with the following content:
the first few rows of the file are :
```
Date,"price","factor_1","factor_2"
2012-06-11,1600.20,1.255,1.548
2012-06-12,1610.02,1.258,1.554
2012-06-13,1618.07,1.249,1.552
2012-06-14,1624.40,1.253,1.556
2012-06-15,1626.15,1.258,1.552
2012-06-16,1626.15,1.263,1.... | [pandas](http://pandas.pydata.org/) to the rescue:
```
import pandas as pd
print pd.read_csv('value.txt')
Date price factor_1 factor_2
0 2012-06-11 1600.20 1.255 1.548
1 2012-06-12 1610.02 1.258 1.554
2 2012-06-13 1618.07 1.249 1.552
3 2012-06-14 1624.40 1.253 1.55... |
Python: How to access the dictionary that has specific key-values in a list | 14,366,061 | 3 | 2013-01-16T19:18:58Z | 14,366,146 | 8 | 2013-01-16T19:24:11Z | [
"python",
"list",
"dictionary",
"key"
] | I have a list of dictionaries:
```
[
{"START":"Denver", "END":"Chicago", "Num":0},
{"START":"Dallas", "END":"Houston", "Num":3},
{"START":"Virginia", "END":"Boston", "Num":1},
{"START":"Washington", "END":"Maine", "Num":7}
]
```
How do I access the dictionary in this list that has `"START":"Virginia", "END":"Boston"`... | The most Pythonic way is probably a list comprehension:
```
[ d for d in dict_list if d["START"] == "Virginia" and d["END"] == "Boston" ]
```
As mgilson pointed out, if you are assuming that there's only one item in the list with that pair of locations, you can use `next` with the same generator expression, instead o... |
python module in virtualenv | 14,366,977 | 3 | 2013-01-16T20:13:36Z | 14,367,079 | 7 | 2013-01-16T20:19:31Z | [
"python",
"virtualenv"
] | I'm using python in virtualenv. I have following module:
`offers/couchdb.py`:
```
from couchdb.client import Server
def get_attributes():
return [i for i in Server()['offers']]
if __name__ == "__main__":
print get_attributes()
```
When I run it from file I get:
```
$ python offers/couchdb.py
Traceback (mo... | You've stumbled across a misfeature: *relative imports*. When you say `from couchdb.client...`, Python first looks for a module under `offers.` that's named `couchdb`. And it finds one: the file you're working on, `offers/couchdb.py`!
The usual fix is to disable this behavior, which is gone in Python 3 anyway. Put thi... |
Pip Install Not working with Scikit-Learn | 14,367,596 | 2 | 2013-01-16T20:51:12Z | 14,367,863 | 7 | 2013-01-16T21:07:20Z | [
"python",
"scikit-learn"
] | When I tried entering `pip install scikit-learn` on Python shell, I got the "invalid syntax" message. I already
have Scipy and Numpy installed so there shouldn't be any depedency issues. What's wrong?
And I am still new to Python so I don't want to manually install the module. I am using Python 2.7 on
Vista 32-bit.
Th... | If you installed everything using windows executable (.exe files) you should also install this as an executable available for download here - [Scikit Learn Executables](http://sourceforge.net/projects/scikit-learn/files/)
Or,
The python shell is not the place to run `pip` commands. So open the command line terminal i... |
flask before request - add exception for specific route | 14,367,991 | 16 | 2013-01-16T21:16:21Z | 14,368,550 | 28 | 2013-01-16T21:52:50Z | [
"python",
"flask"
] | in my before\_request() function, i want to redirect the user to /login if they are not yet logged in. is there a special variable that will give me the current url that will work as the below example does?
```
@app.before_request
def before_request():
# the variable current_url does not exist
# but i want som... | There are a couple of properties on the request object you can check, documented [here](http://flask.pocoo.org/docs/api/#flask.Request.path), `request.path` is probably what you want. Can I suggest [`request.endpoint`](http://flask.pocoo.org/docs/api/#flask.Request.endpoint) though, so you'll be covered should you deci... |
How can I flush the Heroku buildpack CACHE_DIR? | 14,368,027 | 15 | 2013-01-16T21:18:41Z | 21,909,893 | 22 | 2014-02-20T13:54:52Z | [
"python",
"heroku",
"buildpack"
] | During development of our Python/Django application, we accidentally introduced package requirements in requirements.txt that installed conflicting versions of a library. Heroku has cached the broken requirements in the CACHE\_DIR specified by the python buildpack, as documented on their [buildpack API info page](https... | Use `heroku-repo` plugin:
```
$ heroku plugins:install heroku-repo
$ heroku repo:purge_cache -a appname
``` |
Django: Any difference between `QuerySet.__nonzero__` and `QuerySet.exists`? | 14,368,205 | 7 | 2013-01-16T21:30:29Z | 14,369,747 | 9 | 2013-01-16T23:25:18Z | [
"python",
"django"
] | I see that the `QuerySet` class has 2 different methods that seem to serve the same purpose (unless I'm mistaken): `.__nonzero__` and `.exists`. (Yes, I know that `.__nonzero__` is used by `bool`.)
My question: Why do the 2 methods have different implementation if they both just check whether there's any object in the... | > Why does QuerySet.**nonzero** have a non-efficient implementation? Is it trying to achieve something different than .exists? What is the reason that the Django developers don't do **nonzero** = exists?
I think it's because `exists` is only efficient under certain circumstances.
Imagine this common scenario if `__no... |
Django DateTimeField() and timezone.now() | 14,368,290 | 6 | 2013-01-16T21:35:17Z | 14,368,418 | 9 | 2013-01-16T21:43:14Z | [
"python",
"django",
"django-models"
] | OK, weird time zone issues when I'm running function tests. Django 1.4, Python 2.7. Are milliseconds truncated in DateTimeField() on MySQL? That's the only theory I've got.
model file
```
from django.db import models
from django.utils import timezone
class Search(models.Model):
query = models.CharField(max_lengt... | Django ORM converts `DateTimeField` to `Timestamp` in mysql. You can confirm that by looking at the raw sql doing `./manage.py sqlall <appname>`
In mysql `timestamp` does not store milliseconds.
```
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 ... |
code.interact and imports/definitions visibility | 14,368,449 | 8 | 2013-01-16T21:45:30Z | 15,006,363 | 10 | 2013-02-21T15:44:38Z | [
"python",
"function",
"scope",
"visibility",
"python-import"
] | I don't quite understand where **imports** and **function definitions** are **visibile** in a python module.
Here's a simplification of my case:
```
from scapy.all import *
def getA():
return 0
def getB():
return getA() + 1
def getC():
code.interact(local=locals())
return 3
def main():
print g... | As I wrote in a comment above, the solution is:
```
code.interact(local=dict(globals(), **locals()))
```
(take [here](http://stackoverflow.com/questions/7165493/how-to-get-python-interactive-console-in-current-namespace#comment17527678_7165575)) |
How to save back changes made to a HTML file using BeautifulSoup in Python? | 14,369,447 | 11 | 2013-01-16T22:59:13Z | 14,369,600 | 29 | 2013-01-16T23:13:15Z | [
"python",
"html-parsing",
"beautifulsoup"
] | Python noob here...
I have the script below, which modifies the hrefs for a html file (in the future it will be a list of HTML files in a directory). Using beautifulSoup I managed to access the tag values and modify it as I want but I don't know how to save back the changes made to the file. Any help will be greatly a... | ```
newlink = link['href']
# .. make replacements
link['href'] = newlink # store it back
```
Now `print(soup.prettify())` will show changed links. To save the changes to a file:
```
htmlDoc.close()
html = soup.prettify("utf-8")
with open("output.html", "wb") as file:
file.write(html)
```
To preserve original ch... |
Limiting the number of request from any given IP address | 14,370,717 | 2 | 2013-01-17T01:15:54Z | 14,370,928 | 9 | 2013-01-17T01:41:09Z | [
"python",
"google-app-engine",
"webapp2"
] | I am working on a Google App Engine project (python/webapp2) where I am a little concerned with people abusing/spamming the service I am creating with a large number of requests. In an attempt to combat this potential, my idea is to limit the number of requests allowed per IP address in any given hour for certain parts... | In the past, I've done this with memcache, which is much faster, especially since you only really care about approximate limits (approximate because memcache can be flushed by the system, might not be shared by all instances, etc.). You can even use it to expire keys for you. Something like this (which assumes `self` i... |
difference between F(x) and F x in Python | 14,370,962 | 4 | 2013-01-17T01:45:44Z | 14,370,969 | 9 | 2013-01-17T01:47:18Z | [
"python"
] | In Python it is possible to call either `del x` or del (x) . I know how to define a function called F(x) , but I do not know how to define a function that cal be called like `del`, without a tuple as parameters.
What is the difference between `F x` and `F(x)`, and how can I define a function that can be called without... | The main reason is that `del` is actually a [statement](http://docs.python.org/2/reference/simple_stmts.html#the-del-statement) and therefore has special behavior in Python. Therefore you cannot actually define these (and this behavior) yourself\* - it is a built-in part of the language for a set of reserved keywords.
... |
TypeError: unsupported operand type(s) for /: 'str' and 'int' | 14,371,555 | 4 | 2013-01-17T03:02:38Z | 14,371,569 | 7 | 2013-01-17T03:04:04Z | [
"python",
"string",
"types",
"int",
"typeerror"
] | In Python 2.7:
```
a=80
b=100
def status(hp, maxhp):
print "You are at %r percent health." % hp*100/maxhp
status(a,b)
```
Returns:
> TypeError: unsupported operand type(s) for /: 'str' and 'int'
I've already tried putting int() around each variable and each combination of variables. | `%` operator has higher precedence than `*` or `/`.
What you meant is:
```
"You are at %r percent health." % (hp * 100 / maxhp)
```
What you got is:
```
("You are at %r percent health." % hp) * 100 / maxhp
```
Edit: actually, I'm wrong. They have the same precedence and thus are applied left to right.
[Docs: oper... |
Efficient creation of numpy arrays from list comprehension and in general | 14,372,613 | 18 | 2013-01-17T05:17:46Z | 14,372,746 | 23 | 2013-01-17T05:31:27Z | [
"python",
"performance",
"numpy"
] | In my current work i use Numpy and list comprehensions a lot and in the interest of best possible performance i have the following questions:
What actually happens behind the scenes if i create a Numpy array as follows? :
```
a = numpy.array( [1,2,3,4] )
```
My guess is that python first creates an ordinary list con... | I believe than answer you are looking for is using `generator expressions` with [numpy.fromiter](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html).
```
numpy.fromiter((<some_func>(x) for x in <something>),<dtype>,<size of something>)
```
Generator expressions are lazy - they evaluate the expres... |
quotations in input python | 14,372,852 | 2 | 2013-01-17T05:43:19Z | 14,372,890 | 10 | 2013-01-17T05:46:52Z | [
"python"
] | When using Python3, and doing something as simple as
```
x=input("Enter your name: ")
print (x)
```
and trying to run it, the user would have to input their name as "Steve" rather than just Steve.
Is there a way around having to input with quotations? | I think you're mistaken. In Python 3, you *don't* need quotation marks:
```
localhost-2:~ $ python3.3
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = input("Enter your name:")... |
Moving back an iteration in a for loop | 14,374,181 | 10 | 2013-01-17T07:34:26Z | 14,374,229 | 14 | 2013-01-17T07:37:28Z | [
"python",
"for-loop"
] | So I want to do something like this:
```
for i in range(5):
print(i);
if(condition==true):
i=i-1;
```
However, for whatever reason, even though I'm decrementing i, the loop doesn't seem to notice. Is there any way to repeat an iteration? | `for` loops in Python always go forward. If you want to be able to move backwards, you must use a different mechanism, such as `while`:
```
i = 0
while i < 5:
print(i)
if condition:
i=i-1
i += 1
```
Or even better:
```
i = 0
while i < 5:
print(i)
if condition:
do_something()
... |
Find python header path from within python? | 14,375,222 | 3 | 2013-01-17T08:52:14Z | 14,375,459 | 11 | 2013-01-17T09:06:44Z | [
"python",
"numpy",
"header-files"
] | What is the equivalent of
```
numpy.get_include()
```
as used [here](http://docs.scipy.org/doc/numpy-1.6.0/user/c-info.python-as-glue.html?highlight=get_include#instant) for Python, giving me the path to the directory where the Python header files are located? | The header files are in include directory.
You can find the include dir using the distutils.sysconfig module
```
from distutils.sysconfig import get_python_inc
get_python_inc() #this gives the include dir
```
You can read about it [here](http://docs.python.org/2/distutils/setupscript.html#preprocessor-options) |
SQLAlchemy: prevent automatic closing | 14,375,666 | 6 | 2013-01-17T09:18:54Z | 14,388,356 | 8 | 2013-01-17T21:20:20Z | [
"python",
"sql",
"sqlalchemy",
"bulkinsert"
] | I need to insert/update bulk rows via SQLAlchemy. And get inserted rows.
I tried to do it with session.execute:
```
>>> posts = db.session.execute(Post.__table__.insert(), [{'title': 'dfghdfg', 'content': 'sdfgsdf', 'topic': topic}]*2)
>>> posts.fetchall()
ResourceClosedError Traceback (most... | **First answer - on "preventing automatic closing".**
SQLAlchemy runs DBAPI execute() or executemany() with insert and do not do any select queries.
So the exception you've got is expected behavior. ResultProxy object returned after insert query executed wraps DB-API cursor that doesn't allow to do `.fetchall()` on it... |
Is there a recommended format for multi-line imports? | 14,376,900 | 40 | 2013-01-17T10:24:57Z | 14,377,098 | 9 | 2013-01-17T10:35:41Z | [
"python",
"python-2.7",
"pep8"
] | I have read there are three ways for coding multi-line imports in python
With slashes:
```
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
LEFT, DISABLED, NORMAL, RIDGE, END
```
Duplicating senteces:
```
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED,... | Your examples seem to stem from [PEP 328](http://www.python.org/dev/peps/pep-0328/). There, the parenthesis-notation is proposed for exactly this problem, so probably I'd choose this one. |
Is there a recommended format for multi-line imports? | 14,376,900 | 40 | 2013-01-17T10:24:57Z | 14,377,271 | 56 | 2013-01-17T10:45:03Z | [
"python",
"python-2.7",
"pep8"
] | I have read there are three ways for coding multi-line imports in python
With slashes:
```
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
LEFT, DISABLED, NORMAL, RIDGE, END
```
Duplicating senteces:
```
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED,... | Personally I go with parentheses when importing more than one component and sort them alphabetically. Like so:
```
from Tkinter import (
Button,
Canvas,
DISABLED,
END,
Entry,
Frame,
LEFT,
NORMAL,
RIDGE,
Text,
Tk,
)
```
Overall though it's a personal preference and I would a... |
Traversing a sequence of generators | 14,377,907 | 5 | 2013-01-17T11:19:06Z | 14,377,962 | 8 | 2013-01-17T11:21:34Z | [
"python",
"algorithm"
] | I have a sequence of generators: (gen\_0, gen\_1, ... gen\_n)
These generators will create their values lazily but are finite and will have potentially different lengths.
I need to be able to construct another generator that yields the first element of each generator in order, followed by the second and so forth, ski... | I think you need [itertools.izip\_longest](http://docs.python.org/2/library/itertools.html#itertools.izip_longest)
```
>>> list([e for e in t if e is not None] for t in itertools.izip_longest(*some_gen,
fillvalue=None))
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [... |
double for loops in python | 14,379,103 | 2 | 2013-01-17T12:27:00Z | 14,379,157 | 10 | 2013-01-17T12:29:33Z | [
"python"
] | I am trying to get a list of file names in order. Something like
```
files-1-loop-21
files-1-loop-22
files-1-loop-23
files-1-loop-24
files-2-loop-21
files-2-loop-22
files-2-loop-23
.
.
.
and so on
```
As for testing I have written python code as below:
code sample\_1:
```
for md in range(1,5):
for pico in range(... | Try this:
```
for md in range(1,5):
for pico in range(21,25):
print "file-{0}-loop-{1}".format(md, pico)
```
Or:
```
from itertools import product
for md, pico in product(range(1,5), range(21,25)):
print "file-{0}-loop-{1}".format(md, pico)
``` |
Mutli-threading python with Tkinter | 14,379,106 | 3 | 2013-01-17T12:27:05Z | 14,381,671 | 8 | 2013-01-17T14:49:14Z | [
"python",
"multithreading",
"tkinter"
] | I'm drawing little circle on a canvas with these functions :
This is the function who draw the circles :
```
class Fourmis:
def __init__(self, can, posx, posy, name, radius):
self.can = can
self.largeur_can = int(self.can.cget("width"))
self.hauteur_can = int(self.can.cget("height"))
self.posx = po... | When this functionality is needed, what you do is schedule the events you wish to perform by putting them in a queue shared by the threads. This way, in a given thread you specify that you want to run "create(50, ...)" by queueing it, and the main thread dequeue the event and perform it.
Here is a basic example for cr... |
Cross platform GUI with heavy styling | 14,379,231 | 5 | 2013-01-17T12:33:33Z | 14,379,499 | 7 | 2013-01-17T12:48:18Z | [
"python",
"user-interface",
"cross-platform"
] | I was thinking of writing a desktop application for Windows/Linux/OS-X.
One requirement of the GUI is that I need to be able to style it very accurately.
That is: I want to be able to color all elements the way I want to, position elements pixel precise, have borders on single sides of an element, etc. Very similar to... | OS-X has a very distinct and different look and feel to Windows, and an application with homebrew widgets is going to feel different, and usually comes off as odd or even ugly. In and around the time for Windows 98 every company made there own app with their own look and feel. One for the modem, one for the printer, on... |
What does -> mean in Python function definitions? | 14,379,753 | 118 | 2013-01-17T13:03:35Z | 14,379,780 | 95 | 2013-01-17T13:04:57Z | [
"python",
"python-3.x"
] | I've recently noticed something interesting when looking at [Python 3.3 grammar specification](http://docs.python.org/3.3/reference/grammar.html):
```
funcdef: 'def' NAME parameters ['->' test] ':' suite
```
The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in... | It's a [function annotation](http://www.python.org/dev/peps/pep-3107/).
In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters... |
What does -> mean in Python function definitions? | 14,379,753 | 118 | 2013-01-17T13:03:35Z | 15,073,109 | 44 | 2013-02-25T17:46:19Z | [
"python",
"python-3.x"
] | I've recently noticed something interesting when looking at [Python 3.3 grammar specification](http://docs.python.org/3.3/reference/grammar.html):
```
funcdef: 'def' NAME parameters ['->' test] ':' suite
```
The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in... | These are function annotations covered in [PEP 3107](http://www.python.org/dev/peps/pep-3107/). Specifically, the `->` marks the return function annotation.
Examples:
```
>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules':
... return 1/2*m*v**2
...
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v'... |
Export a LaTeX table from pandas DataFrame | 14,380,371 | 23 | 2013-01-17T13:40:24Z | 14,383,654 | 40 | 2013-01-17T16:30:24Z | [
"python",
"latex",
"dataframe",
"pandas"
] | Is there an easy way to export a data frame (or even a part of it) to LaTeX?
*I searched in google and was only able to find solutions using asciitables.* | DataFrames have a `to_latex` method:
```
In [42]: df = pd.DataFrame(np.random.random((5, 5)))
In [43]: df
Out[43]:
0 1 2 3 4
0 0.886864 0.518538 0.359964 0.167291 0.940414
1 0.834130 0.022920 0.265131 0.059002 0.530584
2 0.648019 0.953043 0.263551 0.595798 0.1... |
How do I get the vertices on the shortest path using igraph? | 14,380,796 | 3 | 2013-01-17T14:03:46Z | 14,381,066 | 8 | 2013-01-17T14:19:48Z | [
"python",
"shortest-path",
"igraph"
] | I'm using `igraph` to generate a matrix of shortest path distances between pairs of vertices but I can't figure out how to return the vertices. So far I have:
```
path_length_matrix = ig_graph.shortest_paths_dijkstra(None,None,"distance", "ALL")
```
I'm looking for a function which returns a matrix of paths like the ... | The function you need is `get_shortest_paths` I believe. See <http://packages.python.org/python-igraph/igraph.GraphBase-class.html#get_shortest_paths>
You need to call it individually for each source vertex, and it will give you only a single (arbitrary) shortest path for each pair of nodes. If you need all shortest p... |
What does appending [0] to methods in python do? | 14,382,038 | 2 | 2013-01-17T15:09:39Z | 14,382,160 | 7 | 2013-01-17T15:14:32Z | [
"python"
] | What does appending [0] to methods in python do?
For example, in the following [0] is appended to a method.
```
print "Unexpected error:", sys.exc_info()[0]
``` | It calls the method and gets the 0th element from the returned value.
```
>>> def test():
... return ['item0', 'item1']
...
>>> test()
['item0', 'item1']
>>> test()[0]
'item0'
>>>
``` |
How do I mock a superclass's __init__ create an attribute containing a mock object for a unit test? | 14,382,706 | 7 | 2013-01-17T15:42:58Z | 14,541,403 | 14 | 2013-01-26T20:44:41Z | [
"python",
"mocking"
] | I am attempting to write a unit test for a class's `__init__`:
```
def __init__(self, buildNum, configFile = "configfile.txt"):
super(DevBuild, self).__init__(buildNum, configFile)
if configFile == "configfile.txt":
self.config.MakeDevBuild()
```
The config attribute is set by the super's... | You can't mock `__init__` by setting it directly - see [\_unsupported\_magics in mock.py](http://mock.googlecode.com/hg/mock.py).
As for what you can do, you can mock `__init__` by passing it to patch, like so:
```
mock_makeDevBuild = MagicMock()
def mock_init(self, buildNum, configFile):
self.config = MagicMock(... |
Python 2 Dimension Array (Matrix) with string indices | 14,383,333 | 2 | 2013-01-17T16:12:36Z | 14,383,344 | 7 | 2013-01-17T16:13:31Z | [
"python",
"data-structures",
"dictionary",
"matrix"
] | In Python (2.7), is there a native 2 dimensional data structure that can be accessed through string based indices?
I know you can have a dictionary that can be accessed with a string index, for example:
```
>>> dic = dict()
>>> dic['grumpy'] = 'cat'
>>> print(dict['grumpy'])
'cat'
```
But what I would like is a data... | Use a [`defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict):
```
from collections import defaultdict
nesteddict = defaultdict(dict)
nesteddict['abc']['spam'] = 'ham'
```
Note that what you describe is a simple nested structure; you can also build it without using `defaultdict` b... |
How can I add a background thread to flask? | 14,384,739 | 37 | 2013-01-17T17:29:40Z | 22,900,255 | 29 | 2014-04-06T21:27:07Z | [
"python",
"rest",
"flask"
] | I'm busy writing a small game server to try out flask. The game exposes an API via REST to users. It's easy for users to perform actions and query data, however I'd like to service the "game world" outside the app.run() loop to update game entities, etc. Given that Flask is so cleanly implemented, I'd like to see if th... | Your additional threads must be initiated from the same app that is called by the WSGI server.
The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.
```
import threading
import atexit
from flask import Flask
POOL... |
is there a better way to handle index.html with Tornado? | 14,385,048 | 10 | 2013-01-17T17:48:29Z | 16,032,636 | 12 | 2013-04-16T08:51:31Z | [
"python",
"tornado"
] | I want to know if there is a better way to handle my index.html file with Tornado.
I use StaticFileHandler for all the request,and use a specific MainHandler to handle my main request. If I only use StaticFileHandler I got a 403: Forbidden error
```
GET http://localhost:9000/
WARNING:root:403 GET / (127.0.0.1): is n... | Thanks to the previous answer, here is the solution I prefer:
```
import Settings
import tornado.web
import tornado.httpserver
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler)
]
settings = {
"template_path": Settings.... |
is there a better way to handle index.html with Tornado? | 14,385,048 | 10 | 2013-01-17T17:48:29Z | 27,891,339 | 14 | 2015-01-11T19:47:30Z | [
"python",
"tornado"
] | I want to know if there is a better way to handle my index.html file with Tornado.
I use StaticFileHandler for all the request,and use a specific MainHandler to handle my main request. If I only use StaticFileHandler I got a 403: Forbidden error
```
GET http://localhost:9000/
WARNING:root:403 GET / (127.0.0.1): is n... | Turns out that Tornado's StaticFileHandler already includes *default filename* functionality.
Feature was added in Tornado release 1.2.0:
<https://github.com/tornadoweb/tornado/commit/638a151d96d681d3bdd6ba5ce5dcf2bd1447959c>
To specify a default file name you need to set the "default\_filename" parameter as part of ... |
HTTPS POST request Python | 14,385,173 | 5 | 2013-01-17T17:55:15Z | 15,213,371 | 9 | 2013-03-04T23:51:38Z | [
"python",
"post",
"https",
"urllib2",
"urllib"
] | I want to make a post request to a HTTPS-site that should respond with a .csv file.
I have this Python code:
```
url = 'https://www.site.com/servlet/datadownload'
values = {
'val1' : '123',
'val2' : 'abc',
'val3' : '1b3',
}
data = urllib.urlencode(values)
req = urllib2.Request(url,data)
response = urllib2.urlop... | Is there a reason you've got to use `urllib`? [Requests](http://docs.python-requests.org/en/latest/) is simpler, better in almost every way, and abstracts away some of the cruft that makes `urllib` hard to work with.
As an example, I'd rework you example as something like:
```
import requests
resp = requests.post(url... |
Flask: How to remove cookies? | 14,386,304 | 9 | 2013-01-17T19:08:21Z | 14,386,413 | 20 | 2013-01-17T19:15:09Z | [
"python",
"cookies",
"flask"
] | I set cookies with the code suggested in the docs:
```
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
```
But how do I remove them? There is no remove\_cookie method. I tried:
```
if request.... | There's no HTTP header for deleting a cookie. Traditionally you just set the cookie to a dummy value with an expiration date in the past, so it immediately expires.
```
resp.set_cookie('sessionID', '', expires=0)
```
This will set the session id cookie to an empty string that expires at unixtime `0`, which is almost ... |
Fast numpy fancy indexing | 14,386,822 | 7 | 2013-01-17T19:42:11Z | 14,387,955 | 7 | 2013-01-17T20:56:27Z | [
"python",
"numpy",
"indexing",
"slice"
] | My code for slicing a numpy array (via fancy indexing) is very slow. It is currently a bottleneck in program.
```
a.shape
(3218, 6)
ts = time.time(); a[rows][:, cols]; te = time.time(); print('%.8f' % (te-ts));
0.00200009
```
What is the correct numpy call to get an array consisting of the subset of rows 'rows' and ... | To my surprise this, kind of lenghty expression, which calculates first linear 1D-indices, is more than **50%** faster than the consecutive array indexing presented in the question:
```
(a.ravel()[(
cols + (rows * a.shape[1]).reshape((-1,1))
).ravel()]).reshape(rows.size, cols.size)
```
**UPDATE:** OP updated t... |
Fast numpy fancy indexing | 14,386,822 | 7 | 2013-01-17T19:42:11Z | 14,397,853 | 9 | 2013-01-18T11:20:41Z | [
"python",
"numpy",
"indexing",
"slice"
] | My code for slicing a numpy array (via fancy indexing) is very slow. It is currently a bottleneck in program.
```
a.shape
(3218, 6)
ts = time.time(); a[rows][:, cols]; te = time.time(); print('%.8f' % (te-ts));
0.00200009
```
What is the correct numpy call to get an array consisting of the subset of rows 'rows' and ... | Let my try to summarize the excellent answers by Jaime and TheodrosZelleke and mix in some comments.
1. [Advanced (fancy) indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing) always returns a copy, never a view.
2. `a[rows][:,cols]` implies *two* fancy indexing operations, so an ... |
Invert colors when plotting a PNG file using matplotlib | 14,387,668 | 2 | 2013-01-17T20:36:28Z | 14,388,003 | 8 | 2013-01-17T20:59:03Z | [
"python",
"opencv",
"matplotlib"
] | I'm trying to display a PNG file using matplotlib and of course, python. For this test, I've generated the following image:

Now, I load and transform the image into a multidimensional numpy matrix:
```
import numpy as np
import cv2
from matplotlib import pyplot as ... | It appears that you may somehow have `RGB` switched with `BGR`. Notice that your greens are retained but all the blues turned to red. If `cube` has shape (M,N,3), try swapping `cube[:,:,0]` with `cube[:,:,2]`. You can do that with `numpy` like so:
```
rgb = numpy.fliplr(cube.reshape(-1,3)).reshape(cube.shape)
```
Fro... |
Fastest way to insert these dashes in python string? | 14,387,947 | 4 | 2013-01-17T20:55:23Z | 14,388,008 | 8 | 2013-01-17T20:59:17Z | [
"python",
"string",
"string-formatting"
] | So I know Python strings are immutable, but I have a string:
```
c['date'] = "20110104"
```
Which I would like to convert to
```
c['date'] = "2011-01-04"
```
My code:
```
c['date'] = c['date'][0:4] + "-" + c['date'][4:6] + "-" + c['date'][6:]
```
Seems a bit convoluted, no? Would it be best to save it as a separa... | You could use `.join()` to clean it up a little bit:
```
d = c['date']
'-'.join([d[:4], d[4:6], d[6:]])
``` |
Python function inside of a function | 14,388,970 | 2 | 2013-01-17T22:04:59Z | 14,389,000 | 7 | 2013-01-17T22:07:01Z | [
"python",
"string",
"function"
] | I'm reading an exercise out of a Python book, here is what it says:
Modify do\_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
Write a more general version of print\_spam, called print\_twice, that takes a string as a parameter and p... | Just give the `string` as a second argument to `do_twice`. The `do_twice` functions calls the `print_spam` and supplies the `string` as an argument:
```
def do_twice(f, g):
f(g)
f(g)
def print_spam(s):
print (s)
do_twice(print_spam,'lol')
```
*prints:*
```
lol
lol
``` |
Why does PyCrypto not use the default IV? | 14,389,336 | 11 | 2013-01-17T22:30:24Z | 14,390,238 | 15 | 2013-01-17T23:49:30Z | [
"python",
"aes",
"pycrypto"
] | I am trying to figure out why my Python client and the Ruby server are having a disagreement about how to encrypt data. The only difference I see in the Ruby code and my code is that they are not specifying the Initialization Vector, therefore its falling back to the default of all \x0's
When I try to instantiate PyCr... | This appears to be an error in the class documentation for Pycrypto's [AES](https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html), as the AES implementation has been changed so that the IV is **not** optional for those modes that require one (i.e. you will have to pass 16 bytes of zeroes yo... |
Removing newline from a csv file | 14,390,123 | 4 | 2013-01-17T23:37:41Z | 14,390,220 | 10 | 2013-01-17T23:48:08Z | [
"python",
"newline"
] | I am trying to process a csv file in python that has ^M character in the middle of each row/line which is a newline. I cant open the file in any mode other than 'rU'.
If I do open the file in the 'rU' mode, it reads in the newline and splits the file (creating a newline) and gives me twice the number of rows.
I want ... | Note that, as [the docs](http://docs.python.org/2/library/csv.html) say:
> *csvfile* can be any object which supports the iterator protocol and returns a string each time its `next()` method is called â file objects and list objects are both suitable.
So, you can always stick a filter on the file before handing it ... |
Reshape of pandas series? | 14,390,224 | 7 | 2013-01-17T23:48:24Z | 14,390,487 | 7 | 2013-01-18T00:15:30Z | [
"python",
"numpy",
"pandas",
"reshape"
] | It looks to me like a bug in pandas.Series.
```
a = pd.Series([1,2,3,4])
b = a.reshape(2,2)
b
```
b has type Series but can not be displayed, the last statement gives exception, very lengthy, the last line is "TypeError: %d format: a number is required, not numpy.ndarray". b.shape returns (2,2), which contradicts its... | You can call [`reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) on the *values* array of the Series:
```
In [4]: a.values.reshape(2,2)
Out[4]:
array([[1, 2],
[3, 4]], dtype=int64)
```
I actually think it won't always make sense to apply `reshape` to a Series (do you ignore the... |
Python Requests SSL issue | 14,390,605 | 6 | 2013-01-18T00:27:27Z | 14,483,890 | 12 | 2013-01-23T16:01:13Z | [
"python",
"ssl",
"connect",
"python-requests"
] | It's been days now since I started to look for a solution for this.
I've been trying to use requests to make an https request through a proxy with no luck.
Altough this is included in a bigger project of mine, it all boils done to this:
```
import requests
prox = 'xxx.xxx.xxx.xxx:xxx' # fill in valid proxy
... | I had this same problem but when trying to use oauth2client (Google library for using oauth2 against their APIs). After a day of faffing ("experimentation"), I discovered that I had the env variable set as follows:
```
https_proxy=https://your-proxy:port
```
Changing this to
```
https_proxy=http://your-proxy:port
``... |
Self scanning code to prevent print statments | 14,390,911 | 5 | 2013-01-18T01:01:49Z | 14,391,045 | 7 | 2013-01-18T01:18:27Z | [
"python"
] | I have a python project I'm working on whereby instead of print statements I call a function say() so I can print information while in development and log information during production. However, I often forget this and put print statements in the code by mistake. Is there anyway to have the python program read its own ... | This can be done using the [`ast`](http://docs.python.org/2/library/ast.html) module. The following code will find any calls of the `print` statement and also of the `print()` function in case you are on Python 3 or Python 2 with the `print_function` future.
```
import ast
class PrintFinder(ast.NodeVisitor):
def ... |
suppress Scrapy Item printed in logs after pipeline | 14,390,945 | 11 | 2013-01-18T01:06:38Z | 16,303,725 | 10 | 2013-04-30T15:37:32Z | [
"python",
"scrapy"
] | I have a scrapy project where the item that ultimately enters my pipeline is relatively large and stores lots of metadata and content. Everything is working properly in my spider and pipelines. The logs, however, are printing out the entire scrapy Item as it leaves the pipeline (I believe):
```
2013-01-17 18:42:17-060... | Another approach is to override the `__repr__` method of the `Item` subclasses to selectively choose which attributes (if any) to print at the end of the pipeline:
```
from scrapy.item import Item, Field
class MyItem(Item):
attr1 = Field()
attr2 = Field()
# ...
attrN = Field()
def __repr__(self):
... |
Heatmap in matplotlib with pcolor? | 14,391,959 | 79 | 2013-01-18T03:31:17Z | 16,124,677 | 88 | 2013-04-20T20:09:39Z | [
"python",
"matplotlib",
"data-visualization",
"heatmap"
] | I'd like to make a heatmap like this (shown on [FlowingData](http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/)):

The source data is [here](http://datasets.flowingdata.com/ppg2008.csv), but random data and labels would be fine to use, i.e.... | This is late, but here is my python implementation of the flowingdata NBA heatmap.
**updated:1/4/2014**: thanks everyone
```
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# ------------------------------------------------------------------------
# Filename : heatmap.py
# Date : 2013-04-19
# Updated :... |
Checking a file existence on a remote SSH server using Python | 14,392,432 | 4 | 2013-01-18T04:31:39Z | 14,392,472 | 13 | 2013-01-18T04:38:01Z | [
"python",
"file-io",
"file-exists"
] | I have two servers A and B. I'm suppose to send, let said an image file, from server A to another server B. But before server A could send the file over I would like to check if a similar file exist in server B. I try using os.path.exists() and it does not work.
```
print os.path.exists('ubuntu@serverB.com:b.jpeg')
``... | The `os.path` functions only work on files on the same computer. They operate on *paths*, and `ubuntu@serverB.com:b.jpeg` is not a path.
In order to accomplish this, you will need to remotely execute a script. Something like this will work, usually:
```
def exists_remote(host, path):
"""Test if a file exists at p... |
Per-cell output for threaded IPython Notebooks | 14,393,989 | 6 | 2013-01-18T07:05:16Z | 14,395,336 | 11 | 2013-01-18T08:54:49Z | [
"python",
"web-services",
"web-applications",
"ipython",
"ipython-notebook"
] | I don't want to raise this as an issue, because it seems like a completely unreasonable feature request for what is a fairly amazing tool. But if any readers happen to be familiar with the architecture I'd be interested to know if a potential extension seems feasible.
I recently wrote a notebook with some simple threa... | UPDATE:
> Am I correct in believing the the hard-wiring of Python 2's print statement means that this enhancement can not be implemented with a standard interpreter?
No, the important parts of the print statement are not hardwired at all. print simply writes to sys.stdout, which can be any object with `write` and `fl... |
How to drop extra copy of duplicate index of Pandas Series? | 14,395,678 | 10 | 2013-01-18T09:16:01Z | 14,400,659 | 17 | 2013-01-18T14:10:30Z | [
"python",
"pandas"
] | I have a Series `s` with duplicate index :
```
>>> s
STK_ID RPT_Date
600809 20061231 demo_str
20070331 demo_str
20070630 demo_str
20070930 demo_str
20071231 demo_str
20060331 demo_str
20060630 demo_str
20060930 demo_str
20061231 ... | You can groupby the index and apply a function that returns one value per index group. Here, I take the first value:
```
In [1]: s = Series(range(10), index=[1,2,2,2,5,6,7,7,7,8])
In [2]: s
Out[2]:
1 0
2 1
2 2
2 3
5 4
6 5
7 6
7 7
7 8
8 9
In [3]: s.groupby(s.index).first()
Out[3]:
1 0... |
PyQt4 - Drag and Drop | 14,395,799 | 6 | 2013-01-18T09:23:07Z | 14,410,888 | 13 | 2013-01-19T03:45:21Z | [
"python",
"qt",
"button",
"drag-and-drop",
"pyqt4"
] | Hey I had been going through this [tutorial](http://zetcode.com/tutorials/pyqt4/dragdrop/) for understanding drag and drop methods in PyQt4. However I am not able to understand the following points . It would be nice if somepne could make it clearer to me.
```
def mouseMoveEvent(self, e): //class Button
mimeDat... | That tutorial is seriously outdated. `QDrag.start` is obsolete since [Qt 4.3](http://doc.qt.digia.com/4.3/qdrag-obsolete.html). [`QDrag.exec_`](http://qt-project.org/doc/qt-4.8/qdrag.html#exec) should be used instead.
As you can see from the docs for `exec`, it has a return value. `setDropAction` in `dropEvent` determ... |
Celery: Chaining tasks with multiple arguments | 14,396,267 | 4 | 2013-01-18T09:51:21Z | 14,441,913 | 12 | 2013-01-21T15:29:06Z | [
"python",
"celery"
] | The celery documentation tells me that if multiple tasks are chained together, the result of the first task will be the first argument of the next. My problem is, I can't get it to work when I have a task that returns multiple results.
Example:
```
@task()
def get_comments(url):
#get the comments and the submissi... | There are two mistakes here.
First, you don't have to call `get_comments()` and `render_template()`. Instead, you should use the `.s()` task method. Like:
```
( get_comments.s(url) | render_template.s()).apply_async()
```
In your case, you launch the function first, and then tries to join functions results to a chai... |
Python: Questions about math and negative power | 14,397,964 | 3 | 2013-01-18T11:27:13Z | 14,398,056 | 9 | 2013-01-18T11:32:59Z | [
"python",
"algorithm",
"math"
] | I am trying to implement and algorithm and I am not sure how to implement in Python.
The algorithm is given as `[e ^ -ax] * [((e ^ by) - (e ^ -ax)) / ((e ^ by) + (e ^ -ax))]`
Where:
* `^` represents power of
* `e` is Euler's number with a value of `2.718`
* `a` and `b` are constants and given as `a = 0.2` and `b = 0... | For computing *e**x*, there's no need to write:
```
math.pow(math.e, x)
```
Instead, use [`math.exp`](http://docs.python.org/2/library/math.html#math.exp) and write:
```
math.exp(x)
```
or:
```
from math import exp
exp(x)
``` |
Can SQLAlchemy automatically create relationships from a database schema? | 14,398,329 | 10 | 2013-01-18T11:49:17Z | 14,403,228 | 8 | 2013-01-18T16:28:04Z | [
"python",
"sqlite",
"sqlalchemy",
"relationship",
"foreign-key-relationship"
] | Starting from an existing (SQLite) database with foreign keys, can SQLAlchemy automatically build [relationships](http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#building-a-relationship)?
SQLAlchemy classes are automatically created via `__table_args__ = {'autoload': True}`.
The goal would be to easily access... | **[Update]** As of SQLAlchemy 0.9.1 there is [Automap extension](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html) for doing that.
For SQLAlchemy < 0.9.0 it is possible to use sqlalchemy reflection.
SQLAlchemy reflection loads foreign/primary keys relations between tables. But doesn't create relation... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 14,399,775 | 48 | 2013-01-18T13:14:47Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | It can't take a file handle. The `install_requires` argument can [only be a string or a list of strings](http://peak.telecommunity.com/DevCenter/setuptools#new-and-changed-setup-keywords).
You can, of course, read your file in the setup script and pass it as a list of strings to `install_requires`.
```
import os
from... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 16,624,700 | 130 | 2013-05-18T13:18:24Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | A requirement file can contain comments (`#`) and can include some other files (`--requirement` or `-r`).
Thus, if you really want to parse a `requirement.txt` you should use the pip parser:
```
from pip.req import parse_requirements
# parse_requirements() returns generator of pip.req.InstallRequirement objects
insta... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 18,362,802 | 12 | 2013-08-21T16:23:17Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | Install the current package in Travis. This avoids the use of a `requirements.txt` file.
For example:
```
language: python
python:
- "2.7"
- "2.6"
install:
- pip install -q -e .
script:
- python runtests.py
``` |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 19,081,268 | 27 | 2013-09-29T17:48:42Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | Requirements files use an expanded pip format, which is only useful if you need to complement your `setup.py` with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of `pip freeze` to freeze the entire package set to known-working versions. If you don't n... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 22,649,833 | 16 | 2014-03-26T01:31:31Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | Using `parse_requirements` is problematic because the pip API isn't publicly documented and supported. In pip 1.6, that function is actually moving, so existing uses of it are likely to break.
A more reliable way to eliminate duplication between `setup.py` and `requirements.txt` is to specific your dependencies in `se... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 22,897,828 | 30 | 2014-04-06T18:02:07Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | While not an exact answer to the question, I recommend Donald Stufft's blog post at <https://caremad.io/2013/07/setup-vs-requirement/> for a good take on this problem. I've been using it to great success.
In short, `requirements.txt` is not a `setup.py` alternative, but a deployment complement. Keep an appropriate abs... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 29,655,844 | 17 | 2015-04-15T16:33:09Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | Most of the other answers above don't work with the current version of pip's API. Here is the correct\* way to do it with the current version of pip (6.0.8 at the time of writing, also worked in 7.1.2. You can check your version with pip -V).
```
from pip.req import parse_requirements
from pip.download import PipSessi... |
How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? | 14,399,534 | 129 | 2013-01-18T13:00:14Z | 33,685,899 | 21 | 2015-11-13T04:21:24Z | [
"python",
"pip",
"setuptools",
"requirements.txt"
] | I have a `requirements.txt` file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both `requirements.txt` and `setup.py`, so I was hoping to pass a file handle to the `install_requires` kwarg in `setuptools.setup`.
Is this possible?
If so, how should I go about doing it?
For good measur... | On the face of it, it does seem that `requirements.txt` and `setup.py` are silly duplicates, but it's important to understand that while the form is similar, the intended function is very different.
The goal of a package author, when specifying dependencies, is to say "wherever you install this package, these are the ... |
matplotlib: drawing lines between points ignoring missing data | 14,399,689 | 24 | 2013-01-18T13:09:12Z | 14,399,830 | 28 | 2013-01-18T13:18:36Z | [
"python",
"matplotlib"
] | I have a set of data which I want plotted as a line-graph. For each series, some data is missing (but different for each series). Currently matplotlib does not draw lines which skip missing data: for example
```
import matplotlib.pyplot as plt
xs = range(8)
series1 = [1, 3, 3, None, None, 5, 8, 9]
series2 = [2, None,... | You can mask the NaN values this way:
```
import numpy as np
import matplotlib.pyplot as plt
xs = np.arange(8)
series1 = np.array([1, 3, 3, None, None, 5, 8, 9]).astype(np.double)
s1mask = np.isfinite(series1)
series2 = np.array([2, None, 5, None, 4, None, 3, 2]).astype(np.double)
s2mask = np.isfinite(series2)
plt.p... |
py.test SetUp/TearDown for whole test suite | 14,399,908 | 7 | 2013-01-18T13:25:04Z | 14,400,902 | 10 | 2013-01-18T14:22:16Z | [
"python",
"unit-testing",
"py.test",
"xvfb"
] | I have a Python package that needs access to X11. I want to use Xvfb so that I do not have to have a real X11 installed on the build machines -- Hudson in this case. So, I would like to start a Xvfb server when py.test starts, use that one server for all the tests, then close it down.
How can I do that?
---
**Note**... | It is actually fairly simple. Create a file called `conftest.py` in your project root which contains this:
```
import pytest
import os
import subprocess
import tempfile
@pytest.fixture(scope="session", autouse=True)
def start_xvfb_server (request):
tempdir = tempfile.mkdtemp()
xvfb_cmd = ['Xvfb',
... |
How to return a static HTML file as a response in Django? | 14,400,035 | 5 | 2013-01-18T13:32:45Z | 14,400,167 | 10 | 2013-01-18T13:40:29Z | [
"python",
"django",
"static-html"
] | I have not figured out how I can present a website with pure HTML code and/or HTML + JavaScript + CSS.
I tried to load a HTML file with that just says: *Hello World*.
I know I can do that with Django too, but later on I want to display my website with CSS+JavaScript+HTML.
In the views file I run this code:
```
# Cr... | You are not calling the `render` method there, are you?
Compare:
```
template.render
template.render()
``` |
Python global lists | 14,402,557 | 2 | 2013-01-18T15:51:12Z | 14,402,573 | 10 | 2013-01-18T15:51:45Z | [
"python",
"list",
"globals"
] | I'm learning python, and am having a problem with global variables/lists. I'm writing a basic manual tower of hanoi program, here's the program currently:
```
pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]
def tower_of_hanoi():
global pillar1
global pillar2
global pillar3
print... | It's because you've "declared" it as `pilar1`, not `pillar1` |
Release a message back to SQS | 14,404,007 | 10 | 2013-01-18T17:09:38Z | 14,404,749 | 11 | 2013-01-18T17:55:29Z | [
"python",
"boto",
"amazon-sqs"
] | I have a some EC2 servers pulling work off of a SQS queue. Occasionally, they encounter a situation where the can't finish the job. I have the process email me of the condition. As it stands now, the message stays "in flight" until it times out. I would like for the process to immediately release it back to the queue a... | If you have read a message and decide, for whatever reason, that you do not want to process it and would rather make it immediately available to other readers of the queue, you can simply set that message's `visibility timeout` to zero using the `change_visibility` method of the `Message` object in boto. See [The SQS D... |
How can I see normal print output created during pytest run? | 14,405,063 | 57 | 2013-01-18T18:14:38Z | 14,414,325 | 67 | 2013-01-19T12:22:57Z | [
"python",
"py.test"
] | Sometimes I want to just insert some print statements in my code, and see what gets printed out when I exercise it. My usual way to "exercise" it is with existing pytest tests. But when I run these, I don't seem able to see any standard output (at least from within PyCharm, my IDE).
Is there a simple way to see standa... | The [`-s` switch](http://pytest.org/latest/capture.html) disables per-test capturing. |
How can I see normal print output created during pytest run? | 14,405,063 | 57 | 2013-01-18T18:14:38Z | 38,035,646 | 19 | 2016-06-26T05:58:13Z | [
"python",
"py.test"
] | Sometimes I want to just insert some print statements in my code, and see what gets printed out when I exercise it. My usual way to "exercise" it is with existing pytest tests. But when I run these, I don't seem able to see any standard output (at least from within PyCharm, my IDE).
Is there a simple way to see standa... | In an [upvoted comment](https://stackoverflow.com/questions/14405063/how-can-i-see-normal-print-output-created-during-pytest-run#comment47203398_14414325) to the [accepted answer](https://stackoverflow.com/a/14414325/2809027), [Joe](https://stackoverflow.com/users/1741414/joe) asks:
> Is there any way to print to the ... |
Moving x-axis to the top of a plot in matplotlib | 14,406,214 | 39 | 2013-01-18T19:28:44Z | 14,406,442 | 10 | 2013-01-18T19:42:31Z | [
"python",
"matplotlib",
"plot",
"data-visualization"
] | Based on [this question about heatmaps in matplotlib](http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor), I wanted to move the x-axis titles to the top of the plot.
```
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random... | You want [`set_ticks_position`](http://matplotlib.org/api/axis_api.html#matplotlib.axis.XAxis.set_ticks_position) rather than `set_label_position`:
```
ax.xaxis.set_ticks_position('top') # the rest is the same
```
This gives me:
 |
Moving x-axis to the top of a plot in matplotlib | 14,406,214 | 39 | 2013-01-18T19:28:44Z | 14,406,447 | 48 | 2013-01-18T19:42:58Z | [
"python",
"matplotlib",
"plot",
"data-visualization"
] | Based on [this question about heatmaps in matplotlib](http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor), I wanted to move the x-axis titles to the top of the plot.
```
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random... | Use
```
ax.xaxis.tick_top()
```
to place the tick marks at the top of the image. The command
```
ax.set_xlabel('X LABEL')
ax.xaxis.set_label_position('top')
```
affects the label, not the tick marks.
```
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.