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 |
|---|---|---|---|---|---|---|---|---|---|
Modifying a symlink in python | 8,299,386 | 10 | 2011-11-28T16:58:53Z | 8,299,419 | 8 | 2011-11-28T17:01:09Z | [
"python",
"symlink"
] | How do I change as symlink to point from one file to another in Python? The os.symlink() function only seems to work to create new symlinks. | You could [`os.unlink()`](http://docs.python.org/library/os.html#os.unlink) it first, and then re-create using [`os.symlink()`](http://docs.python.org/library/os.html#os.symlink) to point to the new target. |
Modifying a symlink in python | 8,299,386 | 10 | 2011-11-28T16:58:53Z | 27,103,129 | 11 | 2014-11-24T10:53:31Z | [
"python",
"symlink"
] | How do I change as symlink to point from one file to another in Python? The os.symlink() function only seems to work to create new symlinks. | A little function which tries to symlink and if it fails because of an existing file, it removes it and links again.
```
import os, errno
def symlink_force(target, link_name):
try:
os.symlink(target, link_name)
except OSError, e:
if e.errno == errno.EEXIST:
os.remove(link_name)
... |
Vectorization of this Numpy double loop | 8,299,891 | 4 | 2011-11-28T17:35:45Z | 8,300,067 | 7 | 2011-11-28T17:49:41Z | [
"python",
"numpy",
"linear-algebra"
] | How can I vectorize the following double-loop?
I have one N by A matrix and one N by B matrix, where A and B may differ and N is much smaller than A and B. I want to produce an A by B matrix as follows, but ideally without the loops:
```
import numpy as np
def foo(arr):
# can be anything - just an example so tha... | First vectorise `foo()`, i.e. modify `foo()` in a way that it can correctly operate on an array of shape `(N, A, B)`, returning an array of shape `(A, B)`. This step is usually the difficult one. How this is done entirely depends on what `foo()` does. For the given example, it's very easy to do:
```
def foo(arr):
... |
OpenCV python's API: FlannBasedMatcher | 8,301,962 | 8 | 2011-11-28T20:35:33Z | 8,311,498 | 10 | 2011-11-29T13:26:14Z | [
"python",
"opencv",
"computer-vision"
] | I am trying to rewrite the code described [here](http://opencv.itseez.com/doc/tutorials/features2d/feature_homography/feature_homography.html#feature-homography). using the python API for Opencv.
The step 3 of the code has this lines:
```
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( des... | Looking in the examples provided by OpenCV 2.3.1 under the python2 folder, I found an implementation of a flann based match function which doesn't rely on the FlanBasedMatcher object.
Here is the code:
```
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
flann_params = dict(algorithm = FLANN_INDEX_KDTREE,
... |
Why is `continue` not allowed in a `finally` clause in Python? | 8,302,293 | 35 | 2011-11-28T21:05:50Z | 8,302,601 | 24 | 2011-11-28T21:30:31Z | [
"python",
"syntax-error",
"continue",
"finally"
] | The following code raises a syntax error:
```
>>> for i in range(10):
... print i
... try:
... pass
... finally:
... continue
... print i
...
File "<stdin>", line 6
SyntaxError: 'continue' not supported inside 'finally' clause
```
**Why isn't a `continue` statement allowed inside a `fi... | The use of *continue* in a finally-clause is forbidden because its interpretation would have been problematic. What would you do if the finally-clause were being executed because of an exception?
```
for i in range(10):
print i
try:
raise RuntimeError
finally:
continue # if the loop co... |
Undefined Symbol in C++ When Loading a Python Shared Library | 8,302,810 | 10 | 2011-11-28T21:46:17Z | 12,845,362 | 8 | 2012-10-11T17:38:15Z | [
"python",
"shared-libraries",
"undefined-symbol"
] | I have been trying to get a project of mine to run but I have run into trouble. After much debugging I have narrowed down the problem but have no idea how to proceed.
Some background, I am using a python script inside C++ code. This is somewhat documented on Python, and I managed to get it running very well in my basi... | I experienced the same problem with my application and solved it **without linking** python to the executable.
The setup is as follows:
Executable --*links*--> library --*dynamically-loads*--> plugin --*loads*--> python interpreter
The solution to avoid the ImportErrors was to change the parameters of dlopen, with w... |
Python equivalent of piping file output to gzip in Perl using a pipe | 8,302,911 | 8 | 2011-11-28T21:54:26Z | 8,303,683 | 9 | 2011-11-28T23:07:26Z | [
"python",
"gzip",
"pipe",
"compression",
"filehandle"
] | I need to figure out how to write file output to a compressed file in Python, similar to the two-liner below:
```
open ZIPPED, "| gzip -c > zipped.gz";
print ZIPPED "Hello world\n";
```
In Perl, this uses Unix gzip to compress whatever you print to the ZIPPED filehandle to the file "zipped.gz".
I know how to use "im... | ChristopheD's suggestion of using the [subprocess module](http://docs.python.org/library/subprocess.html) is an appropriate answer to this question. However, it's not clear to me that it will solve your performance problems. You would have to measure the performance of the new code to be sure.
To convert your sample c... |
Why do strptime and strftime behave differently, and what do you do about it? | 8,302,990 | 2 | 2011-11-28T22:03:07Z | 8,303,097 | 7 | 2011-11-28T22:11:31Z | [
"python",
"google-app-engine"
] | I'm on Python 2.5 and running in App Engine, doing pagination with code that looks like:
```
NEXT_FORMAT = "%Y-%m-%d %H:%M:%S"
current = model.completed_on.strftime(NEXT_FORMAT)
completed_before = datetime.datetime.strptime(current, NEXT_FORMAT)
```
Every now and then strftime will drop out a time that looks like `... | Change it to this:
```
NEXT_FORMAT = "%Y-%m-%d %H:%M:%S.%f"
```
This will convert the microsecond part as well.
Or, if you want to strip off the microseconds, you can use replace before you call strptime.
```
current = current.replace(microsecond=0)
``` |
How do I get the text contents of a textarea with webdriver? | 8,303,094 | 7 | 2011-11-28T22:11:19Z | 13,510,057 | 7 | 2012-11-22T09:59:10Z | [
"python",
"selenium",
"webdriver"
] | I'm trying to get the contents of a [textarea](http://www.w3.org/TR/html4/interact/forms.html#h-17.7) in an HTML form using [webdriver in Python](http://code.google.com/p/selenium/wiki/PythonBindings).
I'm getting the text, but newlines are missing. The [selenium docs](http://selenium.googlecode.com/svn/trunk/docs/api... | I have just got attribute value of tag textarea. Below is a sample of Java code.
```
WebElement textarea = driver.findElement(By.id("xf-1242"));
String text = textarea.getAttribute("value");
log.debut(text);
```
I am using Chrome driver, and above code put a text (XML in my case) with newlines in the log.
I ... |
pymongo generator fails - 'return' with argument inside generator | 8,303,483 | 4 | 2011-11-28T22:47:22Z | 8,303,561 | 11 | 2011-11-28T22:54:09Z | [
"python",
"generator",
"pymongo"
] | I am trying to do the following :
```
def get_collection_iterator(collection_name, find={}, criteria=None):
collection = db[collection_name]
# prepare the list of values of collection
if collection is None:
logging.error('Mongo could not return the collecton - ' + collection_name)
return No... | It seems the problem is that Python doesn't allow you to mix `return` and `yield` -- you use both within `get_collection_iterator`.
Clarification (thanks to rob mayoff): `return x` and `yield` can't be mixed, but a bare `return` can |
Elegant way to transform a list of dict into a dict of dicts | 8,303,993 | 7 | 2011-11-28T23:43:32Z | 8,304,026 | 14 | 2011-11-28T23:48:10Z | [
"python",
"dictionary"
] | I have a list of dictionaries like in this example:
```
listofdict = [{'name': 'Foo', 'two': 'Baz', 'one': 'Bar'}, {'name': 'FooFoo', 'two': 'BazBaz', 'one': 'BarBar'}]
```
I know that 'name' exists in each dictionary (as well as the other keys) and that it is unique and does not occur in any of the other dictionarie... | ```
d = {}
for i in listofdict:
d[i.pop('name')] = i
```
if you have Python2.7+:
```
{i.pop('name'): i for i in listofdict}
``` |
Display an attached image on the HTML message | 8,304,618 | 3 | 2011-11-29T01:14:24Z | 8,304,696 | 11 | 2011-11-29T01:24:21Z | [
"python",
"html",
"mime-types",
"sendmail",
"mime-message"
] | I have develop a function in PYTHON that sends emails with one .doc attachment and one image attachment (.jpg)
The message of the email is HTML.
I want to know how to display the Attached Image on the HTML message....is there any instruction that can help me with this???
Thanks a lot....
Here is the function I devel... | In your html, use img tags with a src of:
```
cid:<filename used in your Content-Disposition header>
```
So, for instance:
```
<p>
<img src="cid:image1.jpeg"/>
</p>
``` |
Login to a website through web-scraping tool in Python | 8,304,672 | 7 | 2011-11-29T01:21:43Z | 8,304,715 | 8 | 2011-11-29T01:26:30Z | [
"python",
"selenium",
"beautifulsoup",
"urllib2",
"web-scraping"
] | I am using Selenium webdriver in Python for a web-scraping project.
I would like to login by entering the login details and then click the submit button.
I am able to enter the Username and Password. But I am not able to mouseclick the submit button.
The "submit" button is of type `<input>`.
```
<input type="image"... | I had good luck using `mechanize`. It's pretty straightforward and simple to use.
Here's a stripped-down version of a script I made:
```
from BeautifulSoup import BeautifulSoup
from tidylib import tidy_document
import mechanize
import cookielib
if __name__ == '__main__':
browser = mechanize.Browser()
cookiejar... |
How do I compute the logarithm of 1 minus the exponent of a given small number in python | 8,304,897 | 6 | 2011-11-29T01:54:07Z | 8,305,112 | 7 | 2011-11-29T02:28:36Z | [
"python",
"math",
"numpy",
"floating-point",
"scipy"
] | I am performing a probability computation. I have many very very small numbers, all of which I want to subtract from 1, and do so accurately. I can accurately compute the logarithm of these small numbers. My strategy so far has been like so (using numpy):
Given an array of the log of the small numbers `x`, compute:
`... | In Python 2.7, we added [math.expm1()](http://docs.python.org/library/math.html#math.expm1) for this use case:
```
>>> from math import exp, expm1
>>> exp(1e-5) - 1 # gives result accurate to 11 places
1.0000050000069649e-05
>>> expm1(1e-5) # result accurate to full precision
1.0000050000166668e-05
```
Also, ther... |
The tilde operator in Python | 8,305,199 | 60 | 2011-11-29T02:43:56Z | 8,305,225 | 33 | 2011-11-29T02:48:56Z | [
"python",
"operators"
] | What's the usage of the tilde operator in Python?
One thing I can think about is do something in both sides of a string or list, such as check if a string is palindromic or not:
```
def is_palindromic(s):
return all(s[i] == s[~i] for i in range(len(s) / 2))
```
Any other good usage? | `~` is the [bitwise complement operator](http://en.wikipedia.org/wiki/Bitwise_operation#NOT) in python which essentially calculates `-x - 1`
So a table would look like
```
i ~i
0 -1
1 -2
2 -3
3 -4
4 -5
5 -6
```
So for `i = 0` it would compare `s[0]` with `s[len(s) - 1]`, for `i = 1`, `s[0]` with `s[len(s)... |
The tilde operator in Python | 8,305,199 | 60 | 2011-11-29T02:43:56Z | 8,305,291 | 69 | 2011-11-29T03:02:42Z | [
"python",
"operators"
] | What's the usage of the tilde operator in Python?
One thing I can think about is do something in both sides of a string or list, such as check if a string is palindromic or not:
```
def is_palindromic(s):
return all(s[i] == s[~i] for i in range(len(s) / 2))
```
Any other good usage? | It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.
In Python, for integers, the bits of the [twos-complement representation](ht... |
switching keys and values in a dictionary in python | 8,305,518 | 19 | 2011-11-29T03:36:47Z | 8,305,541 | 30 | 2011-11-29T03:39:46Z | [
"python",
"dictionary",
"key",
"switch-statement"
] | Say I have a dictionary like so:
```
my_dict = {2:3, 5:6, 8:9}
```
Is there a way that I can switch the keys and values to get:
```
{3:2, 6:5, 9:8}
``` | ```
my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
```
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
```
my_dict2 = {y:x for x,y in my_dict.iteritems()}
```
Edit
As noted in the comments by JBernardo, for python 3.x you need to use `items` instead of `iteritems` |
Is there something like RStudio for Python? | 8,305,809 | 83 | 2011-11-29T04:21:51Z | 11,103,988 | 23 | 2012-06-19T15:11:35Z | [
"python",
"ide"
] | In RStudio, you can run parts of code in the code editing window, and the results appear in the console.
You can also do cool stuff like selecting whether you want everything up to the cursor to run, or everything after the cursor, or just the part that you selected, and so on. And there are hot keys for all that stuf... | [Jupyter Notebook](http://jupyter.org/) (previously known as [IPython notebook](http://ipython.org/notebook.html)) is a really cool project for interactive data manipulation in Python (and other languages, including R). It basically allows you to interactively code and document what you're doing in one interface and la... |
Is there something like RStudio for Python? | 8,305,809 | 83 | 2011-11-29T04:21:51Z | 11,303,198 | 25 | 2012-07-03T01:02:50Z | [
"python",
"ide"
] | In RStudio, you can run parts of code in the code editing window, and the results appear in the console.
You can also do cool stuff like selecting whether you want everything up to the cursor to run, or everything after the cursor, or just the part that you selected, and so on. And there are hot keys for all that stuf... | spyder or install python(x,y). it is great.
If you are new to Python, you can install the free Anaconda distribution (<http://continuum.io/downloads.html>), which will install Spyder for you, as well as Python 2.7 and IPython. Spyder is very similar to RStudio. |
Is there something like RStudio for Python? | 8,305,809 | 83 | 2011-11-29T04:21:51Z | 22,718,227 | 7 | 2014-03-28T16:25:48Z | [
"python",
"ide"
] | In RStudio, you can run parts of code in the code editing window, and the results appear in the console.
You can also do cool stuff like selecting whether you want everything up to the cursor to run, or everything after the cursor, or just the part that you selected, and so on. And there are hot keys for all that stuf... | [Pycharm](http://www.jetbrains.com/pycharm/) is a really decent IDE. From what I have seen so far it is the most similar to Rstudio. Another nice piece is that it allows you to install new Python libraries in a fashion similar to Rstudio (which otherwise can be a nightmare). There is now a free 'community' edition.
![... |
Is there something like RStudio for Python? | 8,305,809 | 83 | 2011-11-29T04:21:51Z | 30,388,579 | 29 | 2015-05-22T04:50:32Z | [
"python",
"ide"
] | In RStudio, you can run parts of code in the code editing window, and the results appear in the console.
You can also do cool stuff like selecting whether you want everything up to the cursor to run, or everything after the cursor, or just the part that you selected, and so on. And there are hot keys for all that stuf... | IPython Notebooks are awesome. Here's another, newer browser-based tool I've recently discovered: [Rodeo](https://github.com/yhat/rodeo). My impression is that it seems to better support an RStudio-like workflow.
 |
Python: Extract variables out of namespace | 8,306,171 | 7 | 2011-11-29T05:11:07Z | 8,306,355 | 8 | 2011-11-29T05:35:14Z | [
"python",
"command-line-arguments",
"argparse"
] | I'm using argparse in python to parse commandline arguments:
```
parser = ArgumentParser()
parser.add_argument("--a")
parser.add_argument("--b")
parser.add_argument("--c")
args = parser.parse_args()
```
Now I want to do some calculations with `a`, `b`, and `c`. However, I find it tiresome to write `args.a + args.b + ... | If you want them as globals, you can do:
```
globals().update(vars(args))
```
If you're in a function and want them as local variables of that function, you can do this in Python 2.x as follows:
```
def foo(args):
locals().update(vars(args))
print a, b, c
return
exec "" # forces Python to use a d... |
Deleting an object from an SQLAlchemy session before it's been persisted | 8,306,506 | 12 | 2011-11-29T05:53:52Z | 8,307,323 | 11 | 2011-11-29T07:37:02Z | [
"python",
"sqlalchemy"
] | My application allows users to create and delete `Site` objects. I have implemented this using `session.add()` and `session.delete()`. I then have 'Save' and 'Reset' buttons that call `session.commit()` and `session.rollback()`.
If I add a new `Site`, then save/commit it, and then delete it, everything goes OK. Howeve... | You can `Session.expunge()` it. I think the rationale with `delete()` being that way is, it worries you're not keeping track of things if you send it a pending. But I can see the other side of the story on that, I'll think about it. Basically the state implied by `delete()` includes some assumptions of persistence but ... |
What is wrong with this python list removal loop? | 8,306,606 | 2 | 2011-11-29T06:07:41Z | 8,306,658 | 7 | 2011-11-29T06:12:45Z | [
"python",
"list",
"loops"
] | I have been up far too long tonight working on a long program. But I have hit a simple roadblock. Can any one tell me why this code is working the way it is?
I have two lists. I want list2 to only contain numbers that are not in list1.
logically this seems like it should work. But it doest at all. Why?
```
list1 = [1... | When you modify a sequence you are iterating over, it will yield unexpected results. I'd do it this way, which takes advantage of fast `set` operations.
```
list2 = list(set(list2) - set(list1))
```
Whether this is faster or slower than using a list comprehension depends on the sizes of `list1` and `list2`, and wheth... |
Finding all possible permutations of a given string in python | 8,306,654 | 27 | 2011-11-29T06:12:34Z | 8,306,692 | 47 | 2011-11-29T06:16:28Z | [
"python",
"string",
"permutation"
] | I have a string. I want to generate all permutations from that string, by changing the order of characters in it. For example, say:
```
x='stack'
```
what I want is a list like this,
```
l=['stack','satck','sackt'.......]
```
Currently I am iterating on the list cast of the string, picking 2 letters randomly and tr... | The itertools module has a useful method called permutations(). [The documentation](http://docs.python.org/library/itertools.html#itertools.permutations) says:
> **itertools.permutations(iterable[, r])**
>
> Return successive r length permutations of elements in the iterable.
>
> If r is not specified or is None, then... |
Finding all possible permutations of a given string in python | 8,306,654 | 27 | 2011-11-29T06:12:34Z | 20,955,291 | 17 | 2014-01-06T17:08:04Z | [
"python",
"string",
"permutation"
] | I have a string. I want to generate all permutations from that string, by changing the order of characters in it. For example, say:
```
x='stack'
```
what I want is a list like this,
```
l=['stack','satck','sackt'.......]
```
Currently I am iterating on the list cast of the string, picking 2 letters randomly and tr... | You can get all N! permutations without much code
```
def permutations(string, step = 0):
# if we've gotten to the end, print the permutation
if step == len(string):
print "".join(string)
# everything to the right of step has not been swapped yet
for i in range(step, len(string)):
# ... |
How to extend SQLite with Python functions in Django? | 8,307,242 | 5 | 2011-11-29T07:29:14Z | 8,307,361 | 9 | 2011-11-29T07:43:12Z | [
"python",
"django",
"sqlite"
] | It's possible to [define new SQL functions for SQLite in Python](http://docs.python.org/library/sqlite3.html#sqlite3.Connection.create_function). How can I do this in Django so that the functions are available everywhere?
An example use case is a query which uses the [GREATEST() and LEAST()](http://www.postgresql.org/... | Here's a Django code example that extends SQLite with GREATEST() and LEAST() methods by calling Python's built-in max() and min():
```
from django.db.backends.signals import connection_created
from django.dispatch import receiver
@receiver(connection_created)
def extend_sqlite(connection=None, **kwargs):
connecti... |
how to create class variable dynamically in python | 8,307,612 | 9 | 2011-11-29T08:11:18Z | 8,307,639 | 12 | 2011-11-29T08:14:06Z | [
"python",
"class",
"class-variables"
] | I need to make a bunch of class variables and I would like to do it by looping through a list like that:
```
vars=('tx','ty','tz') #plus plenty more
class Foo():
for v in vars:
setattr(no_idea_what_should_go_here,v,0)
```
is it possible? I don't want to make them for an instance (using self in the \_\_in... | You can run the insertion code immediately after a class is created:
```
class Foo():
...
vars=('tx', 'ty', 'tz') # plus plenty more
for v in vars:
setattr(Foo, v, 0)
``` |
Passing an object to C module, in Python | 8,307,701 | 8 | 2011-11-29T08:19:43Z | 8,308,165 | 8 | 2011-11-29T09:05:52Z | [
"python"
] | I ran into a situation with pure python and C python module.
To summarize, how can I accept and manipulate python object in C module?
My python part will look like this.
```
#!/usr/bin/env python
import os, sys
from c_hello import *
class Hello:
busyHello = _sayhello_obj
class Man:
... | To extract an argument from an invocation of your method, you need to look at the functions documented in [Parsing arguments and building values](http://docs.python.org/c-api/arg.html#parsing-arguments-and-building-values), such as [`PyArg_ParseTuple`](http://docs.python.org/c-api/arg.html#PyArg_ParseTuple). (That's fo... |
Save email attachment (python3, pop3_ssl, gmail) | 8,307,809 | 2 | 2011-11-29T08:30:48Z | 8,308,429 | 7 | 2011-11-29T09:28:04Z | [
"python",
"email",
"python-3.x",
"gmail",
"pop3"
] | I'm trying to save email attachment from Google mail account.
AFAIK, it can be done 'walking' the message and getting its payload,
```
for part in message.walk():
# getting payload, saving attach etc.
```
but it does not work.
See the whole example below:
```
def test_save_attach(self):
self.connection = po... | ```
response = self.connection.retr(i+1)
raw_message = response[1]
```
`raw_message` is not a string. [retr](http://docs.python.org/library/poplib.html#poplib.POP3.retr) returns the message as a list of single lines. you are trying to convert the list into a string with `str(raw_message)` - that doesn't work.
instead... |
Popen does not work anymore with apache/wsgi and python 2.7.2? | 8,309,465 | 8 | 2011-11-29T10:46:28Z | 8,310,359 | 14 | 2011-11-29T12:01:43Z | [
"python",
"apache",
"mod-wsgi"
] | My django application that used to make some shell commands by using python subprocess.Popen does not work anymore since I upgrade to ubuntu to 11.10
To simplify the problem, I put the faulty code into the wsgi script :
```
import os
import sys
from subprocess import Popen,PIPE
p=Popen(['/usr/bin/id'],stdout=PIPE,st... | Because latest Python 2.7 has a bug in it which causes fork run in sub interpreters to fail.
<http://bugs.python.org/issue13156>
Presuming only hosting the one WSGI application, force use of the main interpreter rather than a sub interpreter by adding to your Apache configuration:
```
WSGIApplicationGroup %{GLOBAL}
... |
Are Python instance variables thread-safe? | 8,309,902 | 6 | 2011-11-29T11:23:15Z | 8,309,966 | 17 | 2011-11-29T11:28:04Z | [
"python",
"multithreading",
"thread-safety"
] | OK, check following codes first:
```
class DemoClass():
def __init__(self):
#### I really want to know if self.Counter is thread-safe.
self.Counter = 0
def Increase(self):
self.Counter = self.Counter + 1
def Decrease(self):
self.Counter = self.Counter - 1
def DoThis... | You can use Locks, RLocks, Semaphores, Conditions, Events and Queues.
And this article helped me **a lot**.
Check it out: [Laurent Luce's Blog](http://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/) |
Why do std::string operations perform poorly? | 8,310,039 | 53 | 2011-11-29T11:33:13Z | 8,310,145 | 7 | 2011-11-29T11:43:53Z | [
"c++",
"python",
"performance",
"node.js",
"stl"
] | I made a test to compare string operations in several languages for choosing a language for the server-side application. The results seemed normal until I finally tried C++, which surprised me a lot. So I wonder if I had missed any optimization and come here for help.
The test are mainly intensive string operations, i... | That is the most obvious one: please try to do `s.reserve(limit);` before main loop.
Documentation is [here](http://www.cplusplus.com/reference/string/string/reserve/).
I should mention that direct usage of standard classes in C++ in the same way you are used to do it in Java or Python will often give you sub-par per... |
Why do std::string operations perform poorly? | 8,310,039 | 53 | 2011-11-29T11:33:13Z | 8,310,223 | 67 | 2011-11-29T11:51:45Z | [
"c++",
"python",
"performance",
"node.js",
"stl"
] | I made a test to compare string operations in several languages for choosing a language for the server-side application. The results seemed normal until I finally tried C++, which surprised me a lot. So I wonder if I had missed any optimization and come here for help.
The test are mainly intensive string operations, i... | It's not that `std::string` performs poorly (as much as I dislike C++), it's that string handling is so heavily optimized for those other languages.
Your comparisons of string performance are misleading, and presumptuous if they are intended to represent more than just that.
I know for a fact that [Python string obje... |
Why do std::string operations perform poorly? | 8,310,039 | 53 | 2011-11-29T11:33:13Z | 8,310,511 | 34 | 2011-11-29T12:14:18Z | [
"c++",
"python",
"performance",
"node.js",
"stl"
] | I made a test to compare string operations in several languages for choosing a language for the server-side application. The results seemed normal until I finally tried C++, which surprised me a lot. So I wonder if I had missed any optimization and come here for help.
The test are mainly intensive string operations, i... | So I went and played a bit with this on ideone.org.
Here a slightly modified version of your original C++ program, but with the appending in the loop eliminated, so it only measures the call to `std::string::find()`. *Note that I had to cut the number of iterations to ~40%, otherwise ideone.org would kill the process.... |
Why do std::string operations perform poorly? | 8,310,039 | 53 | 2011-11-29T11:33:13Z | 8,318,254 | 12 | 2011-11-29T21:52:57Z | [
"c++",
"python",
"performance",
"node.js",
"stl"
] | I made a test to compare string operations in several languages for choosing a language for the server-side application. The results seemed normal until I finally tried C++, which surprised me a lot. So I wonder if I had missed any optimization and come here for help.
The test are mainly intensive string operations, i... | The idiomatic C++ solution would be:
```
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
const int limit = 102 * 1024;
std::string s;
s.reserve(limit);
const std::string pattern("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
for (int i = 0; i < limit; ++i) {
s += 'X';
if ... |
Read CSV file with comma within fields in Python | 8,311,900 | 18 | 2011-11-29T13:53:30Z | 8,311,951 | 24 | 2011-11-29T13:58:39Z | [
"python",
"csv"
] | I need to read a CSV file which has fields that have a comma, so I have double quoted the fields which contains commas, such as:
```
1, "text1,text2", "text3, text4", a, b, c
```
But when I try to read the file in Python I get the fields separated by the commas, as following:
```
row[0] = 1
row[1] = text1
row[2] = t... | The Python `csv` module actually does support quoted fields, even by default. Your problem here is that Python by default does not skip the space, so you need to use `skipinitialspace=True`.
```
>>> s = StringIO.StringIO('1, "text1,text2", "text3, text4", a, b, c')
>>> list(csv.reader(s, skipinitialspace=True))
[['1',... |
Python : Postfix stdin | 8,312,001 | 6 | 2011-11-29T14:01:04Z | 20,643,341 | 8 | 2013-12-17T19:48:27Z | [
"python",
"stdin",
"postfix-mta"
] | I want to make postfix send all emails to a python script that will scan the emails.
However, how do I pipe the output from postfix to python ?
What is the stdin for Python ?
Can you give a code example ? | Rather than calling `sys.stdin.readlines()` then looping and passing the lines to `email.FeedParser.FeedParser().feed()` as suggested by Michael, you should instead pass the file object directly to the email parser.
The standard library provides a conveinience function, [`email.message_from_file(fp)`](http://docs.pyth... |
How to see (log) file transfer progress using paramiko? | 8,313,080 | 9 | 2011-11-29T15:09:14Z | 8,313,562 | 13 | 2011-11-29T15:42:29Z | [
"python",
"paramiko"
] | I'm using Paramiko's SFTPClient to transfer file between hosts. I want my script to print the file transfer progress similar to the output seen using scp.
```
$ scp my_file user@host
user@host password:
my_file 100% 816KB 815.8KB/s 00:00
$
```
Any idea?
Thanks in advance | Use the optional callback parameter of the [put function](http://www.lag.net/paramiko/docs/paramiko.SFTPClient-class.html#put). Something like this:
```
def printTotals(transferred, toBeTransferred):
print "Transferred: {0}\tOut of: {1}".format(transferred, toBeTransferred)
sftp.put("myfile","myRemoteFile",callba... |
Best way to add an environment variable in fabric? | 8,313,238 | 31 | 2011-11-29T15:20:04Z | 8,454,134 | 11 | 2011-12-10T03:25:45Z | [
"python",
"fabric"
] | I would like to pass a few values from fabric into the remote environment, and I'm not seeing a great way to do it. The best I've come up with so far is:
```
with prefix('export FOO=BAR'):
run('env | grep BAR')
```
This does seem to work, but it seems like a bit of a hack.
I looked in the GIT repository and it l... | I think your `prefix`-based solution is perfectly valid. However, if you want to have a `shell_env` context manager as the one proposed in [issue#263](https://github.com/fabric/fabric/issues/263), you can use the following alternative implementation in your fab files:
```
from fabric.api import run, env, prefix
from c... |
Best way to add an environment variable in fabric? | 8,313,238 | 31 | 2011-11-29T15:20:04Z | 13,801,188 | 39 | 2012-12-10T12:43:19Z | [
"python",
"fabric"
] | I would like to pass a few values from fabric into the remote environment, and I'm not seeing a great way to do it. The best I've come up with so far is:
```
with prefix('export FOO=BAR'):
run('env | grep BAR')
```
This does seem to work, but it seems like a bit of a hack.
I looked in the GIT repository and it l... | As of fabric 1.5 (released), [`fabric.context_managers.shell_env`](http://docs.fabfile.org/en/1.5/api/core/context_managers.html#fabric.context_managers.shell_env) does what you want.
```
with shell_env(FOO1='BAR1', FOO2='BAR2', FOO3='BAR3'):
local("echo FOO1 is $FOO1")
``` |
Selenium Grid2 - Is it possible to run 10 Chrome instances? | 8,313,310 | 5 | 2011-11-29T15:24:56Z | 8,330,896 | 7 | 2011-11-30T18:21:18Z | [
"python",
"google-chrome",
"selenium-webdriver",
"selenium-grid"
] | Currently Selenium Grid2 running with the default config shows that it can run 5 firefox browsers, 5 chrome browsers and 1 IE. With a max of 5 instances at the same time.
How can I change this so that it runs 10 chrome instances at the same time?
I have succesfully changed the maxsession parameter of the node with **... | I figured it out:
run the node with the argument of MaxSession, and let the browser Configuration have the MaxInstances parameter, ie:
```
java -jar $JARFILE -Dwebdriver.chrome.driver=$CHROMEDRIVER -role webdriver -hub http://$HUB_IP:4444/grid/register -maxSession 10 -browser browserName=chrome,maxInstances=10"
```
... |
In python, is there a way to automatically substitute for missing values? | 8,313,464 | 2 | 2011-11-29T15:34:42Z | 8,313,481 | 12 | 2011-11-29T15:36:21Z | [
"python",
"list"
] | I'm trying to parse a JSON object that consists of an array of objects. Each object contains several fields, but fields are often missing. Here's an example:
```
{
'objects' : [{
'fieldA' : 1,
'fieldB' : 2,
'fieldC' : 3,
},
{
'fieldA' : 7,
'fieldC' : 8,
},
{}... | You need the `dict.get()` method:
```
fieldA = [obj.get("fieldA", "missing") for obj in json["objects"]]
```
Note that the items of a dictionary are accessed with `["key"]`, not with `.key`. |
How can I configure Sphinx to conditionally exclude some pages? | 8,313,476 | 13 | 2011-11-29T15:35:44Z | 34,075,856 | 9 | 2015-12-03T20:49:45Z | [
"python",
"documentation",
"python-sphinx"
] | When generating documentation using Sphinx, I would like to be able to generate two versions of my documentation: one including everything, and one with only a particular set of pages. What's the best way of achieving that?
I could write a build script that moves files around to achieve this but it would be really nic... | Maybe my answer comes a bit late, but I managed to do this with Sphinx via [exclude patterns in the config file](http://sphinx-doc.org/config.html#confval-exclude_patterns).
My documentation is partly for users and partly for admins.
Some pages have file names that contain the word `admin`, and like you, I wanted to... |
Django Selective Dumpdata | 8,313,558 | 18 | 2011-11-29T15:42:15Z | 8,313,933 | 13 | 2011-11-29T16:07:41Z | [
"python",
"django",
"database-design",
"django-models"
] | Is it possible to selectively filter which records Django's dumpdata management command outputs? I have a few models, each with millions of rows, and I only want to dump records in one model fitting a specific criteria, as well as all foreign-key linked records referencing any of those records.
Consider this use-case.... | I think [django-fixture-magic](https://github.com/davedash/django-fixture-magic) might be worth a look at.
You'll find some additional background info in [Scrubbing your Django database](http://blog.mozilla.com/webdev/2011/11/18/scrubbing-your-django-database/). |
Setuid bit on python script : Linux vs Solaris | 8,314,012 | 7 | 2011-11-29T16:13:17Z | 8,314,858 | 18 | 2011-11-29T17:14:33Z | [
"python",
"linux",
"solaris",
"setuid"
] | I am running this small python script on both linux and Solaris **as a not privileged user** :
```
#!/usr/bin/python
import os
print 'uid,euid =',os.getuid(),os.geteuid()
```
Before running, the setuid bit is set on the script (not on python interpreter) :
```
chown root:myusergrp getuid.py
chmod 4750 getuid.py
```
... | Most Unix distributions normally don't allow you to use setuid on a file that uses a #! interpreter. Solaris happens to be one that allows it due to its use of a more secure implementation than most other distributions.
See this FAQ entry for more background about why the mechanism is so dangerous: [How can I get setu... |
Sending http headers with python | 8,315,209 | 5 | 2011-11-29T17:40:28Z | 8,315,292 | 11 | 2011-11-29T17:47:15Z | [
"python",
"html",
"sockets",
"client"
] | I've set up a little script that should feed a client with html.
```
import socket
sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()
print "Incoming:", adress
print client.recv(1024)
print
client.send("Content-Type: text/html\n\n")
client.send('<html><body></body></html>')
... | The response header should include a response code indicating success.
Before the *Content-Type* line, add:
```
client.send('HTTP/1.0 200 OK\r\n')
```
Also, to make the test more visible, put some content in the page:
```
client.send('<html><body><h1>Hello World</body></html>')
```
After the response is sent, close... |
How do I print functions as they are called | 8,315,389 | 24 | 2011-11-29T17:56:10Z | 8,315,566 | 49 | 2011-11-29T18:11:58Z | [
"python",
"callstack"
] | In debugging a Python script, I'd really like to know the entire call stack for my entire program. An ideal situation would be if there were a command-line flag for python that would cause Python to print all function names as they are called (I checked `man Python2.7`, but didn't find anything of this sort).
Because ... | You can do this with a trace function (props to Spacedman for improving the original version of this to trace returns and use some nice indenting):
```
def tracefunc(frame, event, arg, indent=[0]):
if event == "call":
indent[0] += 2
print "-" * indent[0] + "> call function", frame.f_code.co_n... |
Print HTML text of a selenium webelement in Python | 8,316,152 | 5 | 2011-11-29T18:54:59Z | 8,316,622 | 9 | 2011-11-29T19:34:20Z | [
"python",
"selenium",
"beautifulsoup",
"web-scraping",
"urllib2"
] | I am using Selenium webdriver in Python for a web-scraping project.
How to print the HTML text of the selenium.WebElement ?
I intend to use the `BeautifulSoup` to parse the HTML to extract the data of interest.
Thanks | It's not possible to get the raw HTML from a `WebElement`.
You can get the page source from the browser object though: `browser.page_source`. |
Insert list into my database using Python | 8,316,176 | 3 | 2011-11-29T18:56:40Z | 8,316,210 | 10 | 2011-11-29T18:59:42Z | [
"python",
"mysql",
"sql"
] | I want to insert a list in my database but I can't.
Here is an example of what I need:
```
variable_1 = "HELLO"
variable_2 = "ADIOS"
list = [variable_1,variable_2]
INSERT INTO table VALUES ('%s') % list
```
Can something like this be done? Can I insert a list as a value?
When I try it, an error says that is because... | The answer to your original question is: No, you can't insert a list like that.
However, with some tweaking, you could make that code work by using `%r` and passing in a tuple:
```
variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1, variable_2]
print "INSERT INTO table VALUES %r;" % (tuple(varlist),)
```... |
Login to website using python | 8,316,818 | 12 | 2011-11-29T19:51:03Z | 8,316,989 | 23 | 2011-11-29T20:04:12Z | [
"python",
"cookies",
"login"
] | I am trying to login to this [page](http://friends.cisv.org/index.cfm) using Python.
I tried using the steps described on this [other Stack Overflow post](http://stackoverflow.com/questions/189555/how-to-use-python-to-login-to-a-webpage-and-retrieve-cookies-for-later-usage), and got the following code:
```
import url... | I would recommend using the wonderful [`requests`](http://python-requests.org) module.
The code below will get you logged into the site and persist the cookies for the duration of the session.
```
import requests
import sys
EMAIL = ''
PASSWORD = ''
URL = 'http://friends.cisv.org'
def main():
# Start a session ... |
Get intersecting rows across two 2D numpy arrays | 8,317,022 | 10 | 2011-11-29T20:07:18Z | 8,317,155 | 7 | 2011-11-29T20:17:36Z | [
"numpy",
"python"
] | I want to get the intersecting (common) rows across two 2D numpy arrays. E.g., if the following arrays are passed as inputs:
```
array([[1, 4],
[2, 5],
[3, 6]])
array([[1, 4],
[3, 6],
[7, 8]])
```
the output should be:
```
array([[1, 4],
[3, 6])
```
I know how to do this with loo... | You could use Python's sets:
```
>>> import numpy as np
>>> A = np.array([[1,4],[2,5],[3,6]])
>>> B = np.array([[1,4],[3,6],[7,8]])
>>> aset = set([tuple(x) for x in A])
>>> bset = set([tuple(x) for x in B])
>>> np.array([x for x in aset & bset])
array([[1, 4],
[3, 6]])
```
As Rob Cowie points out, this can be... |
Get intersecting rows across two 2D numpy arrays | 8,317,022 | 10 | 2011-11-29T20:07:18Z | 8,317,403 | 8 | 2011-11-29T20:37:59Z | [
"numpy",
"python"
] | I want to get the intersecting (common) rows across two 2D numpy arrays. E.g., if the following arrays are passed as inputs:
```
array([[1, 4],
[2, 5],
[3, 6]])
array([[1, 4],
[3, 6],
[7, 8]])
```
the output should be:
```
array([[1, 4],
[3, 6])
```
I know how to do this with loo... | For short arrays, using sets is probably the clearest and most readable way to do it.
Another way is to use [`numpy.intersect1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.html). You'll have to trick it into treating the rows as a single value, though... This makes things a bit less readabl... |
Data Mining in a Django/Postgres application | 8,317,478 | 19 | 2011-11-29T20:44:51Z | 8,320,117 | 10 | 2011-11-30T01:36:03Z | [
"python",
"django",
"postgresql",
"nosql",
"business-intelligence"
] | I need to build in a analytics (reporting, charting & graphing) system into my Django application. In an ideal world I could just query my Postgres DB and get the data I want but when the amount of data in the DB goes through the roof, I'll hit performance bottlenecks and other issues like index hell.
I'm wondering if... | You might want to consider [Cube](http://square.github.com/cube/). It is not a Django app, but it has a lot of nice features baked in, and Django can communicate to it easily. Also, it is lovely.

You could have you Django app just blast off events into MongoDB wh... |
django manage.py settings default | 8,318,688 | 8 | 2011-11-29T22:31:10Z | 8,318,797 | 10 | 2011-11-29T22:42:39Z | [
"python",
"django"
] | I have a `settings.py` file and a `dev_settings.py` file that I use to override some values for dev purposes. Everytime I run the `./manage.py` command, I have to specify `--settings=whatever.local_settings`. This becomes very tedious to do every time and I am trying to find a way to force manage.py to load my dev\_set... | `manage.py` sets path to settings for you, that's why it's ignoring `DJANGO_SETTINGS_MODULE` (it's basically just script that wraps around `django-admin.py`).
There are 2 easy ways to fix your problem:
1. set `DJANGO_SETTINGS_MODULE` and use `django-admin.py` to run all commands instead of `manage.py`. This is even b... |
try except and programming etiquette | 8,319,401 | 4 | 2011-11-29T23:48:07Z | 8,319,432 | 7 | 2011-11-29T23:52:33Z | [
"python"
] | I'm making a GUI and I'm finding myself to be using a lot of `try` `except` statements. My question is, should I be redesigning my program to use less `try` `except` statements or is `try` `except` a good practice to be using in python programs? I like them because they're informative and make debugging, for me, easier... | One of Python's idioms is: [It's easier to ask for forgiveness than for permission.](http://docs.python.org/glossary.html?highlight=eafp) (Python Glossary, have a look at EAFP).
So it's perfectly acceptable to structure program flow with exception handling (and reasonably fast too, compared to other languages). It fit... |
How to make sure a script only runs after another script | 8,320,304 | 2 | 2011-11-30T02:06:52Z | 8,320,336 | 7 | 2011-11-30T02:12:15Z | [
"python",
"bash",
"cron",
"crontab"
] | I have two python scripts running as `cronjobs`.
ScriptA processes log files and insert records to a `table`, ScriptB uses the records to generate a report.
I have arranged ScriptA to run one hour before ScriptB, but sometimes ScriptB run before ScriptA finish inserting, thus generating a incorrect report.
How do I ... | Wouldn't it be better to make a single cron job that runs ScriptA and then ScriptB? That way you can be sure that ScriptB doesn't run until ScriptA finishes, and you don't need to modify either script.
The cronjob could run a simple shell script like:
```
#!/bin/sh
python ScriptA.py
python ScriptB.py
```
**Edit:** ... |
Can I create a static C array with Cython? | 8,320,951 | 13 | 2011-11-30T03:55:13Z | 8,329,774 | 23 | 2011-11-30T16:54:13Z | [
"python",
"arrays",
"cython"
] | I'd like to do exactly this in Cython:
```
cdef int shiftIndexes[] = [1,-1, 0, 2,-1, -1, 4, 0, -1, 8, 1, -1, 16, 1, 0, 32, 1, 1, 64, 0, 1, 128, -1, 1]
```
I've seen a few references in fixed bug reports and old email lists that static array functionality exists in Cython, but I can't find anty examples and this parti... | Use pointer notation instead:
```
cdef int *shiftIndexes = [1,-1, 0, 2,-1, -1, 4, 0, -1, 8, 1, -1, 16, 1, 0, 32, 1, 1, 64, 0, 1, 128, -1, 1]
```
And it will work like a charm. |
Data truncated for column 'cur_url' at row 1 | 8,321,078 | 4 | 2011-11-30T04:17:41Z | 8,321,111 | 23 | 2011-11-30T04:22:50Z | [
"python",
"django"
] | Using django-socialregistration, got error messages:
```
Data truncated for column 'cur_url' at row 1
```
What went wrong here? | You have tried to insert a larger value than field accepts, so it was literally "cut to fit". |
Django: CSRF token missing or incorrect | 8,321,217 | 11 | 2011-11-30T04:35:23Z | 8,321,270 | 25 | 2011-11-30T04:44:28Z | [
"python",
"django",
"django-views"
] | The error is at location <http://127.0.0.1:8000/fileupload/form.py>
I have version 1.3 of django. I have tried specifying localhost:8000 as stated in someone else's question but this did not work for me. I am trying to have a file upload form but I am receiving an error that form.py does not have the CSRF token.
form... | You need to pass `RequestContext` in render\_to\_response for `csrf_token`
For this : (**views.py**)
```
from django.template import RequestContext
...
return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']}, RequestContext(request))
# Added RequestContext
```
This passes the token for c... |
'AnonymousUser' object has no attribute 'backend' | 8,321,319 | 6 | 2011-11-30T04:54:23Z | 8,324,838 | 7 | 2011-11-30T11:00:50Z | [
"python",
"django"
] | Using django-socialregistration, got following error:
```
'AnonymousUser' object has no attribute 'backend'
```
How,
1. I click on facebook connect url.
2. That took me Facebook and ask me to login. So I did, asked permission, I granted.
3. After that it redirect me to my site. And ask to setup. I provide user and e... | Oh man i used to get this error all the time, basically you are calling
```
self.login(request, user)
```
without calling
`authenticate(username=user, password=pwd)`
first
when you call `authenticate`, django sets the backend attribute on the user, noting which backend to use, see here for more details
<https://do... |
Best way to send email with Python on Mac or Linux? | 8,321,586 | 4 | 2011-11-30T05:34:16Z | 8,321,609 | 12 | 2011-11-30T05:39:07Z | [
"python",
"email"
] | I want to send emails with my python script, but unfortunately it's not as straightforward and smooth as php, where I can just use mail() function.
I've used this example:
```
import smtplib
FROM = "sender@example.com"
TO = ["me@gmail.com"]
SUBJECT = "Hello!"
TEXT = "This message was sent with P... | I rewrote the emailing logic :
```
#!/usr/bin/python -tt
from email.mime.text import MIMEText
from datetime import date
import smtplib
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
SMTP_USERNAME = "email@gmail.com"
SMTP_PASSWORD = "yourpassword"
EMAIL_TO = ["recepient1@gmail.com", "recepient2@gmail.com"]
EMAIL_FRO... |
reduce with empty set as initial value | 8,321,598 | 2 | 2011-11-30T05:36:20Z | 8,321,669 | 7 | 2011-11-30T05:46:32Z | [
"python"
] | I have a list of list and I want to construct a set out of the elements present in all the sublists..
example : `a = [[1,2],[2,3]]` should give `set([1,2,3])`
I tried reduce(lambda x,y:x.update(y),a,set([])) but it raises `AttributeError: 'NoneType'` object has no attribute 'update'
Can someone tell me how to do thi... | As requested:
```
>>> a = [[1,2],[2,3]]
>>> reduce(lambda s, elems: s.union(elems), a, set())
set([1, 2, 3])
```
Another way just for fun:
```
>>> from itertools import chain
>>> set(chain.from_iterable(a))
set([1, 2, 3])
```
And one more just to be cool:
```
>>> set.union(set(), *a)
set([1, 2, 3])
``` |
TypeError: 'builtin_function_or_method' object is not subscriptable | 8,322,534 | 3 | 2011-11-30T07:34:04Z | 8,322,573 | 8 | 2011-11-30T07:38:33Z | [
"python",
"tkinter",
"typeerror"
] | ```
elif( listb[0] == "-test"):
run_all.set("testview")
listb.pop[0]
```
> **ERROR**: Exception in Tkinter callback Traceback (most recent call
> last): File
> "/tools/python/2.7.2/lib/python2.7/lib-tk/Tkinter.py", line 1410,
> in **call**
> return self.func(\*args) File "./edit.py", li... | I think you want
```
listb.pop()[0]
```
The expression `listb.pop` is a valid python expression which results in a reference to the `pop` method, but doesn't actually call that method. You need to add the open and close brackets to call the method. |
Adding a string to a list | 8,322,792 | 4 | 2011-11-30T08:02:35Z | 8,322,811 | 10 | 2011-11-30T08:04:40Z | [
"python",
"string",
"list"
] | ```
>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>>
```
What is happening here ? This should not work, right ? or am I missing something obvious?
```
>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
b + c
TypeError: can only conca... | Strings are iterable: the elements are the string's characters. When you add an iterable to a list, the iterable's *elements* get appended to the list.
Either of the following will do what you're expecting (i.e. append the string, not extend the list with the string's characters):
```
b += [c]
```
or
```
b.append(c... |
Adding a string to a list | 8,322,792 | 4 | 2011-11-30T08:02:35Z | 8,322,816 | 8 | 2011-11-30T08:04:58Z | [
"python",
"string",
"list"
] | ```
>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>>
```
What is happening here ? This should not work, right ? or am I missing something obvious?
```
>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
b + c
TypeError: can only conca... | The `+=` operator *extends* a list instead of appending to it:
```
>>> b = []
>>> c = "1234"
>>> b.append(c)
>>> b
['1234']
>>> b.extend(c)
>>> b
['1234', '1', '2', '3', '4']
>>> b += c
>>> b
['1234', '1', '2', '3', '4', '1', '2', '3', '4']
>>> b += [c]
>>> b
['1234', '1', '2', '3', '4', '1', '2', '3', '4', '1234']
``... |
Mac OS X, pip: specify compiler for packages containing C libraries | 8,323,721 | 6 | 2011-11-30T09:33:00Z | 11,732,053 | 9 | 2012-07-31T01:49:33Z | [
"python",
"c",
"osx-lion",
"pip",
"pypi"
] | I am having some trouble with compiling mapscript (is a package from pypi containing C code) with the default clang compiler using pip.
Here's my attempt:-
```
$ sudo pip install mapscript
Password:
Downloading/unpacking mapscript
Running setup.py egg_info for package mapscript
Requirement already satisfied (use -... | Setting the CC environment variable seems to work, e.g.:
> env CC=/usr/bin/gcc-4.0 pip install pyOpenSSL |
Scraping dynamic content in a website | 8,323,728 | 2 | 2011-11-30T09:33:27Z | 8,324,003 | 9 | 2011-11-30T09:53:20Z | [
"python",
"perl",
"web-scraping"
] | I need to scrape news announcements from this website, [Link](http://www.marketvectorsindices.com/#!News/List).
The announcements seem to be generated dynamically. They dont appear in the source. I usually use mechanize but I assume it wouldnt work. What can I do for this? I'm ok with python or perl. | If the content is generated dynamically, you can use `Windmill` or `Seleninum` to drive the browser and get the data once it's been rendered.
You can find an example [here](http://www.packtpub.com/article/web-scraping-with-python-part-2). |
Python, string format, newline (C++ - std::endl) | 8,325,840 | 4 | 2011-11-30T12:18:44Z | 8,325,866 | 7 | 2011-11-30T12:21:01Z | [
"python",
"newline",
"string-formatting"
] | I format string (in overloading operator **str**) and i don't want to use raw \n or \r\n tags.
Have python cross-platform newline identifier like std::endl in C++?
I trying to google it, but don't found answer. | No. Use `\n`. And in C++, `std::endl` is nothing other than `"\n" << std::flush`, and it is *not* more cross-platform, whatever that would mean. It's only slower, as it forces flushing. |
Python, string format, newline (C++ - std::endl) | 8,325,840 | 4 | 2011-11-30T12:18:44Z | 8,325,958 | 13 | 2011-11-30T12:28:49Z | [
"python",
"newline",
"string-formatting"
] | I format string (in overloading operator **str**) and i don't want to use raw \n or \r\n tags.
Have python cross-platform newline identifier like std::endl in C++?
I trying to google it, but don't found answer. | How about using `os.linesep`? It contains the appropriate line separator for your OS:
```
>>> import os
>>> os.linesep
'\n'
>>> print "line one" + os.linesep + "line two"
line one
line two
``` |
how to delete lowercase words from a string in python | 8,326,839 | 2 | 2011-11-30T13:40:14Z | 8,326,888 | 9 | 2011-11-30T13:43:57Z | [
"python",
"list"
] | I'm new in python and I'm having some issues doing a simple thing.
I've an array (or list as it's said in python) like this:
```
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
```
As you see each element of this array contains some words. These words is both lowercase and uppercase.
How I can del... | ```
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
output = [' '.join(w for w in a.split() if w.isupper()) for a in l]
# or:
output = [' '.join(filter(str.isupper, a.split())) for a in l]
```
returns:
```
['NICE', 'FLOWER', 'GOOD', 'YELLOW']
```
(Don't use `list` as variable name.) |
Convert ASCII chars to Unicode FULLWIDTH latin letters in Python? | 8,326,846 | 10 | 2011-11-30T13:40:53Z | 8,327,158 | 9 | 2011-11-30T14:05:40Z | [
"python",
"string",
"unicode"
] | Can you easily convert between ASCII characters and their Asian full-width Unicode wide characters?
Like:
```
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~
```
to
```
ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï½ï½ï½ï½ï½
ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½ï½... | Those "wide" characters are named `FULLWIDTH LATIN LETTER`: <http://www.unicodemap.org/range/87/Halfwidth%20and%20Fullwidth%20Forms/>
They have range 0xFF00 - -0xFFEF. You can make look-up table or just add 0xFEE0 to ASCII code. |
getting and setting mac file and folder finder labels from Python | 8,328,493 | 6 | 2011-11-30T15:33:54Z | 8,329,047 | 11 | 2011-11-30T16:07:17Z | [
"python",
"osx",
"finder"
] | I have been trying to find out how to get and set the colour of file labels from python.
The closest thing I've found to a solution was [this](http://mail.python.org/pipermail/pythonmac-sig/2005-August/014944.html), but I can't seem to find the module macfile anywhere. Am I just not looking hard enough?
Is there a di... | You can do this in python using the [xattr](http://pypi.python.org/pypi/xattr) module.
Here is an example, taken mostly from [this question](http://superuser.com/questions/295151/mac-os-x-is-there-a-straightforward-way-to-color-ls-output-according-to-finder):
```
from xattr import xattr
from struct import unpack
col... |
Hidden field in Django form not in cleaned_data | 8,328,763 | 8 | 2011-11-30T15:49:26Z | 8,329,109 | 9 | 2011-11-30T16:12:13Z | [
"python",
"django",
"django-forms",
"django-views"
] | I have this form:
```
class CollaboratorForm(forms.Form):
user = forms.CharField(label="Username",max_length=100)
canvas = forms.IntegerField(widget=forms.HiddenInput)
....
def clean_user(self):
user = self.cleaned_data['user']
canvas = self.cleaned_data['canvas']
```
In the view I'm s... | You need to change the method name to clean(), not clean\_user(). 'canvas' is not in the cleaned\_data if you are just validating the user field. |
Whats the difference between Python decorators and Decorator Pattern? | 8,328,824 | 19 | 2011-11-30T15:53:07Z | 8,328,877 | 19 | 2011-11-30T15:56:21Z | [
"python",
"design-patterns",
"decorator"
] | Whats the difference between âPython decoratorsâ and the âdecorator patternâ?
When should I use Python decorators, and when should I use the decorator pattern?
I'm looking for examples of Python decorators and the decorator pattern accomplishing same?
**@AcceptedAnswer**
I now that [Jakob Bowyer's... | **Decorator Pattern** - In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically. The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same cl... |
Python : name 'math' is not defined Error? | 8,329,601 | 14 | 2011-11-30T16:42:16Z | 8,329,617 | 29 | 2011-11-30T16:43:13Z | [
"python"
] | I am a beginner in python and cant understand why this is happening:
```
from math import *
print "enter the number"
n=int(raw_input())
d=2
s=0
while d<n :
if n%d==0:
x=math.log(d)
s=s+x
print d
d=d+1
print s,n,float(n)/s
```
Running it in Python and inputing a non prime gives the error
... | Change
```
from math import *
```
to
```
import math
```
Using `from X import *` is generally not a good idea as it uncontrollably pollutes the global namespace and could present other difficulties. |
Python : name 'math' is not defined Error? | 8,329,601 | 14 | 2011-11-30T16:42:16Z | 8,329,621 | 7 | 2011-11-30T16:43:30Z | [
"python"
] | I am a beginner in python and cant understand why this is happening:
```
from math import *
print "enter the number"
n=int(raw_input())
d=2
s=0
while d<n :
if n%d==0:
x=math.log(d)
s=s+x
print d
d=d+1
print s,n,float(n)/s
```
Running it in Python and inputing a non prime gives the error
... | You need to `import math` rather than `from math import *`. |
Can I get a return value from multiprocessing.Process? | 8,329,974 | 25 | 2011-11-30T17:07:28Z | 8,330,339 | 31 | 2011-11-30T17:33:35Z | [
"python",
"multiprocessing"
] | I've implemented some simple parallelism in a Monte Carlo code using the Python multiprocessing module. I have code that looks like:
```
montecarlos = [MonteCarlo(f,fargs) for fargs in farglist]
jobs = [multiprocessing.Process(mc) for mc in montecarlos]
for job in jobs: job.start()
for job in jobs: job.join()
results ... | The `MonteCarlo` objects have been pickled and sent to child processes to be run - the `.results` attribute in this process isn't populated because the local `mc` has never been run.
If you create a [`multiprocessing.Queue`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue), you can pass that ... |
How to recursively loop through a file structure and rename directories in python | 8,331,446 | 6 | 2011-11-30T19:05:51Z | 8,331,898 | 7 | 2011-11-30T19:40:34Z | [
"python",
"rename",
"directory"
] | I would like to resursively rename directories by changing the last character to lowercase (if it is a letter)
I have done this with the help of my previous posts (sorry for the double posting and not acknowledging the answers)
This code works for Files, but how can I adapt it for directories as well?
```
import fnm... | The problem is that the default of [os.walk](http://docs.python.org/library/os.html#os.walk) is topdown. If you try to rename directories while traversing topdown, the results are unpredictable.
Try setting `os.walk` to go bottom up:
```
for root, subFolders, files in os.walk(rootdir,topdown=False):
```
**Edit**
An... |
Python Dictionary to CSV | 8,331,469 | 18 | 2011-11-30T19:07:44Z | 8,331,638 | 15 | 2011-11-30T19:20:18Z | [
"python",
"csv",
"dictionary"
] | I'm a novice Python user but I have written code to read a CSV into a python dictionary, which works fine. But I'm at the end of my rope trying to get the dictionary back to a CSV. I have written the following:
```
import csv
itemDict={}
listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), deli... | The default writer expects a list, which is why it won't work for you. To use the dictwriter, just change your `listwriter =` line to this:
```
listWriter = csv.DictWriter(
open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'),
fieldnames=itemDict[itemDict.keys()[0]].keys(),
delimiter=',',
quotechar='|... |
Is it possible to split and assign a string in a single statement in Python? | 8,331,478 | 6 | 2011-11-30T19:08:58Z | 8,331,561 | 13 | 2011-11-30T19:15:05Z | [
"python"
] | Can a string be split and some of the words be assigned to a tuple in Python.
E.g
```
a = "Jack and Jill went up the hill"
(user1 , user2) = a.split().pick(1,3) #picks 1 and 3 element in the list.
```
Is such a one liner possible? If so what is the syntax. | If you want to get fancy, you could use [`operator.itemgetter`](http://docs.python.org/library/operator.html#operator.itemgetter):
> Return a callable object that fetches item from its operand using the operandâs `__getitem__()` method. If multiple items are specified, returns a tuple of lookup values.
Example:
``... |
How to get around "sys.exit()" in python nosetest? | 8,332,090 | 9 | 2011-11-30T19:54:14Z | 8,332,117 | 18 | 2011-11-30T19:55:53Z | [
"python",
"mocking",
"nose"
] | It seems that python nosetest will quit when encountered "sys.exit()", and mocking of this built-in doesn't work. Thanks for suggestions. | You can try catching the [SystemExit](http://docs.python.org/library/exceptions.html) exception. It is raised when someone calls `sys.exit()`. |
How to get around "sys.exit()" in python nosetest? | 8,332,090 | 9 | 2011-11-30T19:54:14Z | 8,332,149 | 7 | 2011-11-30T19:58:19Z | [
"python",
"mocking",
"nose"
] | It seems that python nosetest will quit when encountered "sys.exit()", and mocking of this built-in doesn't work. Thanks for suggestions. | ```
import sys
sys.exit = lambda *x: None
```
Keep in mind that programs may reasonably expect not to continue after `sys.exit()`, so patching it out might not actually help... |
Set Django's FileField to an existing file | 8,332,443 | 53 | 2011-11-30T20:20:28Z | 8,337,264 | 15 | 2011-12-01T06:14:48Z | [
"python",
"django",
"file"
] | I have an existing file on disk (say /folder/file.txt) and a FileField model field in Django.
When I do
```
instance.field = File(file('/folder/file.txt'))
instance.save()
```
it re-saves the file as `file_1.txt` (the next time it's `_2`, etc.).
I understand why, but I don't want this behavior - I know the file I w... | If you want to do this permanently, you need to create your own FileStorage class
```
from django.core.files.storage import FileSystemStorage
class MyFileStorage(FileSystemStorage):
# This method is actually defined in Storage
def get_available_name(self, name):
return name # simply returns the name pa... |
Set Django's FileField to an existing file | 8,332,443 | 53 | 2011-11-30T20:20:28Z | 10,906,037 | 62 | 2012-06-05T22:43:07Z | [
"python",
"django",
"file"
] | I have an existing file on disk (say /folder/file.txt) and a FileField model field in Django.
When I do
```
instance.field = File(file('/folder/file.txt'))
instance.save()
```
it re-saves the file as `file_1.txt` (the next time it's `_2`, etc.).
I understand why, but I don't want this behavior - I know the file I w... | just set `instance.field.name` to the path of your file
e.g.
```
class Document(models.Model):
file = FileField(upload_to=get_document_path)
description = CharField(max_length=100)
doc = Document()
doc.file.name = 'path/to/file' # must be relative to MEDIA_ROOT
doc.file
<FieldFile: path/to/file>
``` |
pycurl and SSL cert | 8,332,643 | 18 | 2011-11-30T20:40:02Z | 13,072,667 | 15 | 2012-10-25T16:05:03Z | [
"python",
"ssl",
"pycurl"
] | I am trying to write a pycurl script to access a secured site (HTTPS).
```
c = pycurl.Curl()
c.setopt(pycurl.USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0')
c.setopt(pycurl.URL, 'https://for-example-securedsite')
c.setopt(pycurl.COOKIEFILE, 'cookie.txt')
c.setopt(pycurl.COOKIEJAR, ... | You are right, the way you are doing it subjects you to a man-in-the-middle attack, especially in light of the [most recent SSL vulnerabilities](http://threatpost.com/en_us/blogs/ssl-vulnerabilities-found-critical-non-browser-software-packages-102512). You can resolve it as follows:
```
import pycurl
curl = pycurl.Cur... |
Unordered collection for unhashable objects? | 8,332,710 | 6 | 2011-11-30T20:46:32Z | 8,334,382 | 10 | 2011-11-30T23:13:46Z | [
"python",
"collections"
] | I've got a dict where some of the values are not hashable. I need some way to compare two unordered groups of these to ensure they contain equal elements. I can't use lists because list equality takes the order into account but sets won't work because dicts aren't hashable. I had a look through the python docs, and the... | When duplicate entries don't exist, the usual choices are:
1. If the elements are hashable: `set(a) == set(b)`
2. If the elements are orderable: `sorted(a) == sorted(b)`
3. If all you have is equality: `len(a) == len(b) and all(x in b for x in a)`
If you have duplicates and their multiplicity matters, the choices are... |
How to override constructor of Python class with many arguments? | 8,333,354 | 14 | 2011-11-30T21:44:51Z | 8,333,497 | 25 | 2011-11-30T21:55:46Z | [
"python",
"constructor"
] | Say, I have a class Foo, extending class Bar. And I want to slightly override Foo's consructor. And I don't want even know what signarure of Bar's constructors is. Is there a way to do this?
If you didn't understand, I mean the following:
```
class Bar:
def __init__ (self, arg1=None, arg2=None, ... argN=None):
... | ```
class Parent(object):
def __init__(self, a, b):
print 'a', a
print 'b', b
class Child(Parent):
def __init__(self, c, d, *args, **kwargs):
print 'c', c
print 'd', d
super(Child, self).__init__(*args, **kwargs)
test = Child(1,2,3,4)
```
**Output:**
```
c 1
d 2
a 3
b... |
Passing argument from a list | 8,334,162 | 2 | 2011-11-30T22:51:30Z | 8,334,173 | 8 | 2011-11-30T22:52:39Z | [
"python",
"django",
"list"
] | I have a function that I'm using and I need to pass it a list of arguments, however, it gives an error when I try to pass the list because it can't hash.
The function in question here is the values() method on a Django Queryset, but I think this is a more general python question.
So I have:
```
values_list = ['arg1'... | you need to use [list unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists)
```
models.MyModel.objects.values(*values_list).all()
```
(note the asterisk) |
How do I install Python/Django Modules? | 8,334,614 | 11 | 2011-11-30T23:37:43Z | 8,334,700 | 19 | 2011-11-30T23:45:07Z | [
"python",
"django"
] | I know absolutely nothing about Django, but I am needing to get an existing project running in OSX.
From the project's directory I run `python manage.py runserver` and get the error: `Error: No module named cms`.
Seems like the INSTALLED\_APPS constant (in settings.py) defines the required modules... but how do I ins... | you can install all dependencies in once, if there is a requirements.txt file! you just have to run the follow command:
```
pip install -r requirements.txt
```
otherwise you can install one by one:
```
pip install django-cms
```
Here is the PIP documentation:
<http://pypi.python.org/pypi/pip>
if you are used to ru... |
Selenium and Python on Snow Leopard | 8,334,706 | 5 | 2011-11-30T23:45:54Z | 8,341,766 | 7 | 2011-12-01T12:57:20Z | [
"python",
"osx",
"selenium"
] | I'm trying to use the stock Python (2.6.1) on Snow Leopard with Selenium. Being quite new to Python, I'm a at a bit of a loss for what I've done wrong, as this exact same process worked just fine on my ubuntu box:
1. sudo easy\_install -U selenium
2. Create a simple test with Firefox Selenium UI, and export it as Pyth... | Check your Firefox binary location first. Does it placed at here: /Applications/Firefox.app/Contents/MacOS/firefox
?
For more information, please check this page: <http://code.google.com/p/selenium/wiki/FirefoxDriver> |
Is there a way to negate a boolean returned to variable? | 8,335,029 | 26 | 2011-12-01T00:23:41Z | 8,335,038 | 49 | 2011-12-01T00:25:13Z | [
"python",
"django"
] | I have a Django site, with an `Item` object that has a boolean property `active`. I would like to do something like this to toggle the property from False to True and vice-versa:
```
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = !item.active
item.save()
```
This syntax is v... | You can do this:
`item.active = not item.active`
That should do the trick :) |
Is there a way to negate a boolean returned to variable? | 8,335,029 | 26 | 2011-12-01T00:23:41Z | 8,335,041 | 10 | 2011-12-01T00:25:39Z | [
"python",
"django"
] | I have a Django site, with an `Item` object that has a boolean property `active`. I would like to do something like this to toggle the property from False to True and vice-versa:
```
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = !item.active
item.save()
```
This syntax is v... | `item.active = not item.active` is the pythonic way |
Is there a way to negate a boolean returned to variable? | 8,335,029 | 26 | 2011-12-01T00:23:41Z | 8,335,044 | 12 | 2011-12-01T00:25:52Z | [
"python",
"django"
] | I have a Django site, with an `Item` object that has a boolean property `active`. I would like to do something like this to toggle the property from False to True and vice-versa:
```
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = !item.active
item.save()
```
This syntax is v... | I think you want
```
item.active = not item.active
``` |
Is there a way to negate a boolean returned to variable? | 8,335,029 | 26 | 2011-12-01T00:23:41Z | 8,335,089 | 7 | 2011-12-01T00:31:16Z | [
"python",
"django"
] | I have a Django site, with an `Item` object that has a boolean property `active`. I would like to do something like this to toggle the property from False to True and vice-versa:
```
def toggle_active(item_id):
item = Item.objects.get(id=item_id)
item.active = !item.active
item.save()
```
This syntax is v... | Another (less concise readable, more arithmetic) way to do it would be:
```
item.active = bool(1 - item.active)
``` |
Iterate over nested dictionary | 8,335,096 | 15 | 2011-12-01T00:32:12Z | 8,335,132 | 16 | 2011-12-01T00:37:19Z | [
"python"
] | Is there an easy way of iterating over nested dictionary, which may consist of other objects like lists, tuples, then again dictionaries so that iteration covers all the elements of these other objects?
For example, if I type a key of a nested dictionary object, I would get it all listed in the Python interpreter.
--... | ```
def recurse(d):
if type(d)==type({}):
for k in d:
recurse(d[k])
else:
print d
``` |
How to crawl a website/extract data into database with python? | 8,335,630 | 10 | 2011-12-01T01:51:26Z | 8,335,661 | 10 | 2011-12-01T01:55:49Z | [
"python",
"web-crawler"
] | I'd like to build a webapp to help other students at my university create their schedules. To do that I need to crawl the master schedules (one huge html page) as well as a link to a detailed description for each course into a database, preferably in python. Also, I need to log in to access the data.
* How would that ... | * [`requests`](http://python-requests.org) for downloading the pages.
+ Here's an example of how to login to a website and download pages: <http://stackoverflow.com/a/8316989/311220>
* [`lxml`](http://lxml.de) for scraping the data.
If you want to use a powerful scraping framework there's [`Scrapy`](http://doc.scrap... |
How to print +1 in Python, as +1 (with plus sign) instead of 1? | 8,337,004 | 15 | 2011-12-01T05:37:00Z | 8,337,012 | 26 | 2011-12-01T05:38:33Z | [
"python",
"number-formatting"
] | As mentioned in the title, how do I get Python to print out +1 instead of 1?
```
score = +1
print score
>> 1
```
I know -1 prints as -1 but how can I get positive values to print with + sign without adding it in manually myself.
Thank you. | With [the `%` operator](http://docs.python.org/library/stdtypes.html#string-formatting-operations):
```
print '%+d' % score
```
With [`str.format`](http://docs.python.org/library/stdtypes.html?highlight=str.format#str.format):
```
print '{0:+d}'.format(score)
```
You can see the documentation for the formatting min... |
Find the index of the n'th item in a list | 8,337,069 | 32 | 2011-12-01T05:46:16Z | 8,337,140 | 26 | 2011-12-01T05:53:54Z | [
"python",
"performance",
"indexing"
] | I want to find the index of the n'th occurrence of an item in a list. e.g.,
```
x=[False,True,True,False,True,False,True,False,False,False,True,False,True]
```
What is the index of the n'th true? If I wanted the fifth occurrence (4th if zero-indexed), the answer is 10.
I've come up with:
```
indargs = [ i for i,a i... | I can't say for certain that this is the fastest way, but I imagine it'd be pretty good:
```
i = -1
for j in xrange(n):
i = x.index(True, i + 1)
```
The answer is `i`. |
Find the index of the n'th item in a list | 8,337,069 | 32 | 2011-12-01T05:46:16Z | 8,337,489 | 31 | 2011-12-01T06:44:30Z | [
"python",
"performance",
"indexing"
] | I want to find the index of the n'th occurrence of an item in a list. e.g.,
```
x=[False,True,True,False,True,False,True,False,False,False,True,False,True]
```
What is the index of the n'th true? If I wanted the fifth occurrence (4th if zero-indexed), the answer is 10.
I've come up with:
```
indargs = [ i for i,a i... | The answer from @Taymon using *list.index* was great.
FWIW, here's a functional approach using the [itertools module](http://docs.python.org/library/itertools.html#module-itertools). It works with any iterable input, not just lists:
```
>>> from itertools import compress, count, imap, islice
>>> from functools import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.