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 |
|---|---|---|---|---|---|---|---|---|---|
Pass extra values along with urls to scrapy spider | 23,696,934 | 4 | 2014-05-16T13:51:28Z | 23,697,207 | 8 | 2014-05-16T14:02:25Z | [
"python",
"python-2.7",
"web-scraping",
"scrapy",
"scrapy-spider"
] | I've a list of tuples in the form (id,url)
I need to crawl a product from a list of urls, and when those products are crawled i need to store them in database under their id.
problem is i can't understand how to pass id to parse function so that i can store crawled item under their id. | Initialize start urls in [`start_requests()`](http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spider.Spider.start_requests) and pass `id` in [`meta`](http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request.meta):
```
class MySpider(Spider):
mapping = [(1, 'my_url1'), (2, 'my_url... |
Manually set color of points in legend | 23,698,850 | 10 | 2014-05-16T15:15:49Z | 23,699,299 | 9 | 2014-05-16T15:35:55Z | [
"python",
"numpy",
"matplotlib",
"colors",
"legend"
] | I'm making a scatter plot which looks like this:

(MWE at bottom of question)
As can be seen in the image above the colors of the points in the legend are set to blue automatically by `matplotlib`. I need to set this points to some other color not pr... | You can obtain the legend handles and change their colors doing:
```
ax = plt.gca()
leg = ax.get_legend()
leg.legendHandles[0].set_color('red')
leg.legendHandles[1].set_color('yellow')
``` |
Dependency rule tried to blank out primary key in SQLAlchemy, when foreign key constraint is part of composite primary key | 23,699,651 | 8 | 2014-05-16T15:55:15Z | 23,734,727 | 10 | 2014-05-19T09:54:11Z | [
"python",
"sqlalchemy"
] | I have the following model definitions
```
class Foo(Base):
__tablename__ = 'foo'
id = Column(Integer, primary_key=True)
name = Column(String(200))
class FooCycle(Base):
__tablename__ = 'foocycle'
foo_id = Column(
String(50),
ForeignKey('foo.id'),
primary_key=True
)
... | Based on the comment by van I was able to work out a solution. The default relationship cascade is `"save-update, merge"`. I had to set this to `"save-update, merge, delete, delete-orphan"`.
Adding `delete` by itself did not change the behavior, `delete-orphan` was necessary.
Adding only `delete-orphan` made a deleti... |
Python 2.7: if code block not working | 23,701,606 | 2 | 2014-05-16T17:48:55Z | 23,701,642 | 8 | 2014-05-16T17:51:27Z | [
"python",
"python-2.7",
"if-statement"
] | I have tested out the following program, and there are no errors. But whenever I enter `"hangman"` it won't start the new block of `if` statement code named `"if response_2"`. Why is it not running it?
```
response_2 = raw_input("What would you like to play? Hangman or Word Guess?")
if response_2 == ("Hangman"... | This is because you are *directly comparing* to the tuple with `==`, which will always give `False` as the `raw_input` gives a string, not a `tuple`. You need to check if any one of the responses is in the sequence. Do this with `in`:
```
if response in ('Hangman', 'hangman'):
```
Likewise with the similar comparison... |
Linenumber of shebang line significant? | 23,702,316 | 2 | 2014-05-16T18:30:42Z | 23,702,374 | 7 | 2014-05-16T18:33:31Z | [
"python",
"command-line-interface",
"shebang"
] | I have a simple cli to convert timestamp to human readable datetime. For some reason, when I try to call it I invoke the `import` command from imagemagick instead.
```
> ts 1400029200000
Version: ImageMagick 6.8.7-7 Q16 x86_64 2013-11-27 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio ... | The 'shebang' must be the first line because it is interpreted by the kernel, which looks at the two bytes at the start of an executable file.
If these are `#!` the rest of the line is interpreted as the code to run and with the script file available to that program. At the moment you have a newline and *then* the cha... |
Difference between using [] and list() in Python | 23,703,109 | 6 | 2014-05-16T19:22:38Z | 23,703,120 | 14 | 2014-05-16T19:23:47Z | [
"python",
"list"
] | Can somebody explain this code ?
```
l3 = [ {'from': 55, 'till': 55, 'interest': 15}, ]
l4 = list( {'from': 55, 'till': 55, 'interest': 15}, )
print l3, type(l3)
print l4, type(l4)
```
OUTPUT:
```
[{'till': 55, 'from': 55, 'interest': 15}] <type 'list'>
['till', 'from', 'interest'] <type 'list'>
``` | When you convert a `dict` object to a list, it only takes the keys.
However, if you surround it with square brackets, it keeps everything the same, it just makes it a list of `dict`s, with only one item in it.
```
>>> obj = {1: 2, 3: 4, 5: 6, 7: 8}
>>> list(obj)
[1, 3, 5, 7]
>>> [obj]
[{1: 2, 3: 4, 5: 6, 7: 8}]
>>>
`... |
In Python, is object() equal to anything besides itself? | 23,703,863 | 19 | 2014-05-16T20:15:48Z | 23,703,899 | 16 | 2014-05-16T20:18:13Z | [
"python"
] | If I have the code `my_object = object()` in Python, will `my_object` be equal to anything except for itself?
I suspect the answer lies in the `__eq__` method of the default object returned by `object()`. What is the implementation of `__eq__` for this default object?
EDIT: I'm using Python 2.7, but am also intereste... | `object` doesn't implement `__eq__`, so falls back on the default comparison `id(x) == id(y)`, i.e. *are they the same object instance* (`x is y`)?
As a new instance is created every time you call `object()`, `my_object` will never\* compare equal to anything except itself.
This applies to both 2.x and 3.x:
```
# 3.... |
In Python, is object() equal to anything besides itself? | 23,703,863 | 19 | 2014-05-16T20:15:48Z | 23,703,933 | 28 | 2014-05-16T20:20:50Z | [
"python"
] | If I have the code `my_object = object()` in Python, will `my_object` be equal to anything except for itself?
I suspect the answer lies in the `__eq__` method of the default object returned by `object()`. What is the implementation of `__eq__` for this default object?
EDIT: I'm using Python 2.7, but am also intereste... | `object().__eq__` returns the `NotImplemented` singleton:
```
print(object().__eq__(3))
NotImplemented
```
By the reflexive rules of [rich comparisons](https://docs.python.org/2/reference/datamodel.html#object.__lt__), when `NotImplemented` is returned, [the "reflected" operation is tried](https://docs.python.org/2/r... |
Pass existing Webdriver object to custom Python library for Robot Framework | 23,703,870 | 6 | 2014-05-16T20:16:36Z | 23,704,655 | 11 | 2014-05-16T21:15:44Z | [
"python",
"selenium-webdriver",
"robotframework"
] | I am trying to create a custom Python library for Robot Framework, but I'm new to Python and Robot and I'm not sure how to accomplish what I'm trying to do. I want to pass the Webdriver object that Robot creates using Selenium2Library to my custom Python library so that I could use the Webdriver's methods, such as `fin... | There's nothing built into the library to let you do what you want *per se*. However, you can create your own library that can access selenium features. There are two ways to accomplish this, both which require creating your own library in python. These methods are to to subclass Selenium2Library, or to get a reference... |
Scrapy CrawlSpider for AJAX content | 23,706,111 | 5 | 2014-05-16T23:46:03Z | 23,721,458 | 7 | 2014-05-18T11:36:06Z | [
"python",
"web-scraping",
"scrapy"
] | I am attempting to crawl www.seekingalpha.com for news articles. My start\_url contains:
(1) links to each article: <http://seekingalpha.com/symbol/TSLA>
and
(2) a "More" button that makes an AJAX call that dynamically loads more articles within the same start\_url: <http://seekingalpha.com/account/ajax_headlines_co... | Crawl spider may be too limited for your purposes here. If you need a lot of logic you are usually better off inheriting from Spider.
Scrapy provides CloseSpider exception that can be raised when you need to stop parsing under certain conditions. The page you are crawling returns a message "There are no Focus articles... |
Previous error being masked by current exception context | 23,707,530 | 10 | 2014-05-17T04:21:07Z | 23,743,388 | 15 | 2014-05-19T17:05:41Z | [
"python",
"exception-handling"
] | The following is an example I found at the website for Doug Hellman in a file named "masking\_exceptions\_catch.py". I can't locate the link at the moment. The exception raised in throws() is discarded while that raised by cleanup() is reported.
In his article, Doug remarks that the handling is non-intuitive. Halfway ... | Circling back around to answer. I'll start by not answering your question. :-)
**Does this really work?**
```
def f():
try:
raise Exception('bananas!')
except:
pass
raise
```
So, what does the above do? Cue Jeopardy music.
---
Alright then, pencils down.
```
# python 3.3
4 ex... |
How to upgrade django? | 23,708,895 | 6 | 2014-05-17T07:45:19Z | 23,709,560 | 9 | 2014-05-17T09:07:58Z | [
"python",
"django"
] | My project was running on Django 1.5.4 and I wanted to upgrade it. I did `pip install -U -I django` and now `pip freeze` shows Django 1.6.5 (clearly django has upgraded, I'm in `virtualenv`) but my project is still using Django 1.5.4. How can I use the upgraded version?
UPDATE: Thanks for your comments. I tried everyt... | You can use `--upgrade` with the `pip` command to upgrade Python packages.
```
pip install --upgrade django==1.6.5
``` |
'pip' is not recognized as an internal or external command | 23,708,898 | 66 | 2014-05-17T07:45:57Z | 23,709,194 | 135 | 2014-05-17T08:26:02Z | [
"python",
"django",
"pip"
] | I'm running into a weird error trying to install Django on my computer.
This is the sequence that I've typed into my command line:
```
C:\Python34>python get-pip.py
Requirement already up-to-date: pip in c:\python34\lib\site-packages
Cleaning up...
C:\Python34>pip install Django
'pip' is not recognized as an interna... | **You need to add the path of your pip installation to your PATH system variable**. By default, pip is installed to `C:\Python34\Scripts\pip` (pip now comes bundled with new versions of python), so the path "C:\Python34\Scripts" needs to be added to your PATH variable.
To check if it is already in your PATH variable, ... |
'pip' is not recognized as an internal or external command | 23,708,898 | 66 | 2014-05-17T07:45:57Z | 30,224,223 | 23 | 2015-05-13T20:04:58Z | [
"python",
"django",
"pip"
] | I'm running into a weird error trying to install Django on my computer.
This is the sequence that I've typed into my command line:
```
C:\Python34>python get-pip.py
Requirement already up-to-date: pip in c:\python34\lib\site-packages
Cleaning up...
C:\Python34>pip install Django
'pip' is not recognized as an interna... | For me command:
```
set PATH=%PATH%;C:\Python34\Scripts
```
worked immediately (try after **echo %PATH%** and you will see that your path has the value C:\Python34\Scripts).
Thanks to: <http://stackoverflow.com/a/9546345/1766166> |
How to emulate 4-bit integer in Python 3? | 23,709,429 | 2 | 2014-05-17T08:55:56Z | 23,709,473 | 7 | 2014-05-17T09:00:29Z | [
"python",
"python-3.x"
] | I'd like to emulate overflow behavior of unsigned 4-bit integers, like this:
```
>>> x, y = Int4(10), Int4(9)
>>> x + y
Int4(3)
>>> x * y
Int4(10)
```
Inheritance of builtin `int` seems to work. Is it possible to implement `Int4` class without overriding operator methods like `__add__`? | No, subclassing `int` will not automatically re-use the type when applying arithmetic to it:
```
>>> class Int4(int):
... def __new__(cls, i):
... return super(Int4, cls).__new__(cls, i & 0xf)
...
>>> x, y = Int4(10), Int4(9)
>>> x + y
19
>>> type(x + y)
<type 'int'>
```
You *have* to override the `__add... |
Why does node.js need python | 23,709,739 | 6 | 2014-05-17T09:30:02Z | 23,710,101 | 7 | 2014-05-17T10:14:47Z | [
"python",
"node.js"
] | I am starting up with node
This is from node.js README.md
Prerequisites (Unix only):
```
* GCC 4.2 or newer
* Python 2.6 or 2.7
* GNU Make 3.81 or newer
* libexecinfo (FreeBSD and OpenBSD only)
```
Curious to know why does node.js need Python ?
Does it use Python underneath its API | Node.js is built with [GYP](https://code.google.com/p/gyp/) â cross-platform built tool written in Python. Also some other build steps are implemented in Python. So Python is required for building node from source.
But you also need Python for building native addons. |
Pre-Populate a WTforms in flask, with data from a SQLAlchemy object | 23,712,986 | 6 | 2014-05-17T15:20:03Z | 23,713,807 | 10 | 2014-05-17T16:46:18Z | [
"python",
"flask",
"flask-sqlalchemy",
"flask-wtforms"
] | I am fairly new to flask framework and was creating an edit profile page for a webportal. I am stuck at a point and am unable to autofill a form.
Here is my form class :
```
class EditProfile(Form):
username = TextField('Username', [Required()])
email = TextField('Email', [Required()])
about = TextAreaFi... | You need to pass your object to the form when you create it.
```
form = EditProfile(obj=user) # or whatever your object is called
```
You're going to run into some trouble with
```
query = EditProfile(form.username.data,
form.email.data,
form.about... |
Installing gfortran for numpy with homebrew | 23,713,434 | 5 | 2014-05-17T16:04:13Z | 23,713,435 | 8 | 2014-05-17T16:04:13Z | [
"python",
"numpy",
"fortran",
"homebrew",
"gfortran"
] | I want to install a working version of `numpy` using brew. `brew install numpy` gives the message:
```
==> python setup.py build --fcompiler=gnu95 install --prefix=/usr/local/Cellar/numpy/1.8.1
File "/private/tmp/numpy-ncUw/numpy-1.8.1/numpy/distutils/fcompiler/gnu.py", line 197, in get_flags_opt
v = self.get_version(... | `brew install gcc`
Numpy install now works fine. |
Why does time.clock() return a wrong result? | 23,717,603 | 2 | 2014-05-18T01:01:45Z | 23,717,623 | 11 | 2014-05-18T01:07:14Z | [
"python",
"python-2.7"
] | Why does `time.clock()` give the wrong result? The code is as follows:
```
time_start1 = time.time()
time.sleep(5)
bb = time.time() - time_start1;
print bb;
time_1 = time.clock()
time.sleep(5)
cc = time.clock() - time_1
print cc
```
The results are:
```
5.00506210327
0.006593
```
The second one should be 5.0, but w... | `time.time()` and `time.clock()` are measuring different things.
`time.time()` measures wall clock elapsed time, since the Unix epoch.
On a Linux system, `time.clock()` is measuring *processor time*, which isn't the elapsed time in seconds.
Processor time is an approximation of how much time was spent by the process... |
Perform a substring replacement in a single line in Python | 23,718,238 | 3 | 2014-05-18T03:20:55Z | 23,718,254 | 8 | 2014-05-18T03:25:08Z | [
"python",
"regex"
] | I'm reading in MAC addresses on my LAN using the `arp -a` command and parsing the output. On OS X, some MAC addresses are returned with hex values lacking leading zeros. I've figured out how to insert the leading zeros using regex:
```
>>> mac = '8:AA:C:3:ED:E'
>>> mac = re.sub('^(?P<hex>.)(?=\:)','0\g<hex>',mac)
>>> ... | One option is not to reinvent the wheel and use [`netaddr`](http://pythonhosted.org/netaddr/) module:
```
>>> from netaddr import EUI
>>> mac = '8:AA:C:3:ED:E'
>>> mac = EUI(mac)
>>> mac
EUI('08-AA-0C-03-ED-0E')
>>> str(mac)
'08-AA-0C-03-ED-0E'
```
As a bonus, you would get a nice [standardized API](http://pythonhost... |
Saving output to file using pycurl? | 23,718,508 | 4 | 2014-05-18T04:16:10Z | 23,718,539 | 8 | 2014-05-18T04:24:28Z | [
"python",
"curl",
"pycurl"
] | I'm using pycurl to fetch a jpg from a server, how would I go about saving this to a file?
I can't see an option to do it.
Thanks! | You need to write the file yourself, here is an example:
```
import pycurl
c = pycurl.Curl()
c.setopt(c.URL, 'http://my.server/a.jpg')
with open('o.jpg', 'w') as f:
c.setopt(c.WRITEFUNCTION, f.write)
c.perform()
``` |
pretty print json in python (pythonic way) | 23,718,896 | 13 | 2014-05-18T05:36:02Z | 23,731,752 | 20 | 2014-05-19T07:11:19Z | [
"python",
"json"
] | I've seen pprint lib. However I'm always retriving json data, and I wonder if there is any easy and fast way to achieve a simple decent printing.
```
import requests
r = requests.get('http://server.com/api/2/....')
r.json()
```
(no pretty printing)
The pprint way,
```
>>> import pprint
>>> import requests
>>> r = r... | Python's builtin [JSON module](https://docs.python.org/3/library/json.html) can handle that for you:
```
>>> import json
>>> a = {'hello': 'world', 'a': [1, 2, 3, 4], 'foo': 'bar'}
>>> print(json.dumps(a, indent=2))
{
"hello": "world",
"a": [
1,
2,
3,
4
],
"foo": "bar"
}
``` |
Float values as dictionary key | 23,721,230 | 4 | 2014-05-18T11:07:44Z | 23,721,268 | 10 | 2014-05-18T11:12:57Z | [
"python",
"dictionary",
"floating-point",
"key"
] | I am developing a class for the analysis of microtiter plates. The samples are described in a separate file and the entries are used for an ordered dictionary. One of the keys is pH, which is usually given as float. e.g 6.8
I could import it as decimal with `Decimal('6.8')` in order to avoid a float as dict key. Anoth... | There's no problem using floats as dict keys.
Just `round(n, 1)` them to normalise them to your keyspace. eg.
```
>>> hash(round(6.84, 1))
3543446220
>>> hash(round(6.75, 1))
3543446220
``` |
Limiting the number of combinations /permutations in python | 23,722,473 | 2 | 2014-05-18T13:33:09Z | 23,722,510 | 7 | 2014-05-18T13:37:03Z | [
"python",
"list",
"permutation",
"itertools"
] | I was going to generate some combination using the itertools, when i realized that as the number of elements increase the time taken will increase exponentially. Can i limit or indicate the maximum number of permutations to be produced so that itertools would stop after that limit is reached.
What i mean to say is:
C... | You need to use [`itertools.islice`](https://docs.python.org/2/library/itertools.html#itertools.islice), like this
```
itertools.islice(itertools.product(*big_list), 5000)
```
It doesn't create the entire list in memory, but it returns an iterator which consumes the actual iterable lazily. You can convert that to a l... |
command 'gcc' failed with exit status 1 error while installing scrapy | 23,722,678 | 8 | 2014-05-18T13:54:59Z | 23,760,808 | 31 | 2014-05-20T13:11:17Z | [
"python",
"scrapy",
"centos6"
] | When I want to install Scrapy I meet this error:
```
warning: no previously-included files found matching '*.py'
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages/pyOpenSSL-0.14-py2.7.egg (from Scrapy)
Requirement already satisfied (use --upgrade to upgra... | Your problem is:
`c/_cffi_backend.c:14:17: error: ffi.h: No such file or directory`
You'll need to install the `libffi-devel` package (on Debian/Ubuntu this would be `libffi-dev`). |
plot.subplot ---> 'Figure' object has no attribute 'plot' | 23,723,546 | 4 | 2014-05-18T15:23:57Z | 23,723,625 | 7 | 2014-05-18T15:31:33Z | [
"python",
"matplotlib",
"subplot"
] | I am trying to use subplots similar to what is being shown here:
<http://matplotlib.org/examples/pylab_examples/subplots_demo.html>
```
axarr = plt.subplots(len(column_list), sharex=True)
subp_num = 0
for j in column_list:
axarr[subp_num].plot(df.values[2:,j])
subp_num = subp_num + 1
```
then I get this er... | You have one obvious problem: all of the examples in the link you provide look like
```
f, axarr = plt.subplots(...)
```
where the `f` is the `Figure` you are subsequently treating as if it had a `plot` attribute. If you are working with an arbitrary number of subplots, you could do:
```
axarr = plt.subplots(...)
f,... |
Appending a dictionary to a list in a a loop Python | 23,724,136 | 9 | 2014-05-18T16:20:25Z | 23,724,156 | 13 | 2014-05-18T16:21:46Z | [
"python",
"list",
"dictionary",
"append"
] | I am a basic python programmer so hopefully the answer to my question will be easy.
I am trying to take a dictionary and append it to a list. The dictionary then changes values and then is appended again in a loop. It seems that every time I do this, all the dictionaries in the list change their values to match the one... | You need to append a *copy*, otherwise you are just adding references to the same dictionary over and over again:
```
yourlist.append(yourdict.copy())
```
I used `yourdict` and `yourlist` instead of `dict` and `list`; you don't want to mask the built-in types. |
Possible To Format A List Without * Magic? | 23,725,937 | 7 | 2014-05-18T19:23:07Z | 23,725,969 | 11 | 2014-05-18T19:26:54Z | [
"python",
"pylint"
] | I wrote some Python code which works but Pylint doesn't like the star. It keeps telling me:
```
Used * or ** magic (star-args)
```
Is it possible to write my code without the star? Some info: I'm using [lxml](http://lxml.de/); self.xml is an [objectified](http://lxml.de/objectify.html) XML file.
```
@property
def ve... | There's nothing wrong with the splat operator. Without knowing what the `version_format` function does, it's not possible to say if you could pass an iterable, or iterate the function directly, but frankly there's no reason to. |
Possible To Format A List Without * Magic? | 23,725,937 | 7 | 2014-05-18T19:23:07Z | 23,730,868 | 7 | 2014-05-19T06:19:44Z | [
"python",
"pylint"
] | I wrote some Python code which works but Pylint doesn't like the star. It keeps telling me:
```
Used * or ** magic (star-args)
```
Is it possible to write my code without the star? Some info: I'm using [lxml](http://lxml.de/); self.xml is an [objectified](http://lxml.de/objectify.html) XML file.
```
@property
def ve... | If you don't like that pylint warning, disable it. It was originally introduced because having lots of
```
def some_function(*args, **kwargs):
pass
```
lowers the readability / maintainability of the code. |
Finding which rows have all elements as zeros in a matrix with numpy | 23,726,026 | 4 | 2014-05-18T19:31:31Z | 23,726,100 | 8 | 2014-05-18T19:39:53Z | [
"python",
"numpy",
"matrix"
] | I have a large `numpy` matrix `M`. Some of the rows of the matrix have all of their elements as zero and I need to get the indices of those rows. The naive approach I'm considering is to loop through each row in the matrix and then check each elements. However I think there's a better and a faster approach to accomplis... | Here's one way. I assume numpy has been imported using `import numpy as np`.
```
In [20]: a
Out[20]:
array([[0, 1, 0],
[1, 0, 1],
[0, 0, 0],
[1, 1, 0],
[0, 0, 0]])
In [21]: np.where(~a.any(axis=1))[0]
Out[21]: array([2, 4])
```
It's a slight variation of this answer: [How to check that a... |
How to assign to repeated field? | 23,726,335 | 9 | 2014-05-18T20:06:45Z | 23,726,417 | 13 | 2014-05-18T20:16:04Z | [
"python",
"protocol-buffers"
] | I am using protocol buffers in python and I have inside `Person` message
```
repeated uint64 id
```
but when I try to assign like
```
person.id = [1, 32, 43432]
```
I get error `Assigment not allowed for repeated field "id" in protocol message object`
How to assign to repeated field ? | As per the [documentation](https://developers.google.com/protocol-buffers/docs/reference/python-generated?csw=1#fields), you aren't able to directly assign to a repeated field. In this case, you can call `extend` to add all of the elements in the list to the field.
```
person.id.extend([1, 32, 43432])
``` |
Set up Python 3 build system with Sublime Text 3 | 23,730,866 | 17 | 2014-05-19T06:19:39Z | 23,741,296 | 25 | 2014-05-19T15:11:28Z | [
"python",
"python-3.x",
"sublimetext3"
] | I want to configure Sublime Text 3 to build Python 3, but I don't seem to understand how the builds work. Many tutorials have told me to make a build file containing code such as:
```
{
'cmd': ['/usr/bin/python3', '-u', '$file'],
'file_regex': '^[ ]*File "(â¦*?)", line ([0-9]*)',
'selector': 'source.pytho... | The reason you're getting the error is that you have a Unix-style path to the `python` executable, when you're running Windows. Change `/usr/bin/python3` to `C:/Python32/python.exe` (make sure you use the forward slashes `/` and not Windows-style back slashes `\`). Once you make this change, you should be all set.
Als... |
KeyError when indexing Pandas dataframe | 23,731,564 | 7 | 2014-05-19T07:00:48Z | 23,733,522 | 14 | 2014-05-19T08:52:58Z | [
"python",
"pandas"
] | I am trying to read data from a csv file into a pandas dataframe, and access the first column 'Date'
```
df_ticks=pd.read_csv('values.csv', delimiter=',')
print df_ticks.columns
df_ticks['Date']
```
produces the following result
```
Index([u'Date', u'Open', u'High', u'Low', u'Close', u'Volume'], dtype='object')
K... | As mentioned by alko, it is probably extra character at the beginning of your file.
When using `read_csv`, you can specify `encoding` to deal with encoding and heading character, known as [BOM (Byte order mark)](http://en.wikipedia.org/wiki/Byte_order_mark)
```
df = pd.read_csv('values.csv', delimiter=',', encoding="u... |
Install py2exe for python 2.7 over pip: this package requires Python 3.3 or later | 23,734,172 | 25 | 2014-05-19T09:26:34Z | 23,735,000 | 31 | 2014-05-19T10:08:43Z | [
"python",
"python-2.7",
"pip",
"py2exe",
"pypi"
] | ```
>>> python -c "import sys; print sys.version"
2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
>>> pip --version
pip 1.5.5 from C:\Python27\lib\site-packages (python 2.7)
>>> pip install py2exe
<mumble grumble..>
RuntimeError: This package requires Python 3.3 or later
```
though official [py2ex... | It is missing from [pypi](https://pypi.python.org/pypi/py2exe/), if you click on the `0.6.9` link it brings you to the `0.9.2.0` python 3 package, there seems to be no `0.6.9` package available to download.
Try using `pip install http://sourceforge.net/projects/py2exe/files/latest/download?source=files` |
Install py2exe for python 2.7 over pip: this package requires Python 3.3 or later | 23,734,172 | 25 | 2014-05-19T09:26:34Z | 31,217,264 | 10 | 2015-07-04T05:30:52Z | [
"python",
"python-2.7",
"pip",
"py2exe",
"pypi"
] | ```
>>> python -c "import sys; print sys.version"
2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
>>> pip --version
pip 1.5.5 from C:\Python27\lib\site-packages (python 2.7)
>>> pip install py2exe
<mumble grumble..>
RuntimeError: This package requires Python 3.3 or later
```
though official [py2ex... | There is also a wheel of `py2exe` available for Python 2.x: `py2exe_py2 0.6.9`
You can do: `pip install py2exe_py2`
[Pypi](https://pypi.python.org/pypi/py2exe_py2) link. |
Restrict django FloatField to 2 decimal places | 23,739,030 | 2 | 2014-05-19T13:25:56Z | 23,739,840 | 8 | 2014-05-19T14:02:33Z | [
"python",
"django",
"forms",
"models"
] | I am looking for a way to limit the FloatField in Django to 2 decimal places has anyone got a clue of how this could be done without having to use a DecimalField.
I tried `decimal_places=2`but this was just giving me a migration error within the float field so i am thinking this method must only work within DecimalFie... | If you are only concerned with how your `FloatField` appears in forms, you can use the template filter [`floatformat`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#floatformat).
From the Django Docs:
> If used with a numeric integer argument, floatformat rounds a number to that many decimal places.
... |
locale.getpreferredencoding() - why does this reset string.letters? | 23,743,160 | 15 | 2014-05-19T16:53:04Z | 23,743,499 | 11 | 2014-05-19T17:12:37Z | [
"python"
] | ```
>>> import string
>>> import locale
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> locale.getpreferredencoding()
'UTF-8'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
```
Any workarounds for this?
Platform: Linux
Python2.6.7 and Python2.7.3 seem to be aff... | **Note**: what OP did to solve the issue is to pass `encoding='UTF-8'` to the `open` call. If you run into this issue and are just looking for a fix this works. The rest of the post is an emphasis on *why*.
---
### What happens
As Lukas said, the docs specify:
> On some systems, it is necessary to invoke setlocale(... |
Django Get absolute url for static files | 23,746,238 | 2 | 2014-05-19T20:02:36Z | 23,746,981 | 7 | 2014-05-19T20:50:19Z | [
"python",
"django"
] | In Django, when I use:
```
{{ request.build_absolute_uri }}{% static "img/myimage.jpg" %}
```
It produces: '<http://myurl.com//static/img/myimage.jpg>'. This produces an error.
How can I remove the double slashes?
The STATIC URL is:
```
STATIC_URL = '/static/'
```
But I don't think removing the first '/' would be... | The `build_absolute_uri` method builds an absolute uri for the current page. That means that if you're on e.g. '<http://myurl.com/login/>', the resulted full url would be '<http://myurl.com/login//static/img/myimage.jpg>'.
Instead, use `request.get_host()` (optionally together with `request.scheme` for the url scheme)... |
Filtering all rows with NaT in a column in Dataframe python | 23,747,451 | 10 | 2014-05-19T21:23:00Z | 23,747,587 | 14 | 2014-05-19T21:34:16Z | [
"python",
"pandas",
"dataframe"
] | I have a df like this:
```
a b c
1 NaT w
2 2014-02-01 g
3 NaT x
df=df[df.b=='2014-02-01']
```
will give me
```
a b c
2 2014-02-01 g
```
I want a database of all rows with NaT in column b?
```
df=df[df.b==None] #Doesn't work
```
I want this:
... | `isnull` and `notnull` work with `NaT` so you can handle them much the same way you handle `NaNs`:
```
>>> df
a b c
0 1 NaT w
1 2 2014-02-01 g
2 3 NaT x
>>> df.dtypes
a int64
b datetime64[ns]
c object
```
just use `isnull` to select:
```
df[df.b.isnull()]... |
How to create iterate through a large list of list in python efficiently? | 23,747,487 | 10 | 2014-05-19T21:26:29Z | 23,748,495 | 7 | 2014-05-19T22:59:19Z | [
"python",
"list",
"matrix",
"scipy",
"nested-lists"
] | I have my data as such:
```
data = {'x':Counter({'a':1,'b':45}), 'y':Counter({'b':1, 'c':212})}
```
where my labels are the keys of the `data` and the key of the inner dictionary are features:
```
all_features = ['a','b','c']
all_labels = ['x','y']
```
I need to create list of list as such:
```
[[data[label][feat]... | Converting a dictionary of dictionaries into a numpy or scipy array is, as you are experiencing, not too much fun. If you know `all_features` and `all_labels` before hand, you are probably better off using a scipy sparse COO matrix from the start to keep your counts.
Whether that is possible or not, you will want to k... |
How to generate a list of given length in Java 8? | 23,748,612 | 5 | 2014-05-19T23:14:17Z | 23,748,739 | 8 | 2014-05-19T23:28:33Z | [
"java",
"python",
"java-8"
] | I want to create a list (or collection in general) by calling a method x times. In Python it would be something like this.
```
self.generated = [self.generate() for _ in range(length)]
```
I tried to code something similar in JDK 8.
```
this.generated = IntStream.range(0, length)
.mapToObj(... | I am not Python developer so I may misunderstood your example, but judging from Java example you may be looking for something like
```
Stream.generate(this::generate).limit(length).collect(Collectors.toList());
```
But as [Brian Goetz mentioned](http://stackoverflow.com/questions/23748612/how-to-generate-a-list-of-gi... |
understanding math errors in pandas dataframes | 23,748,842 | 4 | 2014-05-19T23:40:30Z | 23,748,861 | 7 | 2014-05-19T23:43:52Z | [
"python",
"pandas",
"ipython"
] | I'm trying to generate a new column in a pandas dataframe from other columns and am getting some math errors that I don't understand. Here is a snapshot of the problem and some simplifying diagnostics...
I can generate a data frame that looks pretty good:
```
import pandas
import math as m
data = {'loc':['1','2','3'... | math functions such as [math.radians](https://docs.python.org/2/library/math.html#math.radians) expect a numeric value such as a float, not a sequence such as a `pandas.Series`.
Instead, you could use [numpy.radians](http://docs.scipy.org/doc/numpy/reference/generated/numpy.radians.html), since `numpy.radians` can acc... |
Pandas DataFrame to list | 23,748,995 | 25 | 2014-05-20T00:00:09Z | 23,749,057 | 50 | 2014-05-20T00:09:04Z | [
"python",
"pandas",
"tolist"
] | I am pulling a subset of data from a column based on conditions in another column being met.
I can get the correct values back but it is in pandas.core.frame.DataFrame. How do I convert that to list?
```
import pandas as pd
tst = pd.read_csv('C:\\SomeCSV.csv')
lookupValue = tst['SomeCol'] == "SomeValue"
ID = tst[lo... | Use `.values` to get a `numpy.array` and then `.tolist()` to get a list.
For example:
```
import pandas as pd
df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
'b':[3,5,6,2,4,6,7,8,7,8,9]})
```
Result:
```
>>> df['a'].values.tolist()
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
```
or you can just use
```
>... |
Inverse function of numpy.polyval() | 23,749,610 | 4 | 2014-05-20T01:21:00Z | 23,750,248 | 7 | 2014-05-20T02:48:36Z | [
"python",
"numpy"
] | I was wondering is there a convenient inverse function of np.polyval(), where I give the y value and it solves for x?
I know one way I could do this is:
```
import numpy as np
# Set up the question
p = np.array([1, 1, -10])
y = 100
# Solve
p_temp = p
p_temp[-1] -= y
x = np.roots(p_temp)
```
However my guess is mos... | How about something like this?
```
In [19]: p = np.poly1d([1, 1, -10]) # Use a poly1d to represent the polynomial.
In [20]: y = 100
In [21]: (p - y).roots
Out[21]: array([-11., 10.])
```
The `poly1d` object implements the arithmetic operations to return a new `poly1d` object, so `p - y` is a new `poly1d`:
```
In... |
Create conda package across many versions | 23,750,399 | 16 | 2014-05-20T03:06:29Z | 23,750,475 | 14 | 2014-05-20T03:18:24Z | [
"python",
"anaconda",
"conda"
] | I have a very simple Pure Python package on PyPI that I'd like to make available on [binstar](http://binstar.org). My package targets Python 2.6+ and 3.2+ with a single codebase. I also expect that it works equally well on Windows as well as Unix.
Is there a simple way to comprehensively build my package and upload it... | If you want to build recipes for many different versions of the package, use the `--version` flag to `conda skeleton pypi`. I recommend using `package-version` as a naming convention for the recipes.
If you want to build the same package for many different Python versions, use the `--py` flag to `conda build`, like `c... |
What is a cell in the context of an interpreter or compiler? | 23,757,143 | 4 | 2014-05-20T10:22:38Z | 23,830,790 | 7 | 2014-05-23T13:39:20Z | [
"python",
"compiler-construction",
"closures",
"interpreter",
"rust"
] | Python code objects have an attribute `co_cellvars` ([documented here](http://effbot.org/pyref/type-code.htm)). The [documentation to Pypy's bytecode interpreter](http://doc.pypy.org/en/release-1.9/interpreter.html) often uses the term Cell.
In other langauges, Rust [provides a Cell datatype](http://static.rust-lang.o... | In Python, `cell` objects are used to store the [free variables](http://en.wikipedia.org/wiki/Free_variable) of a [closure](http://en.wikipedia.org/wiki/Closure_%28computer_programming%29).
Let's say you want a function that always returns a particular fraction of its argument. You can use a closure to achieve this:
... |
pow or ** for very large number in Python | 23,759,098 | 5 | 2014-05-20T11:53:13Z | 23,759,250 | 12 | 2014-05-20T11:59:26Z | [
"python",
"python-2.7",
"math",
"numpy"
] | I am trying to calculate some `num1**num2` in Python. But the problem is that `num1` is `93192289535368032L` and `num2` is `84585482668812077L`, which are very large numbers.
I tried several methods as follows: First, I tried to calculate it by using the `**` operator. But it took too much time (I waited about 2 hours... | You should pass num3 as the 3rd parameter to `pow`
```
pow(...)
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
``` |
Calculation error with pow operator | 23,759,202 | 9 | 2014-05-20T11:57:20Z | 23,759,218 | 18 | 2014-05-20T11:58:12Z | [
"python"
] | What should `print (-2 ** 2)` return? According to my calculations it should be `4`, but interpreter returns `-4`.
Is this Python's thing or my math is that terrible? | According to [docs](https://docs.python.org/3/reference/expressions.html#operator-precedence), `**` has higher precedence than `-`, thus your code is equivalent to `-(2 ** 2)`. To get the desired result you could put `-2` into parentheses
```
>>> (-2) ** 2
4
```
or use built-in [`pow` function](https://docs.python.or... |
Map equivalent for list comprehension | 23,763,300 | 2 | 2014-05-20T14:57:07Z | 23,763,374 | 8 | 2014-05-20T14:59:52Z | [
"python",
"list-comprehension",
"iterable-unpacking",
"map-function"
] | ```
[foo(item['fieldA'], item['fieldC']) for item in barlist]
```
Is there a map equivalent for this?
I mean, something like this:
```
map(foo, [(item['fieldA'], item['fieldB']) for item in barlist])
```
but it doesn't work.
Just curious. | You are looking for [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap):
```
from itertools import starmap
starmap(foo, ((item['fieldA'], item['fieldB']) for item in barlist))
```
`starmap` applies each item from the iterable as *separate arguments* to the callable. The nested... |
Processing Large Files in Python [ 1000 GB or More] | 23,765,360 | 16 | 2014-05-20T16:33:32Z | 23,766,137 | 22 | 2014-05-20T17:16:29Z | [
"python",
"performance",
"file",
"python-2.7",
"text"
] | Lets say i have a text file of 1000 GB. I need to find how much times a phrase occurs in the text.
Is there any faster way to do this that the one i am using bellow?
How much would it take to complete the task.
```
phrase = "how fast it is"
count = 0
with open('bigfile.txt') as f:
for line in f:
count += ... | I used `file.read()` to read the data in chunks, in current examples the chunks were of size 100 MB, 500MB, 1GB and 2GB respectively. The size of my text file is 2.1 GB.
**Code:**
```
from functools import partial
def read_in_chunks(size_in_bytes):
s = 'Lets say i have a text file of 1000 GB'
with open('d... |
Processing Large Files in Python [ 1000 GB or More] | 23,765,360 | 16 | 2014-05-20T16:33:32Z | 23,838,307 | 7 | 2014-05-23T21:04:17Z | [
"python",
"performance",
"file",
"python-2.7",
"text"
] | Lets say i have a text file of 1000 GB. I need to find how much times a phrase occurs in the text.
Is there any faster way to do this that the one i am using bellow?
How much would it take to complete the task.
```
phrase = "how fast it is"
count = 0
with open('bigfile.txt') as f:
for line in f:
count += ... | Have you looked at using [parallel](https://www.gnu.org/software/parallel/) / [grep](https://www.gnu.org/software/grep/)?
```
cat bigfile.txt | parallel --block 10M --pipe grep -o 'how\ fast\ it\ is' | wc -l
``` |
Processing Large Files in Python [ 1000 GB or More] | 23,765,360 | 16 | 2014-05-20T16:33:32Z | 23,839,675 | 8 | 2014-05-23T23:22:26Z | [
"python",
"performance",
"file",
"python-2.7",
"text"
] | Lets say i have a text file of 1000 GB. I need to find how much times a phrase occurs in the text.
Is there any faster way to do this that the one i am using bellow?
How much would it take to complete the task.
```
phrase = "how fast it is"
count = 0
with open('bigfile.txt') as f:
for line in f:
count += ... | Here is a Python attempt... You might need to play with the THREADS and CHUNK\_SIZE. Also it's a bunch of code in a short time so I might not have thought of everything. I do overlap my buffer though to catch the ones in between, and I extend the last chunk to include the remainder of the file.
```
import os
import th... |
SQLAlchemy Automap does not create class for tables without primary key | 23,765,681 | 8 | 2014-05-20T16:51:47Z | 23,771,348 | 14 | 2014-05-20T22:59:48Z | [
"python",
"sqlalchemy"
] | I am using SQL Alchemy v(0.9.1) which has the automap functionality. This allows me to create classes and relationships automatically. <http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html>
The problem I am experiencing is that when using automap\_base, I see that not all the tables that are available in ... | Figured it out by combing through the reference/reframing the problem.
In case it helps someone else -
Because sql alchemy is based on an identity map model, one cannot map (or automap) that does not have a primary key. An arbitrary primary key should be specified.
<http://docs.sqlalchemy.org/en/rel_1_0/faq/ormconfi... |
RabbitMQ: What Does Celery Offer That Pika Doesn't? | 23,766,658 | 7 | 2014-05-20T17:50:55Z | 23,767,306 | 9 | 2014-05-20T18:28:30Z | [
"python",
"rabbitmq",
"celery",
"task-queue",
"pika"
] | I've been working on getting some distributed tasks working via RabbitMQ.
I spent some time trying to get Celery to do what I wanted and couldn't make it work.
Then I tried using Pika and things just worked, flawlessly, and within minutes.
Is there anything I'm missing out on by using Pika instead of Celery? | What pika provides is just a small piece of what Celery is doing. Pika is Python library for interacting with RabbitMQ. RabbitMQ is a message broker; at its core, it just sends messages to/receives messages from queues. It can be used as a task queue, but it could also just be used to pass messages between processes, w... |
python argparse: arg with no flag | 23,766,689 | 4 | 2014-05-20T17:53:04Z | 23,777,855 | 7 | 2014-05-21T08:27:59Z | [
"python",
"python-3.x",
"argparse"
] | i've the following code:
```
parser.add_argument('file', help='file to test')
parser.add_argument('-revs', help='range of versions', nargs='+', default=False)
```
Is there a way to not use the flag `-revs` when use it, like this:
```
./somescript.py settings.json 1 2 3 4
``` | Yes.
You have multiple solutions:
* As Mrav mentioned, you can use the system argument (sys.argv[0...])
* Or use argparse. From the [documentation](https://docs.python.org/2/library/argparse.html#example) (which is python3 compliant), you can do this way:
```
if __name__ == '__main__':
parser = ArgumentPar... |
How can I convert a HTML Page to PDF using Django | 23,767,073 | 4 | 2014-05-20T18:14:54Z | 23,767,180 | 8 | 2014-05-20T18:20:33Z | [
"python",
"django",
"pdf"
] | I have a web app in Django. It's a plataform to store bills and invoices. Now i'm trying to export those bills un PDF.
I'm using xhtml2pdf but it's not working.
I'm using this code for testing:
<http://obroll.com/generate-pdf-with-xhtml2pdf-pisa-in-django-examples/>
It doesnt give any errors but doesnt generate the ... | Try using this code. It works for me.
Change "template\_testing.html" for your template and add your data to render on "data = {}"
views.py:
```
import os
from django.conf import settings
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
import da... |
Programatically rotate monitor | 23,768,184 | 9 | 2014-05-20T19:19:51Z | 23,787,146 | 7 | 2014-05-21T15:07:58Z | [
"python",
"winapi"
] | I'm working on making a utility script that does a whole bunch of things. One of the things I want to do is to rotate a display; I have multiple monitors, and I want the main one to rotate. I know this sort of thing usually works through `win32api` and I found a few functions there that seem helpful, but I'm struggling... | You are calling the `EnumDisplayDevices` API that returns a PDISPLAY\_DEVICE.
(see [http://msdn.microsoft.com/en-us/library/windows/desktop/dd162609(v=vs.85).aspx](http://msdn.microsoft.com/en-us/library/windows/desktop/dd162609%28v=vs.85%29.aspx))
You can obtain the object in two way:
1) From EnumDisplayDevicesEx
`... |
How to use awscli inside python script? | 23,778,442 | 5 | 2014-05-21T08:54:47Z | 25,327,704 | 7 | 2014-08-15T13:54:43Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"aws-cli"
] | I'm using aws ec2 service with awscli. Now I want to put all the commands I type in the console into a python script. I see that if I write `import awscli` inside a python script it works fine but I don't understand how to use it inside the script. For instance how do I execute the commands `aws ec2 run-instances <argu... | You can do it with brilliant [sh](https://pypi.python.org/pypi/sh) package.
You could mimic python package with sh doing wrapping for you.
```
import sh
s3 = sh.bash.bake("aws s3")
s3.put("file","s3n://bucket/file")
``` |
How can I use a HiddenField to coerce integer data in WTForms? | 23,778,664 | 2 | 2014-05-21T09:04:54Z | 23,793,868 | 9 | 2014-05-21T21:11:42Z | [
"python",
"wtforms",
"flask-wtforms"
] | I have a `WTForm` class like so:
```
class MyForm(Form):
field1 = HiddenField(default=0, validators=NumberRange(min=0, max=20)])
```
consider this markup as rendered by `WTForms`
```
<input type='hidden' name='field1' value='5'></input>
```
This does not pass the `NumberRange` validation. This is because `Hidde... | The recommended trick is to use an `IntegerField` and change the widget to a `HiddenInput`
```
class MyForm(Form):
field1 = IntegerField(widget=HiddenInput())
```
you can also subclass
```
class HiddenInteger(IntegerField):
widget = HiddenInput()
``` |
How to visualize a nonlinear relationship in a scatter plot | 23,784,399 | 4 | 2014-05-21T13:18:58Z | 23,784,713 | 9 | 2014-05-21T13:30:07Z | [
"python",
"matplotlib",
"statsmodels"
] | I want to visually explore the relationship between two variables. The functional form of the relationship is not visible in dense scatter plots like this:

**How can I add a lowess smooth to the scatter plot in Python?**
**Or do you have any other suggestions to vi... | From the `lowess` documentation:
```
Definition: lowess(endog, exog, frac=0.6666666666666666, it=3, delta=0.0, is_sorted=False, missing='drop', return_sorted=True)
[...]
Parameters
----------
endog: 1-D numpy array
The y-values of the observed points
exog: 1-D numpy array
The x-values of the observed points
... |
How to visualize a nonlinear relationship in a scatter plot | 23,784,399 | 4 | 2014-05-21T13:18:58Z | 23,787,562 | 9 | 2014-05-21T15:23:59Z | [
"python",
"matplotlib",
"statsmodels"
] | I want to visually explore the relationship between two variables. The functional form of the relationship is not visible in dense scatter plots like this:

**How can I add a lowess smooth to the scatter plot in Python?**
**Or do you have any other suggestions to vi... | You could also use [seaborn](http://stanford.edu/~mwaskom/software/seaborn/):
```
import numpy as np
import seaborn as sns
x = np.arange(0, 10, 0.01)
ytrue = np.exp(-x / 5) + 2 * np.sin(x / 3)
y = ytrue + np.random.normal(size=len(x))
sns.regplot(x, y, lowess=True)
```

print cursor.description
```
And in sqlite3, I do it this way
```
crs.execute("PRAGMA table_info(%s)" %(tablename[0]))
for info in crs:
print info
```
But this is not w... | You can use [`SHOW columns`](http://dev.mysql.com/doc/refman/5.0/en/show-columns.html):
```
cursor.execute("SHOW columns FROM table_name")
print [columns[0] for column in cursor.fetchall()]
```
FYI, this is essentially the same as using [`desc`](http://dev.mysql.com/doc/refman/4.1/en/describe.html):
```
cursor.execu... |
Python Pandas join dataframes on index | 23,787,072 | 8 | 2014-05-21T15:04:47Z | 23,787,275 | 14 | 2014-05-21T15:12:51Z | [
"python",
"pandas",
"indexing",
"data-analysis"
] | I am trying to join to dataframe on the same column "Date", the code is as follow:
```
import pandas as pd
from datetime import datetime
df_train_csv = pd.read_csv('./train.csv',parse_dates=['Date'],index_col='Date')
start = datetime(2010, 2, 5)
end = datetime(2012, 10, 26)
df_train_fly = pd.date_range(start, end, f... | So let's dissect this:
```
df_train_csv = pd.read_csv('./train.csv',parse_dates=['Date'],index_col='Date')
```
OK first problem here is you have specified that the index column should be 'Date' this means that you will not have a 'Date' column anymore.
```
start = datetime(2010, 2, 5)
end = datetime(2012, 10, 26)
d... |
Django 'polls' is not a registered namespace | 23,787,128 | 5 | 2014-05-21T15:06:54Z | 23,787,310 | 16 | 2014-05-21T15:14:15Z | [
"python",
"django",
"namespaces"
] | I'm learning Django from [THIS][1] tutorial. Evertyhing worked perfectly until this step:
*Now change your polls/index.html template from:*
```
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
```
*to point at the namespaced detail view:*
```
<li><a href="{% url 'polls:detail' poll.id %}">{{ po... | I think you forgot to set the namespace when including the polls urls.
In the root urlconf file
Change
```
url(r'^polls/', include('polls.urls')),
```
to
```
url(r'^polls/', include('polls.urls', namespace="polls")),
``` |
Python Popen shell=False causes OSError: [Errno 2] No such file or directory | 23,787,338 | 5 | 2014-05-21T15:15:18Z | 23,787,467 | 8 | 2014-05-21T15:20:11Z | [
"python",
"popen"
] | I am trying to run the below Popen command in OSX using shell=False:
```
command = "/usr/local/itms/share/iTMSTransporter.woa/iTMSTransporter -m verify -f /Volumes/Stuff/Temp/TMP_S_0_V_TV2.itmsp -u username -p password -o /Volumes/Stuff/Temp/TMP_S_0_V_TV2.itmsp/LOGFILE.txt -s provider -v eXtreme"
self.process1 = Popen... | Popen's first argument should be a list of args. Otherwise you're telling it to find an executable named strangely.
You can use `shlex.split()` to split correctly
like `Popen(shlex.split(command), shell=False, stdin=PIPE)`
further reading: [Popen docs](https://docs.python.org/2/library/subprocess.html#popen-construct... |
Finding Bluetooth low energy with python | 23,788,176 | 6 | 2014-05-21T15:53:11Z | 23,809,773 | 14 | 2014-05-22T14:30:49Z | [
"python",
"bluetooth-lowenergy",
"bluez"
] | Is it possible for this code to be modified to include Bluetooth Low Energy devices as well? <https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py?r=1>
I can find devices like my phone and other bluetooth 4.0 devices, but not any BLE. If this cannot be modified, is it possible t... | As I said in the comment, that library won't work with BLE.
Here's some example code to do a simple BLE scan:
```
import sys
import os
import struct
from ctypes import (CDLL, get_errno)
from ctypes.util import find_library
from socket import (
socket,
AF_BLUETOOTH,
SOCK_RAW,
BTPROTO_HCI,
SOL_HCI,
... |
tf-idf feature weights using sklearn.feature_extraction.text.TfidfVectorizer | 23,792,781 | 10 | 2014-05-21T20:05:35Z | 23,796,566 | 26 | 2014-05-22T01:47:00Z | [
"python",
"scikit-learn",
"tf-idf"
] | this page: <http://scikit-learn.org/stable/modules/feature_extraction.html> mentions:
> As tfâidf is a very often used for text features, there is also another class called **TfidfVectorizer** that combines all the option of **CountVectorizer** and **TfidfTransformer** in a single model.
then I followed the code an... | Since version 0.15, the tf-idf score of each feature can be retrieved via the attribute `idf_` of the `TfidfVectorizer` object:
```
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["This is very strange",
"This is very nice"]
vectorizer = TfidfVectorizer(min_df=1)
X = vectorizer.fit_tran... |
pandas groupby and join lists | 23,794,082 | 4 | 2014-05-21T21:25:17Z | 23,794,283 | 9 | 2014-05-21T21:38:29Z | [
"python",
"pandas"
] | I have a dataframe df, with two columns, I want to groupby one column and join the lists belongs to same group, example:
```
column_a, column_b
1, [1,2,3]
1, [2,5]
2, [5,6]
```
after the process:
```
column_a, column_b
1, [1,2,3,2,5]
2, [5,6]
```
I want to keep all the duplic... | `object` dtype is a catch-all dtype that basically means not int, float, bool, datetime, or timedelta. So it is storing them as a list. `convert_objects` tries to convert a column to one of those dtypes.
You want
```
In [63]: df
Out[63]:
a b c
0 1 [1, 2, 3] foo
1 1 [2, 5] bar
2 2 [5, 6] ... |
BeautifulSoup4: select elements where attributes are not equal to x | 23,798,062 | 4 | 2014-05-22T04:51:51Z | 23,798,363 | 8 | 2014-05-22T05:21:04Z | [
"python",
"html",
"python-2.7",
"beautifulsoup",
"html-parsing"
] | I'd like to do something like this:
```
soup.find_all('td', attrs!={"class":"foo"})
```
I want to find all td that do not have the class of foo.
Obviously the above doesn't work, what does? | `BeautifulSoup` really makes the "soup" beautiful and easy to work with.
You [can pass a function](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments) in the attribute value:
```
soup.find_all('td', class_=lambda x: x != 'foo')
```
Demo:
```
>>> from bs4 import BeautifulSoup
>>> data = """
... |
how to get the same required string with better and shorter way | 23,801,205 | 2 | 2014-05-22T08:09:22Z | 23,801,225 | 8 | 2014-05-22T08:10:49Z | [
"python",
"string"
] | ```
s = 'myName.Country.myHeight'
required = s.split('.')[0]+'.'+s.split('.')[1]
print required
myName.Country
```
How can I get the same 'required' string with better and shorter way? | Use [`str.rpartition`](https://docs.python.org/2/library/stdtypes.html#str.rpartition) like this
```
s = 'myName.Country.myHeight'
print s.rpartition(".")[0]
# myName.Country
```
`rpartition` returns a three element tuple,
1. 1st element being the string before the separator
2. then the separator itself
3. and the t... |
Django serving media files (user uploaded files ) in openshift | 23,807,969 | 11 | 2014-05-22T13:16:50Z | 23,829,831 | 8 | 2014-05-23T12:54:00Z | [
"python",
"django",
"openshift",
"django-media"
] | I have successfully deployed my Django project in openshift. But I need to be able to serve files that are uploaded by users. I user MEDIA\_ROOT and MEDIA\_URL for that. I followed [this](http://masci.wordpress.com/2012/07/17/serving-django-media-files-in-openshift/) tutorial here, but nothing happened. I had to change... | Just for others to know, I solved my problem by correcting the RewriteRule adding media folder to the second part of the rule, so it became
```
RewriteEngine On
RewriteRule ^application/media/(.+)$ /static/media/$1 [L]
```
Hope it helps others. |
Unexpected Exception in numpy.isfinite() | 23,808,327 | 6 | 2014-05-22T13:29:35Z | 23,813,798 | 9 | 2014-05-22T17:42:30Z | [
"python",
"numpy"
] | I get this exception for a reason I do not understand. It is quite complicated, where my np.array v comes from, but here is the code when the exception occurs:
```
print v, type(v)
for val in v:
print val, type(val)
print "use isfinte() with astype(float64): "
np.isfinite(v.astype("float64"))
print "use isfinit... | `H_estim.values` is a numpy array with the data type `object` (take a look at `H_estim.values.dtype`):
```
In [62]: H_estim.values
Out[62]:
array([[3.4000000000000004, 3.6000000000000005, 2.7999999999999998, 3.0],
[3.9000000000000004, 4.3000000000000007, 2.6999999999999993,
3.0999999999999996]], dtype=... |
Simulate interactive python session | 23,809,327 | 4 | 2014-05-22T14:12:31Z | 23,809,736 | 7 | 2014-05-22T14:29:21Z | [
"python"
] | How can I simulate a python interactive session *using input from a file* and save what would be a transcript? In other words, if I have a file `sample.py`:
```
#
# this is a python script
#
def foo(x,y):
return x+y
a=1
b=2
c=foo(a,b)
c
```
I want to get `sample.py.out` that looks like this (python banner omitt... | I think `code.interact` would work:
```
from __future__ import print_function
import code
import fileinput
def show(input):
lines = iter(input)
def readline(prompt):
try:
command = next(lines).rstrip('\n')
except StopIteration:
raise EOFError()
print(prompt, c... |
Scrapy how to ignore items with blank fields using Loader | 23,810,650 | 4 | 2014-05-22T15:07:43Z | 23,812,290 | 7 | 2014-05-22T16:19:50Z | [
"python",
"scrapy",
"scrapyd"
] | I would like to know how to ignore items that don't fill all fields, some kind of droping, because in the output of scrapyd I'm getting pages that don't fill all fields.
I have that code:
```
class Product(scrapy.Item):
source_url = scrapy.Field(
output_processor = TakeFirst()
)
name = scrapy.Fiel... | Validation of data is one of typical use case for pipelines. In your case you only need to write some small amount of code to check for required fields, something along the lines of:
```
from scrapy.exceptions import DropItem
class YourPersonalPipeline(object):
def process_item(self, item, spider):
requir... |
Clear cookies from Requests Python | 23,816,139 | 3 | 2014-05-22T20:06:26Z | 23,816,320 | 12 | 2014-05-22T20:18:34Z | [
"python",
"session",
"cookies",
"python-requests"
] | I created variable: `s = requests.session()`
how to clear all cookies in this variable? | The `Session.cookies` object implements the full [mutable mapping interface](https://docs.python.org/2/library/collections.html#collections.MutableMapping), so you can call:
```
s.cookies.clear()
```
to clear all the cookies.
Demo:
```
>>> import requests
>>> s = requests.session()
>>> s.get('http://httpbin.org/coo... |
Is there a Java 8 equivalent of Python enumerate built-in? | 23,817,840 | 7 | 2014-05-22T22:07:29Z | 23,819,320 | 11 | 2014-05-23T00:41:34Z | [
"java",
"python",
"java-8"
] | 3 years ago a similar question was asked here:
[Is there a Java equivalent of Python's 'enumerate' function?](http://stackoverflow.com/questions/7167253/is-there-a-java-equivalent-of-pythons-enumerate-function)
I really appreciate the `listIterator()` solution. Still, I work a lot with the new streams and lambdas (int... | This question has been asked a few ways before. The key observation is that, unless you have perfect size and splitting information (basically, if your source is an array), then this would be a sequential-only operation.
The "unappealing" answer you propose:
```
IntStream.range(0, myList.size())
.mapToObj(i ... |
OpenCV: When to use GridAdaptedFeatureDetector? | 23,819,086 | 3 | 2014-05-22T15:16:50Z | 23,822,885 | 7 | 2014-05-23T06:57:32Z | [
"python",
"c++",
"opencv",
"image-processing",
"feature-detection"
] | I am trying to make a detector based on descriptors. I am using OpenCV and I have seen that there are many feature types and descriptor types, and also matcher types. More I have also seen that there can be composed types like Grid or Pyramid for feature types.
I have not found a good explanation of them (except for P... | The term *feature* is commonly used for two different things:
* feature *detectors*,
* feature *descriptors*.
A detector aims at.. well... *detecting* good interesting points, i.e., points that are stable under viewpoint and illumination changes and that yield good performance in tasks like homography estimation or o... |
How can I return True if x is in either of multiple lists? | 23,820,144 | 3 | 2014-05-23T02:39:55Z | 23,820,165 | 10 | 2014-05-23T02:42:10Z | [
"python",
"list",
"return"
] | ```
>>> list1 = ['yes', 'yeah']
>>> list2 = ['no', 'nope']
>>> 'no' in list2
True
>>> 'no' in list1
False
>>> 'no' in (list1, list2)
False
>>> 'no' in (list1 and list2)
True
>>> 'yes' in (list1 and list2)
False #want this to be true
>>> 'yes' in (list1 or list2)
True
>>> 'no' in (list1 or list2)
False #want this to be ... | You can do that using `any`:
```
>>> any('yes' in i for i in (list1, list2))
True
```
Or, just concatenate the lists:
```
>>> 'yes' in list1+list2
True
``` |
Upload files to Google cloud storage from appengine app | 23,823,206 | 5 | 2014-05-23T07:17:29Z | 23,824,492 | 8 | 2014-05-23T08:32:57Z | [
"python",
"google-app-engine",
"google-cloud-storage"
] | I'm sure the answer to this question is easy, but for me it's proven to be very frustrating since I can't put any solution I've found into practical code for my own use.
I'm building an app on the app engine that let's the user upload a file, which then gets acted on by the app. The size of the file is typically aroun... | If I understand correctly, what you're trying to do is serve a form from App Engine that allows a user to choose a file to upload.
Since the uploaded file may be large, you don't want to handle the upload in App Engine, but have the file uploaded directly to Google Cloud Storage.
This can be done, and it's not too dif... |
Read lines from a file as a shift register with two cells in Python | 23,823,280 | 3 | 2014-05-23T07:22:08Z | 23,823,376 | 7 | 2014-05-23T07:27:03Z | [
"python"
] | I need to read the lines of a file in such way that will behave as a shift register with two cell.
For example:
```
with open("filename", 'r') as file:
--first iteration--
present = line1
next = line2
do something
--second iteration--
present = line2
next = line3
do something
--third iteration--
pre... | Sure:
```
with open("filename", 'r') as file:
current_line = next(file) # Get 1st line, advance iterator to 2nd line
for next_line in file:
do_something(current_line, next_line)
current_line = next_line
``` |
\text does not work in a matplotlib label | 23,824,687 | 5 | 2014-05-23T08:44:08Z | 23,856,968 | 8 | 2014-05-25T15:33:52Z | [
"python",
"matplotlib"
] | I am using matplotlib together with latex labels for the axis, title and colorbar labels
While it works really great most of the time, it has some issues when you have a formula using \text.
One really simple example.
```
from matplotlib import pyplot as plt
plt.plot([1,2,3])
plt.title(r"$f_{\text{cor, r}}$")
plt.s... | `\text` won't work because it requires the *amsmath* package (not included in mathtext - the math rendering engine of matplotlib). So you basically have two options:
* use latex based font rendering
```
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text... |
karger min cut algorithm in python 2.7 | 23,825,200 | 2 | 2014-05-23T09:10:17Z | 23,825,533 | 9 | 2014-05-23T09:26:17Z | [
"python",
"algorithm",
"min"
] | Here is my code for the karger min cut algorithm.. To the best of my knowledge the algorithm i have implemented is right. But I don get the answer right. If someone can check what's going wrong I would be grateful.
```
import random
from random import randint
#loading data from the text file#
with open('data.txt') as... | So Karger's algorithm is a `random alogorithm'. That is, each time you run it it produces a solution which is in no way guaranteed to be best. The general approach is to run it lots of times and keep the best solution. For lots of configurations there will be many solutions which are best or approximately best, so you ... |
karger min cut algorithm in python 2.7 | 23,825,200 | 2 | 2014-05-23T09:10:17Z | 25,085,521 | 8 | 2014-08-01T17:22:49Z | [
"python",
"algorithm",
"min"
] | Here is my code for the karger min cut algorithm.. To the best of my knowledge the algorithm i have implemented is right. But I don get the answer right. If someone can check what's going wrong I would be grateful.
```
import random
from random import randint
#loading data from the text file#
with open('data.txt') as... | This code also works.
```
import random, copy
data = open("***.txt","r")
G = {}
for line in data:
lst = [int(s) for s in line.split()]
G[lst[0]] = lst[1:]
def choose_random_key(G):
v1 = random.choice(list(G.keys()))
v2 = random.choice(list(G[v1]))
return v1, v2
def karger(G):
length = []
... |
How to make a simple multithreaded socket server in Python that remembers clients | 23,828,264 | 6 | 2014-05-23T11:39:56Z | 23,828,265 | 8 | 2014-05-23T11:39:56Z | [
"python",
"sockets",
"python-2.7",
"echo-server"
] | How do I make a simple Python echo server that remembers clients and doesn't create a new socket for each request? Must be able to support concurrent access. I want to be able to connect once and continually send and receive data using this client or similar:
```
import socket
sock = socket.socket(socket.AF_INET, soc... | You can use a thread per client to avoid the blocking `client.recv()` then use the main thread just for listening for new clients. When one connects, the main thread creates a new thread that just listens to the new client and ends when it doesn't talk for 60 seconds.
```
import socket
import threading
class Threaded... |
Unpacking into a list | 23,831,243 | 4 | 2014-05-23T14:00:11Z | 23,831,364 | 10 | 2014-05-23T14:05:25Z | [
"python"
] | Is there any difference in Python between unpacking into a tuple:
```
x, y, z = v
```
and unpacking into a list?
```
[x, y, z] = v
``` | Absolutely nothing, even down to the bytecode (using [`dis`](https://docs.python.org/2/library/dis.html)):
```
>>> def list_assign(args):
[x, y, z] = args
return x, y, z
>>> def tuple_assign(args):
x, y, z = args
return x, y, z
>>> import dis
>>> dis.dis(list_assign)
2 0 LOAD_FAST ... |
python abstract attribute (not property) | 23,831,510 | 11 | 2014-05-23T14:12:21Z | 23,833,055 | 7 | 2014-05-23T15:24:54Z | [
"python"
] | What's the best practice to define an abstract instance attribute, but not as a property?
I would like to write something like:
```
class AbstractFoo(metaclass=ABCMeta):
@property
@abstractmethod
def bar(self):
pass
class Foo(AbstractFoo):
def __init__(self):
self.bar = 3
```
Inste... | If you really want to enforce that a subclass define a given attribute, you can use metaclass. Personally, I think it may be overkill and not very pythonic, but you could do something like this:
```
class AbstractFooMeta(type):
def __call__(cls, *args, **kwargs):
"""Called when you call Foo(*args, **kw... |
Accessing request headers in flask-restless preprocessor | 23,833,708 | 2 | 2014-05-23T15:58:27Z | 23,892,183 | 7 | 2014-05-27T14:31:05Z | [
"python",
"flask",
"flask-restless"
] | I'm building an API with Flask-Restless that requires an API key, that will be in the `Authorization` HTTP header.
In the Flask-Restless example [here](http://flask-restless.readthedocs.org/en/latest/index.html) for a preprocessor:
```
def check_auth(instance_id=None, **kw):
# Here, get the current user from the ... | In a normal Flask request-response cycle, the [`request` context](https://flask.readthedocs.org/en/latest/reqcontext/) is active when the Flask-Restful preprocessors and postprocessors are being run.
As such, using:
```
from flask import request, abort
def check_auth(instance_id=None, **kw):
current_user = None
... |
pillow installed, but "no module named pillow" - python2.7 - Windows 7 - python -m install pillow | 23,834,663 | 5 | 2014-05-23T16:54:14Z | 23,834,693 | 15 | 2014-05-23T16:55:59Z | [
"python",
"windows",
"python-2.7",
"pip"
] | Using python 2.7 on Windows 7
installed package pillow with
```
python -m pip install pillow
```
Got success message (`Successfully installed pillow`). Closed and re-opened cmd terminal.
But when I try to
```
import pillow
```
I get the error message
```
ImportError: No module named pillow
```
If `python -m pip ... | Try using
```
import PIL
```
or
```
from PIL import ...
```
instead. [`Pillow`](http://pillow.readthedocs.org/en/latest/) is a fork of [`PIL`](http://www.pythonware.com/products/pil/), the Python Imaging Library, which is no longer maintained. However, to maintain backwards compatibility, the old module name is use... |
Many tutorials on writing csv files have the mode set to 'wb', why? | 23,835,866 | 4 | 2014-05-23T18:11:16Z | 23,837,729 | 7 | 2014-05-23T20:16:50Z | [
"python"
] | For example: [Writing to csv file in Python](http://stackoverflow.com/questions/16745468/writing-to-csv-file-in-python)
```
with open('StockPrice.csv', 'wb') as f:
```
Why would we need to open in binary for a csv file?
Is this just habit, or is there a use-case for when binary is necessary for a csv file? | It's necessary to use the mode `"wb"` when writing output using the `csv` module on Windows, because the `csv` module will write out line-ends as `\r\n` regardless of what platform you're running on.
If you're running on Windows, and you have a file open with mode `"w"`, Python will add an extra carriage return every ... |
Add Leading Zeros to Strings in Pandas Dataframe | 23,836,277 | 5 | 2014-05-23T18:36:54Z | 23,836,353 | 9 | 2014-05-23T18:42:07Z | [
"python",
"pandas"
] | I have a pandas data frame where the first 3 columns are strings:
```
ID text1 text 2
0 2345656 blah blah
1 3456 blah blah
2 541304 blah blah
3 201306 hi blah
4 12313201308 hello blah
```
I want to add lead... | Try:
```
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
```
or even
```
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
``` |
Add Leading Zeros to Strings in Pandas Dataframe | 23,836,277 | 5 | 2014-05-23T18:36:54Z | 31,553,791 | 8 | 2015-07-22T04:18:59Z | [
"python",
"pandas"
] | I have a pandas data frame where the first 3 columns are strings:
```
ID text1 text 2
0 2345656 blah blah
1 3456 blah blah
2 541304 blah blah
3 201306 hi blah
4 12313201308 hello blah
```
I want to add lead... | `str` attribute contains most of the methods in string.
```
df['ID'] = df['ID'].str.zfill(15)
```
See more: <http://pandas.pydata.org/pandas-docs/stable/text.html> |
Beginning with two separate tuples, how to make one non-nested tuple? | 23,838,535 | 2 | 2014-05-23T21:25:20Z | 23,838,550 | 7 | 2014-05-23T21:26:24Z | [
"python",
"list",
"tuples"
] | Suppose I have two tuples:
```
tuple1 = ("a", "b", "c")
tuple2 = ("y", "z")
```
I'd like to return one tuple:
```
return_tuple == ("a", "b", "c", "y", "z")
```
The challenge for me here is that tuples are immutable, so I cannot simply append tuple2 to tuple1. I am aware that I can convert both to lists and then bac... | Just add the tuples together with the `+` operator:
```
>>> tuple1 = ("a", "b", "c")
>>> tuple2 = ("y", "z")
>>> tuple1 + tuple2 # This creates a new tuple object
('a', 'b', 'c', 'y', 'z')
>>> tuple1 # tuple1 is unaffected
('a', 'b', 'c')
>>> tuple2 # tuple2 is also unaffected
('y', 'z')
>>>
```
Note that you can ... |
How to fill upper triangle of numpy array with zeros in place? | 23,839,688 | 2 | 2014-05-23T23:24:08Z | 23,839,864 | 7 | 2014-05-23T23:50:03Z | [
"python",
"numpy"
] | What is the best way to fill in the lower triangle of a numpy array with zeros in place so that I don't have to do the following:
```
a=np.random.random((5,5))
a = np.triu(a)
```
since np.triu returns a copy, not a view. Preferable this would require no list indexing as well since I am working with large arrays. | Digging into the internals of [`triu`](https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/twodim_base.py#L427) you'll find that it just multiplies the input by the output of [`tri`](https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/twodim_base.py#L349).
So you can just multiply the array in-place by the output of... |
Using Python 3 in virtualenv | 23,842,713 | 124 | 2014-05-24T08:05:53Z | 23,842,752 | 250 | 2014-05-24T08:11:01Z | [
"python",
"python-3.x",
"virtualenv"
] | Using [virtualenv](https://virtualenv.pypa.io/en/latest/), I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used `brew install python3` to install it on my Mac. Now, how do I create a virtualenv that uses the new version?
e.g. sudo virtualenv envPython3
If I try... | simply run
```
virtualenv -p python3 envname
```
Update after OP's edit:
There was a bug in the OP's version of virtualenv, as described [here](https://github.com/pypa/virtualenv/issues/463). The problem was fixed by running:
```
pip install --upgrade virtualenv
``` |
Using Python 3 in virtualenv | 23,842,713 | 124 | 2014-05-24T08:05:53Z | 30,233,408 | 24 | 2015-05-14T09:09:36Z | [
"python",
"python-3.x",
"virtualenv"
] | Using [virtualenv](https://virtualenv.pypa.io/en/latest/), I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used `brew install python3` to install it on my Mac. Now, how do I create a virtualenv that uses the new version?
e.g. sudo virtualenv envPython3
If I try... | Python 3 has a built-in support for virtual environments - [venv](https://docs.python.org/3/library/venv.html#module-venv). It might be better to use that instead. Referring to the docs:
> Creation of virtual environments is done by executing the pyvenv
> script:
>
> `pyvenv /path/to/new/virtual/environment` |
Using Python 3 in virtualenv | 23,842,713 | 124 | 2014-05-24T08:05:53Z | 32,672,975 | 12 | 2015-09-19T20:38:09Z | [
"python",
"python-3.x",
"virtualenv"
] | Using [virtualenv](https://virtualenv.pypa.io/en/latest/), I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used `brew install python3` to install it on my Mac. Now, how do I create a virtualenv that uses the new version?
e.g. sudo virtualenv envPython3
If I try... | I'v tried [pyenv](https://github.com/yyuu/pyenv) and it's very handy for switching python versions (global, local in folder or in the virtualenv):
```
brew install pyenv
```
then install Python version you want:
```
pyenv install 3.5.0
```
and simply create virtualenv with path to needed interpreter version:
```
v... |
Using Python 3 in virtualenv | 23,842,713 | 124 | 2014-05-24T08:05:53Z | 34,417,952 | 8 | 2015-12-22T14:21:01Z | [
"python",
"python-3.x",
"virtualenv"
] | Using [virtualenv](https://virtualenv.pypa.io/en/latest/), I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used `brew install python3` to install it on my Mac. Now, how do I create a virtualenv that uses the new version?
e.g. sudo virtualenv envPython3
If I try... | ```
virtualenv --python=/usr/bin/python3 <name of env>
```
worked for me. |
Using Python 3 in virtualenv | 23,842,713 | 124 | 2014-05-24T08:05:53Z | 36,096,474 | 8 | 2016-03-19T00:36:03Z | [
"python",
"python-3.x",
"virtualenv"
] | Using [virtualenv](https://virtualenv.pypa.io/en/latest/), I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used `brew install python3` to install it on my Mac. Now, how do I create a virtualenv that uses the new version?
e.g. sudo virtualenv envPython3
If I try... | Install prerequisites.
```
sudo apt-get install python3 virtualenvwrapper
```
Create a Python3 based virtual environment. Optionally enable `--system-site-packages`
```
mkvirtualenv -p /usr/bin/python3 <venv-name>
```
Set into the virtual environment.
```
workon <venv-name>
```
Install other requirements using `p... |
Move all zeroes to the beginning of a list in Python | 23,844,828 | 5 | 2014-05-24T12:06:12Z | 23,844,848 | 13 | 2014-05-24T12:07:48Z | [
"python",
"list"
] | I have a list like below:
```
a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]
```
and I want to push all zeroes to the beginning of that list. The result must be like below.
```
a = [0, 0, 0, 0, 4, 5, 6, 7, 1, 5]
```
How to do it in Python 2? | You could sort the list:
```
a.sort(key=lambda v: v != 0)
```
The `key` function tells Python to sort values by wether or not they are `0`. `False` is sorted before `True`, and values are then sorted based on their original relative position.
For `0`, `False` is returned, sorting all those values first. For the rest... |
Move all zeroes to the beginning of a list in Python | 23,844,828 | 5 | 2014-05-24T12:06:12Z | 23,844,928 | 12 | 2014-05-24T12:18:01Z | [
"python",
"list"
] | I have a list like below:
```
a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]
```
and I want to push all zeroes to the beginning of that list. The result must be like below.
```
a = [0, 0, 0, 0, 4, 5, 6, 7, 1, 5]
```
How to do it in Python 2? | This can be done without sorting.
## Solutions
Initialization:
```
In [8]: a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]
In [9]: from itertools import compress, repeat, chain
```
`list.count` and [`itertools.compress`](https://docs.python.org/3/library/itertools.html#itertools.compress)
```
In [10]: x = [0] * a.count(0); x.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.