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 terminate process from Python using pid? | 17,856,928 | 18 | 2013-07-25T11:37:00Z | 17,858,114 | 32 | 2013-07-25T12:32:30Z | [
"python",
"linux",
"process",
"terminal"
] | I'm trying to write some short script in python which would start another python code in subprocess if is not already started else terminate terminal & app (Linux).
So it looks like:
```
#!/usr/bin/python
from subprocess import Popen
text_file = open(".proc", "rb")
dat = text_file.read()
text_file.close()
def do(da... | Using the awesome [`psutil`](https://github.com/giampaolo/psutil) library it's pretty simple:
```
p = psutil.Process(pid)
p.terminate() #or p.kill()
```
If you don't want to install a new library, you can use the `os` module:
```
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
```
---
If ... |
Fail to install lxml in MacOS 10.8.4 | 17,857,858 | 9 | 2013-07-25T12:19:39Z | 17,865,021 | 21 | 2013-07-25T17:38:35Z | [
"python",
"osx",
"lxml",
"libxml2"
] | I am having trouble installing lxml to my Mac OS.
I am having the following error when building it. This is the error I have when using `pip install lxml`
> /private/var/folders/9s/s5hl5w4x7zjdjkdljw9cnsrm0000gn/T/pip-build-khuevu/lxml/src/lxml/includes/etree\_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not f... | Turn out xmlversion.h is not included in compilation path even though it is in PATH. Modify the C\_INCLUDE\_PATH env fix the error for me:
> C\_INCLUDE\_PATH=/usr/local/Cellar/libxml2/2.9.1/include/libxml2:$C\_INCLUDE\_PATH |
Fail to install lxml in MacOS 10.8.4 | 17,857,858 | 9 | 2013-07-25T12:19:39Z | 19,811,479 | 19 | 2013-11-06T11:53:45Z | [
"python",
"osx",
"lxml",
"libxml2"
] | I am having trouble installing lxml to my Mac OS.
I am having the following error when building it. This is the error I have when using `pip install lxml`
> /private/var/folders/9s/s5hl5w4x7zjdjkdljw9cnsrm0000gn/T/pip-build-khuevu/lxml/src/lxml/includes/etree\_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not f... | If you are running Mavericks with Xcode installed, you can also use:
```
export C_INCLUDE_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include/libxml2:$C_INCLUDE_PATH
``` |
Custom headers in Phantomjs Selenium WebDriver | 17,858,663 | 14 | 2013-07-25T12:56:19Z | 17,862,456 | 26 | 2013-07-25T15:32:47Z | [
"python",
"selenium",
"selenium-webdriver",
"phantomjs",
"ghostdriver"
] | According to [this](https://github.com/detro/ghostdriver/pull/229) it is possible now to modify headers. Atm i need to modify Accept-Language in PhantomJS webdriver. This code doesn't work
```
DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders.Accept-Language'] = 'ru-RU'
driver = webdriver.PhantomJS()
```
Is... | The latest version ([1.9.1](https://code.google.com/p/phantomjs/downloads/list)) of PhantomJS is release Jun/5/2013. The pull request is merged [Jun/23/2013](https://github.com/detro/ghostdriver/commit/43a8fbcb6cbe55c459b659e44a61858ef1169a71).
If you are using 1.9.1 version of PhantomJS, custom headers will not work.... |
BeautifulSoup return unexpected extra spaces | 17,859,832 | 6 | 2013-07-25T13:45:16Z | 17,862,059 | 10 | 2013-07-25T15:17:13Z | [
"python",
"html",
"text",
"beautifulsoup"
] | I am trying to grab some text from html documents with BeautifulSoup. In a very relavant case for me, it originates a strange and interesting result: after a certain point, the soup is full of extra spaces within the text (a space separates every letter from the following one). I tried to search the web in order to fin... | I believe this is a bug with Lxml's HTML parser.
Try:
```
from bs4 import BeautifulSoup
import urllib2
html = urllib2.urlopen ("http://www.beppegrillo.it")
prova = html.read()
soup = BeautifulSoup(prova.replace('ISO-8859-1', 'utf-8'))
print soup
```
Which is a workaround for the problem.
I believe the issue was fixe... |
Handling both specific and general Python exceptions? | 17,860,896 | 5 | 2013-07-25T14:28:39Z | 17,860,987 | 10 | 2013-07-25T14:32:46Z | [
"python"
] | I would like to catch a specific exception and handle it accordingly - then I would like to continue and perform the generic handling that other exceptions would have to.
Coming from a C background, I could have previously utilised gotos to achieve the desired effect.
This is what I'm currently doing is and it works ... | You could *reraise* the exception, and handle the generic case in the outer handler of a nested setup:
```
try:
try:
output_var = some_magical_function()
except IntegrityError as zde:
integrity_error_handling()
raise
except ALLExceptions as ae: # all exceptions INCLUDING the IntregityEr... |
cursor.fetchall() vs list(cursor) in Python | 17,861,152 | 7 | 2013-07-25T14:38:58Z | 17,861,853 | 20 | 2013-07-25T15:08:48Z | [
"python",
"cursor",
"mysql-python"
] | Both methods return a list of the returned items of the query, did I miss something here? or they have identical usages indeed? any differences performance wise? | If you are using the default cursor, a `MySQLdb.cursors.Cursor`, *the entire result set will be stored on the client side* (i.e. in a Python list) by the time the `cursor.execute()` is completed.
Therefore, even if you use
```
for row in cursor:
```
you will not be getting any reduction in memory footprint. The enti... |
How to inject variable into scope with a decorator in python | 17,862,185 | 19 | 2013-07-25T15:21:58Z | 17,862,336 | 17 | 2013-07-25T15:28:26Z | [
"python",
"scope",
"closures",
"decorator"
] | [Disclaimer: there may be more pythonic ways of doing what I want to do, but I want to know how python's scoping works here]
I'm trying to find a way to make a decorator that does something like injecting a name into the scope of another function (such that the name does not leak outside the decorator's scope). For ex... | You can't. Scoped names (closures) are determined at compile time, you cannot add more at runtime.
The best you can hope to achieve is to add *global* names, using the function's *own* global namespace:
```
def decorator_factory(value):
def msg_decorator(f):
def inner_dec(*args, **kwargs):
g =... |
Following hyperlink and "Filtered offsite request" | 17,862,474 | 5 | 2013-07-25T15:33:31Z | 17,865,509 | 11 | 2013-07-25T18:04:07Z | [
"python",
"callback",
"web-scraping",
"scrapy"
] | I know that there are several related threads out there, and they have helped me a lot, but I still can't get all the way. I am at the point where running the code doesn't result in errors, but I get nothing in my `csv` file. I have the following `Scrapy` spider that starts on one webpage, then follows a hyperlink, and... | You need to modify your yielded `Request` in `parse` to use `parse2` as its callback.
EDIT: `allowed_domains` shouldn't include the http prefix eg:
```
allowed_domains = ["boliga.dk"]
```
Try that and see if your spider still runs correctly instead of leaving `allowed_domains` blank |
Save a file depending on the user Python | 17,863,389 | 3 | 2013-07-25T16:12:53Z | 17,863,514 | 7 | 2013-07-25T16:19:30Z | [
"python"
] | Good morning to all! I am trying write a script in Python that saves the file in each user directory.
Example for user 1, 2 and 3.
```
C:\Users\user1\Documents\ArcGIS\file1.gdb
C:\Users\user2\Documents\ArcGIS\file1.gdb
C:\Users\user3\Documents\ArcGIS\file1.gdb
```
I am not really sure how can I do this, thanks!!! | In Python you can use [os.path.expanduser](http://docs.python.org/2/library/os.path.html?highlight=os.path#os.path.expanduser) to get the User's home directory.
```
>>> import os
>>> os.path.expanduser("~")
```
This is a platform independent way of determining the user's home directory.
You can then concatenate the ... |
Get Image Dimensions from Url in Python | 17,864,603 | 2 | 2013-07-25T17:17:00Z | 17,865,274 | 12 | 2013-07-25T17:51:21Z | [
"python",
"image",
"python-imaging-library",
"dimensions"
] | I want to get the image dimensions as seen from a viewer on a website.
I'm using beautiful soup and I get image links like this:
```
links = soup.findAll('img', {"src":True})
```
The way I get the image dimensions is by using:
```
link.has_key('height')
height = link['height']
```
and similarly with width as well.... | Your main issue is you are searching the html source for references to height and width. In most cases (when things are done well), images don't have height and width specified in html, in which case they are rendered at the height and width of the image file itself.
To get the height and width of the image file, you ... |
Python curiosity: [] > lambda n: n | 17,864,973 | 2 | 2013-07-25T17:35:49Z | 17,865,001 | 7 | 2013-07-25T17:37:20Z | [
"python",
"list",
"lambda",
"comparison-operators"
] | One of my coworkers was using the builtin [max](http://docs.python.org/2/library/functions.html#max) function (on Python 2.7), and he found a weird behavior.
By mistake, instead of using the keyword argument *key* (as in `key=lambda n: n`) to pre-sort the list passed as a parameter, he did:
```
>>> max([1,2,3,3], la... | Python 2 orders objects of different types rather arbitrarily. It did this to make lists *always* sortable, whatever the contents. Which direction that comparison comes out as is really not of importance, just that one always wins. As it happens, the [C implementation](http://hg.python.org/cpython/file/0012d4f0ca59/Obj... |
Shallow copy: why is list changing but not a string? | 17,865,672 | 4 | 2013-07-25T18:12:49Z | 17,865,737 | 14 | 2013-07-25T18:16:22Z | [
"python",
"shallow-copy"
] | I understand that when you do a shallow copy of a dictionary, you actually make a copy of the references. So if I do this:
```
x={'key':['a','b','c']}
y=x.copy()
```
So the reference of the list ['a','b','c'] is copied into y. Whenever I change the list ( `x['key'].remove('a')` for example), both dict x and y will ch... | You're doing two different things. When you do
```
x['key'].remove('a')
```
you mutate the object that `x['key']` references. If another variable references the same object, you'll see the change from that point of view, too:

![Pythontutor visualizatio... |
simplifying maybe Monad | 17,866,148 | 9 | 2013-07-25T18:38:43Z | 17,866,292 | 8 | 2013-07-25T18:45:40Z | [
"python",
"haskell",
"monads"
] | I am trying to understand *maybe* [Monad](http://en.wikipedia.org/wiki/Monad_%28functional_programming%29#The_Maybe_monad) but most of the examples I saw used some language-specific feature. To ensure that I have gotten it conceptually right I thought of writing a generic implementation. Below is what I came up with.
... | You're very close, but the signature of `bind` is
```
m a -> (a -> m b) -> m b
```
So it's "unwrapping" `m` and passing the contained value to the next function. You currently have
```
m a -> ( () -> m b) -> m b
```
Since you're just ignoring the `val` bind gets, you should have
```
def bind(val, func):
if val... |
Doing DateTime Comparisons in Filter SQLAlchemy | 17,868,743 | 11 | 2013-07-25T21:06:22Z | 17,875,113 | 22 | 2013-07-26T07:11:54Z | [
"python",
"sql",
"sqlalchemy"
] | I'm a bit confused about filtering in SQLAlchemy.
I currently am trying to filter out entries greater than 10 weeks, so I have
```
current_time = datetime.datetime.utcnow()
potential = session.query(Subject).filter(Subject.time < current_time - datetime.timedelta(weeks=10))
```
However, the `potential.count()` alwa... | If you switch the `<` to a `>` you can get all subjects within the last ten weeks:
```
current_time = datetime.datetime.utcnow()
ten_weeks_ago = current_time - datetime.timedelta(weeks=10)
subjects_within_the_last_ten_weeks = session.query(Subject).filter(
Subject.time > ten_weeks_ago).all()
```
Filter generate... |
Unable to install Pygame using pip | 17,869,101 | 60 | 2013-07-25T21:31:29Z | 19,875,416 | 86 | 2013-11-09T11:29:31Z | [
"python",
"pygame",
"install",
"pip"
] | I'm trying to install Pygame. I am running Windows 7 with Enthought Python Distribution. I successfully installed `pip`, but when I try to install Pygame using `pip`, I get the following error:
> "Could not install requirement Pygame because of HTTP error HTTP error
> 400: Bad request for URL ..."
I can't find anythi... | **Steps to install PyGame using pip**
1. Install build dependencies (on linux):
```
sudo apt-get build-dep python-pygame
```
2. Install mercurial to use `hg` (on linux):
```
sudo apt-get install mercurial
```
On Windows you can use the installer: <http://mercurial.selenic.com/wiki/Download>
3. ... |
Unable to install Pygame using pip | 17,869,101 | 60 | 2013-07-25T21:31:29Z | 24,278,506 | 14 | 2014-06-18T06:31:08Z | [
"python",
"pygame",
"install",
"pip"
] | I'm trying to install Pygame. I am running Windows 7 with Enthought Python Distribution. I successfully installed `pip`, but when I try to install Pygame using `pip`, I get the following error:
> "Could not install requirement Pygame because of HTTP error HTTP error
> 400: Bad request for URL ..."
I can't find anythi... | Try doing this:
```
sudo apt-get install mercurial
sudo pip install hg+http://bitbucket.org/pygame/pygame
``` |
Unable to install Pygame using pip | 17,869,101 | 60 | 2013-07-25T21:31:29Z | 34,445,909 | 9 | 2015-12-24T00:56:55Z | [
"python",
"pygame",
"install",
"pip"
] | I'm trying to install Pygame. I am running Windows 7 with Enthought Python Distribution. I successfully installed `pip`, but when I try to install Pygame using `pip`, I get the following error:
> "Could not install requirement Pygame because of HTTP error HTTP error
> 400: Bad request for URL ..."
I can't find anythi... | An update to this may be required, as it stands in version 1.9.1 it should simply install using:
`pip install pygame`
However, it look like there is a bug with their pypi repository, see:
<https://bitbucket.org/pygame/pygame/issues/59/pygame-has-no-pypi-page-and-cant-be>
So, if you want the most recent release, you ... |
scipy.optimize dll load failure on Windows 8 | 17,869,104 | 7 | 2013-07-25T21:31:39Z | 17,891,391 | 9 | 2013-07-26T21:33:03Z | [
"python",
"windows",
"scipy"
] | I am attempting to import scipy.optimize using Python 3.3.1 on Windows 8. I am using scipy-0.12.0. When I attempt to import, Python returns the following error:
```
>>> import scipy.optimize
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\site-packages\scipy\optimize\__... | It may be a problem with using an incompatible version of Numpy. We solved this problem on a computer at work by **using a Numpy-MKL build** from [Christoph Gohlke's website](http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy). This solved our problems on Windows 8 computers, because the builds for Scipy from his website... |
printing a two dimensional array in python | 17,870,612 | 5 | 2013-07-25T23:44:27Z | 17,871,279 | 17 | 2013-07-26T01:05:58Z | [
"python",
"printing"
] | I have to print this python code in a 5x5 array the array should look like this :
```
0 1 4 (infinity) 3
1 0 2 (infinity) 4
4 2 0 1 5
(inf)(inf) 1 0 3
3 4 5 3 0
```
can anyone help me print this table? using indices.
```
for k in range(n):
for i in range(n):
for j in range(n):... | A combination of [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and [`str` joins](http://docs.python.org/2/library/stdtypes.html#str.join) can do the job:
```
inf = float('inf')
A = [[0,1,4,inf,3],
[1,0,2,inf,4],
[4,2,0,1,5],
[inf,inf,1,0,3],
[3,4,5,3... |
If statement in lambdas Python | 17,871,591 | 2 | 2013-07-26T01:49:11Z | 17,871,625 | 12 | 2013-07-26T01:53:21Z | [
"python"
] | I wanted to declare an `if` statement inside a `lambda` function:
Suppose:
```
cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)
```
Is it possible to filter out the 'cat' into `result`? | If you want to filter out all the strings that have `'cat'` in them, then just use
```
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda x: not 'cat' in x.lower(), cells)
['Dog', 'Snake', 'Lion']
```
If you want to keep those that have `'cat'` in them, just remove the `not`.
```
>>> filter(lambda x: 'cat... |
Building Mesa for windows 7. Mesa 9.1 | 17,871,781 | 5 | 2013-07-26T02:11:19Z | 17,917,331 | 15 | 2013-07-29T06:30:10Z | [
"python",
"c",
"opengl",
"mesa"
] | I went through all the steps on the compiling / installing page on Mesa's site, and read the FAQ. The final command that you send to scons for compilation throws errors within python scripts. This is my output. What am I doing wrong? Also if anyone has compiled dll's for mesa using up to date mesa and mingw, or VS2012,... | Common `scons` options:
```
build=release
machine=x86
platform=windows
libgl-gdi
```
1. ~~Linux (Debian Wheezy), `toolchain=crossmingw`: **Fails** during linking phase because it can't find `__vscprintf`, among other things.~~ **Works** as of Debian Jessie 8.5 & Mesa `d2f42a945ec0fbcc51b59cfd329258bd62ebf0d2` via:
... |
How to add Python to Windows registry | 17,872,234 | 20 | 2013-07-26T03:08:40Z | 30,982,219 | 12 | 2015-06-22T14:15:10Z | [
"python",
"registry",
"enthought"
] | I've downloaded Enthought Canopy EPD Free (now Canopy Express) from <https://www.enthought.com/products/epd/free/> and want to install SciKit Learn (<http://sourceforge.net/projects/scikit-learn/files/>) which is not part of the basic EPD Free install.
When trying to install it does not find Python in the Windows regi... | I faced to the same problem. I solved it by
1. navigate to `HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath` and edit the default key with the output of
`C:\> where python.exe` command.
2. navigate to `HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup` and edit the default key w... |
Determine maximum number of columns from sqlite3 | 17,872,665 | 5 | 2013-07-26T03:58:45Z | 17,872,934 | 7 | 2013-07-26T04:31:00Z | [
"python",
"sqlite",
"sqlite3"
] | Is it possible to get the maximum number of columns supported from `sqlite3` at runtime? This database limitation is established with a compile-time variable `SQLITE_MAX_COLUMN` (see [limits](http://www.sqlite.org/limits.html)). The default is normally 2000 columns.
I'm looking for something accessible from either the... | ~~This appears to be impossible in practical terms (i.e. without a very expensive brute-force approach along the lines of dan04's rather brilliant answer).~~
The source ([1](http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/sqlite3), [2](http://hg.python.org/cpython/file/2f4c4db9aee5/Modules/_sqlite)) for the `sqlite... |
Deep copy a list in Python | 17,873,384 | 27 | 2013-07-26T05:12:19Z | 17,873,397 | 57 | 2013-07-26T05:13:22Z | [
"python",
"list",
"copy",
"deep-copy"
] | I have some problem with a List copy:
So After I got `E0` from `'get_edge'`, I make a copy of `E0` by calling `'E0_copy = list(E0)'`. Here I guess `E0_copy` is a deep copy of `E0`, and I pass `E0_copy` into `'karger(E)'`. But in the main function.
Why does the result of `'print E0[1:10]'` before the for loop is not ... | `E0_copy` is not a deep copy. You don't make a deep copy using `list()` (Both `list(...)` and `testList[:]` are shallow copies).
You use [`copy.deepcopy(...)`](http://docs.python.org/2/library/copy.html#copy.deepcopy) for deep copying a list.
```
deepcopy(x, memo=None, _nil=[])
Deep copy operation on arbitrary Py... |
Flask url_for() with multiple parameters | 17,873,820 | 12 | 2013-07-26T05:46:51Z | 17,873,868 | 7 | 2013-07-26T05:51:07Z | [
"python",
"html",
"flask"
] | ### The Problem:
I have an a input button in a form that when its submitted should redirect two parameters , `search_val` and `i`, to a `more_results()` function, (listed below), but I get a type error when wsgi builds.
The error is: `TypeError: more_results() takes exactly 2 arguments (1 given)`
html:
```
<form a... | Your route doesn't specify how to fill in more than just the one `past_val` arg. Flask can't magically create a URL that will pass two arguments if you don't give it a two-argument pattern. |
Flask url_for() with multiple parameters | 17,873,820 | 12 | 2013-07-26T05:46:51Z | 17,874,943 | 27 | 2013-07-26T07:03:14Z | [
"python",
"html",
"flask"
] | ### The Problem:
I have an a input button in a form that when its submitted should redirect two parameters , `search_val` and `i`, to a `more_results()` function, (listed below), but I get a type error when wsgi builds.
The error is: `TypeError: more_results() takes exactly 2 arguments (1 given)`
html:
```
<form a... | It's also possible to create routes that support variable number of arguments, by specifying default values to some of the arguments:
```
@app.route('/foo/<int:a>')
@app.route('/foo/<int:a>/<int:b>')
@app.route('/foo/<int:a>/<int:b>/<int:c>')
def test(a, b=None, c=None):
pass
``` |
Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything | 17,874,360 | 15 | 2013-07-26T06:25:37Z | 17,874,427 | 31 | 2013-07-26T06:30:58Z | [
"python",
"email",
"python-2.7",
"mod-wsgi",
"wsgi"
] | It seems easy to get the
```
From
To
Subject
```
etc via
```
import email
b = email.message_from_string(a)
bbb = b['from']
ccc = b['to']
```
assuming that `"a"` is the raw-email string which looks something like this.
```
a = """From [email protected] Thu Jul 25 19:28:59 2013
Received: from a1.local.tld (localhost... | Use [Message.get\_payload](http://docs.python.org/2/library/email.message#email.message.Message.get_payload)
```
b = email.message_from_string(a)
if b.is_multipart():
for payload in b.get_payload():
# if payload.is_multipart(): ...
print payload.get_payload()
else:
print b.get_payload()
``` |
Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything | 17,874,360 | 15 | 2013-07-26T06:25:37Z | 32,840,516 | 12 | 2015-09-29T09:30:58Z | [
"python",
"email",
"python-2.7",
"mod-wsgi",
"wsgi"
] | It seems easy to get the
```
From
To
Subject
```
etc via
```
import email
b = email.message_from_string(a)
bbb = b['from']
ccc = b['to']
```
assuming that `"a"` is the raw-email string which looks something like this.
```
a = """From [email protected] Thu Jul 25 19:28:59 2013
Received: from a1.local.tld (localhost... | To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.
As the before-mentioned attachments can and very often are of text/plain or ... |
Checking if path is a socket in Python 2.7 | 17,877,296 | 6 | 2013-07-26T09:09:19Z | 17,971,324 | 8 | 2013-07-31T13:08:58Z | [
"python",
"file",
"sockets",
"types",
"path"
] | What would be the best way in Python 2.7 to find out if a path is a socket?
[os.path](http://docs.python.org/2/library/os.path.html) has *is...* functions for [directories](http://docs.python.org/2/library/os.path.html#os.path.isdir), [normal files](http://docs.python.org/2/library/os.path.html#os.path.isfile) and [li... | Well, this is straight forward and works, so I take this as the canonical way. |
Python Subprocess Error in using "cp" | 17,880,847 | 5 | 2013-07-26T12:04:04Z | 17,880,895 | 8 | 2013-07-26T12:06:40Z | [
"python",
"subprocess",
"cp"
] | I was trying to use subprocess calls to perform a copy operation (code below):
```
import subprocess
pr1 = subprocess.call(['cp','-r','./testdir1/*','./testdir2/'], shell = True)
```
and I got an error saying:
```
cp: missing file operand
Try `cp --help' for more information.
```
When I try with `shell=False` , I ... | When using `shell=True`, pass a string, not a list to `subprocess.call`:
```
subprocess.call('cp -r ./testdir1/* ./testdir2/', shell=True)
```
[The docs say](http://docs.python.org/2/library/subprocess.html#subprocess.Popen):
> On Unix with shell=True, the shell defaults to /bin/sh. If args is a
> string, the string... |
Faster way to calculate sum of squared difference between an image (M, N) and a template (3, 3) for template matching? | 17,881,489 | 6 | 2013-07-26T12:36:34Z | 17,885,996 | 8 | 2013-07-26T16:01:55Z | [
"python",
"image-processing",
"numpy",
"scipy",
"vectorization"
] | I am implementing an algorithm for Texture Synthesis as outlined [here](http://graphics.cs.cmu.edu/people/efros/research/NPS/alg.html). For this I need to calculate the Sum of Squared Differences, a metric to estimate the error between the `template` and different positions across the `image`. I have a slow working imp... | This is basically an improvement over Warren Weckesser's answer. The way to go is clearly with a multidimensional windowed view of the original array, but you want to keep that view from triggering a copy. If you expand your `sum((a-b)**2)`, you can turn it into `sum(a**2) + sum(b**2) - 2*sum(a*b)`, and this multiply-t... |
"[:,]" list slicing python, what does it mean? | 17,882,205 | 3 | 2013-07-26T13:10:34Z | 17,882,232 | 10 | 2013-07-26T13:11:45Z | [
"python",
"numpy"
] | I'm reading some code and I see `" list[:,i] for i in range(0,list))......"`
I am mystified as to what comma is doing in there, `:,` and google offers no answers as you cant google punctuation.
Any help greatly appreciated! | You are looking at [`numpy`](http://www.numpy.org/) multidimensional array slicing.
The comma marks a tuple, read it as `[(:, i)]`, which `numpy` arrays interpret as: first dimension to be sliced end-to-end (all rows) with `:`, then for each row, `i` selects *one* column.
See [Indexing, Slicing and Iterating](http://... |
Why won't this python regex compile? | 17,882,893 | 2 | 2013-07-26T13:41:44Z | 17,882,939 | 7 | 2013-07-26T13:43:28Z | [
"python",
"regex"
] | I have a python script with the following regular expression to grab two strings (that may contain escaped quotes) from NSLocalizedString macros in my code:
```
NSLocalizedString\(@"(?:\\.|[^"\\]*)",\s*@"(?:\\.|[^"\\]*)"\s*\)
```
It works fine in RegexRx and matches exactly as expected...
",\s*@"(?:\\.|[^"\\]*)"\s*\)', re.DOTALL)
```
because backslashes have meaning in a regular Python string *too*. A raw string literal (a string literal prefixed with `r`) ignores (most) escape sequences that Python supports.
See [The Back... |
Moving up one directory in Python | 17,885,516 | 14 | 2013-07-26T15:37:37Z | 17,885,558 | 15 | 2013-07-26T15:39:30Z | [
"python",
"directory"
] | Is there a simple way to move up one directory in python using a single line of code? Something similar to `cd ..` in command line | Use the `os` module:
```
import os
os.chdir('..')
```
should work |
Moving up one directory in Python | 17,885,516 | 14 | 2013-07-26T15:37:37Z | 17,885,568 | 16 | 2013-07-26T15:39:55Z | [
"python",
"directory"
] | Is there a simple way to move up one directory in python using a single line of code? Something similar to `cd ..` in command line | ```
>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\
``` |
Moving up one directory in Python | 17,885,516 | 14 | 2013-07-26T15:37:37Z | 17,885,723 | 8 | 2013-07-26T15:47:39Z | [
"python",
"directory"
] | Is there a simple way to move up one directory in python using a single line of code? Something similar to `cd ..` in command line | Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: <https://pypi.python.org/pypi/Unipath>
so that you could do some... |
Setting Cell Formats with xlwt format strings | 17,887,160 | 8 | 2013-07-26T17:08:19Z | 18,137,254 | 11 | 2013-08-08T22:28:10Z | [
"python",
"python-2.7",
"xlwt"
] | I've looked around for several different xlwt formats for cells, but I can't find a comprehensive list.
Excel provides the following options for cell content formatting:
(general, number, currency, accounting, date, time, percentage, fraction, scientific, text, special, custom)
Obviously custom isn't what I want, but w... | I've found a list. I was just being stupid about looking for it.
The GitHub project has a list of number format strings here:
<https://github.com/python-excel/xlwt/blob/master/examples/num_formats.py> |
Python: BaseHTTPRequestHandler - Read raw post | 17,888,504 | 4 | 2013-07-26T18:28:20Z | 20,879,937 | 9 | 2014-01-02T09:34:14Z | [
"python",
"httpserver",
"basehttpserver",
"basehttprequesthandler"
] | How do I read the raw http post STRING. I've found several solutions for reading a parsed version of the post, however the project I'm working on submits a raw xml payload without a header. So I am trying to find a way to read the post data without it being parsed into a key => value array. | `self.rfile.read(int(self.headers.getheader('Content-Length')))` will return the raw HTTP POST data as a string.
Breaking it down:
1. The header 'Content-Length' specifies how many bytes the HTTP POST data contains.
2. `self.headers.getheader('Content-Length')` returns the content length (value of the header) as a st... |
How to delete everything after a certain character in a string? | 17,891,443 | 7 | 2013-07-26T21:37:08Z | 17,891,495 | 9 | 2013-07-26T21:41:00Z | [
"python",
"string",
"character",
"python-3.3"
] | How would I delete everything after a certain character of a string in python? For example I have a string containing a file path and some extra characters. How would I delete everything after .zip? I've tried `rsplit` and `split` , but neither included the .zip when deleting extra characters.
Any suggestions? | Just take the first portion of the split, and add `'.zip'` back:
```
s = 'test.zip.zyz'
s = s.split('.zip', 1)[0] + '.zip'
```
Alternatively you could use slicing, here is a solution where you don't need to add `'.zip'` back to the result (the `4` comes from `len('.zip')`):
```
s = s[:s.index('.zip')+4]
```
Or anot... |
How to delete everything after a certain character in a string? | 17,891,443 | 7 | 2013-07-26T21:37:08Z | 17,891,558 | 8 | 2013-07-26T21:47:51Z | [
"python",
"string",
"character",
"python-3.3"
] | How would I delete everything after a certain character of a string in python? For example I have a string containing a file path and some extra characters. How would I delete everything after .zip? I've tried `rsplit` and `split` , but neither included the .zip when deleting extra characters.
Any suggestions? | `str.partition`:
```
>>> s='abc.zip.blech'
>>> ''.join(s.partition('.zip')[0:2])
'abc.zip'
>>> s='abc.zip'
>>> ''.join(s.partition('.zip')[0:2])
'abc.zip'
>>> s='abc.py'
>>> ''.join(s.partition('.zip')[0:2])
'abc.py'
``` |
Annotating points from a Pandas Dataframe in Matplotlib plot | 17,891,493 | 6 | 2013-07-26T21:40:58Z | 17,901,942 | 9 | 2013-07-27T20:00:03Z | [
"python",
"matplotlib",
"pandas"
] | Given a `DataFrame` like:
```
LIST_PRICE SOLD_PRICE
MOYRLD
1999-03-31 317062.500000 314800
1999-06-30 320900.000000 307100
1999-09-30 400616.666667 366160
1999-12-31 359900.000000 NaN
2000-03-31 359785.714286 330750
```
Using the code:
```
import matplotlib.dates as mdates... | You can access the index values with the `index` attribute of the `DataFrame`. So you can simply use
```
ax3.annotate('Test',
(df5.index[1], df5['SOLD_PRICE'][1]),
xytext=(15, 15),
textcoords='offset points',
arrowprops=dict(arrowstyle='-|>'))
```
This gives (based... |
Pip install error. Setuptools.command not found | 17,892,071 | 10 | 2013-07-26T22:33:51Z | 17,892,100 | 16 | 2013-07-26T22:37:57Z | [
"python",
"python-2.7",
"pip",
"pymongo"
] | I'm using a clean instance of Ubuntu server and would like to install some python packages in my virtualenv.
I receive the following output from the command 'pip install -r requirements.txt'
```
Downloading/unpacking pymongo==2.5.2 (from -r requirements.txt (line 7))
Downloading pymongo-2.5.2.tar.gz (303kB): 303kB ... | Try installing:
```
sudo apt-get install python-setuptools
```
if this doesn't work try:
```
curl -O https://bootstrap.pypa.io/get-pip.py
python get-pip.py
```
**Edit:** If you have several (possible conflicting) python installations or environments, the following commands can be useful to debug which executables a... |
Reference Static Images From Javascript in Django | 17,893,101 | 4 | 2013-07-27T00:40:09Z | 17,893,349 | 8 | 2013-07-27T01:22:17Z | [
"python",
"django",
"django-staticfiles"
] | So I'm working on a Django project and am trying to figure out how to get Javascript to be able to render images from my static directory. I've modified my settings.py to load static files (images, js, etc.) from myproject/static and my templates from myproject/templates. Now at the top of each of these templates I hav... | `getHeader.js` is not related to django in any way. It's just a text file being loaded by the browser. Therefore it's not aware of django syntax like {% static %} or {{ foo }}.
There are a few ways around this.. a common way is to define a global javascript variable which is your `STATIC_URL` which you can then refere... |
ptrepack sortby needs 'full' index | 17,893,370 | 3 | 2013-07-27T01:25:18Z | 17,959,914 | 8 | 2013-07-31T01:00:08Z | [
"python",
"pandas",
"pytables"
] | I am trying to ptrepack a HDF file that was created with pandas HDFStore pytables interface.
The main index of the dataframe was time but I made some more columns `data_columns` so that I can filter for data on-disk via these data\_columns.
Now I would like to sort the HDF file by one of those columns (because the sel... | I have tested several of the options Jeff mentions in our chatty discussions above.
Please have a look at this notebook, hopefully it will help you to make relevant decisions for your data storage: <http://nbviewer.ipython.org/810bd0720bb1732067ff>
The gist for the notebook is here: <https://gist.github.com/michaelaye... |
format strings and named arguments in Python | 17,895,835 | 19 | 2013-07-27T08:29:40Z | 17,895,844 | 37 | 2013-07-27T08:30:50Z | [
"python",
"string",
"arguments",
"string-formatting"
] | **Case 1:**
```
"{arg1} {arg2}".format (10, 20)
```
It will give `KeyError: 'arg1'` because I didn't pass the named arguments.
**Case 2:**
```
"{arg1} {arg2}".format(arg1 = 10, arg2 = 20)
```
Now it will work properly because I passed the named arguments.
And it prints `'10 20'`
**Case 3:**
And, If I pass wrong ... | Named replacement fields (the `{...}` parts in a [format string](http://docs.python.org/2/library/string.html#format-string-syntax) match against *keyword arguments* to the `.format()` method, and not *positional arguments*.
Keyword arguments are like keys in a dictionary; order doesn't matter, as they are matched aga... |
Python regex with slash | 17,899,848 | 2 | 2013-07-27T16:11:04Z | 17,899,873 | 8 | 2013-07-27T16:14:28Z | [
"python",
"regex"
] | Why does
```
len(re.findall('[0-9999][/][0-9999]', '15/11/2012'))
```
correctly return 2, but
```
len(re.findall('[0-9999][/][0-9999][/]', '15/11/2012'))
```
return 0? Shouldnât it return 1? | You're misunderstanding character classes. The expression, `[abc123]` matches a *single* character—namely one of the characters in the bracket. The `-` is a *range operator* in character classes, but regular expressions are not aware of *numeric* ranges, only *string* ranges. In other words, `[0-9999]` is equivalent to... |
Represent a tree hierarchy using an Excel spreadsheet to be easily parsed by Python CSV reader? | 17,900,112 | 8 | 2013-07-27T16:38:41Z | 17,902,474 | 9 | 2013-07-27T21:08:01Z | [
"python",
"excel",
"csv",
"tree",
"hierarchy"
] | I have a non-technical client who has some hierarchical product data that I'll be loading into a tree structure with Python. The tree has a variable number of levels, and a variable number nodes and leaf nodes at each level.
The client already knows the hierarchy of products and would like to put everything into an Ex... | For future readers, I ended up using a column-based hierarchy where each row is the complete traversal to a leaf. So you end up with as many rows as there are leafs.
```
Electronics | Computers | Laptops
Electronics | Computers | Desktop
Electronics | Game Systems | Xbox
Electronics | Game Systems | PS3
Electron... |
Numpy argsort - what is it doing? | 17,901,218 | 36 | 2013-07-27T18:44:55Z | 17,901,248 | 12 | 2013-07-27T18:47:52Z | [
"python",
"numpy"
] | Why is numpy giving this result:
```
x = numpy.array([1.48,1.41,0.0,0.1])
print x.argsort()
>[2 3 1 0]
```
when I'd expect it to do this:
> [3 2 0 1]
Clearly my understanding of the function is lacking. | `[2, 3, 1, 0]` indicates that the smallest element is at index 2, the next smallest at index 3, then index 1, then index 0.
There are [a number of ways](http://stackoverflow.com/q/5284646/190597) to get the result you are looking for:
```
import numpy as np
import scipy.stats as stats
def using_indexed_assignment(x)... |
Numpy argsort - what is it doing? | 17,901,218 | 36 | 2013-07-27T18:44:55Z | 17,901,252 | 32 | 2013-07-27T18:48:07Z | [
"python",
"numpy"
] | Why is numpy giving this result:
```
x = numpy.array([1.48,1.41,0.0,0.1])
print x.argsort()
>[2 3 1 0]
```
when I'd expect it to do this:
> [3 2 0 1]
Clearly my understanding of the function is lacking. | According to [the documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy-argsort)
> Returns the indices that would sort an array.
* `2` is the index of `0.0`.
* `3` is the index of `0.1`.
* `1` is the index of `1.41`.
* `0` is the index of `1.48`. |
Django - How to make a variable available to all templates? | 17,901,341 | 23 | 2013-07-27T18:58:17Z | 17,901,516 | 51 | 2013-07-27T19:15:44Z | [
"python",
"django",
"django-nonrel"
] | I would like to know how to pass a variable to all my templates, without repeating the same code on every method in my views.py file?
In the example below I would like to make categories (an array of category objects) available to all templates in the web app.
```
Eg: I would like to avoid writing 'categories':catego... | What you want It's a `TEMPLATE_CONTEXT_PROCESSORS` and it's very easy to create one for example assuming you have got an app named `custom_app` you have to follow the next steps to create one.
* Add `custom_app` to `INSTALLED_APPS` in `settings.py`
* Create a `context_processors.py` into `custom_app` folder.
* Add the... |
Gradient calculation with python | 17,901,363 | 5 | 2013-07-27T18:59:41Z | 17,902,449 | 18 | 2013-07-27T21:04:27Z | [
"python",
"numpy",
"gradient"
] | I would like to know how does `numpy.gradient` work.
I used gradient to try to calculate *group velocity* (group velocity of a wave packet is the derivative of frequencies respect to wavenumbers, not a group of velocities). I fed a 3 column array to it, the first 2 colums are x and y coords, the third column is the fre... | You need to give `gradient` a matrix that describes your angular frequency values for your `(x,y)` points. e.g.
```
def f(x,y):
return np.sin((x + y))
x = y = np.arange(-5, 5, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([f(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
gx,gy = np.gradien... |
Python testing whether a string is one of a certain set of values | 17,902,492 | 4 | 2013-07-27T21:10:24Z | 17,902,498 | 8 | 2013-07-27T21:11:13Z | [
"python",
"string",
"equality"
] | I'm learning python on codecademy and my current task is this:
> Write a function, shut\_down, that takes one parameter (you can use
> anything you like; in this case, we'd use s for string). The shut\_down
> function should return **"Shutting down..."** when it gets **"Yes"**, **"yes"**,
> or **"YES"** as an argument... | You forgot to write `s == "no"` in your first `elif:`
```
def shut_down(s):
if s == "Yes" or s == "yes" or s == "YES":
return "Shutting down..."
elif s == "No" or "no" or "NO": # you forgot the s== in this line
return "Shutdown aborted!"
else:
return "Sorry, I didn't un... |
multiprocessing pool.map call functions in certain order | 17,903,355 | 13 | 2013-07-27T23:07:54Z | 17,904,154 | 11 | 2013-07-28T01:32:14Z | [
"python",
"parallel-processing",
"multiprocessing",
"map-function"
] | How can I make multiprocessing.pool.map distribute processes in numerical order?
---
More Info:
I have a program which processes a few thousand data files, making a plot of each one. I'm using a `multiprocessing.pool.map` to distribute each file to a processor and it works great. Sometimes this takes a long time, a... | The reason that this occurs is because each process is given a predefined amount of work to do at the start of the call to map which is dependant on the `chunksize`. We can work out the default `chunksize` by looking at the source for [pool.map](http://hg.python.org/cpython/file/1c54def5947c/Lib/multiprocessing/pool.py... |
Using GeopositionField to find closest database entries | 17,903,883 | 2 | 2013-07-28T00:40:41Z | 17,944,261 | 8 | 2013-07-30T10:16:10Z | [
"python",
"django",
"geolocation",
"geocoding",
"django-geoposition"
] | I am using [GeopositionField](https://github.com/philippbosch/django-geoposition/blob/master/docs/index.rst) in Django to store the coordinates of my user. Now I want to find a list of 20 users who are closest to current user. Can that functionality be acheaved my GeopositionField? I know that GeoDjango makes it easy t... | For the distance between two points you can use Geopy.
From the [documetation](https://code.google.com/p/geopy/wiki/GettingStarted#Calculating_distances):
Here's an example usage of distance.distance:
```
>>> from geopy import distance
>>> _, ne = g.geocode('Newport, RI')
>>> _, cl = g.geocode('Cleveland, OH')
... |
Python - difference between two strings | 17,904,097 | 13 | 2013-07-28T01:22:19Z | 17,904,977 | 26 | 2013-07-28T04:25:44Z | [
"python",
"string",
"python-3.x",
"diff"
] | I'd like to store a lot of words in a list. Many of these words are very similar. For example I have word `afrykanerskojÄzyczny` and many of words like `afrykanerskojÄzycznym`, `afrykanerskojÄzyczni`, `nieafrykanerskojÄzyczni`. What is the effective (fast and giving small diff size) solution to find difference betw... | You can use [ndiff](http://docs.python.org/2/library/difflib.html#difflib.ndiff) in the difflib module to do this. It has all the information necessary to convert one string into another string.
A simple example:
```
import difflib
cases=[('afrykanerskojÄzyczny', 'afrykanerskojÄzycznym'),
('afrykanerskojÄz... |
Handling tcpdump output in python | 17,904,231 | 5 | 2013-07-28T01:48:54Z | 17,904,501 | 8 | 2013-07-28T02:44:02Z | [
"python",
"subprocess",
"popen",
"tcpdump"
] | Im trying to handle tcpdump output in python.
What I need is to run tcpdump (which captures the packets and gives me information) and read the output and process it.
The problem is that tcpdump keeps running forever and I need to read the packet info as soon as it outputs and continue doing it.
I tried looking into ... | You can make tcpdump line-buffered with "-l". Then you can use subprocess to capture the output as it comes out.
```
import subprocess as sub
p = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
print row.rstrip() # process here
``` |
Django Python: global name 'render' is not defined | 17,906,075 | 2 | 2013-07-28T07:40:36Z | 17,906,082 | 10 | 2013-07-28T07:41:31Z | [
"python",
"django",
"render"
] | I am getting an error in my Django project, and it looks like it's coming from my views.py file:
```
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def get_date_time(request):
now = datetime.datetime.now()
return render(... | You need to import [`render`](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render) from [`django.shortcuts`](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#module-django.shortcuts) as it is not a built-in function.:
```
from django.shortcuts import render
``` |
How do I start writing or creating an app for leap motion? (python) | 17,906,305 | 4 | 2013-07-28T08:12:56Z | 17,912,517 | 7 | 2013-07-28T20:23:38Z | [
"python",
"python-2.7",
"leap-motion"
] | I have tried googling this, but it is a lot of programming talk i do not necessarily completely understand. All i have done so far is download the SDK for Leap Motion and found that programs can be written with python. which is a programming language i am somewhat familiar with.
From the samples on the SDK it seems it... | ~~To begin, here's the Leap Motion Python documentation overview:
<https://developer.leapmotion.com/documentation/Languages/Python/Guides/Leap_Overview.html>~~
~~You can find Leap.py within the LeapSDK/lib/ directory. Review the following link for information about the file structure of the Leap Motion SDK:
<https://d... |
How to find k biggest numbers from a list of n numbers assuming n > k | 17,906,949 | 2 | 2013-07-28T09:45:23Z | 17,907,220 | 7 | 2013-07-28T10:21:03Z | [
"python",
"list",
"max"
] | I am looking for some code in Python which could return `k` largest numbers from an unsorted list of `n` numbers. First I thought to do this by sorting the list first, but this might turn out to be very bulky.
For example the list from which I want to find `k` largest number be `list1`
```
> list1 = [0.5, 0.7, 0.3, 0... | Python has all batteries included - use [`heapq`](http://docs.python.org/2/library/heapq.html) module :)
```
from heapq import nlargest
data = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
print nlargest(3, data)
```
it's also faster than sorting the whole array, because it's using partial heapsort |
Sphinx doesn't find Python packages when using autodoc | 17,907,609 | 13 | 2013-07-28T11:10:24Z | 17,908,262 | 17 | 2013-07-28T12:37:06Z | [
"python",
"documentation",
"python-sphinx"
] | I'm trying to create documentation for test Python project before doing it for the real project.
My system : Win7 64 bit, python 2.7.5 64 bit.
My project name is **testDoc**. It includes python pakage, named **t**, which includes 2 modules **t1** and **t2** and `__init__.py`.
`__init__.py` contains:
```
import t1
im... | I don't know what the "absolute path to testDoc" is, but from the Sphinx output I can see that the testDoc directory structure is `testDoc/t/docs`. The `docs` directory is where conf.py is.
For the module search path to be set up properly, you need to go two levels up from conf.py:
```
sys.path.insert(0, os.path.absp... |
Why does Python remove the last character of a string? | 17,908,531 | 2 | 2013-07-28T13:07:50Z | 17,908,545 | 8 | 2013-07-28T13:08:47Z | [
"python",
"strip"
] | For example, if I do this `str(bin(66))` I get `0b1000010`, but if I do this `str(bin(66)).strip("0b")`, I get `100001` (notice the missing '0').
I think I'm misusing the strip function. | `strip` strips characters from both sides. Use `lstrip` to only strip characters from the left-hand side.
```
In [27]: str(bin(66)).strip("0b")
Out[27]: '100001'
In [28]: str(bin(66)).lstrip("0b")
Out[28]: '1000010'
```
Alternatively, just use the `format` method:
```
In [38]: '{:b}'.format(66)
Out[38]: '1000010'
`... |
Python argparse mutual exclusive group | 17,909,294 | 43 | 2013-07-28T14:37:17Z | 17,909,525 | 46 | 2013-07-28T14:59:21Z | [
"python",
"argparse"
] | What I need is:
```
pro [-a xxx | [-b yyy -c zzz]]
```
I tried this but does not work. Could someone help me out?
```
group= parser.add_argument_group('Model 2')
group_ex = group.add_mutually_exclusive_group()
group_ex.add_argument("-a", type=str, action = "store", default = "", help="test")
group_ex_2 = group_ex.ad... | `add_mutually_exclusive_group` doesn't make an entire group mutually exclusive. It makes options within the group mutually exclusive.
What you're looking for is [subcommands](http://docs.python.org/dev/library/argparse.html#sub-commands). Instead of prog [ -a xxxx | [-b yyy -c zzz]], you'd have:
```
prog
command 1... |
Python argparse mutual exclusive group | 17,909,294 | 43 | 2013-07-28T14:37:17Z | 27,675,614 | 11 | 2014-12-28T10:38:16Z | [
"python",
"argparse"
] | What I need is:
```
pro [-a xxx | [-b yyy -c zzz]]
```
I tried this but does not work. Could someone help me out?
```
group= parser.add_argument_group('Model 2')
group_ex = group.add_mutually_exclusive_group()
group_ex.add_argument("-a", type=str, action = "store", default = "", help="test")
group_ex_2 = group_ex.ad... | While [Jonathan's answer](http://stackoverflow.com/a/17909525/492620) is perfectly fine for complex options, there is a very simple solution which will work for the simple cases, e.g. 1 option excludes 2 other options like in
```
command [- a xxx | [ -b yyy | -c zzz ]]
```
or even as in the original question:
```
pr... |
Append integer to beginning of list in Python | 17,911,091 | 99 | 2013-07-28T17:54:33Z | 17,911,094 | 126 | 2013-07-28T17:55:11Z | [
"python",
"list",
"variables",
"append"
] | I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list.
Writing `a + list` I get errors. The compiler handles `a` as integer, thus I cannot use append, or extend either.
How would you do this? | ```
>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li # Don't use 'list' as variable name.
[5, 1, 2, 3]
``` |
Append integer to beginning of list in Python | 17,911,091 | 99 | 2013-07-28T17:54:33Z | 17,911,209 | 160 | 2013-07-28T18:07:05Z | [
"python",
"list",
"variables",
"append"
] | I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list.
Writing `a + list` I get errors. The compiler handles `a` as integer, thus I cannot use append, or extend either.
How would you do this? | ```
>>>var=7
>>>array = [1,2,3,4,5,6]
>>>array.insert(0,var)
>>>array
[7, 1, 2, 3, 4, 5, 6]
```
How it works:
`array.insert(i, x)`
Insert an item at a given position. The first argument is the index of the element before which to insert, so `array.insert(0, x)` inserts at the front of the list, and `array.insert(len... |
Append integer to beginning of list in Python | 17,911,091 | 99 | 2013-07-28T17:54:33Z | 17,911,515 | 17 | 2013-07-28T18:38:16Z | [
"python",
"list",
"variables",
"append"
] | I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list.
Writing `a + list` I get errors. The compiler handles `a` as integer, thus I cannot use append, or extend either.
How would you do this? | Another way of doing the same,
```
list[0:0] = [a]
``` |
Append integer to beginning of list in Python | 17,911,091 | 99 | 2013-07-28T17:54:33Z | 36,529,893 | 14 | 2016-04-10T12:44:28Z | [
"python",
"list",
"variables",
"append"
] | I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list.
Writing `a + list` I get errors. The compiler handles `a` as integer, thus I cannot use append, or extend either.
How would you do this? | Note that if you are trying to do that operation often, especially in loops, **a list is the wrong data structure**.
Lists are not optimized for modifications at the front, and `somelist.insert(0, something)` is an [O(n) operation](https://wiki.python.org/moin/TimeComplexity).
`somelist.pop(0)` and `del somelist[0]` ... |
Is it possible to define a class constant inside an Enum? | 17,911,188 | 28 | 2013-07-28T18:05:21Z | 18,035,135 | 19 | 2013-08-03T16:49:40Z | [
"python",
"python-3.x",
"enums",
"constants",
"class-constants"
] | Python 3.4 introduces a new module [`enum`](http://docs.python.org/3.4/library/enum.html), which adds an [enumerated type](http://en.wikipedia.org/wiki/Enumerated_type) to the language. The documentation for `enum.Enum` provides [an example](http://docs.python.org/3.4/library/enum.html#planet) to demonstrate how it can... | This is advanced behavior which will not be needed in 90+% of the enumerations created.
According to the docs:
> The rules for what is allowed are as follows: `_sunder_` names (starting and ending with a single underscore) are reserved by enum and cannot be used; all other attributes defined within an enumeration wil... |
Is it possible to define a class constant inside an Enum? | 17,911,188 | 28 | 2013-07-28T18:05:21Z | 18,075,283 | 9 | 2013-08-06T08:33:26Z | [
"python",
"python-3.x",
"enums",
"constants",
"class-constants"
] | Python 3.4 introduces a new module [`enum`](http://docs.python.org/3.4/library/enum.html), which adds an [enumerated type](http://en.wikipedia.org/wiki/Enumerated_type) to the language. The documentation for `enum.Enum` provides [an example](http://docs.python.org/3.4/library/enum.html#planet) to demonstrate how it can... | The most elegant solution (IMHO) is to use mixins / base class to provide the correct behavior.
* base class to provide the behavior that's needed for all implementation that's common to e.g. `Satellite` and `Planet`.
* [mixins are interesting](http://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they... |
add element with attributes in minidom python | 17,911,674 | 6 | 2013-07-28T18:53:59Z | 20,547,348 | 8 | 2013-12-12T15:22:19Z | [
"python",
"python-2.7",
"attributes",
"minidom"
] | I want to add a child node with attributes to a specific tag. my xml is
```
<deploy>
</deploy>
```
and the output should be
```
<deploy>
<script name="xyz" action="stop"/>
</deploy>
```
so far my code is:
```
dom = parse("deploy.xml")
script = dom.createElement("script")
dom.childNodes[0].appendChild(script)
dom... | [xml.dom.Element.setAttribute](http://docs.python.org/2/library/xml.dom.html?highlight=setattribute#xml.dom.Element.setAttribute)
```
xmlFile = minidom.parse( FILE_PATH )
for script in SCRIPTS:
newScript = xmlFile.createElement("script")
newScript.setAttribute("name" , script.name)
newScript.setAttribu... |
Python Global Variable not updating | 17,911,831 | 4 | 2013-07-28T19:09:37Z | 17,911,839 | 8 | 2013-07-28T19:10:22Z | [
"python"
] | Im new with Python and programming but cant seem to understand why this function does not update the global variable
```
global weight
weight = 'value'
def GetLiveWeight():
SetPort()
while interupt == False:
port.write(requestChar2)
liveRaw = port.read(9)
liveRaw += port.read(port.inWai... | You need to declare that `weight` is global *inside* `GetLiveWeight`, not outside it.
```
weight = 'value'
def GetLiveWeight():
global weight
```
The [`global` statement](http://docs.python.org/2/reference/simple_stmts.html#the-global-statement) tells Python that within the scope of the `GetLiveWeight` function, ... |
Selenium (with python) how to modify an element css style | 17,911,980 | 11 | 2013-07-28T19:27:08Z | 17,912,095 | 8 | 2013-07-28T19:40:14Z | [
"python",
"selenium",
"selenium-webdriver"
] | I'm trying to change CSS style of an element (example: from `"visibility: hidden;"` to `"visibility: visible;"`) using selenium `.execute_script`. (any other method through selenium+python would be accepted gracefully).
my code:
```
driver = webdriver.Firefox()
driver.get("http://www.example.com")
elem = driver.find... | Here is an example without using any jQuery. It will hide Google's logo.
```
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.google.com")
driver.execute_script("document.getElementById('lga').style.display = 'none';")
```
The same idea could be used to show a hidden element by setti... |
u'\ufeff' in Python string | 17,912,307 | 19 | 2013-07-28T20:02:46Z | 17,912,811 | 30 | 2013-07-28T20:56:17Z | [
"python"
] | I get an error with the following patter:
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 155: ordinal not in range(128)
```
Not sure what `u'\ufeff'` is, it shows up when I'm web scraping. How can I remedy the situation? The `.replace()` string method doesn't work on it. | The Unicode character `U+FEFF` is the byte order mark, or BOM, and is used to tell the difference between big- and little-endian UTF-16 encoding. If you decode the web page using the right codec, Python will remove it for you. Examples:
```
#!python2
#coding: utf8
u = u'ABC'
e8 = u.encode('utf-8') # encode with... |
concatenate all items from two lists in Python | 17,912,661 | 2 | 2013-07-28T20:40:47Z | 17,912,695 | 13 | 2013-07-28T20:44:31Z | [
"python"
] | I want to produce a list of possible websites from two lists:
```
strings = ["string1", "string2", "string3"]
tlds = ["com', "net", "org"]
```
to produce the following output:
```
string1.com
string1.net
string1.org
string2.com
string2.net
string2.org
```
I've got to this:
```
for i in strings:
print... | `itertools.product` is designed for this purpose.
```
url_tuples = itertools.product(strings, tlds)
urls = ['.'.join(url_tuple) for url_tuple in url_tuples]
print(urls)
``` |
Fitting data using UnivariateSpline in scipy python | 17,913,330 | 7 | 2013-07-28T21:58:36Z | 17,914,134 | 17 | 2013-07-28T23:38:07Z | [
"python",
"numpy",
"scipy",
"curve-fitting"
] | I have a experimental data to which I am trying to fit a curve using UnivariateSpline function in scipy. The data looks like:
```
x y
13 2.404070
12 1.588134
11 1.760112
10 1.771360
09 1.860087
08 1.955789
07 1.910408
06 1.655911
05 1.778952
04 2.624719
03 1.698099
02 3.022... | There are a few issues.
The first issue is the order of the x values. From the documentation for `scipy.interpolate.UnivariateSpline` we find
```
x : (N,) array_like
1-D array of independent input data. MUST BE INCREASING.
```
Stress added by me. For the data you have given the x is in the reversed order.
To deb... |
Nested dictionary comprehension python | 17,915,117 | 7 | 2013-07-29T02:14:44Z | 17,915,141 | 10 | 2013-07-29T02:17:46Z | [
"python",
"syntax",
"nested",
"list-comprehension",
"dictionary-comprehension"
] | I'm having trouble understanding nested dictionary comprehensions in Python 3. The result I'm getting from the example below outputs the correct structure without error, but only includes one of the inner key: value pairs. I haven't found an example of a nested dictionary comprehension like this; Googling "nested dicti... | `{inner_k: myfunc(inner_v)}` isn't a dictionary comprehension. It's just a dictionary.
You're probably looking for something like this instead:
```
data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()}
```
For the sake of readability, don't ne... |
Nested dictionary comprehension python | 17,915,117 | 7 | 2013-07-29T02:14:44Z | 17,915,192 | 11 | 2013-07-29T02:26:49Z | [
"python",
"syntax",
"nested",
"list-comprehension",
"dictionary-comprehension"
] | I'm having trouble understanding nested dictionary comprehensions in Python 3. The result I'm getting from the example below outputs the correct structure without error, but only includes one of the inner key: value pairs. I haven't found an example of a nested dictionary comprehension like this; Googling "nested dicti... | Adding some line-breaks and indentation:
```
data = {
outer_k: {inner_k: myfunc(inner_v)}
for outer_k, outer_v in outer_dict.items()
for inner_k, inner_v in outer_v.items()
}
```
... makes it obvious that you actually have a single, "2-dimensional" dict comprehension. What you actually want is probably:
... |
Load iPython with custom packages imported | 17,915,385 | 5 | 2013-07-29T02:55:04Z | 17,925,836 | 7 | 2013-07-29T13:49:43Z | [
"python",
"python-2.7",
"automation",
"ipython"
] | Does anyone know if it is possible to load ipython preloaded with custom packages please?
I'm running Python 2.7 on Windows 8.
When I load a DOS prompt, I run ipython preloaded with pylab by typing
```
ipython --pylab
```
I've managed to create a shortcut to open a DOS prompt with this automatically fired, thus eff... | What you want is a startup script.
First run `ipython locate profile` to find the profile folder. Then find a `startup` folder in there. Create a .py file (any name) in the startup folder with the imports you want, and IPython will run that whenever you it starts. |
Python code evaluation order? | 17,915,994 | 2 | 2013-07-29T04:22:12Z | 17,916,002 | 10 | 2013-07-29T04:23:17Z | [
"python",
"order-of-evaluation"
] | The output of following code is
```
5
3
```
I am new to Python, could anybody explain to me why?
```
import sys
def Main():
str='1+2'
print eval(str)
class A:
def __init__(self):
self.x = 5
a = A()
print a.x
if __name__=="__main__":
Main()
``` | Python code is evaluated from top-down, not from `Main()`.
The interpreter sees the `a = A()` line first, and prints `a.x` which is equal to 5, then it checks for the `if` condition and prints `eval(str)` which is `3`.
Hence the output,
```
5
3
``` |
Permission denied on git repository with Fabric | 17,916,273 | 2 | 2013-07-29T04:51:36Z | 17,924,417 | 7 | 2013-07-29T12:44:06Z | [
"python",
"git",
"fabric"
] | I'm writing a fab script to do a `git pull` on a remote server, but I get `Permission denied (publickey,keyboard-interactive).` when fabric runs the command.
If I ssh to the server and then do the pull, it works. (I've already setup the keys on the server, so it doesn't ask for passphrases, etc.)
Here's my fabric tas... | you need to edit fabfile like this in order to enable ssh agent fowarding option.
```
from fabric.api import *
env.hosts = ['123.456.789.101']
env.user = 'John'
env.key_filename = '/Users/John/.ssh/google_compute_engine'
env.forward_agent = True
def update():
'''
update workers code
'''
with cd('~/myrepo'):
... |
How named tuples are implemented internally in python? | 17,916,853 | 5 | 2013-07-29T05:49:19Z | 17,917,050 | 12 | 2013-07-29T06:05:56Z | [
"python",
"tuples",
"namedtuple"
] | Named tuples are easy to create, lightweight object types. `namedtuple` instances can be referenced using object-like variable deferencing or the standard tuple syntax. If these data structures can be accessed both by object deferencing & indexes, how are they implemented internally? Is it via hash tables? | Actually, it's very easy to find out how a given `namedtuple` is implemented: if you pass the keyword argument `verbose=True` when creating it, its class definition is printed:
```
>>> Point = namedtuple('Point', "x y", verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import item... |
How to install Flask on Windows? | 17,917,254 | 13 | 2013-07-29T06:24:35Z | 17,917,380 | 29 | 2013-07-29T06:33:14Z | [
"python",
"flask"
] | I have a project to do for after create a webpage that display the latest weather from my CSV file.
I would like some details how to do it *(don't really get the <http://flask.pocoo.org/docs/installation/#installation> installation setup)*
Can anyone mind explain me how to do it simply?
Thanks.
I'm running on Windo... | Install pip as described here: [How to install pip on windows?](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows)
Then do
```
pip install flask
```
That installation tutorial is a bit misleading, it refers to actually running it in a production environment. |
How to query MultiIndex index columns values in pandas | 17,921,010 | 9 | 2013-07-29T09:56:50Z | 18,103,894 | 21 | 2013-08-07T12:51:15Z | [
"python",
"pandas",
"indexing",
"slice",
"multi-index"
] | Code example:
```
In [171]: A = np.array([1.1, 1.1, 3.3, 3.3, 5.5, 6.6])
In [172]: B = np.array([111, 222, 222, 333, 333, 777])
In [173]: C = randint(10, 99, 6)
In [174]: df = pd.DataFrame(zip(A, B, C), columns=['A', 'B', 'C'])
In [175]: df.set_index(['A', 'B'], inplace=True)
In [176]: df
Out[176]:
C
A... | To query the *df* by the *MultiIndex* values, for example where *(A > 1.7) and (B < 666)*:
```
In [536]: result_df = df.loc[(df.index.get_level_values('A') > 1.7) & (df.index.get_level_values('B') < 666)]
In [537]: result_df
Out[537]:
C
A B
3.3 222 43
333 59
5.5 333 56
```
Hence, to get for... |
table polls_choice has no column named poll_id | 17,922,198 | 4 | 2013-07-29T10:55:20Z | 17,922,608 | 9 | 2013-07-29T11:15:44Z | [
"python",
"django",
"sqlite"
] | I'm on part 2 of the Django tutorial. This is the error I get when try to add a "choice" in Django administration
```
DatabaseError: table polls_choice has no column named poll_id
```
This is what I get when I run the command
```
python manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
"id" integer NOT NUL... | It sounds like you added the poll foreign key after you ran syncdb. The `syncdb` creates the table, but does not do migrations if you add/change/remove fields.
For Django 1.7+, you should use migrations instead of syncdb. For Django < 1.7, [south](http://south.aeracode.org/) is highly recommended for doing database mi... |
pylint doesn't point to virtualenv python | 17,923,090 | 9 | 2013-07-29T11:41:51Z | 17,924,034 | 18 | 2013-07-29T12:27:28Z | [
"python",
"virtualenv",
"pylint"
] | I am pretty new to python and currenty I am trying to use pylint for checking code quality. I am getting a problem. My pylint doesn't point to virtualenv python interpreter. Here is the output that I get when I run pylint --version
```
$ pylint --version
pylint 0.21.1,
astng 0.20.1, common 0.50.3
Python 2.6.... | A cheap trick is to run (the global) pylint using the virtualenv python. You can do this using `python $(which pylint)` instead of just `pylint`. On zsh, you can also do `python =pylint`. |
Can't upgrade Scipy | 17,925,381 | 9 | 2013-07-29T13:28:03Z | 17,926,782 | 12 | 2013-07-29T14:33:03Z | [
"python",
"scipy",
"upgrade"
] | I'm trying to upgrade `Scipy` from `0.9.0` to `0.12.0`. I use the command:
```
sudo pip install --upgrade scipy
```
and I get all sorts of errors which can be seen [in the pip.log file here](http://pastebin.com/09JRVDhH) and I'm unfortunately not python-savvy enough to understand what's wrong. Any help will be apprec... | The error messages all state the same: You lack BLAS (Basic Linear Algebra Subroutines) on your system, or scipy cannot find it. When installing packages from source in ubuntu, as you are effectively trying to do with pip, one of the easiest ways to make sure dependencies are in place is by the command
```
$ sudo apt-... |
Adjusting gridlines on a 3D Matplotlib figure | 17,925,545 | 6 | 2013-07-29T13:36:29Z | 17,929,595 | 14 | 2013-07-29T16:45:34Z | [
"python",
"matplotlib"
] | I'm getting ready for a presentation and I have some example figures of 3D matplotlib figures. However, the gridlines are too light to see on the projected images.

I tried using the grid-method that works for 2D figures:
```
points = (5*np.random.randn(3, 50)+np... | If you don't mind having all the lines thicker then you could adjust the default rc settings.
Given a graph such as:

We can add:
```
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 2
```
To increase the default line width of all lines, ... |
How to count distinct values in a column of a pandas group by object? | 17,926,273 | 14 | 2013-07-29T14:10:21Z | 17,926,411 | 16 | 2013-07-29T14:16:46Z | [
"python",
"group-by",
"pandas"
] | I have a pandas data frame and group it by two columns (for example `col1` and `col2`). For fixed values of `col1` and `col2` (i.e. for a group) I can have several different values in the `col3`. I would like to count the number of distinct values from the third columns.
For example, If I have this as my input:
```
1... | ```
df.groupby(['col1','col2'])['col3'].nunique().reset_index()
``` |
How to count distinct values in a column of a pandas group by object? | 17,926,273 | 14 | 2013-07-29T14:10:21Z | 17,926,436 | 13 | 2013-07-29T14:18:03Z | [
"python",
"group-by",
"pandas"
] | I have a pandas data frame and group it by two columns (for example `col1` and `col2`). For fixed values of `col1` and `col2` (i.e. for a group) I can have several different values in the `col3`. I would like to count the number of distinct values from the third columns.
For example, If I have this as my input:
```
1... | ```
In [17]: df
Out[17]:
0 1 2
0 1 1 1
1 1 1 1
2 1 1 2
3 1 2 3
4 1 2 3
5 1 2 3
6 2 1 1
7 2 1 2
8 2 1 3
9 2 2 3
10 2 2 3
11 2 2 3
In [19]: df.groupby([0,1])[2].apply(lambda x: len(x.unique()))
Out[19]:
0 1
1 1 2
2 1
2 1 3
2 1
dtype: int64
``` |
reStructuredText: how to use continuation lines in tables? | 17,928,572 | 2 | 2013-07-29T15:53:42Z | 17,929,237 | 7 | 2013-07-29T16:27:33Z | [
"python",
"python-sphinx",
"restructuredtext",
"docutils"
] | I have the following neat little table in reStructuredText:
```
====== ======= ====== =====================
Symbol Meaning Type Example
====== ======= ====== =====================
G Era Text "GG" -> "AD"
y Year Number "yy" -> "03"
"yyyy" -> "2003... | What you need is a [line block](http://docutils.sourceforge.net/docs/user/rst/quickref.html#line-blocks):
```
====== ======= ====== =====================
Symbol Meaning Type Example
====== ======= ====== =====================
G Era Text "GG" -> "AD"
y Year Number | "yy" ->... |
groupby for pandas Series not working | 17,929,426 | 5 | 2013-07-29T16:37:47Z | 17,929,591 | 9 | 2013-07-29T16:45:20Z | [
"python",
"pandas"
] | I am unable to do a groupby on a pandas Series object. DataFrames are fine, but I cannot seem to do groupby with a Series. Has anyone been able to get this to work?
```
>>> import pandas as pd
>>> a = pd.Series([1,2,3,4], index=[4,3,2,1])
>>> a
4 1
3 2
2 3
1 4
dtype: int64
>>> a.groupby()
Traceback (most r... | You need to pass a mapping of some kind (could be a dict/function/index)
```
In [6]: a
Out[6]:
4 1
3 2
2 3
1 4
dtype: int64
In [7]: a.groupby(a.index).sum()
Out[7]:
1 4
2 3
3 2
4 1
dtype: int64
In [3]: a.groupby(lambda x: x % 2 == 0).sum()
Out[3]:
False 6
True 4
dtype: int64
``` |
How can I dynamically create class methods for a class in python | 17,929,543 | 28 | 2013-07-29T16:42:53Z | 17,930,262 | 31 | 2013-07-29T17:21:46Z | [
"python",
"class",
"metaprogramming",
"static-methods",
"setattr"
] | If I define a little python program as
```
class a():
def _func(self):
return "asdf"
# Not sure what to resplace __init__ with so that a.func will return asdf
def __init__(self, *args, **kwargs):
setattr(self, 'func', classmethod(self._func))
if __name__ == "__main__":
a.func
```
I ... | You can dynamically add a classmethod to a class by simple assignment to the class object or by setattr on the class object. Here I'm using the python convention that classes start with capital letters to reduce confusion:
```
# define a class object (your class may be more complicated than this...)
class A(object):
... |
sorting a counter in python by keys | 17,930,814 | 8 | 2013-07-29T17:51:12Z | 17,930,886 | 20 | 2013-07-29T17:55:12Z | [
"python",
"python-2.7",
"dictionary"
] | I have a counter that looks a bit like this:
```
Counter: {('A': 10), ('C':5), ('H':4)}
```
I want to sort on keys specifically in an alphabetical order, NOT by `counter.most_common()`
is there any way to achieve this? | Just use [sorted](http://docs.python.org/2/library/functions.html#sorted):
```
>>> from collections import Counter
>>> counter = Counter({'A': 10, 'C': 5, 'H': 7})
>>> counter.most_common()
[('A', 10), ('H', 7), ('C', 5)]
>>> sorted(counter.items())
[('A', 10), ('C', 5), ('H', 7)]
``` |
'ascii' codec can't decode error when use pip to install uwsgi | 17,931,726 | 9 | 2013-07-29T18:41:47Z | 18,566,059 | 15 | 2013-09-02T05:13:46Z | [
"python",
"django",
"uwsgi"
] | I am setting up uwsgi following this tutorial: <https://uwsgi.readthedocs.org/en/latest/tutorials/Django_and_nginx.html>.
I run `pip install uwsgi` within virtualenv, but get the problem as follows:
```
Command /home/timyitong/superleagues/bin/python -c "import setuptools;__file__='/home/timyitong/superleagues/build/u... | Try installing first libevent-devel and python-devel
```
yum install libevent-devel python-devel
```
and then installing
```
pip install uwsgi
``` |
'ascii' codec can't decode error when use pip to install uwsgi | 17,931,726 | 9 | 2013-07-29T18:41:47Z | 20,986,067 | 16 | 2014-01-08T02:46:24Z | [
"python",
"django",
"uwsgi"
] | I am setting up uwsgi following this tutorial: <https://uwsgi.readthedocs.org/en/latest/tutorials/Django_and_nginx.html>.
I run `pip install uwsgi` within virtualenv, but get the problem as follows:
```
Command /home/timyitong/superleagues/bin/python -c "import setuptools;__file__='/home/timyitong/superleagues/build/u... | It's a question asked a year ago? I come here by Google.
I notice that the asker is Chinese, same as me.
So, maybe we face the same problem.
Oh, sorry for my bad English!
I HAVE FOUND THE RIGHT ANSWER!
It is because when Python installs some packages, it will check the Windows Registry, some Chinese software like Ali... |
replace dictionary keys (strings) in Python | 17,933,168 | 6 | 2013-07-29T20:04:31Z | 17,933,239 | 17 | 2013-07-29T20:08:22Z | [
"python",
"dictionary"
] | After CSV import, I have following dictionary with keys in different language:
```
dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'}
```
Now I want to change keys to English and (also to all lowercase). Which should be:
```
dic = {'first_name': 'John', 'last_name': '... | you have dictionary type, it fits perfectly
```
>>> dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'}
>>> tr = {'voornaam':'first_name', 'Achternaam':'last_name', 'telephone':'phone', 'Mobielnummer':'mobile'}
>>> dic = {tr[k]: v for k, v in dic.items()}
{'mobile': '2345... |
Using numpy.genfromtxt to read a csv file with strings containing commas | 17,933,282 | 17 | 2013-07-29T20:11:02Z | 17,933,417 | 7 | 2013-07-29T20:18:04Z | [
"python",
"numpy",
"pandas",
"genfromtxt"
] | I am trying to read in a csv file with `numpy.genfromtxt` but some of the fields are strings which contain commas. The strings are in quotes, but numpy is not recognizing the quotes as defining a single string. For example, with the data in 't.csv':
```
2012, "Louisville KY", 3.5
2011, "Lexington, KY", 4.0
```
the co... | The problem with the additional comma, `np.genfromtxt` does not deal with that.
One simple solution is to read the file with `csv.reader()` from python's [csv](http://docs.python.org/2/library/csv.html) module into a list and then dump it into a numpy array if you like.
If you really want to use `np.genfromtxt`, note... |
Using numpy.genfromtxt to read a csv file with strings containing commas | 17,933,282 | 17 | 2013-07-29T20:11:02Z | 17,942,117 | 13 | 2013-07-30T08:37:54Z | [
"python",
"numpy",
"pandas",
"genfromtxt"
] | I am trying to read in a csv file with `numpy.genfromtxt` but some of the fields are strings which contain commas. The strings are in quotes, but numpy is not recognizing the quotes as defining a single string. For example, with the data in 't.csv':
```
2012, "Louisville KY", 3.5
2011, "Lexington, KY", 4.0
```
the co... | You can use [pandas](https://github.com/pydata/pandas/pull/4384) (the becoming default library for working with dataframes (heterogeneous data) in scientific python) for this. It's [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html) can handle this. From the docs:
> quot... |
python postgres can I fetchall() 1 million rows? | 17,933,344 | 2 | 2013-07-29T20:14:24Z | 17,933,402 | 12 | 2013-07-29T20:17:39Z | [
"python",
"postgresql",
"fetchall"
] | I am using **psycopg2** module in python to read from postgres database, I need to some operation on all rows in a column, that has more than 1 million rows.
I would like to know would `cur.fetchall()` fail or cause my server to go down? (since my RAM might not be that big to hold all that data)
```
q="SELECT names f... | Consider using [server side cursor](http://initd.org/psycopg/docs/usage.html#server-side-cursors):
> When a database query is executed, the Psycopg cursor usually fetches
> all the records returned by the backend, transferring them to the
> client process. If the query returned an huge amount of data, a
> proportional... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.