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 |
|---|---|---|---|---|---|---|---|---|---|
Comparing two lists in python if elements exist | 22,011,812 | 3 | 2014-02-25T10:46:17Z | 22,011,882 | 7 | 2014-02-25T10:49:02Z | [
"python"
] | I have two lists where I want to check if elements from a exists in b
```
a=[1,2,3,4]
b=[4,5,6,7,8,1]
```
This is what I tried ( didn't work though!)
```
a=[1,2,3,4]
b=[4,5,6,7,3,1]
def detect(list_a, list_b):
for item in list_a:
if item in list_b:
return True
return False # not found
... | Your code returns as soon as first element exists in both lists. To check all elements you could try this for example:
```
def detect(list_a, list_b):
return set(list_a).issubset(list_b)
```
Other possibility, without creating a `set`:
```
def detect(list_a, list_b):
return all(x in list_b for x in list_a)
`... |
How to set number of ticks in plt.colorbar? | 22,012,096 | 4 | 2014-02-25T10:58:18Z | 22,013,008 | 12 | 2014-02-25T11:34:20Z | [
"python",
"matplotlib",
"colorbar"
] | When I plot a matrix with a colorbar, then the colorbar has 10 ticks. Since the colorbar has to be pretty small, the ticklabels overlap. Therefore I want to reduce the number of ticks from 10 to 5. I do not want to reduce the font size!
Is there an easy way to do this? I do not want to set the ticks manually... | The [MaxNLocator](http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.MaxNLocator) ticker might suit your purposes?
> class **matplotlib.ticker.MaxNLocator**
>
> Select no more than N intervals at nice locations
For example:
```
from matplotlib import ticker
# (generate plot here)
cb = plt.colorbar()
tick_l... |
Python peewee joins multiple tables | 22,016,778 | 6 | 2014-02-25T14:14:57Z | 22,104,051 | 10 | 2014-02-28T19:21:39Z | [
"python",
"join",
"foreign-keys",
"peewee"
] | I want to be able to join multiple tables in peewee. However the scenario is a little difficult for me to figure out how to get it to work with peewee.
I have the following tables:
Ticket
TicketCategory
TicketBooking
Event
Here are my models:
```
class TicketCategory(BaseModel):
venue_id = IntegerField()
na... | Going to try answering this one more time.
```
(TicketBooking
.select(
TicketBooking,
Ticket,
TicketCategory,
Event)
.join(Ticket)
.join(TicketCategory)
.join(Event)
.where(
TicketBooking.user_id == user_id,
TicketBooking.deleted >> None
))
```
You're almost there. Try instead:
... |
Python: Is isinstance() necessary in this case? | 22,018,652 | 5 | 2014-02-25T15:24:33Z | 22,018,814 | 7 | 2014-02-25T15:31:34Z | [
"python",
"method-overloading"
] | I defined a class `Time` that has three int attributes: `hrs, min, sec`
And I defined methods `intToTime()` that convert a `Time` instance to an `int`, which is the number of seconds in that time, and also a method `timeToInt()` that do the reverse.
I'd like them to implement `__add__`, so I can do things like **"Tim... | You really have two choices: EAFP or LYBL. EAFP (easier to ask forgiveness than permission) means use try/except:
```
def __add__(self, other):
try:
return Time.intToTime(self, Time.timeToInt(self)+Time.timeToInt(other))
except AttributeError as e:
return Time.intToTime(self, Time.timeToInt(self) +... |
Pandas Writing Dataframe Columns to csv | 22,019,763 | 6 | 2014-02-25T16:07:59Z | 22,019,831 | 13 | 2014-02-25T16:11:05Z | [
"python",
"csv",
"pandas"
] | I'm writing a script to reduce a large .xlsx file with headers into a csv, and then write a new csv file with only the required columns based on header name.
```
import pandas
import csv
df = pandas.read_csv('C:\\Python27\\Work\\spoofing.csv')
time = df["InviteTime (Oracle)"]
orignum = df["Orig Number"]
origip = df[... | The way to select specific columns is this -
```
header = ["InviteTime (Oracle)", "Orig Number", "Orig IP Address", "Dest Number"]
df.to_csv('output.csv', columns = header)
``` |
Share image from mpldatacursor with others | 22,021,297 | 2 | 2014-02-25T17:09:53Z | 22,024,663 | 9 | 2014-02-25T19:50:52Z | [
"python",
"pdf",
"svg",
"matplotlib"
] | I am using the example at [How to show data labels when you mouse over data](http://stackoverflow.com/questions/21998663/how-to-show-data-labels-when-you-mouse-over-data) to make an image where data appears when you mouse over points. This works really well but is there some way of saving it so I can send the image to ... | There may be ways to make things work with svg and a bit of javascript or pdf tooltips, as you suggested (I didn't know pdf tooltips existed until you mentioned them!).
As an aside, I should take a moment to mention [`mpld3`](https://github.com/jakevdp/mpld3) which recreates matplotlib figures as javascript visualizat... |
Django/MySQL-python - Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled) | 22,023,387 | 6 | 2014-02-25T18:45:30Z | 22,023,388 | 7 | 2014-02-25T18:45:30Z | [
"python",
"mysql",
"django"
] | So many people have experienced this problem on SO, yet almost all the answers are useless.
```
Traceback (most recent call last):
File "/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run
self.validate(display_num_errors=True)
File "/venv/local/lib/pyth... | After much trial/error, the problem was narrowed down to passwords using an old encryption style.
```
mysql> select User, Password from mysql.user;
| user1 | *113D91F3A36D29C287C457A20D602FA384B8569F |
| user2 | 5d78f2535e56dfe0 |
```
Tools such as Navicat do not automatically use newer style pass... |
Django/MySQL-python - Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled) | 22,023,387 | 6 | 2014-02-25T18:45:30Z | 22,628,258 | 23 | 2014-03-25T07:45:10Z | [
"python",
"mysql",
"django"
] | So many people have experienced this problem on SO, yet almost all the answers are useless.
```
Traceback (most recent call last):
File "/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run
self.validate(display_num_errors=True)
File "/venv/local/lib/pyth... | For MySQL Workbench 6.08 in the Manage Server Connections, Connection tab, Advanced sub-tab you must check the box '**Use the old authentication protocol**.'
 |
Django/MySQL-python - Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled) | 22,023,387 | 6 | 2014-02-25T18:45:30Z | 30,037,546 | 8 | 2015-05-04T18:40:31Z | [
"python",
"mysql",
"django"
] | So many people have experienced this problem on SO, yet almost all the answers are useless.
```
Traceback (most recent call last):
File "/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run
self.validate(display_num_errors=True)
File "/venv/local/lib/pyth... | I had the same problem trying to connect with `mysql` command line client, and I could avoid the error with `--skip-secure-auth` option.
For example:
```
mysql DBNAME -h HOST_NAME_OR_IP -u DB_USER --password="PASSWORD" --skip-secure-auth
```
Same parameter for the other *mysqlX* commands like `mysqldump`. |
Shape Detection in python using OpenCV | 22,023,923 | 4 | 2014-02-25T19:13:50Z | 22,042,006 | 7 | 2014-02-26T12:52:07Z | [
"python",
"opencv",
"shapes"
] | I'm working on a project in which I use OpenCV to detect shapes and their colors.
There are 5 colors (red, green, yellow, blue and white) and 4 shapes (rectangle, star, circle and heart). I've been able to reliably discern the colors and I can detect the shapes when the image used is a drawn image like [this](http://i... | Here is the code I proceed with your image, the code will do
1. Blur the source
2. Canny Edge detection.
3. Find contour.
4. approxPolyDP for the contour.
5. Check total size of approxPolyDP points.
> Code:
```
Mat src=imread("src.jpg",1);
Mat thr,gray;
blur(src,src,Size(3,3));
cvtColor(src,gray,CV_BGR2G... |
Jinja2 template not rendering if-elif-else statement properly | 22,024,661 | 5 | 2014-02-25T19:50:45Z | 22,024,797 | 10 | 2014-02-25T19:56:49Z | [
"python",
"css",
"jinja2"
] | I am trying to set the text color using css in a jinja2 template. In the following code I want to set the output string to print in a specific font color if the variable contains a string. Everytime the template is generated though it prints in red due to the else statement, it never see the first two conditions even t... | You are testing if the values of the *variables* `error` and `Already` are present in `RepoOutput[RepoName.index(repo)]`. If these variables don't exist then an [undefined object](http://jinja.pocoo.org/docs/templates/#variables) is used.
Both of your `if` and `elif` tests therefore are false; there is no undefined ob... |
Calculating permutations without repetitions in Python | 22,025,211 | 4 | 2014-02-25T20:17:38Z | 22,025,273 | 7 | 2014-02-25T20:20:37Z | [
"python",
"itertools"
] | I have two lists of items:
```
A = 'mno'
B = 'xyz'
```
I want to generate all permutations, without replacement, simulating replacing all combinations of items in A with items in B, without repetition. e.g.
```
>>> do_my_permutation(A, B)
['mno', 'xno', 'mxo', 'mnx', 'xyo', 'mxy', 'xyz', 'zno', 'mzo', 'mnz', ...]
``... | Is this what you need:
```
["".join(elem) for elem in itertools.permutations(A+B, 3)]
```
and replace `permutations` with `combinations` if you want all orderings of the same three letters to be collapsed down into a single item (e.g. so that `'mxo'` and `'mox'` do not each individually appear in the output). |
openssl, python requests error: "certificate verify failed" | 22,027,418 | 15 | 2014-02-25T22:14:57Z | 22,032,661 | 9 | 2014-02-26T05:32:27Z | [
"python",
"openssl",
"python-requests"
] | If I run the following command from my development box:
```
$ openssl s_client -connect github.com:443
```
I get the following last line of output:
```
Verify return code: 20 (unable to get local issuer certificate)
```
If I try to do this with requests I get another failed request:
```
>>> import requests
>>> r =... | > If I run the following command from my development box:
>
> ```
> $ openssl s_client -connect github.com:443
> ```
>
> I get the following last line of output:
>
> ```
> Verify return code: 20 (unable to get local issuer certificate)
> ```
You are missing `DigiCert High Assurance EV CA-1` as a root of trust:
```
$ ... |
Python: Getting a WindowsError instead of an IOError | 22,027,508 | 5 | 2014-02-25T22:21:04Z | 22,027,543 | 10 | 2014-02-25T22:23:00Z | [
"python",
"windows",
"exception-handling"
] | I am trying to understand exceptions with Python 2.7.6, on Windows 8.
Here's the code I am testing, which aims to create a new directory at `My_New_Dir`. If the directory already exists, I want to delete the entire directory and its contents, and then create a fresh directory.
```
import os
dir = 'My_New_Dir'
try:
... | `WindowsError` is a subclass of `OSError`. From the [exceptions documentation](http://docs.python.org/2/library/exceptions.html#exceptions.WindowsError):
> Raised when a Windows-specific error occurs or when the error number does not correspond to an `errno` value. The `winerror` and `strerror` values are created from... |
Django - DateTimeField received a naive datetime | 22,028,004 | 4 | 2014-02-25T22:54:10Z | 22,028,380 | 9 | 2014-02-25T23:19:57Z | [
"python",
"django",
"datetime"
] | Basically I have the following model:
```
class Event(models.Model):
start = models.DateTimeField(default=0)
```
and when I try to create an object using datetime.datetime.strptime I get
```
Event.objects.create(start=datetime.datetime.strptime("02/03/2014 12:00 UTC",
... | That warning is logged since you are using time zones and you are creating a datetime object "manually". I also suggest you to turn the warning into an error by adding:
```
import warnings
warnings.filterwarnings('error',
r"DateTimeField .* received a naive datetime",
Ru... |
Matplotlib boxplot without outliers | 22,028,064 | 7 | 2014-02-25T22:58:07Z | 22,028,426 | 17 | 2014-02-25T23:23:26Z | [
"python",
"matplotlib",
"boxplot"
] | Is there any way of hiding the outliers when plotting a boxplot in matplotlib (python)?
I'm using the simplest way of plotting it:
```
from pylab import *
boxplot([1,2,3,4,5,10])
show()
```
This gives me the following plot:
(I cannot post the image because I have not enough reputation, but basically it is a b... | In current versions of matplotlib you can do:
```
boxplot([1,2,3,4,5,10], showfliers=False)
```
or
```
boxplot([1,2,3,4,5,10], sym='')
```
In older versions, only the second approach will work.
The [docs](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot) for `boxplot` do mention this, btw as, "E... |
Tried Python BeautifulSoup and Phantom JS: STILL can't scrape websites | 22,028,775 | 3 | 2014-02-25T23:49:00Z | 22,030,553 | 11 | 2014-02-26T02:32:58Z | [
"javascript",
"python",
"web-scraping",
"beautifulsoup",
"phantomjs"
] | You may have seen my desperate frustrations over the past few weeks on here. I've been scraping some wait time data and am still unable to grab data from these two sites
<http://www.centura.org/erwait>
<http://hcavirginia.com/home/>
At first I tried BS4 for Python. Sample code below for HCA Virgina
```
from Beautif... | The problem you're facing is that the elements are created by JS, and it might take some time to load them. You need a scraper which handles JS, and can wait until the required elements are created.
You can use [PyQt4](http://www.riverbankcomputing.co.uk/software/pyqt/download). Adapting [this recipe from webscraping.... |
Weighted average using pivot tables in pandas | 22,032,153 | 3 | 2014-02-26T04:58:02Z | 22,043,089 | 7 | 2014-02-26T13:37:10Z | [
"python",
"pandas",
"pivot-table"
] | I have written some code to compute a weighted average using pivot tables in pandas. However, I am not sure how to add the actual column which performs the weighted averaging (Add a new column where each row contains value of 'cumulative'/'COUNT').
The data looks like so:
```
VALUE COUNT GRID agb
1 43 ... | So you want, for each value of `grid`, the weighted average of the `agb` column where the weights are the values in the `count` column. If that interpretation is correct, I think this does the trick with `groupby`:
```
import numpy as np
import pandas as pd
np.random.seed(0)
n = 50
df = pd.DataFrame({'count': np.ran... |
Numpy: Drop rows with all nan or 0 values | 22,032,668 | 9 | 2014-02-26T05:32:51Z | 22,033,364 | 10 | 2014-02-26T06:18:48Z | [
"python",
"numpy",
"pandas"
] | I'd like to drop all values from a table if the rows = `nan` or `0`.
I know there's a way to do this using pandas i.e `pandas.dropna(how = 'all')` but I'd like a numpy method to remove rows with all `nan` or `0`.
Is there an efficient implementation of this? | ```
import numpy as np
a = np.array([
[1, 0, 0],
[0, np.nan, 0],
[0, 0, 0],
[np.nan, np.nan, np.nan],
[2, 3, 4]
])
mask = np.all(np.isnan(a) | np.equal(a, 0), axis=1)
a[~mask]
``` |
Where to use pass statement in python?How can i use pass statement efficiently? | 22,035,622 | 2 | 2014-02-26T08:24:46Z | 22,035,660 | 7 | 2014-02-26T08:26:43Z | [
"python"
] | I am unable to understand the use of the `pass` statement in Python.
I have found some sample code [here](http://www.tutorialspoint.com/python/python_pass_statement.htm) in which there is a `pass` statement but I am unable to figure out what it is useful for in this context:
```
for letter in 'Python':
if letter... | A *pass* is a NOP in Python. It has no effect on efficiency. It is merely used as a syntactic placeholder to mark an empty block.
You can use the [*dis* module](http://docs.python.org/2.7/library/dis.html#module-dis) to see that there is no difference in the generated code when using the [pass-statement](http://docs.p... |
Flask-restful: marshal complex object to json | 22,035,974 | 11 | 2014-02-26T08:43:10Z | 22,063,095 | 18 | 2014-02-27T08:37:16Z | [
"python",
"json",
"rest",
"flask",
"flask-restful"
] | I have a question regarding flask restful extension. I'm just started to use it and faced one problem. I have `flask-sqlalchemy` entities that are connected many-to-one relation and I want that restful endpoint return parent entity with all its children in `json` using marshaller. In my case Set contains many parameter... | I found solution to that problem myself.
After playing around with `flask-restful` i find out that i made few mistakes:
Firstly `set_marshaller` should look like this:
```
blob_marshaller = {
'id': fields.String,
'title': fields.String,
'parameters': fields.Nested(parameter_marshaller)
}
```
Restless ma... |
python set comprehension made out of different lists | 22,036,612 | 2 | 2014-02-26T09:11:36Z | 22,036,656 | 7 | 2014-02-26T09:13:38Z | [
"python",
"set",
"python-2.6"
] | ```
expected = {
'l1': ['abc', 'def', 'ghi', 'jkl'],
'l2': ['abc', 'ghi', 'jkl', 'mno']
}
```
I would like to get `set(['abc', 'def', 'ghi', 'jkl', 'mno'])` using python 2.6+ (so `{x for x in ...}` is not what I want).
I've tried
```
all_files = set(files for files in expected.values())
```
but it throws:
... | ```
>>> expected = {
... 'l1': ['abc', 'def', 'ghi', 'jkl'],
... 'l2': ['abc', 'ghi', 'jkl', 'mno']
... }
>>> set(f for files in expected.itervalues() for f in files)
set(['jkl', 'abc', 'ghi', 'def', 'mno'])
```
or using [`itertools.chain.from_iterable`](http://docs.python.org/2/library/itertools.html#itertool... |
Modify or Delete Exif tag 'Orientation' in Python | 22,045,882 | 6 | 2014-02-26T15:28:26Z | 22,840,805 | 7 | 2014-04-03T14:30:34Z | [
"python",
"python-imaging-library",
"exif"
] | I need some of my pictures to be displayed with the same orientation whether the software reads the exif data or not. One solution (the only one that could fit actually) would be to rotate the image according to the exif tag if it exists and then delete or modify this tag to '1'.
**Example**
*Let's say an image has ... | ### note:
This answer works for Python2.7 - you can probably just swap Pillow for PIL in Python3, but I can't speak to that from experience. Note that unlike pyexiv2 and most of the other packages that allow you to modify EXIF metadata, the pexif library is standalone and pure python, so it does not need to bind to an... |
Django dynamically get view url and check if its the current page | 22,047,251 | 9 | 2014-02-26T16:24:32Z | 22,047,996 | 23 | 2014-02-26T16:53:27Z | [
"python",
"django",
"django-templates"
] | Consider this basic menu:
```
<ul class="nav navbar-nav">
<li class="active"><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'about' %}">About</a></li>
</ul>
```
I'm trying to give the current page's link an active class, and I want to do this dynamically based on current url and the view's url. So t... | I usually use template inheritance in my navigation, in a similar way to the [answer alecxe linked to](http://stackoverflow.com/questions/340888/navigation-in-django). However, it is possible to compare the use the current URL in an if tag, as you are trying to do.
The [`url`](https://docs.djangoproject.com/en/1.6/ref... |
Configuring Flask to correctly load Bootstrap js and css files | 22,047,398 | 6 | 2014-02-26T16:30:12Z | 22,047,703 | 12 | 2014-02-26T16:42:41Z | [
"python",
"flask"
] | How can you use the "url\_for" directive in Flask to correctly set things up so a html page that uses Bootstrap and RGraph works ?
Say my html page looks like this (partial snippet) :-
```
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="scripts/bootstrap/dist/css... | Put the `scripts` directory in your `static` subdirectory, then use:
```
<link href="{{ url_for('static', filename='scripts/bootstrap/dist/css/bootstrap.css') }}" rel="stylesheet">
```
The pattern here is:
```
{{ url_for('static', filename='path/inside/the/static/directory') }}
```
which will be replaced with the c... |
How to use Bigquery streaming insertall on app engine & python | 22,049,248 | 12 | 2014-02-26T17:48:54Z | 22,053,924 | 9 | 2014-02-26T21:38:28Z | [
"python",
"google-app-engine",
"google-bigquery"
] | I would like to develop an app engine application that directly stream data into a BigQuery table.
According to Google's documentation there is a simple way to stream data into bigquery:
* <http://googlecloudplatform.blogspot.co.il/2013/09/google-bigquery-goes-real-time-with-streaming-inserts-time-based-queries-and-m... | Minimal working (as long as you fill in the right ids for your project) example:
```
import httplib2
from apiclient import discovery
from oauth2client import appengine
_SCOPE = 'https://www.googleapis.com/auth/bigquery'
# Change the following 3 values:
PROJECT_ID = 'your_project'
DATASET_ID = 'your_dataset'
TABLE_ID... |
A simple Hello World setuptools package and installing it with pip | 22,051,360 | 10 | 2014-02-26T19:31:02Z | 22,188,676 | 11 | 2014-03-05T04:38:10Z | [
"python",
"pip",
"setuptools",
"distutils",
"pypi"
] | I'm having trouble figuring out how to install my package using setuptools, and I've tried reading the documentation on it and SO posts, but I can't get it to work properly. I'm trying to get a simple helloworld application to work. This is how far I got:
helloworld.py:
```
print("Hello, World!")
```
README.txt:
``... | Okay, so after some effort, I finally managed to get a simple **"hello world"** example working for setuptools. The Python documentation is usually amazing, but I wish the documentation was better on this in particular.
I'm going to write a fairly detailed guide on how I achieved this, and I'll assume no prior backgro... |
Can I access sys.argv in python in interactive mode? | 22,052,539 | 5 | 2014-02-26T20:28:02Z | 22,052,636 | 12 | 2014-02-26T20:34:33Z | [
"python",
"read-eval-print-loop",
"argv"
] | I'd like to do something like:
```
% python foo bar
import sys
sys.argv
```
to get:
```
% ['foo', 'bar']
```
but of course python dies when you enter an argument which is not a script or goes into non interactive mode if you do.
Can I do this somehow? | Use `-` as script name:
```
python - foo bar
```
Test:
```
>>> import sys
>>> sys.argv
['-', 'foo', 'bar']
``` |
Difference between numpy.array shape (R, 1) and (R,) | 22,053,050 | 64 | 2014-02-26T20:55:35Z | 22,074,424 | 100 | 2014-02-27T16:26:01Z | [
"python",
"numpy",
"matrix",
"multidimensional-array"
] | In `numpy`, some of the operations return in shape `(R, 1)` but some return `(R,)`. This will make matrix multiplication more tedious since explicit `reshape` is required. For example, given a matrix `M`, if we want to do `numpy.dot(M[:,0], numpy.ones((1, R)))` where `R` is the number of rows (of course, the same issue... | ### 1. The meaning of shapes in NumPy
You write, "I know literally it's list of numbers and list of lists where all list contains only a number" but that's a bit of an unhelpful way to think about it.
The best way to think about NumPy arrays is that they consist of two parts, a *data buffer* which is just a block of ... |
OLS Regression: Scikit vs. Statsmodels? | 22,054,964 | 10 | 2014-02-26T22:34:31Z | 22,070,343 | 15 | 2014-02-27T13:42:25Z | [
"python",
"scikit-learn",
"linear-regression",
"statsmodels"
] | *Short version*: I was using the scikit LinearRegression on some data, but I'm used to p-values so put the data into the statsmodels OLS, and although the R^2 is about the same the variable coefficients are all different by large amounts. This concerns me since the most likely problem is that I've made an error somewhe... | It sounds like you are not feeding the same matrix of regressors `X` to both procedures (but see below). Here's an example to show you which options you need to use for sklearn and statsmodels to produce identical results.
```
import numpy as np
import statsmodels.api as sm
from sklearn.linear_model import LinearRegre... |
Uniqueness in a list of lists with lists | 22,057,235 | 2 | 2014-02-27T01:29:43Z | 22,057,283 | 7 | 2014-02-27T01:33:37Z | [
"python",
"list"
] | I have a list of lists and some of the lists have a list in it:
```
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
```
I have tried getting uniqueness to obtain:
```
x = [[[1,2],3],[[3,4],5]]
```
But no luck - any ideas?
I have so far used:
```
unique_data = [list(el) for el in set(tuple(el) for el in x)]
```
on a list of... | ```
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
print [item for idx, item in enumerate(x) if x.index(item) == idx]
# [[[1, 2], 3], [[3, 4], 5]]
```
We can do this in O(N) like this
```
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
x = tuple(tuple(tuple(j) if isinstance(j, list) else j for j in i) for i in x)
from collections import ... |
Hashing a file in Python | 22,058,048 | 9 | 2014-02-27T02:50:27Z | 22,058,673 | 15 | 2014-02-27T03:52:35Z | [
"python",
"hash",
"md5",
"sha1",
"hashlib"
] | I want python to read to the EOF so I can get an appropriate hash, whether it is sha1 or md5. Please help. Here is what I have so far:
```
import hashlib
inputFile = raw_input("Enter the name of the file:")
openedFile = open(inputFile)
readFile = openedFile.read()
md5Hash = hashlib.md5(readFile)
md5Hashed = md5Hash.... | **TL;DR use buffers to not use tons of memory.**
We get to the crux of your problem, I believe, when we consider the memory implications of working with **very large files**. We don't want this bad boy to churn through 2 gigs of ram for a 2 gigabyte file so, as [pasztorpisti](http://stackoverflow.com/users/3059438/pas... |
Getting "pika.exceptions.ConnectionClosed" error while using rabbitmq in python | 22,061,082 | 3 | 2014-02-27T06:49:46Z | 22,070,795 | 7 | 2014-02-27T14:00:39Z | [
"python",
"rabbitmq",
"pika"
] | I am using "hello world" tutorial in :<http://www.rabbitmq.com/tutorials/tutorial-two-python.html> .
`worker.py` looks like this
```
import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_que... | There is a concept of `heartbeats`. It's basically a way how the server can make sure that the client is still connected.
when you do
```
time.sleep( body.count('.') )
```
You blocking the code by `N` number of seconds. It means that if server would like to send a `heartbeat` frame to check if your client is still a... |
How to use django-contact-form (third-party app)? | 22,061,178 | 3 | 2014-02-27T06:55:15Z | 22,061,179 | 13 | 2014-02-27T06:55:15Z | [
"python",
"django",
"email-integration",
"contact-form"
] | **[django-contact-form](https://bitbucket.org/ubernostrum/django-contact-form)** is a popular third-party application. It aims to remove tedium and repetition by providing simple, extensible contact-form functionality for Django-powered sites. However I found the [documentation](http://django-contact-form.readthedocs.o... | ## 1. Install
```
pip install django-contact-form
```
## 2. Add necessary configuration to `settings.py`
```
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]' # this is my email address, use yours
EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD'] ... |
tornado vs wsgi(with gunicorn) | 22,062,307 | 10 | 2014-02-27T07:53:31Z | 22,067,306 | 20 | 2014-02-27T11:36:01Z | [
"python",
"tornado",
"wsgi",
"uwsgi",
"gunicorn"
] | I read [this](http://rz.scale-it.pl/2013/01/25/tornado___the_best_web_framework.html) about Tornado:
> On the other hand, if you already have a WSGI app and want to run it
> on a blazing fast tornado.httpserver.HTTPServer, wraps it with
> tornado.wsgi.WSGIContainer. But you need to be careful. Since your
> original ap... | If you are running a WSGI application on top of Tornado, then there isn't a great deal of difference between Tornado and gunicorn in as much as nothing else can happen so long as the WSGI request is being handled by the application in a specific process. In the case of gunicorn because it only has one thread handling r... |
Split value of string within array of arrays in Python | 22,064,666 | 4 | 2014-02-27T09:46:23Z | 22,064,717 | 12 | 2014-02-27T09:48:53Z | [
"python",
"arrays"
] | I've an arrays of arrays called `arr` and I want to split the second value of each array. This means, if I've `0-6` I would like to modify it to `'0','6'`
What I have:
```
arr = [['PROVEEDOR', '0-6', '11111'], ['tiempo ida pulidor', '6-14', '33333']]
```
What I would like to have:
```
arr = [['PROVEEDOR', '0', '6',... | If you want to do it inplace:
```
In [83]: arr = [['PROVEEDOR', '0-6', '11111'], ['tiempo ida pulidor', '6-14', '33333']]
In [84]: for i in arr:
...: i[1:2]=i[1].split('-')
In [85]: arr
Out[85]: [['PROVEEDOR', '0', '6', '11111'], ['tiempo ida pulidor', '6', '14', '33333']]
``` |
Is there a way to remove duplicate and continuous words/phrases in a string? | 22,065,164 | 5 | 2014-02-27T10:07:11Z | 22,065,423 | 14 | 2014-02-27T10:19:04Z | [
"python",
"regex",
"string"
] | Is there a way to remove duplicate and **continuous** words/phrases in a string? E.g.
**[in]:** `foo foo bar bar foo bar`
**[out]:** `foo bar foo bar`
I have tried this:
```
>>> s = 'this is a foo bar bar black sheep , have you any any wool woo , yes sir yes sir three bag woo wu wool'
>>> [i for i,j in zip(s.split(... | You can use re module for that.
```
>>> s = 'foo foo bar bar'
>>> re.sub(r'\b(.+)\s+\1\b', r'\1', s)
'foo bar'
>>> s = 'foo bar foo bar foo bar'
>>> re.sub(r'\b(.+)\s+\1\b', r'\1', s)
'foo bar foo bar'
```
If you want to match any number of consecutive occurrences:
```
>>> s = 'foo bar foo bar foo bar'
>>> re.sub(r... |
Why does np.arccos(1.0) give nan if fed by np.arange? | 22,067,169 | 2 | 2014-02-27T11:30:28Z | 22,067,509 | 7 | 2014-02-27T11:44:17Z | [
"python",
"numpy",
"trigonometry"
] | Can anyone replicate this?
```
import numpy as np
print np.arccos(1.0)
print np.arccos(1)
for x in np.arange(0.7,1,0.05):
print x
print np.arccos(x)
```
Output:
```
0.0
0.0
0.7
0.795398830184
0.75
0.722734247813
0.8
0.643501108793
0.85
0.55481103298
0.9
0.451026811796
0.95
0.317560429292
1.0
nan
```
Note th... | This is normal floating point inaccuracy. Adding 0.05 many times to 0.7 does not necessarily add up to 1 exactly.
Changing `print x` to `print repr(x)` outputs 1.0000000000000002 for the last `x`.
```
>>> np.arccos(1.0000000000000002)
__main__:1: RuntimeWarning: invalid value encountered in arccos
nan
``` |
Iterate over sections in a config file | 22,068,050 | 3 | 2014-02-27T12:07:02Z | 22,068,274 | 14 | 2014-02-27T12:16:23Z | [
"python",
"file",
"configuration",
"sections"
] | I recently go introduced to the library configparser. I would be to check if each section has at least one Boolean value set to one. For example...
```
[Horizontal_Random_Readout_Size]
Small_Readout = 0
Medium_Readout = 0
Large_Readout = 0
```
The above would cause an error.
```
[Vertical_Random_Readout_Size]
Smal... | Using [`ConfigParser`](http://docs.python.org/2/library/configparser.html) you have to parse your config.
After parsing you will get all sections using [`.sections()`](http://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.sections) method.
You can iterate over each section and use [`.items()... |
RealTime output from a subprogram to stdout of a pyQT Widget | 22,069,321 | 5 | 2014-02-27T13:01:08Z | 22,110,924 | 12 | 2014-03-01T06:18:09Z | [
"python",
"subprocess",
"pyqt4"
] | Hi I have seen there are already many questions on this issue however none of them seems to answer my query .
As per below link i even tried winpexpect as i am using windows , however it dosent seems to e working for me .
[Getting realtime output from ffmpeg to be used in progress bar (PyQt4, stdout)](http://stackover... | [`QProcess`](http://qt-project.org/doc/qt-4.8/qprocess.html) is very similar to `subprocess`, but it's much more convenient to use in (Py)Qt code. Because it utilizes signals/slots. Also, it runs the process asynchronously so you don't have use `QThread`.
I've modified (and cleaned) your code for `QProcess`:
```
impo... |
python garbage collector behavior on compound objects | 22,069,727 | 9 | 2014-02-27T13:18:06Z | 22,069,815 | 13 | 2014-02-27T13:21:11Z | [
"python",
"garbage-collection",
"python-internals"
] | Does python garbage collector cleans up a compound object if some of its parts are still referenced
e.g.
```
def foo():
A = [ [1, 3, 5, 7], [2, 4, 6, 8]]
return A[1]
B = foo()
```
Will `A[0]` be garbage collected?
Is there a way to confirm the same through code? | Nothing references the list `A` and the nested list `A[0]`, so yes, they will be deleted from memory.
The nested list object referenced by `A[1]` has no connection back to its original container.
Note that it's not the garbage collector that does this; the GC only deals in breaking circular references. This simple ca... |
Create a legend with pandas and matplotlib.pyplot | 22,070,263 | 7 | 2014-02-27T13:38:49Z | 22,070,926 | 22 | 2014-02-27T14:06:13Z | [
"python",
"matplotlib",
"pandas"
] | This is my first attempt at plotting with python and I'm having problems creating a legend.
These are my imports:
```
import matplotlib.pyplot as plt
import pandas
```
I load my data like this:
```
data = pandas.read_csv( 'data/output/limits.dat', sep=r"\s+", encoding = 'utf-8' )
```
and plot it like this:
```
ax... | I think what you want to do is be able to display a legend for a subset of the lines on your plot. This should do it:
```
df = pd.DataFrame(np.random.randn(400, 4), columns=['one', 'two', 'three', 'four'])
ax1 = df.cumsum().plot()
lines, labels = ax1.get_legend_handles_labels()
ax1.legend(lines[:2], labels[:2], loc='b... |
Generate random array of floats between a range | 22,071,987 | 6 | 2014-02-27T14:50:23Z | 22,072,276 | 7 | 2014-02-27T15:00:58Z | [
"python",
"arrays",
"random",
"numpy"
] | This might be a silly question but I haven't been able to find a function to generate an array of random floats of a given length between a certain range.
I've looked at [Random sampling](http://docs.scipy.org/doc/numpy/reference/routines.random.html) but no function seems to do what I need.
[random.uniform](http://d... | `np.random.uniform` fits your use case:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html>
```
sampl = np.random.uniform(low=0.5, high=13.3, size=(50,))
``` |
Failed to install Python Cryptography package with PIP and setup.py | 22,073,516 | 120 | 2014-02-27T15:50:27Z | 22,210,069 | 216 | 2014-03-05T21:47:59Z | [
"python",
"cryptography",
"pip"
] | When I try to install the [Cryptography](https://cryptography.io) package for Python through either `pip install cryptography` or by downloading the package from [their site](https://github.com/pyca/cryptography) and running `python setup.py`, I get the following error:
---
```
D:\Anaconda\Scripts\pip-script.py run o... | I had a similar issue, and found i was simply missing a dependancy (libssl-dev, for me). As referenced in <https://cryptography.io/en/latest/installation/>, ensure that all dependancies are met:
### On Windows
If youâre on Windows youâll need to make sure you have OpenSSL installed. There are pre-compiled binarie... |
Failed to install Python Cryptography package with PIP and setup.py | 22,073,516 | 120 | 2014-02-27T15:50:27Z | 24,961,925 | 33 | 2014-07-25T18:05:46Z | [
"python",
"cryptography",
"pip"
] | When I try to install the [Cryptography](https://cryptography.io) package for Python through either `pip install cryptography` or by downloading the package from [their site](https://github.com/pyca/cryptography) and running `python setup.py`, I get the following error:
---
```
D:\Anaconda\Scripts\pip-script.py run o... | For those of you running OS X, here is what worked for me:
```
brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include"
pip install cryptography
```
(Running 10.9 Mavericks)
You may also want to try merging the flags and pip commands to the fo... |
Failed to install Python Cryptography package with PIP and setup.py | 22,073,516 | 120 | 2014-02-27T15:50:27Z | 34,043,901 | 7 | 2015-12-02T13:25:34Z | [
"python",
"cryptography",
"pip"
] | When I try to install the [Cryptography](https://cryptography.io) package for Python through either `pip install cryptography` or by downloading the package from [their site](https://github.com/pyca/cryptography) and running `python setup.py`, I get the following error:
---
```
D:\Anaconda\Scripts\pip-script.py run o... | Nick Woodham's answer didn't work on OSX 10.11 El Capitan for me, but this did.
```
brew install openssl
CFLAGS="-I/usr/local/opt/openssl/include" pip install cryptography==0.8
``` |
Failed to install Python Cryptography package with PIP and setup.py | 22,073,516 | 120 | 2014-02-27T15:50:27Z | 35,809,886 | 16 | 2016-03-05T04:10:02Z | [
"python",
"cryptography",
"pip"
] | When I try to install the [Cryptography](https://cryptography.io) package for Python through either `pip install cryptography` or by downloading the package from [their site](https://github.com/pyca/cryptography) and running `python setup.py`, I get the following error:
---
```
D:\Anaconda\Scripts\pip-script.py run o... | This worked for me in El Capitan
```
brew install pkg-config libffi openssl
env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install cryptography
```
You can also check the thread here : <https://github.com/pyca/cryptography/issues/2350> |
Failed to install Python Cryptography package with PIP and setup.py | 22,073,516 | 120 | 2014-02-27T15:50:27Z | 35,867,594 | 11 | 2016-03-08T12:37:15Z | [
"python",
"cryptography",
"pip"
] | When I try to install the [Cryptography](https://cryptography.io) package for Python through either `pip install cryptography` or by downloading the package from [their site](https://github.com/pyca/cryptography) and running `python setup.py`, I get the following error:
---
```
D:\Anaconda\Scripts\pip-script.py run o... | Apparently on recent versions of OSX this may be caused by Apple shipping their own version of OpenSSL, which doesn't work with the cryptography library.
Recent versions of the cryptography library ship with their own native dependencies, but to get them you'll need to upgrade pip, and possibly also virtual env. So fo... |
Failed to install Python Cryptography package with PIP and setup.py | 22,073,516 | 120 | 2014-02-27T15:50:27Z | 37,781,781 | 20 | 2016-06-13T04:21:27Z | [
"python",
"cryptography",
"pip"
] | When I try to install the [Cryptography](https://cryptography.io) package for Python through either `pip install cryptography` or by downloading the package from [their site](https://github.com/pyca/cryptography) and running `python setup.py`, I get the following error:
---
```
D:\Anaconda\Scripts\pip-script.py run o... | Since this SO question keeps coming up I'll drop a response here too (I am one of the pyca/cryptography developers). Here's what you need to reliably install pyca/cryptography on the 3 major platforms.
Please note in all these cases it is **highly recommended** that you install into a virtualenv and not into the globa... |
Python: How to sort a list of lists by the most common first element? | 22,073,540 | 3 | 2014-02-27T15:51:31Z | 22,073,615 | 9 | 2014-02-27T15:54:08Z | [
"python",
"list",
"sorting"
] | How do you sort a list of lists by the count of the first element? For example, if I had the following list below, I'd want the list to be sorted so that all the 'University of Georgia' entries come first, then the 'University of Michigan' entries, and then the 'University of Florida' entry.
```
l = [['University of M... | ```
from collections import Counter
c = Counter(item[0] for item in l)
print sorted(l, key = lambda x: -c[x[0]])
```
**Output**
```
[['University of Georgia', 'Anne Greene', 'ba'],
['University of Georgia', 'Sara Dean', 'ms'],
['University of Georgia', 'Beth Johnson', 'bs'],
['University of Michigan', 'James Jon... |
xhtml2pdf ImportError - Django | 22,075,485 | 9 | 2014-02-27T17:11:25Z | 22,077,096 | 16 | 2014-02-27T18:23:25Z | [
"python",
"django",
"pip",
"reportlab",
"xhtml2pdf"
] | I installed `xhtml2pdf` using `pip` for use with Django. I am getting the following ImportError:
```
Reportlab Toolkit Version 2.2 or higher needed
```
But I have reportlab 3.0
```
>>> import reportlab
>>> print reportlab.Version ... | In `util.py` edit the following lines:
```
if not (reportlab.Version[0] == "2" and reportlab.Version[2] >= "1"):
raise ImportError("Reportlab Version 2.1+ is needed!")
REPORTLAB22 = (reportlab.Version[0] == "2" and reportlab.Version[2] >= "2")
```
And set to:
```
if not (reportlab.Version[:3] >="2.1"):
rais... |
Python lists: indices of heapq.nlargest with repeating values in list | 22,076,427 | 5 | 2014-02-27T17:51:49Z | 22,076,461 | 9 | 2014-02-27T17:53:19Z | [
"python",
"list"
] | Suppose I have a list of numbers:
```
my_list = [3, 8, 4, 2, 8, 1, 1, 2, 5, 1]
```
I now want to find the indices of the 2 greatest numbers in this list. So, I try:
```
import heapq
max_vals = heapq.nlargest(2, my_list)
index1 = my_list.index(max_vals[0])
index2 = my_list.index(max_vals[1])
print index1
print index2... | You can apply `heapq.nlargest` on `enumerate(list)`"
```
>>> import heapq
>>> data = heapq.nlargest(2, enumerate(my_list), key=lambda x:x[1])
>>> indices, vals = zip(*data)
>>> indices
(1, 4)
>>> vals
(8, 8)
``` |
MongoDB Update-Upsert Performance Barrier (Performance falls off a cliff) | 22,077,685 | 3 | 2014-02-27T18:49:49Z | 22,080,532 | 9 | 2014-02-27T21:13:58Z | [
"python",
"performance",
"mongodb",
"upsert"
] | I'm performing a repetitive update operation to add documents into my MongoDB as part of some performance evaluation. I've discovered a huge non-linearity in execution time based on the number of updates (w/ upserts) I'm performing:
Looping with the following command in Python...
```
collection.update({'timestamp': x... | You should put an ascending index on your "timestamp" field:
```
collection.ensure_index("timestamp") # shorthand for single-key, ascending index
```
If this index should contain unique values:
```
collection.ensure_index("timestamp", unique=True)
```
Since the spec is not indexed and you are performing updates, t... |
Installing py-ldap on Mac OS X Mavericks (missing sasl.h) | 22,079,173 | 23 | 2014-02-27T20:04:34Z | 22,627,536 | 27 | 2014-03-25T07:03:00Z | [
"python",
"ldap",
"osx-mavericks"
] | I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011... | **A workaround**
/usr/include appears to have moved
```
$ xcrun --show-sdk-path
$ sudo ln -s <the_path_from_above_command>/usr/include /usr/include
```
Now run pip install! |
Installing py-ldap on Mac OS X Mavericks (missing sasl.h) | 22,079,173 | 23 | 2014-02-27T20:04:34Z | 25,129,076 | 57 | 2014-08-04T23:29:02Z | [
"python",
"ldap",
"osx-mavericks"
] | I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011... | using pieces from both @hharnisc and @mick-t answers.
```
pip install python-ldap \
--global-option=build_ext \
--global-option="-I$(xcrun --show-sdk-path)/usr/include/sasl"
``` |
Installing py-ldap on Mac OS X Mavericks (missing sasl.h) | 22,079,173 | 23 | 2014-02-27T20:04:34Z | 31,108,577 | 8 | 2015-06-29T05:45:04Z | [
"python",
"ldap",
"osx-mavericks"
] | I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011... | In my particular case, I couldn't simply use the `pip` arguments noted in other answers because I'm using it with `tox` to install dependencies from a requirements.txt file, and I need my tox.ini to remain compatible with non-Mac environments.
I was able to resolve this in much simpler fashion: exporting `CFLAGS` such... |
Create a PyCharm configuration that runs a module a la "python -m foo" | 22,081,065 | 11 | 2014-02-27T21:39:54Z | 22,081,452 | 9 | 2014-02-27T22:01:10Z | [
"python",
"pycharm"
] | My python entrypoint needs to be run as a module (not a script), as in:
```
python -m foo.bar
```
The following does not work (and is not supposed to):
```
python foo/bar.py
```
How can I create a run confirguration in pycharm that runs my code using the first invokation above? | According to `man python`, the `-m` option
> **-m module-name**
> Searches sys.path for the named module and runs the corresponding .py file as a script.
So most of the time you can just right-click on `bar.py` in the Project tool window and select `Run bar`.
If you really need to use the `-m` option, then specify... |
Find the root of the git repository where the file lives | 22,081,209 | 4 | 2014-02-27T21:47:41Z | 22,081,487 | 8 | 2014-02-27T22:03:26Z | [
"python",
"git"
] | When working in Python (e.g. running a script), how can I find the path of the root of the git repository where the script lives?
So far I know I can get the current path with:
```
path_to_containing_folder = os.path.dirname(os.path.realpath(__file__))
```
How can I then find out where the git repository lives? | Looking for a `.git` directory will not work in all cases. The correct git command is:
```
git rev-parse --show-toplevel
``` |
get previous row's value and calculate new column pandas python | 22,081,878 | 6 | 2014-02-27T22:23:27Z | 22,082,596 | 17 | 2014-02-27T23:04:08Z | [
"python",
"pandas"
] | Is there a way to look back to a previous row, and calculate a new variable? so as long as the previous row is the same case what is the (previous change) - (current change), and attribute it to the previous 'ChangeEvent' in new columns?
here is my DataFrame
```
>>> df
ChangeEvent StartEvent case chan... | The way to get the previous is using the shift method:
```
In [11]: df1.change.shift(1)
Out[11]:
0 NaT
1 2014-03-08
2 2014-04-08
3 2014-05-08
4 2014-06-08
Name: change, dtype: datetime64[ns]
```
Now you can subtract these columns. *Note: This is with 0.13.1 (datetime stuff has had a lot of work recen... |
On Windows, how to convert a timestamps BEFORE 1970 into something manageable? | 22,082,103 | 3 | 2014-02-27T22:35:57Z | 22,082,178 | 8 | 2014-02-27T22:39:59Z | [
"python",
"windows"
] | Summary: "negative" timestamps on Mac work fine, but on Windows I can't convert them into something usable.
Details:
I can have a file on Windows whose modification time is, say 1904:
```
$ ls -l peter.txt
-rw-r--r-- 1 sync Administ 1 Jan 1 1904 peter.txt
```
In python:
```
>>> import os
>>> ss = os... | ```
>>> datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)
datetime.datetime(1904, 1, 1, 8, 0)
``` |
How do Scrapy rules work with crawl spider | 22,082,938 | 14 | 2014-02-27T23:28:05Z | 22,094,696 | 8 | 2014-02-28T12:03:39Z | [
"python",
"regex",
"web-crawler",
"scrapy"
] | I have hard time to understand scrapy crawl spider rules. I have example that doesn't work as I would like it did, so it can be two things:
1. I don't understand how rules work.
2. I formed incorrect regex that prevents me to get results that I need.
OK here it is what I want to do:
I want to write crawl spider that... | You are right, according to the [source code](https://github.com/scrapy/scrapy/blob/master/scrapy/contrib/spiders/crawl.py#L51-54) before returning each response to the callback function, the crawler loops over the Rules, starting, from the first. You should have it in mind, when you write the rules. For example the fo... |
What base_name parameter do I need in my route to make this Django API work? | 22,083,090 | 9 | 2014-02-27T23:38:25Z | 22,102,670 | 18 | 2014-02-28T18:07:53Z | [
"python",
"django",
"rest"
] | I am building a Django application that exposes a REST API by which users can query my application's models. I'm following the instructions [**here**](http://www.django-rest-framework.org/tutorial/quickstart#testing-our-api).
My Route looks like this in myApp's url.py:
```
from rest_framework import routers
router = ... | Try doing this in your urls.py. The third parameter 'Person' can be anything you want.
```
router.register(r'person/food', views.PersonViewSet, 'Person')
``` |
Django: How to pre-populate FormView with dynamic (non-model) data? | 22,083,218 | 14 | 2014-02-27T23:46:40Z | 22,083,336 | 25 | 2014-02-27T23:54:50Z | [
"python",
"django",
"django-templates"
] | I have a FormView view, with some additional GET context supplied using get\_context\_data():
```
class SignUpView(FormView):
template_name = 'pages_fixed/accounts/signup.html'
form_class = SignUpForm
def get_context_data(self, **kwargs):
context = super(SignUpView, self).get_context_data(**kwargs... | You can override the FormView class's 'get\_initial' method. See [here](http://ccbv.co.uk/projects/Django/1.6/django.views.generic.edit/FormView/) for more info,
e.g.
```
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = super(SignUpView, self).get_initia... |
Send text "http" over python socket | 22,083,359 | 5 | 2014-02-27T23:56:21Z | 22,084,161 | 8 | 2014-02-28T01:05:26Z | [
"python",
"sockets",
"http",
"browser",
"response"
] | I am trying to create a HTTP server using python. The thing is I am getting everything to work except for sending a response message; if the message has a text `http`, the `send()` doesn't work.
Here is the snippet of the code:
```
connectionSocket.send('HTTP/1.1 200 OK text/html')
```
Here are the others I tried:
... | You are not returning a correctly formed HTTP response. Your line
```
connectionSocket.send('HTTP/1.1 200 OK text/html') ## this is not working
```
is not even terminated by a newline, then immediately followed by the content of your file. Protocols like HTTP specify fairly rigorously what must be sent, and I find it... |
Pandas DataFrame performance | 22,084,338 | 12 | 2014-02-28T01:24:19Z | 22,084,742 | 19 | 2014-02-28T02:02:17Z | [
"python",
"dictionary",
"pandas"
] | Pandas is really great, but I am really surprised by how inefficient it is to retrieve values from a Pandas.DataFrame. In the following toy example, even the DataFrame.iloc method is more than 100 times slower than a dictionary.
The question: Is the lesson here just that dictionaries are the better way to look up valu... | A dict is to a bicycle as a DataFrame is to a car.
You can pedal 10 feet on a bicycle faster than you can start a car, get it in gear, etc, etc. But if you need to go a mile, the car wins.
For certain small, targeted purposes, a dict may be faster.
And if that is all you need, then use a dict, for sure! But if you nee... |
how do you filter pandas dataframes by multiple columns | 22,086,116 | 15 | 2014-02-28T04:21:02Z | 22,086,347 | 16 | 2014-02-28T04:40:28Z | [
"python",
"filter",
"pandas"
] | To filter a dataframe (df) by a single column, if we consider data with male and females we might:
```
males = df[df[Gender]=='Male']
```
Question 1 - But what if the data spanned multiple years and i wanted to only see males for 2014?
In other languages I might do something like:
```
if A = "Male" and if B = "2014... | Using `&` operator, don't forget to wrap the sub-statements with `()`:
```
males = df[(df[Gender]=='Male') & (df[Year]==2014)]
```
To store your dataframes in a `dict` using a for loop:
```
from collections import defaultdict
dic={}
for g in ['male', 'female']:
dic[g]=defaultdict(dict)
for y in [2013, 2014]:
... |
Map/reduce equivalent for a list comprehension with multiple for clauses | 22,091,389 | 5 | 2014-02-28T09:40:46Z | 22,117,904 | 9 | 2014-03-01T17:41:31Z | [
"python",
"map",
"functional-programming",
"list-comprehension",
"fold"
] | I want to write a [functional](https://en.wikipedia.org/wiki/Functional_programming) equivalent of the list comprehensions using higher-order functions only and without side effects. I do this for strictly learning purposes. *I know that list comprehensions are Pythonic.* In Python `map(f, xs)` is equivalent to `[f(x) ... | This is the pattern of a [monad](http://en.wikipedia.org/wiki/Monad_%28functional_programming%29), specifically the list monad. In many languages, monads are hidden behind some kind of syntactic sugar, such as C#'s [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query), Scala's [sequence comprehensions](http://... |
Python Google Drive API - list the entire drive file tree | 22,092,402 | 3 | 2014-02-28T10:25:56Z | 22,110,005 | 7 | 2014-03-01T04:14:03Z | [
"python",
"google-api",
"google-drive-sdk"
] | I'm building a python application that uses the Google drive APIs, so fare the development is good but I have a problem to retrieve the entire Google drive file tree, I need that for two purposes:
1. Check if a path exist, so if i want upload test.txt under root/folder1/folder2 I want to check if the file already exis... | Stop thinking about Drive as being a tree structure. It isn't. "Folders" are simply labels, eg. a file can have multiple parents.
In order to build a representation of a tree in your app, you need to do this ...
1. Run a Drive List query to retrieve all Folders
2. Iterate the result array and examine the parents prop... |
pandas Subtract Dataframe with a row from another dataframe | 22,093,471 | 4 | 2014-02-28T11:09:40Z | 22,093,806 | 7 | 2014-02-28T11:23:13Z | [
"python",
"pandas",
"dataframe"
] | I would like to subtract all rows in a dataframe with one row from another dataframe.
(Difference from one row)
Is there an easy way to do this? (like df-df2 )
```
df = pd.DataFrame(abs(np.floor(np.random.rand(3, 5)*10)),
... columns=['a', 'b', 'c', 'd', 'e'])
df
Out[18]:
a b c d e
0 8 9 ... | Pandas NDFrames generally try to perform operations on items with matching indices. `df - df2` only performs subtraction on the first row, because the `0` indexed row is the only row with an index shared in common.
The operation you are looking for looks more like a NumPy array operation performed with "broadcasting":... |
How to catch exceptions in workers in Multiprocessing | 22,094,852 | 6 | 2014-02-28T12:10:49Z | 22,094,948 | 8 | 2014-02-28T12:14:56Z | [
"python",
"python-2.7",
"multiprocessing"
] | I'm working with the multiprocessing module in Python (2.7.3) and want to debug some stuff going on in my workers. However, I seem to not be able to catch any exceptions in the worker threads.
A minimal example:
```
import multiprocessing as mp
a=[1]
def worker():
print a[2]
def pool():
pool = mp.Pool(pro... | The error is not raised unless you call [`get` method](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.AsyncResult.get) of [`AsyncResult`](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.AsyncResult) (the return value of the `apply_async`):
According to the [`Async... |
How to code a Python function that accepts float, list or numpy.array? | 22,095,000 | 5 | 2014-02-28T12:17:06Z | 22,095,756 | 7 | 2014-02-28T12:51:41Z | [
"python",
"arrays",
"numpy"
] | I have the following simple Python function:
```
def get_lerp_factor( a, x, b ):
if x <= a: return 0.
if x >= b: return 1.
return (x - a) / (b - a)
```
Many numpy functions, like numpy.sin(x) can handle a float or an array.
So how can I extend this in the same manner, so that it can also handle a numpy a... | You need [`numpy.asarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html). This takes as its first argument:
> Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
and it returns:
> Array inte... |
Unpacking more than one list as argument for a function | 22,098,105 | 17 | 2014-02-28T14:37:54Z | 22,098,232 | 17 | 2014-02-28T14:44:08Z | [
"python"
] | If I have a function like:
```
def f(a,b,c,d):
print a,b,c,d
```
Then why does this works:
```
f(1,2,3,4)
f(*[1,2,3,4])
```
But not this:
```
f(*[1,2] , *[3,4])
f(*[1,2] , *[3,4])
^
SyntaxError: invalid syntax
```
?
**EDIT** :
For information, the original problem was to replace one of the... | Because, as per the [Function call syntax](http://docs.python.org/3/reference/expressions.html#calls), this is how the argument list is defined
```
argument_list ::= positional_arguments ["," keyword_arguments]
["," "*" expression] ["," keyword_arguments]
["," "**" expression... |
Unpacking more than one list as argument for a function | 22,098,105 | 17 | 2014-02-28T14:37:54Z | 22,099,309 | 9 | 2014-02-28T15:32:42Z | [
"python"
] | If I have a function like:
```
def f(a,b,c,d):
print a,b,c,d
```
Then why does this works:
```
f(1,2,3,4)
f(*[1,2,3,4])
```
But not this:
```
f(*[1,2] , *[3,4])
f(*[1,2] , *[3,4])
^
SyntaxError: invalid syntax
```
?
**EDIT** :
For information, the original problem was to replace one of the... | **Starting in Python 3.5, this** ***does*** **work**.
[PEP 448](http://legacy.python.org/dev/peps/pep-0448/) was implemented in Python 3.5. Quoting from the PEP, it allows, among other things:
> Arbitrarily positioned unpacking operators:
>
> ```
> >>> print(*[1], *[2], 3)
> 1 2 3
> >>> dict(**{'x': 1}, y=2, **{'z': ... |
Sort list after numerical value in string | 22,098,649 | 3 | 2014-02-28T15:02:45Z | 22,098,691 | 10 | 2014-02-28T15:04:46Z | [
"python",
"sorting"
] | I have a list, where each item has the format "title, runtime" e.g. "Bluebird, 4005"
How can I sort that list in Python, according to the runtime part of the string for each item?
Is there a way to do this without using regex? | ```
words_list = ["Bluebird, 4005", "ABCD, 1", "EFGH, 2677", "IJKL, 2"]
print sorted(words_list, key = lambda x: int(x.split(",")[1]))
# ['ABCD, 1', 'IJKL, 2', 'EFGH, 2677', 'Bluebird, 4005']
``` |
Understanding python policy for finding the minimum in a list of list | 22,098,902 | 6 | 2014-02-28T15:14:16Z | 22,098,980 | 7 | 2014-02-28T15:18:10Z | [
"python",
"list"
] | I have the following list of lists of values and I want to find the min value among all the values.
```
Q = [[8.85008011807927, 4.129896248976861, 5.556804136197901],
[8.047707185696948, 7.140707521433818, 7.150610818529693],
[7.5326340018228555, 7.065307672838521, 6.862894377422498]]
```
I was planning ... | Lists are compared using their [lexicographical order](http://en.wikipedia.org/wiki/Lexicographical_order)1 (i.e. first elements compared, then the second, then the third and so on), so just because `list_a < list_b` *doesn't mean* that the smallest element in `list_a` is less than the smallest element in `list_b`, whi... |
pandas replace multiple values one column | 22,100,130 | 2 | 2014-02-28T16:08:55Z | 22,100,489 | 7 | 2014-02-28T16:24:50Z | [
"python",
"pandas",
"replace"
] | In a column risklevels I want to replace Small with 1, Medium with 5 and High with 15.
I tried:
```
dfm.replace({'risk':{'Small': '1'}},{'risk':{'Medium': '5'}},{'risk':{'High': '15'}})
```
But only the medium were replaced.
What is wrong ? | Your replace format is off
```
In [21]: df = pd.DataFrame({'a':['Small', 'Medium', 'High']})
In [22]: df
Out[22]:
a
0 Small
1 Medium
2 High
[3 rows x 1 columns]
In [23]: df.replace({'a' : { 'Medium' : 2, 'Small' : 1, 'High' : 3 }})
Out[23]:
a
0 1
1 2
2 3
[3 rows x 1 columns]
``` |
Consuming a kinesis stream in python | 22,100,206 | 14 | 2014-02-28T16:12:21Z | 22,403,036 | 20 | 2014-03-14T10:54:50Z | [
"python",
"amazon-web-services",
"stream",
"boto"
] | I cant seem to find a decent example that shows how can I consume an AWS Kinesis stream via Python. Can someone please provide me with some examples I could look into?
Best | you should use boto.kinesis:
```
from boto import kinesis
```
After you created a stream:
step 1: connect to aws kinesis:
```
auth = {"aws_access_key_id":"id", "aws_secret_access_key":"key"}
connection = kinesis.connect_to_region('us-east-1',**auth)
```
step 2: get the stream info (like how many shards, if it is a... |
Can not get mysql-connector-python to install in virtualenv | 22,100,757 | 18 | 2014-02-28T16:37:45Z | 22,829,966 | 34 | 2014-04-03T06:52:59Z | [
"python",
"mysql"
] | I'm using Amazon Linux AMI release 2013.09. I've install virtualenv and after activation then I run pip install mysql-connector-python, but when I run my app I get an error: `ImportError: No module named mysql.connector`. Has anyone else had trouble doing this? I can install it outside of virtualenv and my script runs ... | Several things. There is an inconsistency in package naming so you may want to do:
```
pip search mysql-connector
```
to find out what it is called on your platform. I got two results `mysql-connector-python` and `mysql-connector-repackaged`.
so try this first:
```
pip install mysql-connector-python
```
this may a... |
Can not get mysql-connector-python to install in virtualenv | 22,100,757 | 18 | 2014-02-28T16:37:45Z | 33,053,044 | 13 | 2015-10-10T10:39:50Z | [
"python",
"mysql"
] | I'm using Amazon Linux AMI release 2013.09. I've install virtualenv and after activation then I run pip install mysql-connector-python, but when I run my app I get an error: `ImportError: No module named mysql.connector`. Has anyone else had trouble doing this? I can install it outside of virtualenv and my script runs ... | Solution I found:
```
sudo pip install mysql-connector-python-rf
``` |
Iterated function in Python | 22,102,933 | 6 | 2014-02-28T18:22:18Z | 22,103,011 | 10 | 2014-02-28T18:27:18Z | [
"python"
] | Given a function `f( )`, a number `x` and an integer `N`, I want to compute the List:
```
y = [x, f(x), f(f(x)), ..., f(f... M times...f(f(x)) ]
```
An obvious way to do this in Python is the following Python code:
```
y = [x]
for i in range(N-1):
y.append(f(y[-1]))
```
But I want to know if there is a better o... | There are several ways to optimize this code:
1. It is faster to using `itertools.repeat(None, times)` to control the number of loops (this avoids creating new, unused integer objects on every iteration).
2. You can gain speed by putting this in a function or generator (local variables are faster than global variables... |
Get total physical memory in Python | 22,102,999 | 14 | 2014-02-28T18:26:20Z | 22,103,295 | 23 | 2014-02-28T18:42:35Z | [
"python",
"linux",
"memory"
] | How can I get the total physical memory within Python in a distribution agnostic fashion? I don't need used memory, just the total physical memory. | your best bet for a cross-platform solution is to use the [psutil](https://github.com/giampaolo/psutil) package (available on [PyPI](https://pypi.python.org/pypi/psutil)).
```
from psutil import virtual_memory
mem = virtual_memory()
mem.total # total physical memory available
```
Documentation for `virtual_memory` ... |
Get total physical memory in Python | 22,102,999 | 14 | 2014-02-28T18:26:20Z | 22,103,515 | 7 | 2014-02-28T18:53:33Z | [
"python",
"linux",
"memory"
] | How can I get the total physical memory within Python in a distribution agnostic fashion? I don't need used memory, just the total physical memory. | Regular expressions work well for this sort of thing, and might help with any minor differences across distributions.
```
import re
meminfo = open('/proc/meminfo').read()
matched = re.search(r'^MemTotal:\s+(\d+)', meminfo)
if matched:
mem_total_kB = int(matched.groups()[0])
``` |
Get total physical memory in Python | 22,102,999 | 14 | 2014-02-28T18:26:20Z | 28,161,352 | 13 | 2015-01-27T00:35:03Z | [
"python",
"linux",
"memory"
] | How can I get the total physical memory within Python in a distribution agnostic fashion? I don't need used memory, just the total physical memory. | **Using `os.sysconf`:**
```
import os
mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') # e.g. 4015976448
mem_gib = mem_bytes/(1024.**3) # e.g. 3.74
```
Note:
* `SC_PAGE_SIZE` is often 4096.
* `SC_PAGESIZE` and `SC_PAGE_SIZE` are equal.
* For more info, see [`man sysconf`](http://linux.die.net/m... |
Why does this Python code give me the wrong answer? | 22,103,271 | 3 | 2014-02-28T18:41:14Z | 22,103,298 | 14 | 2014-02-28T18:42:47Z | [
"python",
"python-2.x"
] | I wrote a simple Python code to solve a certain Hydraulic formula (The [Manning's equation](http://en.wikipedia.org/wiki/Manning_formula)):
```
import math
def mannings(units,A,P,S,n):
if units=='SI':
k=1.0
elif units=='US':
k=1.49
R=A/P
V=(k/n)*(math.pow(R,(2/3)))*(math.sqrt(S))
Q... | Your problem is that `2/3` is an integer division and therefore evaluates to `0`. You want `2.0/3` to force a floating-point division. Or else include `from __future__ import division` at the top of your file to use the Python 3-style division in Python 2.x.
Assuming you don't use the `__future__` solution, you will a... |
Django, RabbitMQ, & Celery - why does Celery run old versions of my tasks after I update my Django code in development? | 22,103,401 | 8 | 2014-02-28T18:47:20Z | 22,103,551 | 9 | 2014-02-28T18:55:29Z | [
"python",
"django",
"rabbitmq",
"celery",
"django-celery"
] | So I have a Django app that occasionally sends a task to Celery for asynchronous execution. I've found that as I work on my code in development, the Django development server knows how to automatically detect when code has changed and then restart the server so I can see my changes. However, the RabbitMQ/Celery section... | > I've found that as I work on my code in development, the Django
> development server knows how to automatically detect when code has
> changed and then restart the server so I can see my changes. However,
> the RabbitMQ/Celery section of my app doesn't pick up on these sorts
> of changes in development.
What you've ... |
Does matplotlib have a function for drawing diagonal lines in axis coordinates? | 22,104,256 | 10 | 2014-02-28T19:33:00Z | 22,105,008 | 13 | 2014-02-28T20:17:41Z | [
"python",
"numpy",
"matplotlib"
] | Matplotlib Axes have the functions `axhline` and `axvline` for drawing horizontal or vertical lines at a given y or x coordinate (respectively) independently of the data scale on an Axes.
Is there a similar function for plotting a constant diagonal? For example, if I have a scatterplot of variables with a similar doma... | Plotting a diagonal line based from the bottom-left to the top-right of the screen is quite simple, you can simply use `ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3")`. The method `ax.get_xlim()` will simply return the current values of the x-axis (and similarly for the y-axis).
However, if you want to be able... |
Does matplotlib have a function for drawing diagonal lines in axis coordinates? | 22,104,256 | 10 | 2014-02-28T19:33:00Z | 28,216,751 | 8 | 2015-01-29T14:10:18Z | [
"python",
"numpy",
"matplotlib"
] | Matplotlib Axes have the functions `axhline` and `axvline` for drawing horizontal or vertical lines at a given y or x coordinate (respectively) independently of the data scale on an Axes.
Is there a similar function for plotting a constant diagonal? For example, if I have a scatterplot of variables with a similar doma... | Drawing a diagonal from the lower left to the upper right corners of your plot would be accomplished by the following
`ax.plot([0, 1], [0, 1], transform=ax.transAxes)`
Using `transform=ax.transAxes`, the supplied `x` and `y` coordinates are interpreted as *axes* coordinates instead of *data* coordinates.
This, as @f... |
Python pandas Removing UserWarning and looping efficiently | 22,104,466 | 3 | 2014-02-28T19:45:35Z | 22,104,548 | 7 | 2014-02-28T19:50:19Z | [
"python",
"pandas",
"iteration"
] | Lets say I have code similar to this:
```
import pandas as pd
df=pd.DataFrame({'Name': [ 'Jay Leno', 'JayLin', 'Jay-Jameson', 'LinLeno', 'Lin Jameson', 'Python Leno', 'Python Lin', 'Python Jameson', 'Lin Jay', 'Python Monte'],
'Class': ['Rat','L','H','L','L','H', 'H','L','L','Circus']})
df['status']=... | Use [non-capturing parentheses](http://docs.python.org/2/library/re.html#regular-expression-syntax) `(?:...)`:
```
pattern1=['^Jay(?:\s|-)?(?:Leno|Lin|Jameson)$','^Python(?:\s|-)?(?:Jay|Leno|Lin|Jameson|Monte)$','^Lin(?:\s|-)?(?:Leno|Jay|Jameson|Monte)$' ]
pattern2=['^Python(?:\s|-)?(?:Jay|Leno|Lin|Jameson|Monte)$' ]
... |
How to draw dynamic programming table in python | 22,104,785 | 3 | 2014-02-28T20:03:31Z | 22,107,085 | 8 | 2014-02-28T22:30:10Z | [
"python",
"matplotlib",
"pygame",
"dynamic-programming"
] | What is a good way to draw a dynamic programming such as this one (with the path) in python?

I have looked online and I see [pygame](http://pygame.org/news.html) but is that really the best option for this sort of technical drawing?
One option might be ... | The following code yields an approximation of the figure you want, using native Matplotlib tables:
```
import matplotlib.pylab as plt
import numpy as np
def get_coord(table, irow, icol):
# get coordinates of a cell. This seems to work, don't ask why.
cell = table.get_celld()[irow+1,icol] # row 0 is column hea... |
How do I install pyPDF2 module using windows? | 22,106,380 | 8 | 2014-02-28T21:42:27Z | 22,115,563 | 8 | 2014-03-01T14:27:27Z | [
"python",
"pypdf"
] | As a newbie... I am having difficulties installing pyPDF2 module. I have downloaded. Where and how do I install (setup.py) so I can use module in python interpreter? | To install setup.py files under Windows you can choose this way with the command line:
1. hit windows key
2. type cmd
3. excute the command line (black window)
4. type `cd C:\Users\User\Downloads\pyPDF2` to go into the directory where the `setup.py` is (this is mine if I downloaded it) The path can be copied from the ... |
Google Style Guide properties for getters and setters | 22,107,289 | 3 | 2014-02-28T22:46:16Z | 22,107,432 | 8 | 2014-02-28T22:58:51Z | [
"python",
"google-style-guide"
] | I'm curious about one of the recommendations in the [Google Python style guide concerning properties](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Properties#Properties "Google Python style guide concerning properties").
In it, they give the following example:
```
class Square(object):
"... | In the style guide they do give a reason:
> Inheritance with properties can be non-obvious if the property itself is not overridden. Thus one must make sure that accessor methods are called indirectly to ensure methods overridden in subclasses are called by the property (using the Template Method DP).
(where *Templat... |
Are list-comprehensions and functional functions faster than "for loops"? | 22,108,488 | 29 | 2014-03-01T00:38:59Z | 22,108,549 | 7 | 2014-03-01T00:44:45Z | [
"python",
"performance",
"for-loop",
"list-comprehension",
"map-function"
] | In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why, technically, they "run in a C speed", while "the for loop runs in the python virtual machine speed"?.
Suppose that in a game that I'm developing I need to draw complex and huge maps u... | If you check the [info on python.org](https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops), you can see this summary:
```
Version Time (seconds)
Basic loop 3.47
Eliminate dots 2.45
Local variable & no dots 1.79
Using map function 0.54
```
But you really **should** read the above article in details to under... |
Are list-comprehensions and functional functions faster than "for loops"? | 22,108,488 | 29 | 2014-03-01T00:38:59Z | 22,108,640 | 36 | 2014-03-01T00:56:05Z | [
"python",
"performance",
"for-loop",
"list-comprehension",
"map-function"
] | In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why, technically, they "run in a C speed", while "the for loop runs in the python virtual machine speed"?.
Suppose that in a game that I'm developing I need to draw complex and huge maps u... | The following are rough guidelines and educated guesses based on experience. You should `timeit` or profile your concrete use case to get hard numbers, and those numbers may occasionally disagree with the below.
A list comprehension is usually a tiny bit faster than the precisely equivalent `for` loop (that actually b... |
Django: How to make a datetime object aware of the timezone in which it was created? | 22,108,634 | 6 | 2014-03-01T00:55:46Z | 22,109,768 | 21 | 2014-03-01T03:36:44Z | [
"python",
"django",
"datetime",
"django-models",
"timezone"
] | I am running a program that requests ocean tide data from a remote server. The `time` and `date` of this tide data is being computed based on my machine's local time zone. I want to use these local dates and times to create a `datetime` object, which I will then save in a Django model.
```
datetime_obj = datetime(loc_... | First, make sure you're familiar with Django's [documentation on timezones](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/), set `USE_TZ = True`, and install `pytz`.
I don't quite understand where your date is coming from. If it's coming from the server as part of their data (i.e. it represents when the ... |
How to build a Django REST-Api that returns a custom list of models? | 22,108,636 | 2 | 2014-03-01T00:55:51Z | 22,114,793 | 7 | 2014-03-01T13:08:34Z | [
"python",
"django",
"api",
"rest"
] | I'm having a great deal of trouble trying build my API using the Django Rest Framework. I have been stuck on the same issue now for several days. I've tried numerous solutions and code-snippets and asked plenty of people but to no avail. I've tried to follow all the instructions in the docs, but to me they are unclear ... | `base_name` is used so the router can properly name the URLs. The DefaultRouter you are using uses the model or queryset attributes of the view set. But since you are using viewsets.ViewSet which has neither, the router cannot determine the base name used to name the generated URL patterns (eg, 'myobject-detail' or 'my... |
Tail Recursion Fibonacci | 22,111,252 | 2 | 2014-03-01T06:59:07Z | 22,111,492 | 26 | 2014-03-01T07:27:05Z | [
"python",
"big-o",
"fibonacci"
] | How do I implement a recursive Fibonacci function with no loops running in O(n)? | Typically I'd be against posting an answer to a homework question like this, but everything posted so far seems to be overcomplicating things. As said in the comments above, you should just use recursion to solve the problem like you would do iteratively.
Here's the iterative solution:
```
def fib(n):
a, b = 0, 1
... |
OverflowError Python int too large to convert to C long | 22,114,088 | 18 | 2014-03-01T12:02:08Z | 22,114,284 | 30 | 2014-03-01T12:22:31Z | [
"python",
"python-2.7"
] | ```
#!/usr/bin/python
import sys,math
n = input("enter a number to find the factors : ")
j,flag,b= 0l,False,0l
for b in xrange(1,n+1):
a = n + (b*b)
j = long(math.sqrt(a))
if a == j*j:
flag = True
break
if flag:
c = j+b
d = j-b
print "the first factor is : ",c ," and the... | Annoyingly, in Python 2, `xrange` requires its arguments to fit into a C long. There isn't quite a drop-in replacement in the standard library. However, you don't quite need a drop-in replacement. You just need to keep going until the loop `break`s. That means you want [`itertools.count`](http://docs.python.org/2/libra... |
python syntax help sep="", '\t' | 22,116,482 | 8 | 2014-03-01T15:45:43Z | 22,116,523 | 11 | 2014-03-01T15:49:00Z | [
"python",
"python-3.x",
"syntax"
] | I am having a bit of trouble trying to find an answer to this. I would like to know what the syntax `sep=""` and `\t` mean. I have found a little bit of info about it but I didn't quite understand what the purpose of using the syntax was. looking for an explanation of what it does and when/why you would use it.
an exa... | `sep=''` in the context of a function call sets the named argument `sep` to an empty string. See the [`print()` function](http://docs.python.org/3/library/functions.html#print); `sep` is the separator used between multiple values when printing. The default is a space (`sep=' '`), this function call makes sure that ther... |
How do I return a list of the 3 lowest values in another list | 22,117,834 | 2 | 2014-03-01T17:36:08Z | 22,117,859 | 7 | 2014-03-01T17:37:40Z | [
"python",
"min",
"built-in"
] | How do I return a list of the 3 lowest values in another list. For example I want to get the 3 lowest values of this list:
```
in_list = [1, 2, 3, 4, 5, 6]
input: function(in_list, 3)
output: [1, 2, 3]
``` | You can use [`heapq.nsmallest`](http://docs.python.org/3/library/heapq.html#heapq.nsmallest):
```
>>> from heapq import nsmallest
>>> in_list = [1, 2, 3, 4, 5, 6]
>>> nsmallest(3, in_list)
[1, 2, 3]
>>>
``` |
matplotlib imshow - default colour normalisation | 22,121,239 | 14 | 2014-03-01T22:28:48Z | 22,122,723 | 24 | 2014-03-02T01:26:20Z | [
"python",
"matplotlib",
"normalization",
"imshow"
] | I have consistently had problems with my colour maps when using `imshow`, some colours seem to just become black. I have finally realised that `imshow` seems to, by default, normalise the matrix of floating point values I give it.
I would have expected an array such as `[[0,0.25],[0.5,0.75]]` to display the appropriat... | Just specify `vmin=0, vmax=1`.
By default, `imshow` normalizes the data to its min and max. You can control this with either the `vmin` and `vmax` arguments or with the `norm` argument (if you want a non-linear scaling).
As a quick example:
```
import matplotlib.pyplot as plt
data = [[0, 0.25], [0.5, 0.75]]
fig, a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.