title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How to state in requirements.txt a direct github source | 16,584,552 | 113 | 2013-05-16T10:06:42Z | 20,460,931 | 46 | 2013-12-09T00:07:54Z | [
"python",
"github",
"pip",
"requirements.txt"
] | I've installed a library using the command
```
pip install git+git://github.com/mozilla/elasticutils.git
```
which installs it directly from a Github repository. This works fine and I want to have that dependency in my `requirements.txt`. I've looked at other tickets like [this](http://stackoverflow.com/questions/902... | First, install with `git+git`. Example of installing `kronok`'s branch of the `brabeion` project:
```
pip install -e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion
```
Second, use `pip freeze > requirements.txt` to get the right thing in your `requirements.txt`. In th... |
How to state in requirements.txt a direct github source | 16,584,552 | 113 | 2013-05-16T10:06:42Z | 26,174,655 | 11 | 2014-10-03T07:09:14Z | [
"python",
"github",
"pip",
"requirements.txt"
] | I've installed a library using the command
```
pip install git+git://github.com/mozilla/elasticutils.git
```
which installs it directly from a Github repository. This works fine and I want to have that dependency in my `requirements.txt`. I've looked at other tickets like [this](http://stackoverflow.com/questions/902... | Since pip `v1.5`, (released Jan 1 2014: [CHANGELOG](https://github.com/pypa/pip/blob/develop/CHANGES.txt), [PR](https://github.com/pypa/pip/pull/1215)) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:
```
pip install -e git+https://git.repo/some_repo.git#egg=my_subd... |
How to state in requirements.txt a direct github source | 16,584,552 | 113 | 2013-05-16T10:06:42Z | 34,518,202 | 35 | 2015-12-29T20:01:56Z | [
"python",
"github",
"pip",
"requirements.txt"
] | I've installed a library using the command
```
pip install git+git://github.com/mozilla/elasticutils.git
```
which installs it directly from a Github repository. This works fine and I want to have that dependency in my `requirements.txt`. I've looked at other tickets like [this](http://stackoverflow.com/questions/902... | `requirements.txt` allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1
```
[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e git+gi... |
How to state in requirements.txt a direct github source | 16,584,552 | 113 | 2013-05-16T10:06:42Z | 35,998,253 | 16 | 2016-03-14T21:17:36Z | [
"python",
"github",
"pip",
"requirements.txt"
] | I've installed a library using the command
```
pip install git+git://github.com/mozilla/elasticutils.git
```
which installs it directly from a Github repository. This works fine and I want to have that dependency in my `requirements.txt`. I've looked at other tickets like [this](http://stackoverflow.com/questions/902... | Normally your `requirements.txt` file would look something like this:
```
package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...
```
To specify a Github repo, you do not need the `package-name==` convention.
The examples below update `package-two`. The text between `@` and `#` denotes the specifics of the pa... |
Python list sorting dependant on if items are in another list | 16,586,061 | 8 | 2013-05-16T11:18:13Z | 16,586,099 | 11 | 2013-05-16T11:20:31Z | [
"python",
"list",
"sorting"
] | Say I have a list:
```
A = [1,2,3,4,5,6,7,8,9,0]
```
and a second list:
```
B = [3,6,9]
```
What is the best way to sort list A so that anything that matches an item in list B will appear at the beginning so that the result would be:
```
[3,6,9,1,2,4,5,7,8,0]
``` | ```
>>> A = [1,2,3,4,5,6,7,8,9,0]
>>> B = [3,6,9]
>>> sorted(A,key=lambda e: e not in B)
[3, 6, 9, 1, 2, 4, 5, 7, 8, 0]
```
How this works:
`sorted` sorts an interable based on the result of `key(element)` for each element (the default value for `key` is `None` which results in it sorting based on the elements direct... |
TypeError: ObjectId('') is not JSON serializable | 16,586,180 | 33 | 2013-05-16T11:25:17Z | 16,586,274 | 8 | 2013-05-16T11:30:50Z | [
"python",
"mongodb",
"json"
] | My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.
Error:
```
TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
```
Print:
```
{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'... | As a quick replacement, you can change `{'owner': objectid}` to `{'owner': str(objectid)}`.
But defining your own `JSONEncoder` is a better solution, it depends on your requirements. |
TypeError: ObjectId('') is not JSON serializable | 16,586,180 | 33 | 2013-05-16T11:25:17Z | 16,586,277 | 40 | 2013-05-16T11:30:54Z | [
"python",
"mongodb",
"json"
] | My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.
Error:
```
TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
```
Print:
```
{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'... | You should define you own [`JSONEncoder`](http://docs.python.org/2/library/json.html#json.JSONEncoder) and using it:
```
import json
from bson import ObjectId
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.de... |
TypeError: ObjectId('') is not JSON serializable | 16,586,180 | 33 | 2013-05-16T11:25:17Z | 18,405,626 | 54 | 2013-08-23T14:41:55Z | [
"python",
"mongodb",
"json"
] | My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.
Error:
```
TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
```
Print:
```
{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'... | [Pymongo](http://api.mongodb.org/python/current/index.html) provides [json\_util](http://api.mongodb.org/python/current/api/bson/json_util.html) - you can use that one instead to handle BSON types |
Use **kwargs both in function calling and definition | 16,586,888 | 6 | 2013-05-16T12:02:20Z | 16,586,990 | 11 | 2013-05-16T12:06:41Z | [
"python"
] | Suppose I have a function `get_data` which takes some number of keyword arguments. Is there some way I can do this
```
def get_data(arg1, **kwargs):
print arg1, arg2, arg3, arg4
arg1 = 1
data['arg2'] = 2
data['arg3'] = 3
data['arg4'] = 4
get_data(arg1, **data)
```
*So the idea is to avoid typing the argument... | `**kwargs` is a plain dictionary. Try this:
```
def get_data(arg1, **kwargs):
print arg1, kwargs['arg2'], kwargs['arg3'], kwargs['arg4']
```
Also, check documentation on [keyword arguments](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments). |
Sending DDC/CI commands to monitor on Windows using Python? | 16,588,133 | 10 | 2013-05-16T12:58:26Z | 18,065,609 | 8 | 2013-08-05T18:55:21Z | [
"python",
"windows",
"screen"
] | I would like to have my monitors controlled from Windows (simple stuff such as changing the input source), but cannot find a way of sending DDC/CI commands from Python...
Any clue about a library or method that could help here? | This is easily possible using the [windows monitor API](http://msdn.microsoft.com/en-us/library/windows/desktop/dd692982%28v=vs.85%29.aspx). I don't think there are any Python bindings out there and pywin32 doesn't contain those functions. However, using [`ctypes`](http://docs.python.org/2/library/ctypes.html) to call ... |
AttributeError while querying: Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute | 16,589,208 | 16 | 2013-05-16T13:46:33Z | 16,609,126 | 14 | 2013-05-17T12:31:08Z | [
"python",
"sqlalchemy",
"attributeerror"
] | The following code:
```
Base = declarative_base()
engine = create_engine(r"sqlite:///" + r"d:\foo.db",
listeners=[ForeignKeysListener()])
Session = sessionmaker(bind = engine)
ses = Session()
class Foo(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
name = Column... | The is not an explanation of why this is happening, in technical terms as I am unable to describe it precise technical terms. However, you can accomplish the same goal by using:
```
ses.query(FooBar).join(Foobar.bar).join(Bar.foo).filter(Foo.name == "blah")
``` |
AttributeError while querying: Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute | 16,589,208 | 16 | 2013-05-16T13:46:33Z | 24,763,356 | 22 | 2014-07-15T16:23:20Z | [
"python",
"sqlalchemy",
"attributeerror"
] | The following code:
```
Base = declarative_base()
engine = create_engine(r"sqlite:///" + r"d:\foo.db",
listeners=[ForeignKeysListener()])
Session = sessionmaker(bind = engine)
ses = Session()
class Foo(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
name = Column... | This is because you are trying to access `bar` from the `FooBar` class rather than a `FooBar` instance. The `FooBar` class does not have any `bar` objects associated with it--`bar` is just an sqlalchemy *InstrumentedAttribute*. This is why you get the error:
```
AttributeError: Neither 'InstrumentedAttribute' object n... |
Django allauth does not find /accounts/login view due to "No module named path.to" | 16,589,661 | 5 | 2013-05-16T14:06:28Z | 21,733,041 | 8 | 2014-02-12T16:00:24Z | [
"python",
"django",
"django-allauth"
] | I've installed django\_allauth but the accounts/login view shows this error.
```
ImportError at /accounts/login/
No module named path.to
Request Method: GET
Request URL: http://chew.local:5000/accounts/login/
Django Version: 1.5.1
Exception Type: ImportError
Exception Value:
No module named path.to
Exception Lo... | Take a look at your settings. I think you did a copy paste fault:
This snippet what might cause this error is from <https://django-allauth.readthedocs.org/en/latest/index.html?highlight=path.to#facebook>
```
SOCIALACCOUNT_PROVIDERS = \
{'facebook':
{'SCOPE': ['email', 'publish_stream'],
'AUTH_PARAM... |
Most efficient property to hash for numpy array | 16,589,791 | 21 | 2013-05-16T14:12:51Z | 16,592,241 | 18 | 2013-05-16T15:58:25Z | [
"python",
"numpy"
] | I need to be able to store a `numpy` `array` in a `dict` for caching purposes. Hash speed is important.
The `array` represents indicies, so while the actual identity of the object is not important, the value is. Mutabliity is not a concern, as I'm only interested in the current value.
What should I hash in order to s... | You can simply hash the underlying buffer, if you make it read-only:
```
>>> a = random.randint(10, 100, 100000)
>>> a.flags.writeable = False
>>> %timeit hash(a.data)
100 loops, best of 3: 2.01 ms per loop
>>> %timeit hash(a.tostring())
100 loops, best of 3: 2.28 ms per loop
```
For very large arrays, `hash(str(a))`... |
matplotlib: Group boxplots | 16,592,222 | 28 | 2013-05-16T15:57:29Z | 16,598,291 | 48 | 2013-05-16T22:07:48Z | [
"python",
"matplotlib",
"boxplot"
] | Is there a way to group boxplots in matplotlib?
Assume we have three groups "A", "B", and "C" and for each we want to create a boxplot for both "apples" and "oranges". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visua... | How about using colors to differentiate between "apples" and "oranges" and spacing to separate "A", "B" and "C"?
Something like this:
```
from pylab import plot, show, savefig, xlim, figure, \
hold, ylim, legend, boxplot, setp, axes
# function for setting the colors of the box plots pairs
def setBoxC... |
matplotlib: Group boxplots | 16,592,222 | 28 | 2013-05-16T15:57:29Z | 16,602,925 | 11 | 2013-05-17T06:36:06Z | [
"python",
"matplotlib",
"boxplot"
] | Is there a way to group boxplots in matplotlib?
Assume we have three groups "A", "B", and "C" and for each we want to create a boxplot for both "apples" and "oranges". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visua... | A simple way would be to use [pandas](http://pandas.pydata.org/).
I adapted an example from the [plotting documentation](http://pandas.pydata.org/pandas-docs/stable/visualization.html#box-plotting):
```
In [1]: import pandas as pd
In [2]: df = pd.DataFrame(np.random.rand(12,2), columns=['Apples', 'Oranges'] )
In [3]... |
matplotlib: Group boxplots | 16,592,222 | 28 | 2013-05-16T15:57:29Z | 20,132,614 | 9 | 2013-11-21T21:46:18Z | [
"python",
"matplotlib",
"boxplot"
] | Is there a way to group boxplots in matplotlib?
Assume we have three groups "A", "B", and "C" and for each we want to create a boxplot for both "apples" and "oranges". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visua... | Here is my version. It stores data based on categories.
```
import matplotlib.pyplot as plt
import numpy as np
data_a = [[1,2,5], [5,7,2,2,5], [7,2,5]]
data_b = [[6,4,2], [1,2,5,3,2], [2,3,5,1]]
mu = [3.93, 7.761, 14.319]
alpha = [0.9996197532958419, 0.9702573729698682, 0.9375845650647818]
ticks = ['A', 'B', 'C']
d... |
parsing rST to HTML on the fly using Docutils | 16,592,991 | 6 | 2013-05-16T16:39:33Z | 16,593,200 | 11 | 2013-05-16T16:52:03Z | [
"python",
"pyramid",
"docutils"
] | I want to parse .rst files to .html files on the fly to display as a webpage. I'm using pyramid, and I haven't found any quick help on how to use docutils inside python code and make it write to a buffer.
Anyone have any links to a simple tutorial or any other suggestions on how to do that? | One way is to do something like:
```
>>> a = """=====\nhello\n=====\n\n - one\n - two\n"""
>>> import docutils
>>> docutils.core.publish_parts(a, writer_name='html')['html_body']
u'<div class="document" id="hello">\n<h1 class="title">hello</h1>\n<blockquote>\n<ul class="simple">\n<li>one</li>\n<li>two</li>\n</ul>\n</b... |
How to configure interactive python to allow blank lines inside methods | 16,593,938 | 6 | 2013-05-16T17:37:19Z | 16,594,013 | 7 | 2013-05-16T17:41:17Z | [
"python"
] | Is it possible to test methods inside interactive python and retain blank lines within them?
```
def f1():
import random
import time
time.sleep(random.randint(1, 4))
```
This gives the familiar error
```
IndentationError: unexpected indent
```
So, yes a workaround is to remove all blank lines inside function... | Might not be much help, but it works if the blank lines are indented. Dots shown for clarity:
```
def f1():
....import random
....import time
....
....time.sleep(random.randint(1, 4))
``` |
python list comprehension to produce two values in one iteration | 16,594,904 | 12 | 2013-05-16T18:33:41Z | 16,594,936 | 21 | 2013-05-16T18:35:18Z | [
"python",
"list",
"list-comprehension"
] | I want to generate a list in python as follows -
```
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....]
```
You would have figured out, it is nothing but `n, n*n`
I tried writing such a list comprehension in python as follows -
```
lst_gen = [i, i*i for i in range(1, 10)]
```
But doing this, gives a syntax error.
What would ... | Use [`itertools.chain.from_iterable`](http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable):
```
>>> from itertools import chain
>>> list(chain.from_iterable((i, i**2) for i in xrange(1, 6)))
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25]
```
Or you can also use a [generator](http://wiki.python.org/moin/Ge... |
Standalone colorbar (matplotlib) | 16,595,138 | 8 | 2013-05-16T18:48:01Z | 16,599,889 | 12 | 2013-05-17T01:05:45Z | [
"python",
"matplotlib"
] | I'm rendering some graphics in python with matplotlib, and will include them into a LaTeX paper (using LaTex's nice tabular alignment instead of fiddling with matplotlib's `ImageGrid`, etc.). **I would like to create and save a standalone colorbar with `savefig`, without needing to use `imshow`.**
(the `vlim, vmax` pa... | You can create some dummy image and then hide it's axe. Draw your colorbar in a customize Axes.
```
import pylab as pl
import numpy as np
a = np.array([[0,1]])
pl.figure(figsize=(9, 1.5))
img = pl.imshow(a, cmap="Blues")
pl.gca().set_visible(False)
cax = pl.axes([0.1, 0.2, 0.8, 0.6])
pl.colorbar(orientation="h", cax=... |
Pandas Convert 'NA' to NaN | 16,596,188 | 4 | 2013-05-16T19:48:25Z | 16,596,294 | 7 | 2013-05-16T19:55:01Z | [
"python",
"pandas",
"bioinformatics"
] | I just picked up Pandas to do with some data analysis work in my biology research. Turns out one of the proteins I'm analyzing is called 'NA'.
I have a matrix with pairwise 'HA, M1, M2, NA, NP...' on the column headers, and the same as "row headers" (for the biologists who might read this, I'm working with influenza).... | Turn off NaN detection this way: `pd.read_csv(filename, keep_default_na=False)`
I originally suggested `na_filter=False`, which gets the job done. But, if I understand Jeff's comments below, this is a cleaner solution.
Example:
```
In [1]: pd.read_csv('test')
Out[1]:[4]: pd.read_csv('test', keep_default_na=False)
Ou... |
Pulling data to the template from an external database with django | 16,596,261 | 6 | 2013-05-16T19:52:57Z | 16,599,966 | 7 | 2013-05-17T01:16:46Z | [
"python",
"mysql",
"xml",
"django",
"json"
] | I'm going to attempting to build a web app where users can visit a url, login and view reports and other information. However the data for the reports are stored in an external database. It's a MySQL database which I'm going to have access to.
I've done a little research on google and not have much luck finding any ex... | No problem! I do this all the time.
As far as the "don't edit or update the data", just don't add anything to your app that would update the data. Salem's suggestion about using permissions on the MySQL side is a good idea as well.
For retrieving the data, you have two options:
1) You can create Django models that c... |
Why is numpy slower than python? How to make code perform better | 16,597,066 | 6 | 2013-05-16T20:40:31Z | 16,597,107 | 13 | 2013-05-16T20:43:01Z | [
"python",
"performance",
"numpy"
] | I revrite my neural net from pure python to numpy, but now it is working even slower. So I tried this two functions:
```
def d():
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = [i*j for i,j in zip(a,b)]
return c
def e():
a = np.array([1,2,3,4,5])
b = np.array([10,20,30,40,50])
c = a*b
return... | I would assume that the discrepancy is because you're constructing lists and arrays in `e` whereas you're only constructing lists in `d`. Consider:
```
import numpy as np
def d():
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = [i*j for i,j in zip(a,b)]
return c
def e():
a = np.array([1,2,3,4,5])
b ... |
Appending to an empty data frame in Pandas? | 16,597,265 | 55 | 2013-05-16T20:52:29Z | 16,597,375 | 110 | 2013-05-16T20:58:48Z | [
"python",
"pandas"
] | Is it possible to append to an empty data frame that doesn't contain any indices or columns?
I have tried to do this, but keep getting an empty dataframe at the end.
e.g.
```
df = pd.DataFrame()
data = ['some kind of data here' --> I have checked the type already, and it is a dataframe]
df.append(data)
```
The resu... | That should work:
```
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
```
but the `append` doesn't happen in-place, so you'll have to store the output if you want it:
```
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 ... |
Appending to an empty data frame in Pandas? | 16,597,265 | 55 | 2013-05-16T20:52:29Z | 31,839,240 | 24 | 2015-08-05T17:38:03Z | [
"python",
"pandas"
] | Is it possible to append to an empty data frame that doesn't contain any indices or columns?
I have tried to do this, but keep getting an empty dataframe at the end.
e.g.
```
df = pd.DataFrame()
data = ['some kind of data here' --> I have checked the type already, and it is a dataframe]
df.append(data)
```
The resu... | And if you want to add a row, you can use a dictionary:
```
df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)
```
which gives you:
```
age height name
0 9 2 Zed
``` |
Is there a library for urllib2 for python which we can download? | 16,597,865 | 4 | 2013-05-16T21:33:15Z | 16,597,893 | 8 | 2013-05-16T21:35:36Z | [
"python",
"urllib2"
] | I need to use urllib2 with BeautifulSoup. I found the download file for BeautifulSoup and installed it, however, I couldn't find any download files for urllib2, is there another way to intall that module? | The module comes with Python, simply import it:
```
import urllib2
```
If you're using Python3, the `urllib` was replaced by [urllib.request](http://docs.python.org/3.0/library/urllib.request.html). The Urllib PEP (Python3): <http://www.python.org/dev/peps/pep-3108/#urllib-package>. |
how to login to a website with python and mechanize | 16,598,145 | 15 | 2013-05-16T21:56:12Z | 16,598,227 | 16 | 2013-05-16T22:02:54Z | [
"python",
"cookies",
"login",
"website",
"mechanize"
] | i'm trying to log in to the website <http://www.magickartenmarkt.de> and do some analyzing in the member-area (<https://www.magickartenmarkt.de/?mainPage=showWants>). I saw other examples for this, but i don't get why my approaches didn't work. I identified the right forms for the first approach, but it's not clear if ... | Why not use a browser instance to facilitate navigation? Mechanize also has the ability to select particular forms (e.g. nr = 0 will select the first form on the page)
```
browser = mechanize.Browser()
browser.open(YOUR URL)
browser.select_form(nr = 0)
browser.form['username'] = USERNAME
browser.form['password'] = PAS... |
nltk.download() hangs on OS X | 16,598,830 | 7 | 2013-05-16T22:55:28Z | 16,638,537 | 12 | 2013-05-19T19:22:23Z | [
"python",
"nltk"
] | `nltk.download()` is hanging for me on OS X. Here is what happens:
```
$python
>>> Python 2.7.2 (default, Oct 11 2012, 20:14:37)
>>> [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
>>> import nltk
>>> nltk.download()
showing info http://nltk.github.com/nltk_data/
```
After that, it comp... | Try running `nltk.download_shell()` instead as there is most likely an issue displaying the downloader UI. Running the `download_shell()` function will bypass it. |
How to print a for loop as a list | 16,598,914 | 2 | 2013-05-16T23:04:58Z | 16,598,950 | 9 | 2013-05-16T23:08:30Z | [
"python",
"for-loop"
] | So I have:
```
s = (4,8,9), (1,2,3), (4,5,6)
for i, (a,b,c) in enumerate(s):
k = [a,b,c]
e = k[0]+k[1]+k[2]
print e
```
It would print:
```
21
6
15
```
But I want it to be:
```
(21,6,15)
```
I tried using this but it's not what I wanted:
```
print i,
```
So is this possible? | Here are a few options:
* Using tuple unpacking and a generator:
```
print tuple(a+b+c for a, b, c in s)
```
* Using `sum()` and a generator:
```
print tuple(sum(t) for t in s)
```
* Using `map()`:
```
print tuple(map(sum, s))
``` |
List of dictionaries from pairs in list | 16,599,007 | 3 | 2013-05-16T23:15:00Z | 16,599,038 | 10 | 2013-05-16T23:18:13Z | [
"python",
"list",
"dictionary"
] | Looking for a way to transform a list of coordinates into pairs of dictionaries, i.e if:
```
l = [1 2 3 4 5 6 7 8]
```
I want to create a list of dictionaries:
```
output = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, ... ]
```
Any ideas on how to do this "pythonically"? | The typical way is with the ["grouper"](http://docs.python.org/2/library/itertools.html#recipes) recipe:
```
from itertools import izip
def grouper(iterable,n):
return izip(*[iter(iterable)]*n)
output = [{'x':a,'y':b} for a,b in grouper(l,2)]
```
The advantage here is that it will work with *any iterable*. The i... |
Tuple unpacking | 16,600,068 | 2 | 2013-05-17T01:29:08Z | 16,600,079 | 7 | 2013-05-17T01:30:25Z | [
"python",
"python-3.x",
"tuples"
] | I have a tuple that looks like this:
`('Elizabeth', 'Peter, Angela, Thomas')`
How could I separate the last value in it so it would look like this:
`('Elizabeth', 'Peter', 'Angela', 'Thomas')` | ```
>>> names = ('Elizabeth', 'Peter, Angela, Thomas')
>>> [y for x in names for y in x.split(', ')]
['Elizabeth', 'Peter', 'Angela', 'Thomas']
```
There's also this way, I prefer the first however:
```
>>> ', '.join(names).split(', ')
['Elizabeth', 'Peter', 'Angela', 'Thomas']
```
Of course you can convert the resu... |
return output of dictionary to alphabetical order | 16,600,174 | 5 | 2013-05-17T01:44:04Z | 16,600,185 | 11 | 2013-05-17T01:45:03Z | [
"python",
"dictionary",
"alphabetical"
] | The following code prints out the word in the txt file and then how many instances there are of that word (e.g. a, 26) the problem is that it doesn't print it out in alphabetical order. Any help would be much appreciated
```
import re
def print_word_counts(filename):
s=open(filename).read()
words=re.findall('[... | You just need to sort the items. The builtin `sorted` should work wonderfully:
```
for key,value in sorted(dic.items()):
...
```
If you drop the `e.sort()` line, then this should run in approximately the same amount of time. The reason that it doesn't work is because dictionaries are based on `hash` tables which ... |
How to parse string dates with 2-digit year? | 16,600,548 | 7 | 2013-05-17T02:34:57Z | 16,600,636 | 8 | 2013-05-17T02:47:22Z | [
"python",
"date",
"y2k",
"2-digit-year"
] | I need to parse strings representing 6-digit dates in the format `yymmdd` where `yy` ranges from 59 to 05 (1959 to 2005). According to the [`time`](http://docs.python.org/2/library/time.html) module docs, Python's default pivot year is 1969 which won't work for me.
Is there an easy way to override the pivot year, or c... | I'd use `datetime` and parse it out normally. Then I'd use `datetime.datetime.replace` on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
```
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
dd = dd.replace(year=dd.year-100)
``` |
Python index a list where a regex matches | 16,602,373 | 2 | 2013-05-17T05:57:51Z | 16,602,404 | 9 | 2013-05-17T05:59:25Z | [
"python",
"regex",
"list"
] | Again recognizing that this is similar to a few other questions on SO but which I haven't been able to convert for my purposes. eg. with the snippet below
```
import re
a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake']
s = re.compile('custard')
```
I'd like to be able to get a list
`[2,4]`
... | ```
>>> import re
>>> a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake']
>>> [i for i, s in enumerate(a, start=1) if re.search('custard', s)]
[2, 4]
```
**note** Python uses 0-index so I added the `start=1` parameter to `enumerate`. In practice you should leave off `start=1` to have the default... |
How to compare each item in a list with the rest, only once? | 16,603,282 | 18 | 2013-05-17T07:02:12Z | 16,603,347 | 11 | 2013-05-17T07:05:57Z | [
"python"
] | Say I have an array/list of things I want to compare. In languages I am more familiar with, I would do something like
```
for( int i=0, i<mylist.size(); i++)
for (int j=i+1, j<mylist.size(); j++)
compare(mylist[i],mylist[j])
```
This ensures we only compare each pair once. For context, I am doing collisio... | Use `itertools.combinations(mylist, 2)`
```
mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
print x,y
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4
``` |
How to compare each item in a list with the rest, only once? | 16,603,282 | 18 | 2013-05-17T07:02:12Z | 16,603,357 | 33 | 2013-05-17T07:06:33Z | [
"python"
] | Say I have an array/list of things I want to compare. In languages I am more familiar with, I would do something like
```
for( int i=0, i<mylist.size(); i++)
for (int j=i+1, j<mylist.size(); j++)
compare(mylist[i],mylist[j])
```
This ensures we only compare each pair once. For context, I am doing collisio... | Of course this will generate each pair twice as each for loop will go through every item of the list. You could use some [itertools](http://docs.python.org/3/library/itertools.html) magic:
```
import itertools
for a, b in itertools.combinations(mylist, 2):
compare(a, b)
```
[`itertools.combinations`](http://docs.... |
IntegrityError: null value in column "city_id " violates not-null constraint | 16,603,657 | 6 | 2013-05-17T07:25:16Z | 16,603,756 | 8 | 2013-05-17T07:31:51Z | [
"python",
"django",
"models"
] | I two model:
```
class City(models.Model):
name = models.CharField(max_length=50)
country = models.OneToOneField(Country)
def __unicode__(self):
return self.name
class UserProfile(models.Model):
user = models.OneToOneField(User)
city = models.OneToOneField(City)
```
when I syncdb and c... | ```
city = models.OneToOneField(City)
```
Are you sure you want only one user per city? I think you need
```
city = models.ForeignKey(City, null=True, blank=True)
```
`null, blank` because the `sycndb` will create a profile and will fail if no `city` is passed.
Alternatively, you can pass `default=default_city_id` ... |
object has no attribute '__getitem__' | 16,604,915 | 8 | 2013-05-17T08:43:39Z | 16,604,967 | 12 | 2013-05-17T08:46:21Z | [
"python",
"django",
"model",
"admin"
] | I have two model like this:
```
class School(models.Model):
name = models.CharField(max_length = 50)
def __unicode__(self):
return self.name
class Education(models.Model):
user_profile = models.ForeignKey(UserProfile, related_name='Education')
school = models.OneToOneField(School)
def _... | To fix this you need `__unicode__` to return `str` (not an object).
```
def __unicode__(self):
return unicode(self.school)
``` |
While loop python | 16,605,916 | 3 | 2013-05-17T09:38:26Z | 16,605,932 | 7 | 2013-05-17T09:39:57Z | [
"python",
"while-loop"
] | I am new to python and am having problems seeing why this code does not work. I would like it to return [10,122,2].
```
close = [5000,5010,5132,5134]
def difference():
x = 0
data = []
while x < len(close):
diff = close[x+1]-close[x]
data.append(diff)
x = x + 1
return data
```
... | You limit `x` to be smaller than `len(close)`, but the last index of a list is at `len(close) - 1` (0 based indexing). This means in the last iteration of your loop `x + 1` will be equal to `len(close)` and out of bounds.
This works:
```
while x < len(close) - 1:
diff = close[x+1]-close[x]
data.append(diff)
... |
Calling python method from C++ (or C) callback | 16,606,872 | 11 | 2013-05-17T10:31:23Z | 16,609,899 | 19 | 2013-05-17T13:08:01Z | [
"c++",
"python",
"c",
"callback",
"python-c-api"
] | I am trying to call methods in a python class from C++. The C++ method from which this is called is a C++ callback.
Within this method when I am trying to call python method, it was giving `segmentation fault`.
I have saved an instance of python function in a global variable like
```
// (pFunc is global variable of ... | There are a few things you need to do if you are invoking a Python function from a C/C++ callback. First when you save off your python function object, you need to increment the reference count with:
```
Py_INCREF(pFunc)
```
Otherwise Python has no idea you are holding onto an object reference, and it may garbage col... |
One liner: creating a dictionary from list with indices as keys | 16,607,704 | 39 | 2013-05-17T11:19:52Z | 16,607,772 | 85 | 2013-05-17T11:23:18Z | [
"python",
"list",
"dictionary",
"python-3.x"
] | I want to create a dictionary out of a given list, *in just one line*. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
```
a = [51,27,13,56] #given list
d = one-line-statement #one line statement to create dictionary
print(d)
```
Output:
```
... | ```
a = [51,27,13,56]
b = dict(enumerate(a))
print(b)
```
will produce
```
{0: 51, 1: 27, 2: 13, 3: 56}
```
> [`enumerate(sequence, start=0)`](http://docs.python.org/2/library/functions.html#enumerate)
>
> Return an enumerate object. *sequence* must be a sequence, an *iterator*, or some other object which supports i... |
One liner: creating a dictionary from list with indices as keys | 16,607,704 | 39 | 2013-05-17T11:19:52Z | 16,607,836 | 13 | 2013-05-17T11:27:16Z | [
"python",
"list",
"dictionary",
"python-3.x"
] | I want to create a dictionary out of a given list, *in just one line*. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
```
a = [51,27,13,56] #given list
d = one-line-statement #one line statement to create dictionary
print(d)
```
Output:
```
... | Try `enumerate`: it will return a list (or iterator) of tuples `(i, a[i])`, from which you can build a `dict`:
```
a = [51,27,13,56]
b = dict(enumerate(a))
print b
``` |
One liner: creating a dictionary from list with indices as keys | 16,607,704 | 39 | 2013-05-17T11:19:52Z | 16,608,304 | 10 | 2013-05-17T11:50:38Z | [
"python",
"list",
"dictionary",
"python-3.x"
] | I want to create a dictionary out of a given list, *in just one line*. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
```
a = [51,27,13,56] #given list
d = one-line-statement #one line statement to create dictionary
print(d)
```
Output:
```
... | With another constructor, you have
```
a = [51,27,13,56] #given list
d={i:x for i,x in enumerate(a)}
print(d)
``` |
Python exception handling in list comprehension | 16,610,997 | 5 | 2013-05-17T14:02:41Z | 16,611,498 | 9 | 2013-05-17T14:26:30Z | [
"python",
"exception-handling",
"list-comprehension"
] | I have a Python function called `plot_pdf(f)` that might throw an error. I use a list comprehension to iterate over a list of files on this function:
```
[plot_pdf(f) for f in file_list]
```
I want to use try-except block to skip any possible errors during the iteration loop and continue with the next file. So is the... | ```
try:
[plot_pdf(f) for f in file_list] # using list comprehensions
except:
print ("Exception: ", sys.exc_info()[0])
continue
```
If `plot_pdf(f)` throws an error during execution of comprehension, then, it is catched in the `except` clause, other items in comprehension won't be evaluated.
It is not po... |
using arctan / arctan2 to plot a from 0 to 2Ï | 16,613,546 | 7 | 2013-05-17T16:07:00Z | 16,614,914 | 8 | 2013-05-17T17:34:39Z | [
"python",
"numpy",
"matplotlib"
] | I am trying to replicate a plot in Orbital Mechanics by Curtis but I just can't quite get it. However, I have made head way by switching to `np.arctan2` from `np.arctan`.
Maybe I am implementing `arctan2` incorrectly?
```
import pylab
import numpy as np
e = np.arange(0.0, 1.0, 0.15).reshape(-1, 1)
nu = np.linspace(... | The common practice is to sum 2\*pi in the negative results of `arctan()`, [which can be done efficiently](http://stackoverflow.com/a/10335159/832621). The OP's suggestion to replace arctan(x) by arctan2(1,1/x), despite not yet explained, produces the same results without the need to sum 2\*pi. Both are shown below:
`... |
Python code efficiency | 16,614,198 | 2 | 2013-05-17T16:48:26Z | 16,614,400 | 13 | 2013-05-17T17:00:49Z | [
"python",
"matrix"
] | This program tests if a matrix is an identity matrix or not.
I have pasted my code beneath, and would like to know ways in which I can optimize the efficiency of this code. Also I am new to python programming, are there some built in functions that can solve the purpose too?
```
def is_identity_matrix(test):
... | ```
def is_identity_matrix(listoflist):
return all(val == (x == y)
for y, row in enumerate(listoflist)
for x, val in enumerate(row))
```
(though, this does not check if the matrix is square, and it returns True for an empty list)
Explanation: Inside `all` we have a generator expression with... |
Python urlparse.parse_qs unicode url | 16,614,695 | 10 | 2013-05-17T17:20:07Z | 16,614,758 | 12 | 2013-05-17T17:24:00Z | [
"python",
"django",
"urlencode",
"urlparse"
] | `urlparse.parse_qs` is usefull for parsing url parameters, and it works fine with simple ASCII url, represented by `str`. So i can parse a query and then construct the same path using `urllib.urlencode` from parsed data:
```
>>> import urlparse
>>> import urllib
>>>
>>> path = '/?key=value' #path is str
>>> query = ur... | Encode back to bytes *before* passing it to `.parse_qs()`, using ASCII:
```
query_dict = urlparse.parse_qs(query.encode('ASCII'))
```
This does the same thing as `str()` but with an explicit encoding. Yes, this is safe, the URL encoding uses ASCII codepoints *only*.
`parse_qs` was handed a Unicode value, so it retur... |
Adding a simple value to a string | 16,615,630 | 2 | 2013-05-17T18:26:44Z | 16,615,653 | 7 | 2013-05-17T18:28:14Z | [
"python",
"string"
] | If I have a string lets say ohh
```
path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio'
```
And I want to add a `"` at the end of the string how do I do that? Right now I have it like this.
```
path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio'
w = '"'
final = os.path.join(path2,... | just do:
```
path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'
``` |
Adding a simple value to a string | 16,615,630 | 2 | 2013-05-17T18:26:44Z | 16,615,667 | 7 | 2013-05-17T18:29:06Z | [
"python",
"string"
] | If I have a string lets say ohh
```
path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio'
```
And I want to add a `"` at the end of the string how do I do that? Right now I have it like this.
```
path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio'
w = '"'
final = os.path.join(path2,... | How about?
```
path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'
```
Or, as you had it
```
final = path2 + w
```
It's also worth mentioning that you can use raw strings (r'stuff') to avoid having to escape backslashes. Ex.
```
path2 = r'"C:\Users\bgbesase\Documents\Brent\Code\Visual Studi... |
How to write text on a image in windows using python opencv2 | 16,615,662 | 11 | 2013-05-17T18:28:57Z | 16,615,935 | 14 | 2013-05-17T18:46:46Z | [
"python",
"windows",
"opencv"
] | I am a newbee to Python OpenCV.
I wanted to put some text on an Image.
I am writing the code as:
cv2.putText(image,"Hello World!!!", (x,y), cv2.CV\_FONT\_HERSHEY\_SIMPLEX, 2, 255)
It gives ERROR, saying 'module' object has no attribute 'CV\_FONT\_HERSHEY\_SIMPLEX'
**Query**
Can't i use the font type as above? I sear... | Was `CV_FONT_HERSHEY_SIMPLEX` in cv(1)?
Here's all I have available for cv2 "FONT":
```
FONT_HERSHEY_COMPLEX
FONT_HERSHEY_COMPLEX_SMALL
FONT_HERSHEY_DUPLEX
FONT_HERSHEY_PLAIN
FONT_HERSHEY_SCRIPT_COMPLEX
FONT_HERSHEY_SCRIPT_SIMPLEX
FONT_HERSHEY_SIMPLEX
FONT_HERSHEY_TRIPLEX
FONT_ITALIC
```
Dropping the 'CV\_' seems to ... |
Deleting all columns except a few python-pandas | 16,616,141 | 11 | 2013-05-17T19:00:47Z | 16,616,454 | 16 | 2013-05-17T19:24:38Z | [
"python",
"pandas"
] | Say I have a data table
```
1 2 3 4 5 6 .. n
A x x x x x x .. x
B x x x x x x .. x
C x x x x x x .. x
```
And I want to slim it down so that I only have, say, columns 3 and 5 deleting all other and maintaining the structure. How could I do this with pandas? I think I understand how t... | If you have a list of columns you can just select those:
```
In [11]: df
Out[11]:
1 2 3 4 5 6
A x x x x x x
B x x x x x x
C x x x x x x
In [12]: col_list = [3, 5]
In [13]: df = df[col_list]
In [14]: df
Out[14]:
3 5
A x x
B x x
C x x
``` |
why isn't numpy.mean multithreaded? | 16,617,973 | 10 | 2013-05-17T21:09:48Z | 16,618,280 | 10 | 2013-05-17T21:35:31Z | [
"python",
"multithreading",
"performance",
"numpy"
] | I've been looking for ways to easily multithread some of my simple analysis code since I had noticed numpy it was only using one core, despite the fact that it is supposed to be multithreaded.
I know that numpy is configured for multiple cores, since I can see tests using numpy.dot use all my cores, so I just reimplem... | > I've been looking for ways to easily multithread some of my simple analysis code since I had noticed numpy it was only using one core, despite the fact that it is supposed to be multithreaded.
Who says it's supposed to be multithreaded?
`numpy` is primarily designed to be as fast as possible on a single core, and t... |
How to add parameters to a built file in Sublime Text 3 before execution | 16,618,240 | 5 | 2013-05-17T21:32:10Z | 16,619,406 | 9 | 2013-05-18T00:01:15Z | [
"python",
"python-3.x",
"sublimetext"
] | i'm currently making a program that runs on terminal. I have added some arguments some of them required. But I can't test my program in Sublime Text because I can't specify any parameters to test it, there is any option that I need to enable to specify the arguments?
I want to add it to my built program use before run... | You can create a new build system for sublime text and run your script with fixed arguments.
Create a new File in your Packages/User directory (`CTRL-SHIFT-P --> "Browse Packages"`)
New File: `Packages/User/my_build.sublime-build`
with the following content:
```
{
"cmd": ["python", "$file", "arg1", "arg2"]
}
```... |
Why Is the Output of My Range Function Not a List? | 16,618,847 | 3 | 2013-05-17T22:33:59Z | 16,618,866 | 10 | 2013-05-17T22:35:47Z | [
"python",
"python-3.x"
] | According to the Python documentation, when I do range(0, 10) the output of this function is a list from 0 to 9 i.e. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. However the Python installation on my PC is not outputting this, despite many examples of this working online.
Here is my test code...
```
test_range_function = range(0,... | That's because `range` and other functional-style methods, such as `map`, `reduce`, and `filter`, return iterators in Python 3. In Python 2 they returned lists.
[Whatâs New In Python 3.0](http://docs.python.org/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists):
> `range()` now behaves like `xrange()` used... |
In Python, how to write a set containing a set? | 16,619,121 | 7 | 2013-05-17T23:11:34Z | 16,619,136 | 15 | 2013-05-17T23:14:05Z | [
"python"
] | We know in Python, a set can be defined by writing out all its elements like this:
```
a_set={1,"xyz"}
```
And books of Python all say elements of a set can be any datatype. So we should be able to write out a set containing a set. I tried to write it as:
```
a_set={1,{"xyz"}}
```
But [IDLE](http://en.wikipedia.org... | The inner most sets need to be of type [frozenset](http://docs.python.org/2/library/stdtypes.html#frozenset) which is an immutable version of a set.
```
>>> a_set = {1, frozenset(['xyz'])}
>>> a_set
set([1, frozenset(['xyz'])])
```
From the [docs](http://docs.python.org/2/library/stdtypes.html#frozenset):
> **class ... |
Regex which matches the longer string in an OR | 16,619,401 | 8 | 2013-05-18T00:00:25Z | 16,619,508 | 7 | 2013-05-18T00:18:19Z | [
"python",
"regex"
] | # Motivation
I'm parsing addresses and need to get the address and the country in separated matches, but the countries might have aliases, e.g.:
```
UK == United Kingdom,
US == USA == United States,
Korea == South Korea,
```
and so on...
# Explanation
So, what I do is create a big regex with all possible country ... | Your problem is [greediness](http://www.regular-expressions.info/repeat.html#greedy).
The `.*` right at the beginning tries to match as much as possible. That is everything until the end of the string. But then the rest of your pattern fails. So the engine backtracks, and discards the last character matched with `.*` ... |
Reading a 6.9GB file causes a segmentation fault | 16,619,644 | 2 | 2013-05-18T00:45:19Z | 16,619,670 | 11 | 2013-05-18T00:49:42Z | [
"python"
] | I'm trying to open the latest Japanese Wikipedia database for reading in Python 3.3.1 on Linux, but am getting a `Segmentation fault (core dumped)` error with this short program:
```
with open("jawiki-latest-pages-articles.xml") as f:
text = f.read()
```
The file itself is quite large:
```
-rw-r--r-- 1 fredrick ... | Don't read the whole article at once. Even if your Python distribution is compiled as a 64-bit program (it's simply impossible to allocate more than 4 GB of virtual memory in a 32-bit program), and even if you have enough RAM to store it all, it's still a bad idea to read it all into memory at once.
One simple option ... |
Delete related object via OneToOneField | 16,620,324 | 4 | 2013-05-18T03:14:34Z | 16,620,382 | 7 | 2013-05-18T03:24:56Z | [
"python",
"django",
"django-models"
] | Is there some clever way how to perform delete in this situation?
```
class Bus(models.Model):
wheel = OneToOneField(Wheel)
class Bike(models.Model):
wheel = OneToOneField(Wheel)
pedal = OneToOneField(Pedal)
class Car(models.Model):
wheel = OneToOneField(Wheel)
class Wheel(models.Model):... | Here is the thing, since `Car` links to `Wheel`, it is the dependent model in the relationship. Therefore when you delete a `Wheel`, it deletes all dependent models (including related `Car` rows). However when you delete a `Car`, since `Wheel` does not depend on `Car`, it is not removed.
In order to delete parent rela... |
Delete related object via OneToOneField | 16,620,324 | 4 | 2013-05-18T03:14:34Z | 16,621,653 | 7 | 2013-05-18T07:05:28Z | [
"python",
"django",
"django-models"
] | Is there some clever way how to perform delete in this situation?
```
class Bus(models.Model):
wheel = OneToOneField(Wheel)
class Bike(models.Model):
wheel = OneToOneField(Wheel)
pedal = OneToOneField(Pedal)
class Car(models.Model):
wheel = OneToOneField(Wheel)
class Wheel(models.Model):... | Cascading delete is already provided by django, through [`on_delete`](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete) attribute value `CASCADE`. It is also available for `OneToOneField` along with `ForeignKey`.
> ForeignKey.on\_delete
>
> When an object referenced by a F... |
Tracing an ignored exception in Python? | 16,620,932 | 5 | 2013-05-18T05:11:44Z | 16,620,987 | 7 | 2013-05-18T05:22:22Z | [
"python",
"exception",
"ignore"
] | My app has a custom audio library that itself uses the BASS library.
I create and destroy BASS stream objects throughout the program.
When my program exits, randomly (I haven't figured out the pattern yet) I get the following notice on my console:
```
Exception TypeError: "'NoneType' object is not callable" in <boun... | The message that the exception was ignored is because all exceptions raised in a `__del__` method are ignored to keep the data model sane. Here's the relevant portion of [the docs](http://docs.python.org/2/reference/datamodel.html#object.__del__):
> **Warning:** Due to the precarious circumstances under which `__del__... |
How to use python numpy.savetxt to write strings and float number to an ASCII file? | 16,621,351 | 31 | 2013-05-18T06:20:20Z | 16,622,262 | 51 | 2013-05-18T08:37:15Z | [
"python",
"list",
"numpy",
"output"
] | I have a set of lists that contain both strings and float numbers, such as:
```
import numpy as num
NAMES = num.array(['NAME_1', 'NAME_2', 'NAME_3'])
FLOATS = num.array([ 0.5 , 0.2 , 0.3 ])
DAT = num.column_stack((NAMES, FLOATS))
```
I want to stack these two lists together and write them to a text fil... | You have to specify the format (`fmt`) of you data in `savetxt`, in this case as a string (`%s`):
```
num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s")
```
The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message. |
How to use python numpy.savetxt to write strings and float number to an ASCII file? | 16,621,351 | 31 | 2013-05-18T06:20:20Z | 35,209,070 | 10 | 2016-02-04T18:42:14Z | [
"python",
"list",
"numpy",
"output"
] | I have a set of lists that contain both strings and float numbers, such as:
```
import numpy as num
NAMES = num.array(['NAME_1', 'NAME_2', 'NAME_3'])
FLOATS = num.array([ 0.5 , 0.2 , 0.3 ])
DAT = num.column_stack((NAMES, FLOATS))
```
I want to stack these two lists together and write them to a text fil... | The currently accepted answer does not actually addresses the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment
```
import numpy as np
names = np.array(['... |
How to append multiple items in one line in Python | 16,621,498 | 27 | 2013-05-18T06:41:09Z | 16,621,512 | 76 | 2013-05-18T06:43:36Z | [
"python"
] | I have:
```
count = 0
i = 0
while count < len(mylist):
if mylist[i + 1] == mylist[i + 13] and mylist[i + 2] == mylist[i + 14]:
print mylist[i + 1], mylist[i + 2]
newlist.append(mylist[i + 1])
newlist.append(mylist[i + 2])
newlist.append(mylist[i + 7])
newlist.append(mylist[i + 8])
newli... | No. The method for appending an entire sequence is `list.extend()`.
```
>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]
``` |
Do I need a return statement after a Python exception? | 16,622,217 | 7 | 2013-05-18T08:31:21Z | 16,622,235 | 11 | 2013-05-18T08:33:57Z | [
"python",
"exception"
] | I'm rather new to python, and I want to make sure I'm doing this correctly. I'd like to have an exception class:
```
class UnknownCommandReceived(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
```
I will raise the exception at the end of t... | No you don't. The `return` statement is unreachable.
Also, static-analysis tools, such as `pyflakes` will report that as an error. |
Python and Homebrew Vim | 16,625,421 | 2 | 2013-05-18T14:34:11Z | 16,628,550 | 11 | 2013-05-18T20:15:37Z | [
"python",
"osx",
"vim",
"homebrew"
] | On my Mac, I use `MacVim` with `homebrew` for most of my editing.
```
~|â vim --version
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Jun 20 2012 13:16:02)
Compiled by [email protected]
Normal version without GUI. Features included (+) or not (-):
-arabic +autocmd -balloon_eval -browse +builtin_terms +byte_offset +cind... | No. This thing is *not* Vim or MacVim installed with Homebrew: it is the default Vim that comes with Mac OS X.
The default Vim has been sucking in a number of ways for quite a long time, chiefly `-xterm-clipboard`, and that's the main reason why people usually install a "proper" Vim. Installing MacVim *doesn't* replac... |
Python: checking if point is inside a polygon | 16,625,507 | 15 | 2013-05-18T14:43:13Z | 23,453,678 | 29 | 2014-05-04T07:19:15Z | [
"python",
"scripting",
"polygon",
"point"
] | I have a class describing a Point (has 2 coordinates x and y) and a class describing a Polygon which has a list of Points which correspond to corners (self.corners)
I need to check if a Point is in a Polygon
Here is the function that is supposed to check if the Point in in the Polygon. I am using the Ray Casting Metho... | I would suggest using the `Path` class from `matplotlib`
```
import matplotlib.path as mplPath
import numpy as np
poly = [190, 50, 500, 310]
bbPath = mplPath.Path(np.array([[poly[0], poly[1]],
[poly[1], poly[2]],
[poly[2], poly[3]],
[poly[3], poly[0]]]))
... |
What is the performance impact of non-unique indexes in pandas? | 16,626,058 | 13 | 2013-05-18T15:44:31Z | 16,629,125 | 27 | 2013-05-18T21:26:37Z | [
"python",
"performance",
"indexing",
"pandas",
"binary-search"
] | From the pandas documentation, I've gathered that unique-valued indices make certain operations efficient, and that non-unique indices are occasionally tolerated.
From the outside, it doesn't look like non-unique indices are taken advantage of in any way. For example, the following `ix` query is slow enough that it se... | When index is unique, pandas use a hashtable to map key to value O(1). When index is non-unique and sorted, pandas use binary search O(logN), when index is random ordered pandas need to check all the keys in the index O(N).
You can call `sort_index` method:
```
import numpy as np
import pandas as pd
x = np.random.ran... |
Python, cPickle, pickling lambda functions | 16,626,429 | 17 | 2013-05-18T16:17:51Z | 16,626,452 | 8 | 2013-05-18T16:19:57Z | [
"python",
"arrays",
"numpy",
"lambda",
"pickle"
] | I have to pickle an array of objects like this:
```
import cPickle as pickle
from numpy import sin, cos, array
tmp = lambda x: sin(x)+cos(x)
test = array([[tmp,tmp],[tmp,tmp]],dtype=object)
pickle.dump( test, open('test.lambda','w') )
```
and it gives the following error:
```
TypeError: can't pickle function objects... | You'll have to use an actual function instead, one that is importable (not nested inside another function):
```
import cPickle as pickle
from numpy import sin, cos, array
def tmp(x):
return sin(x)+cos(x)
test = array([[tmp,tmp],[tmp,tmp]],dtype=object)
pickle.dump( test, open('test.lambda','w') )
```
The function... |
Python, cPickle, pickling lambda functions | 16,626,429 | 17 | 2013-05-18T16:17:51Z | 16,626,757 | 18 | 2013-05-18T16:52:48Z | [
"python",
"arrays",
"numpy",
"lambda",
"pickle"
] | I have to pickle an array of objects like this:
```
import cPickle as pickle
from numpy import sin, cos, array
tmp = lambda x: sin(x)+cos(x)
test = array([[tmp,tmp],[tmp,tmp]],dtype=object)
pickle.dump( test, open('test.lambda','w') )
```
and it gives the following error:
```
TypeError: can't pickle function objects... | The built-in pickle module is unable to serialize several kinds of python objects (including lambda functions, nested functions, and functions defined at the command line).
The [picloud](https://pypi.python.org/pypi/cloud/2.7.2) package includes a more robust pickler, that can pickle lambda functions.
```
from pickle... |
functools.partial on class method | 16,626,789 | 15 | 2013-05-18T16:56:03Z | 16,626,797 | 18 | 2013-05-18T16:57:23Z | [
"python",
"exception",
"methods",
"functools"
] | I'm trying to define some class methods using another more generic class method as follows:
```
class RGB(object):
def __init__(self, red, blue, green):
super(RGB, self).__init__()
self._red = red
self._blue = blue
self._green = green
def _color(self, type):
return geta... | You are creating partials on the *function*, not the method. `functools.partial()` objects are not descriptors, they will not themselves add the `self` argument and cannot act as methods themselves. You can *only* wrap bound methods or functions, they don't work at all with unbound methods. This is [documented](http://... |
HTTP error 403 in Python 3 Web Scraping | 16,627,227 | 13 | 2013-05-18T17:47:06Z | 16,627,277 | 24 | 2013-05-18T17:52:11Z | [
"python",
"http",
"web",
"http-status-code-403"
] | I was trying to scrap a website for practice, but I kept on getting the HTTP Error 403 (does it think I'm a bot)?
Here is my code:
```
#import requests
import urllib.request
from bs4 import BeautifulSoup
#from urllib import urlopen
import re
webpage = urllib.request.urlopen('http://www.cmegroup.com/trading/products/... | This is probably because of `mod_security` or some similar server security feature which blocks known spider/bot user agents (`urllib` uses something like `python urllib/3.3.0`, it's easily detected). Try setting a known browser user agent with:
```
from urllib.request import Request, urlopen
req = Request('http://ww... |
Check if an undirected graph is a tree in networkx | 16,627,495 | 2 | 2013-05-18T18:18:32Z | 16,628,381 | 7 | 2013-05-18T19:53:22Z | [
"python",
"graph",
"tree",
"networkx"
] | I would like to know if there is a simple way to check whether a certain undirected graph in networkx is a tree or not | The fastest way for a graph G(V,E) might be to check if |V| = |E| + 1 and that G is connected:
```
import networkx as nx
def is_tree(G):
if nx.number_of_nodes(G) != nx.number_of_edges(G) + 1:
return False
return nx.is_connected(G)
if __name__ == '__main__':
print(is_tree(nx.path_graph(5)))
pr... |
Euclidean algorithm (GCD) with multiple numbers? | 16,628,088 | 3 | 2013-05-18T19:19:31Z | 16,628,166 | 12 | 2013-05-18T19:27:33Z | [
"python",
"math",
"greatest-common-divisor"
] | So I'm writing a program in Python to get the GCD of any amount of numbers.
```
def GCD(numbers):
if numbers[-1] == 0:
return numbers[0]
# i'm stuck here, this is wrong
for i in range(len(numbers)-1):
print GCD([numbers[i+1], numbers[i] % numbers[i+1]])
print GCD(30, 40, 36)
```
The f... | You can use `reduce`:
```
>>> from fractions import gcd
>>> reduce(gcd,(30,40,60))
10
```
which is equivalent to;
```
>>> lis = (30,40,60,70)
>>> res = gcd(*lis[:2]) #get the gcd of first two numbers
>>> for x in lis[2:]: #now iterate over the list starting from the 3rd element
... res = gcd(res,x)
>>> res
1... |
Euclidean algorithm (GCD) with multiple numbers? | 16,628,088 | 3 | 2013-05-18T19:19:31Z | 16,628,379 | 11 | 2013-05-18T19:53:10Z | [
"python",
"math",
"greatest-common-divisor"
] | So I'm writing a program in Python to get the GCD of any amount of numbers.
```
def GCD(numbers):
if numbers[-1] == 0:
return numbers[0]
# i'm stuck here, this is wrong
for i in range(len(numbers)-1):
print GCD([numbers[i+1], numbers[i] % numbers[i+1]])
print GCD(30, 40, 36)
```
The f... | Since GCD is associative, `GCD(a,b,c,d)` is the same as `GCD(GCD(GCD(a,b),c),d)`. In this case, Python's [`reduce`](http://docs.python.org/2/library/functions.html#reduce) function would be a good candidate for reducing the cases for which `len(numbers) > 2` to a simple 2-number comparison. The code would look somethin... |
Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone | 16,628,819 | 17 | 2013-05-18T20:51:01Z | 17,027,507 | 10 | 2013-06-10T15:30:34Z | [
"python",
"pandas"
] | You can use the function `tz_localize` to make a Timestamp or DateTimeIndex timezone aware, but how can you do the opposite: how can you convert a timezone aware Timestamp to a naive one, while preserving its timezone?
An example:
```
In [82]: t = pd.date_range(start="2013-05-18 12:00:00", periods=10, freq='s', tz="E... | I think you can't achieve what you want in a more efficient manner than you proposed.
The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz\_info. The timezone information is used only for display purposes when printing t... |
ImproperlyConfigured: Error loading MySQLdb module pycharm | 16,630,725 | 2 | 2013-05-19T01:49:58Z | 17,605,427 | 7 | 2013-07-11T23:49:00Z | [
"python",
"django",
"pycharm"
] | I'm getting this error when trying to launch my project, I think there is a mismatch in the architecture of the mysql with the python version? However I can't point out what exactly is wrong, and how to fix it.
Thank you
```
ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/... | In PyCharm, make sure to point to the correct path for MySQL. If it's running in the console but not in PyCharm; check the Environment Variables. On the top navigation, next to the green arrow, click on the arrow pointing down / Edit configuration then in Env variables add the path to mysql. In my case:
```
DYLD_LIBRA... |
Conditional loop in python | 16,631,248 | 4 | 2013-05-19T03:47:10Z | 16,631,274 | 7 | 2013-05-19T03:51:51Z | [
"python"
] | ```
list=['a','a','x','c','e','e','f','f','f']
i=0
count = 0
while count < len(list)-2:
if list[i] == list[i+1]:
if list [i+1] != list [i+2]:
print list[i]
i+=1
count +=1
else:print "no"
else:
i +=1
count += 1
```
I'm getting:
```
el... | Here is the fixed-up code (added a `count += 1` after the else-clause to make sure it terminates):
```
list=['a','a','x','c','e','e','f','f','f']
i=0
count = 0
while count < len(list)-2:
if list[i] == list[i+1]:
if list [i+1] != list [i+2]:
print list[i]
i+=1
count +=1... |
Python - emulate sum() using list comprehension | 16,632,124 | 17 | 2013-05-19T06:45:19Z | 16,632,125 | 27 | 2013-05-19T06:46:06Z | [
"python",
"list"
] | Is it possible to emulate something like sum() using [list comprehension](http://en.wikipedia.org/wiki/List_comprehension#Python) ?
For example - I need to calculate the product of all elements in a list :
```
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
```
Code that is doing ... | ```
>>> from operator import mul
>>> nums = [1, 2, 3]
>>> reduce(mul, nums)
6
```
On Python 3 you will need to add this import: `from functools import reduce`
[**Implementation Artifact**](http://stackoverflow.com/questions/2638478/recursive-list-comprehension-in-python)
In Python `2.5` / `2.6` You could use `vars()... |
Python - emulate sum() using list comprehension | 16,632,124 | 17 | 2013-05-19T06:45:19Z | 16,632,149 | 24 | 2013-05-19T06:49:37Z | [
"python",
"list"
] | Is it possible to emulate something like sum() using [list comprehension](http://en.wikipedia.org/wiki/List_comprehension#Python) ?
For example - I need to calculate the product of all elements in a list :
```
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
```
Code that is doing ... | No; a list comprehension produces a list that is just as long as its input. You will need one of Python's other functional tools (specifically `reduce()` in this case) to [fold](http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29) the sequence into a single value. |
Python - emulate sum() using list comprehension | 16,632,124 | 17 | 2013-05-19T06:45:19Z | 16,632,227 | 7 | 2013-05-19T07:04:27Z | [
"python",
"list"
] | Is it possible to emulate something like sum() using [list comprehension](http://en.wikipedia.org/wiki/List_comprehension#Python) ?
For example - I need to calculate the product of all elements in a list :
```
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
```
Code that is doing ... | List comprehension always creates another list, so it's not useful in combining them (e.g. to give a single number). Also, there's no way to make an assignment in list comprehension, unless you're super sneaky.
The only time I'd ever see using list comprehensions as being useful for a sum method is if you only want to... |
remove a specific column in numpy | 16,632,568 | 6 | 2013-05-19T08:05:09Z | 16,634,740 | 9 | 2013-05-19T12:40:40Z | [
"python",
"numpy"
] | ```
>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
```
I am deleting the 3rd column as
```
>>> np.hstack(((np.delete(arr, np.s_[2:], 1)),(np.delete(arr, np.s_[:3],1))))
array([[ 1, 2, 4],
[ 5, 6, 8],
[ 9, 1... | If you ever want to delete more than one columns, you just pass indices of columns you want deleted as a list, like this:
```
>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> np.delete(a, [1,3], axis=1)
array([[ 0, 2],
[ 4, 6],
[ 8... |
int.__mul__ , executes 2X slower than operator.mul | 16,633,424 | 14 | 2013-05-19T09:59:56Z | 16,635,003 | 14 | 2013-05-19T13:12:20Z | [
"python",
"c"
] | If you look at the following timings:
```
C:\Users\Henry>python -m timeit -s "mul = int.__mul__" "reduce(mul,range(10000))"
1000 loops, best of 3: 908 usec per loop
C:\Users\Henry>python -m timeit -s "from operator import mul" "reduce(mul,range(10000))"
1000 loops, best of 3: 410 usec per loop
```
There is a signifi... | [`int.__mul__`](http://hg.python.org/cpython/file/026ee0057e2d/Objects/intobject.c#l1374) is a slot wrapper, namely, a [PyWrapperDescrObject](http://hg.python.org/cpython/file/026ee0057e2d/Objects/descrobject.c#l574), while [`operator.mul`](http://hg.python.org/cpython/file/026ee0057e2d/Modules/operator.c#l91) is a bui... |
python pip still looking for previous installation | 16,633,590 | 13 | 2013-05-19T10:19:12Z | 16,634,367 | 20 | 2013-05-19T11:50:47Z | [
"python",
"homebrew"
] | After experiencing [this](https://github.com/mxcl/homebrew/issues/17312) brew issue with sqlite3, I did
```
brew rm sqlite python python3
```
then
```
brew install python python3
```
This installed python2.7.5 as the default interpreter and as brew installs pip along with python, I thought I would be able to
```
p... | It sounds like your `/usr/local/share/python/pip` is pointing to the wrong version of Python. Check the first line of that file, and if it looks like...
```
#!/usr/local/Cellar/python/2.7.3/bin/python
```
...then you'll need to change it to point to the correct version of Python. |
Does python logging flush every log? | 16,633,911 | 22 | 2013-05-19T10:59:59Z | 16,634,444 | 26 | 2013-05-19T12:00:18Z | [
"python",
"performance",
"logging",
"flush"
] | When I write a log to file using the standard module **logging**, will each log be flushed to disk separately?
For example, will the following code flush log by 10 times?
```
logging.basicConfig(level=logging.DEBUG, filename='debug.log')
for i in xrange(10):
logging.debug("test")
```
if so, will it slow d... | Yes, it does flush the output at every call. You can see this in the source code for the `StreamHandler`:
```
def emit(self, record):
"""
Emit a record.
If a formatter is specified, it is used to format the record.
The record is then written to the stream with a trailing newline. If
exception inf... |
Pandas: reshaping data | 16,637,171 | 9 | 2013-05-19T17:03:17Z | 16,637,607 | 25 | 2013-05-19T17:47:42Z | [
"python",
"pandas",
"category",
"vectorization"
] | I have a pandas Series which presently looks like this:
```
14 [Yellow, Pizza, Restaurants]
...
160920 [Automotive, Auto Parts & Supplies]
160921 [Lighting Fixtures & Equipment, Home Services]
160922 [Food, Pizza, Candy Stores]
160923 [Hair Removal, Nail Salons, Beau... | ```
In [9]: s = Series([list('ABC'),list('DEF'),list('ABEF')])
In [10]: s
Out[10]:
0 [A, B, C]
1 [D, E, F]
2 [A, B, E, F]
dtype: object
In [11]: s.apply(lambda x: Series(1,index=x)).fillna(0)
Out[11]:
A B C D E F
0 1 1 1 0 0 0
1 0 0 0 1 1 1
2 1 1 0 0 1 1
``` |
Iteratively writing to HDF5 Stores in Pandas | 16,637,271 | 16 | 2013-05-19T17:14:26Z | 16,637,572 | 11 | 2013-05-19T17:43:49Z | [
"python",
"io",
"pandas",
"hdf5",
"pytables"
] | [Pandas](http://pandas.pydata.org/pandas-docs/dev/io.html#notes-caveats) has the following examples for how to store `Series`, `DataFrames` and `Panels`in HDF5 files:
## Prepare some data:
```
In [1142]: store = HDFStore('store.h5')
In [1143]: index = date_range('1/1/2000', periods=8)
In [1144]: s = Series(randn(5)... | 1. As soon as the statement is exectued, eg `store['df'] = df`. The `close` just closes the actual file (which will be closed for you if the process exists, but will print a warning message)
2. Read the section <http://pandas.pydata.org/pandas-docs/dev/io.html#storing-in-table-format>
It is generally not a good ide... |
Relative import in Python 3 not working | 16,637,428 | 27 | 2013-05-19T17:28:41Z | 16,637,555 | 16 | 2013-05-19T17:42:34Z | [
"python",
"python-3.x",
"import",
"module",
"relative"
] | I have the following directory:
```
mydirectory
âââ __init__.py
âââ file1.py
âââ file2.py
```
I have a function f defined in file1.py.
If, in file2.py, I do
```
from .file1 import f
```
I get the following error:
> SystemError: Parent module '' not loaded, cannot perform relative
> import
Why?... | since `file1` and `file2` are in the same directory, you don't even need to have an `__init__.py` file. If you're going to be scaling up, then leave it there.
To import something in a file in the same directory, just do like this
`from file1 import f`
i.e., you don't need to do the relative path `.file1` because the... |
Relative import in Python 3 not working | 16,637,428 | 27 | 2013-05-19T17:28:41Z | 16,637,588 | 17 | 2013-05-19T17:45:27Z | [
"python",
"python-3.x",
"import",
"module",
"relative"
] | I have the following directory:
```
mydirectory
âââ __init__.py
âââ file1.py
âââ file2.py
```
I have a function f defined in file1.py.
If, in file2.py, I do
```
from .file1 import f
```
I get the following error:
> SystemError: Parent module '' not loaded, cannot perform relative
> import
Why?... | When launching a python source file, it is forbidden to import another file, that is in the current package, using relative import.
In [documentation](http://docs.python.org/3/tutorial/modules.html#intra-package-references) it is said:
*Note that relative imports are based on the name of the current module. Since the... |
Relative import in Python 3 not working | 16,637,428 | 27 | 2013-05-19T17:28:41Z | 33,195,094 | 22 | 2015-10-18T06:42:39Z | [
"python",
"python-3.x",
"import",
"module",
"relative"
] | I have the following directory:
```
mydirectory
âââ __init__.py
âââ file1.py
âââ file2.py
```
I have a function f defined in file1.py.
If, in file2.py, I do
```
from .file1 import f
```
I get the following error:
> SystemError: Parent module '' not loaded, cannot perform relative
> import
Why?... | Launching modules inside a package as executables is a *bad practice*.
When you develop something you either build a library, which is intended to be imported by other programs and thus it doesn't make much sense to allow executing its submodules directly, or you build an executable in which case there's no reason to ... |
How to create a PixBuf from file with Gdk3? | 16,637,504 | 3 | 2013-05-19T17:36:03Z | 18,993,717 | 8 | 2013-09-24T23:19:43Z | [
"python",
"gtk3",
"gdkpixbuf"
] | Environment: Python3
Libraries:
```
from gi.repository import Gtk, Gdk
import cairo
```
I want to create a 'pixbuf from file' but the method does not longer exist in Gdk3.
```
pb = Gdk.pixbuf_new_from_file('sunshine.png')
Gdk.cairo_set_source_pixbuf(cr, pb, 0, 0)
```
Result in: AttributeError: 'gi.repository.Gdk' ... | The question is old, but maybe it helps someone:
```
from gi.repository import GdkPixbuf
pixbuf = GdkPixbuf.Pixbuf.new_from_file('sunshine.png')
```
Tested on GdkPixbuf.\_version == '2.0' |
python tornado get request url | 16,637,735 | 9 | 2013-05-19T17:59:45Z | 16,637,937 | 16 | 2013-05-19T18:18:39Z | [
"python",
"url",
"get",
"tornado"
] | Here is my code:
```
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write(self.request.url)
def main():
settings = {"template_path": "html","static_path": "static"}
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/story/page1", MainHan... | You can get current url inside [`RequestHandler`](http://www.tornadoweb.org/en/stable/web.html) using `self.request.uri`:
```
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write(self.request.uri)
``` |
Setting HTTP status code in Bottle? | 16,638,117 | 15 | 2013-05-19T18:37:10Z | 16,638,290 | 24 | 2013-05-19T18:53:44Z | [
"python",
"http",
"http-headers",
"bottle"
] | How do I set the HTTP status code of my response in Bottle?
```
from bottle import app, run, route, Response
@route('/')
def f():
Response.status = 300 # also tried `Response.status_code = 300`
return dict(hello='world')
'''StripPathMiddleware defined:
http://bottlepy.org/docs/dev/recipes.html#ignore-trai... | I believe you should be using [`response`](http://bottlepy.org/docs/dev/api.html#bottle.response)
`from bottle import response; response.status = 300` |
Setting HTTP status code in Bottle? | 16,638,117 | 15 | 2013-05-19T18:37:10Z | 16,641,525 | 9 | 2013-05-20T01:59:50Z | [
"python",
"http",
"http-headers",
"bottle"
] | How do I set the HTTP status code of my response in Bottle?
```
from bottle import app, run, route, Response
@route('/')
def f():
Response.status = 300 # also tried `Response.status_code = 300`
return dict(hello='world')
'''StripPathMiddleware defined:
http://bottlepy.org/docs/dev/recipes.html#ignore-trai... | Bottle's built-in response type handles status codes gracefully. Consider something like:
```
return bottle.HTTPResponse(status=300, body=theBody)
```
As in:
```
import json
from bottle import HTTPResponse
@route('/')
def f():
theBody = json.dumps({'hello': 'world'}) # you seem to want a JSON response
retur... |
Set email as username in Django 1.5 | 16,638,414 | 5 | 2013-05-19T19:09:16Z | 16,638,473 | 18 | 2013-05-19T19:15:27Z | [
"python",
"django"
] | I am reading the docs at: <https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#substituting-a-custom-user-model>
So in my settings.py I put:
```
AUTH_USER_MODEL = 'membership.User'
```
And in my membership app models.py I have this:
```
from django.contrib.auth.models import AbstractBaseUser
class User(... | `AbstractBaseUser` doesn't have email field, the `AbstractUser` does.
If you want to use email as a unique identifier, then you need to subclass from AbstractBaseUser and define email field with `unique=True` and also write other functionality, for example `Manager` of the model:
```
from django.contrib.auth.models i... |
Understanding shannon entropy of a data set | 16,638,553 | 2 | 2013-05-19T19:23:35Z | 16,638,971 | 7 | 2013-05-19T20:07:51Z | [
"python",
"machine-learning",
"decision-tree",
"entropy"
] | I'm reading `Machine Learning In Action` and am going through the decision tree chapter. I understand that decision trees are built such that splitting the data set gives you a way to structure your branches and leafs. This gives you more likely information at the top of the tree and limits how many decisions you need ... | The potential ambiguity here is that the dataset you are looking at contains both features and outcome variable, the outcome variable being in the last column. The problem you are trying to solve for is "Do feature 1 and feature 2 help me predict the Outcome"?
Another way to state this is, if I split my data according... |
Why does Python's itertools.cycle need to create a copy of the iterable? | 16,638,639 | 7 | 2013-05-19T19:33:52Z | 16,638,648 | 11 | 2013-05-19T19:35:42Z | [
"python",
"iterator",
"cycle",
"itertools"
] | The documentation for Python's itertools.cycle() gives a pseudo-code implementation as:
```
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
... | Iterables can only be iterated over *once*.
You create a *new* iterable in your loop instead. Cycle cannot do that, it has to work with whatever you passed in. `cycle` cannot simply recreate the iterable. It thus is forced to store all the elements the original iterator produces.
If you were to pass in the following ... |
reverse numerical sort for list in python | 16,638,963 | 4 | 2013-05-19T20:07:19Z | 16,638,988 | 8 | 2013-05-19T20:08:53Z | [
"python",
"algorithm",
"list",
"sorting",
"reverse"
] | I'm trying to create python implementations from an algorithms book I'm going through. Though I'm sure that python probably has these functions built in, I thought it would be a good exercise to learn the language a bit.
The algorithm given was to create an insertion sorting loop for a numerical array. This I was able... | `range` does not include the end value. When you do `range(len(sort_this)-2, 0, -1)`, your iteration goes from `len(sort_this)-2` to 1, so you never hit the first element (at index 0). Change your range to `range(len(sort_this)-2, -1, -1)` |
How do I change the background of a Frame in Tkinter? | 16,639,125 | 7 | 2013-05-19T20:23:44Z | 16,640,226 | 11 | 2013-05-19T22:39:44Z | [
"python",
"python-3.x",
"background",
"tkinter",
"frame"
] | I have been creating an *Email* program using Tkinter, in Python 3.3.
On various sites I have been seeing that the Frame widget can get a different background using `Frame.config(background="color")`.
However, when I use this in my Frames it gives the following error:
```
_tkinter.TclError: unknown option "-Background... | The root of the problem is that you are unknowingly using the `Frame` class from the `ttk` package rather than from the `tkinter` package. The one from `ttk` does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
... |
HDF5 taking more space than CSV? | 16,639,877 | 15 | 2013-05-19T21:57:11Z | 16,641,346 | 20 | 2013-05-20T01:29:43Z | [
"python",
"pandas",
"hdf5",
"pytables"
] | Consider the following example:
## Prepare the data:
```
import string
import random
import pandas as pd
matrix = np.random.random((100, 3000))
my_cols = [random.choice(string.ascii_uppercase) for x in range(matrix.shape[1])]
mydf = pd.DataFrame(matrix, columns=my_cols)
mydf['something'] = 'hello_world'
```
## Set ... | Copy of my answer from the issue: <https://github.com/pydata/pandas/issues/3651>
Your sample is really too small. HDF5 has a fair amount of overhead with really small sizes (even 300k entries is on the smaller side). The following is with no compression on either side. Floats are really more efficiently represented in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.