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 |
|---|---|---|---|---|---|---|---|---|---|
why is plotting with Matplotlib so slow? | 8,955,869 | 49 | 2012-01-21T19:11:13Z | 11,093,027 | 9 | 2012-06-19T00:50:34Z | [
"python",
"matplotlib"
] | I'm currently evaluating different python plotting libraries. Right now I'm trying matplotlib and I'm quite disappointed with the performance. The following example is modified from <http://www.scipy.org/Cookbook/Matplotlib/Animations> and gives me only ~ 8 frames per second!
Am I doing something wrong, or why is the ... | Matplotlib makes great publication-quality graphics, but is not very well optimized for speed.
There are a variety of python plotting packages that are designed with speed in mind:
* <http://pyqwt.sourceforge.net/>
[ edit: pyqwt is no longer maintained; the previous maintainer is recommending pyqtgraph ]
* <http:/... |
How to determine CPU and memory cost of a function? | 8,956,193 | 10 | 2012-01-21T19:59:22Z | 8,957,968 | 7 | 2012-01-22T00:24:43Z | [
"python",
"memory-management",
"cpu-usage"
] | Can someone suggest what would be the best practice or a suitable library to determine:
1. Number of **CPU cycles** used during execution of a Python function?
2. Amount of **Memory** used by the same Python function?
I had looked at **guppy** and **meliae**, but still can't get granular to the function level? Am I m... | You may want to look into a `CPU profiler` for Python:
<http://docs.python.org/library/profile.html>
Example output of `cProfile.run(command[, filename])`
```
2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(fu... |
SQLAlchemy relationship on many-to-many association table | 8,956,245 | 3 | 2012-01-21T20:07:14Z | 8,962,098 | 7 | 2012-01-22T15:18:17Z | [
"python",
"sqlalchemy"
] | I am trying to build a relationship to another many-to-many relationship, the code looks like this:
```
from sqlalchemy import Column, Integer, ForeignKey, Table, ForeignKeyConstraint, create_engine
from sqlalchemy.orm import relationship, backref, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import de... | You need to map supervision\_association\_table so that you can create relationships to/from it.
I may be glossing over something here, but it seems like since you have many-to-many here you really can't have Client.schedules - if I say Client.schedules.append(some\_schedule), which row in "supervision" is it pointing... |
Can't assign to operator error, I don't understand? | 8,956,825 | 5 | 2012-01-21T21:25:41Z | 8,956,876 | 8 | 2012-01-21T21:31:38Z | [
"python",
"operator-keyword"
] | ```
def RandomString (length,distribution):
string = ""
for t in distribution:
((t[1])/length) * t[1] += string
return shuffle (string)
```
This returns a syntax error as described in the title. In this example, distribution is a list of `tuples`, with each `tuple` containing a letter, and its dist... | Python is upset because you are attempting to assign a value to something that can't be assigned a value.
```
((t[1])/length) * t[1] += string
```
When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on ... |
Python out of memory on large CSV file (numpy) | 8,956,832 | 27 | 2012-01-21T21:26:46Z | 8,964,779 | 52 | 2012-01-22T21:16:17Z | [
"python",
"memory",
"csv",
"numpy",
"scipy"
] | I have a 3GB CSV file that I try to read with python, I need the median column wise.
```
from numpy import *
def data():
return genfromtxt('All.csv',delimiter=',')
data = data() # This is where it fails already.
med = zeros(len(data[0]))
data = data.T
for i in xrange(len(data)):
m = median(data[i])
med[... | As other folks have mentioned, for a really large file, you're better off iterating.
However, you do commonly want the entire thing in memory for various reasons.
`genfromtxt` is much less efficient than `loadtxt` (though it handles missing data, whereas `loadtxt` is more "lean and mean", which is why the two functio... |
How to iterate through every class declaration, descended from a particular base class? | 8,956,928 | 4 | 2012-01-21T21:38:44Z | 8,962,480 | 8 | 2012-01-22T16:13:27Z | [
"python",
"sqlalchemy",
"python-elixir"
] | I was wandering how does elixir\sqlalchemy get to know all the entity classes I've declared in my model, when I call `setup_all()`? I need that kind of functionality in a little project of mine, but I have no clue. I've tried to steptrace through elixir's `setup_all()`, and I found that it keeps a collection of all ent... | For class definitions, this is easier (no importing)
```
def find_subclasses(cls):
results = []
for sc in cls.__subclasses__():
results.append(sc)
return results
```
I'm not sure if you wanted this, or objects. If you want objects:
```
import gc
def find_subclasses(cls):
results = []
for... |
Creating fibonacci sequence generator (Beginner Python) | 8,957,310 | 3 | 2012-01-21T22:35:24Z | 8,957,322 | 7 | 2012-01-21T22:37:20Z | [
"python"
] | Hi I'm trying to create a Fibonacci sequence generator in Python. This is my code:
```
d =raw_input("How many numbers would you like to display")
a = 1
b = 1
print a
print b
for d in range(d):
c = a + b
print c
a = b
b = c
```
When I ran this program, I get the error:
```
File "Fibonacci Sequence... | raw\_input returns a string. So convert d to an integer with:
```
d = int(d)
```
One more thing: Do not use `for d in range(d)`. It works but it is awful, unpythonic, whatever.
Try this way for example:
```
numbers = raw_input("How many numbers would you like to display")
a = 1
b = 1
print a
print b
for d in ra... |
What are Python dictionary view objects? | 8,957,750 | 97 | 2012-01-21T23:48:19Z | 8,957,898 | 15 | 2012-01-22T00:10:55Z | [
"python",
"view",
"dictionary"
] | In python 2.7, we got the [dictionary view methods](http://docs.python.org/library/stdtypes.html#dictionary-view-objects) available.
Now, I know the pro and cons of the following:
* `dict.items()` (and `values`, `keys`): returns a list, so you can actually store the result
* `dict.iteritems()` (and the like): returns... | The view methods return a list(not a copy of the list, compared to `.keys()`, `.items()` and `.values()`), so it is more lightweight, but reflects the current contents of dictionary.
From [Python 3.0 - dict methods return views - why?](http://stackoverflow.com/questions/340850/python-3-0-dict-methods-return-views-why)... |
What are Python dictionary view objects? | 8,957,750 | 97 | 2012-01-21T23:48:19Z | 8,957,924 | 12 | 2012-01-22T00:16:12Z | [
"python",
"view",
"dictionary"
] | In python 2.7, we got the [dictionary view methods](http://docs.python.org/library/stdtypes.html#dictionary-view-objects) available.
Now, I know the pro and cons of the following:
* `dict.items()` (and `values`, `keys`): returns a list, so you can actually store the result
* `dict.iteritems()` (and the like): returns... | Just from reading the docs I get this impression:
1. Views are "pseudo-set-like", in that they don't support indexing, so what you can do with them is test for membership and iterate over them (because keys are hashable and unique, the keys and items views are more "set-like" in that they don't contain duplicates).
2.... |
What are Python dictionary view objects? | 8,957,750 | 97 | 2012-01-21T23:48:19Z | 8,960,727 | 87 | 2012-01-22T11:30:04Z | [
"python",
"view",
"dictionary"
] | In python 2.7, we got the [dictionary view methods](http://docs.python.org/library/stdtypes.html#dictionary-view-objects) available.
Now, I know the pro and cons of the following:
* `dict.items()` (and `values`, `keys`): returns a list, so you can actually store the result
* `dict.iteritems()` (and the like): returns... | Dictionary views are essentially what their name says: **views are simply like a window** on the keys and values (or items) of a dictionary. Here is an excerpt from the [official documentation](http://docs.python.org/py3k/library/stdtypes.html#dictionary-view-objects) for Python 3:
```
>>> dishes = {'eggs': 2, 'sausa... |
What are Python dictionary view objects? | 8,957,750 | 97 | 2012-01-21T23:48:19Z | 16,600,136 | 11 | 2013-05-17T01:38:41Z | [
"python",
"view",
"dictionary"
] | In python 2.7, we got the [dictionary view methods](http://docs.python.org/library/stdtypes.html#dictionary-view-objects) available.
Now, I know the pro and cons of the following:
* `dict.items()` (and `values`, `keys`): returns a list, so you can actually store the result
* `dict.iteritems()` (and the like): returns... | As you mentioned `dict.items()` returns a copy of the dictionaryâs list of (key, value) pairs which is wasteful and `dict.iteritems()` returns an iterator over the dictionaryâs (key, value) pairs.
Now take the following example to see the difference between an interator of dict and a view of dict
```
>>> d = {"x"... |
Python Child cannot use a Module the Parent Imported | 8,957,859 | 4 | 2012-01-22T00:04:56Z | 8,957,891 | 8 | 2012-01-22T00:10:33Z | [
"python",
"inheritance",
"import",
"polymorphism"
] | I have a funny import error when using Inheritence in Python.
In a parent class I import the module sqlite3, in a child class I then try to use a sqlite3 function but I get an error saying "NameError: global name 'sqlite3' is not defined". **Why does this happen & how do I fix it?**
The 2 classes are in separate file... | the sqlite3 module is imported into the Parent module hence you need to access it through that module
```
self.db = Parent.sqlite3.connect("test.db")
```
It is not directly imported into the Child module unless you tell python to do so, for example
```
from Parent import *
```
Will give you access to all the member... |
Measure Network Data with Python | 8,958,614 | 7 | 2012-01-22T03:03:11Z | 8,958,853 | 16 | 2012-01-22T04:03:59Z | [
"python",
"networking",
"traffic-measurement"
] | I'm currently writing a program to shut down a computer when over a period of time (say, half an hour) network traffic is below a certain threshold.
Here's the pseudocode that I've worked will give the correct logic:
```
BEGIN SUBPROGRAM
loopFlag = True
Wait 5 minutes # Allows time for boot and for the mac... | To check the network traffic on your system, i recommend you look into `psutil` [here](http://code.google.com/p/psutil/) :
```
>>> psutil.network_io_counters(pernic=True)
{'lo': iostat(bytes_sent=799953745, bytes_recv=799953745, packets_sent=453698, packets_recv=453698),
'eth0': iostat(bytes_sent=734324837, bytes_re... |
What is the difference between class and instance variables in Python? | 8,959,097 | 30 | 2012-01-22T05:01:25Z | 8,959,145 | 9 | 2012-01-22T05:14:53Z | [
"python",
"class",
"variables",
"self"
] | What is the difference between class and instance variables in Python?
```
class Complex:
a = 1
```
and
```
class Complex:
def __init__(self):
self.a = 1
```
Using the call: `x = Complex().a` in both cases assigns x to 1.
A more in-depth answer about `__init__()` and `self` will be appreciated. | What you're calling an "instance" variable isn't actually an instance variable; it's a **class variable**. See the [language reference about classes](http://docs.python.org/reference/compound_stmts.html#class-definitions).
In your example, the `a` appears to be an instance variable because it is immutable. It's nature... |
What is the difference between class and instance variables in Python? | 8,959,097 | 30 | 2012-01-22T05:01:25Z | 8,959,269 | 54 | 2012-01-22T05:43:39Z | [
"python",
"class",
"variables",
"self"
] | What is the difference between class and instance variables in Python?
```
class Complex:
a = 1
```
and
```
class Complex:
def __init__(self):
self.a = 1
```
Using the call: `x = Complex().a` in both cases assigns x to 1.
A more in-depth answer about `__init__()` and `self` will be appreciated. | When you write a class block, you create *class attributes* (or class variables). All the names you assign in the class block, including methods you define with `def` become class attributes.
After a class instance is created, anything with a reference to the instance can create instance attributes on it. Inside metho... |
os.path.isfile does not work as expected | 8,959,187 | 7 | 2012-01-22T05:25:01Z | 8,959,348 | 9 | 2012-01-22T06:01:30Z | [
"python"
] | I am trying to scan my harddrive for jpg and mp3 files.
I have written the following script which works if I pass it a directory with file in the root but does not return anything if I pass it the root directory.
I am new to Python so would love some help.
```
def findfiles(dirname,fileFilter):
filesBySize = {}... | Ah yes.
You're calling `os.path.isfile(f)` where `f` is the filename within the `path`. You'll need to provide an *absolute* path. If, indeed, this call is necessary (it should always return `True`).
Try changing your for-loop to:
```
qualified_filenames = (os.path.join(path, filename) for filename in fnames)
... |
Get page generated with Javascript in Python | 8,960,288 | 19 | 2012-01-22T09:59:23Z | 8,960,386 | 28 | 2012-01-22T10:16:04Z | [
"javascript",
"python",
"html",
"download",
"urllib2"
] | I'd like to download web page generated by `Javascript` and store it to string variable in `Python` code. The page is generated when you click on button.
If I would know the resulting URL I would use `urllib2` but this is not the case.
thank you | You could use [Selenium Webdriver](http://seleniumhq.org/docs/03_webdriver.html):
```
#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait
# use firefox to get page with javascript generated content
w... |
Stackless in PyPy and PyPy + greenlet - differences | 8,960,747 | 13 | 2012-01-22T11:34:03Z | 8,992,115 | 12 | 2012-01-24T18:34:15Z | [
"python",
"gevent",
"pypy",
"python-stackless",
"greenlets"
] | New version of PyPy ships with integrated *Stackless*.
As far as I know the bundled Stackless is not the same as the origin Stackless from 2001 with continuations. So mainly it is the green threads framework with dispatcher.
*Greenlet* is a spin-of Stackless which provides the Stackless green threads functionality as ... | **Does PyPy ships with an asynchronous IO library for Stackless to be used instead of standard one?**
As of PyPy 2.6.1 and PyPy3 2.4.0 you can use [asyncio](https://docs.python.org/3/library/asyncio.html) (via the pypi package) to replace *the asynchronous features* of stackless.
**Is there any benefit from using "na... |
if, elif not working as expected | 8,960,763 | 2 | 2012-01-22T11:38:48Z | 8,960,786 | 9 | 2012-01-22T11:42:18Z | [
"python"
] | I am new to Python and I do not know why but the `if`, `elif` in the following code is not working as I expect it to. However,
* It works perfectly when I type 1 to 7
* it works perfectly when I type 0 8 or 9 (it says "Try again")
* It does not work if I type 10 to 69, 100 to any number
When I say it does not work I ... | Strings are compared [lexicographically](http://en.wikipedia.org/wiki/Lexicographical_order): `'10'` is greater than `'1'` but less than `'7'`. Now consider this code:
```
elif (choice >= '1' and choice <= '7'):
```
In addition to accepting `'7'`, this will accept any string beginning with `1`, `2`, `3`, `4`, `5` or ... |
Pass parameter to fabric task | 8,960,777 | 80 | 2012-01-22T11:40:15Z | 8,960,883 | 134 | 2012-01-22T12:00:04Z | [
"python",
"fabric"
] | How can I pass a parameter to a fabric task when calling "fab" from the command line? For example:
```
def task(something=''):
print "You said %s" % something
```
```
$ fab task "hello"
You said hello
Done.
```
Is it possible to do this without prompting with `fabric.operations.prompt`? | Fabric uses the following syntax for passing arguments to tasks:
```
fab task:'hello world'
fab task:something='hello'
fab task:foo=99,bar=True
fab task:foo,bar
```
You can read more about it in [Fabric docs](http://docs.fabfile.org/en/latest/usage/fab.html#per-task-arguments). |
Comparing None with built-in types using arithmetic operators? | 8,961,005 | 13 | 2012-01-22T12:22:43Z | 8,961,036 | 15 | 2012-01-22T12:27:54Z | [
"python",
"comparison",
"cpython"
] | ```
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> None > 0
False
>>> None == 0
False
>>> None < 0
True
```
* Is comparing `None` using arithmetic operators well defined for built-in types (integers in this c... | The only meaningful comparison you can really use with `None` is `if obj is None:` (or `if obj is not None:`).
Comparison between different types has been removed from Python 3 for good reasons - they were a common source of errors and lead to confusion. For example
```
>>> "3" < 4
False
```
In Python 3, you get a `... |
python data structure validation using Validator (or something similar) | 8,961,106 | 9 | 2012-01-22T12:39:36Z | 8,961,343 | 8 | 2012-01-22T13:16:51Z | [
"python",
"json",
"validation",
"jsonschema"
] | I'm dealing with data input in the form of json documents.
These documents need to have a certain format, if they're not compliant, they should be ignored. I'm currently using a messy list of 'if thens' to check the format of the json document.
I have been experimenting a bit with different python json-schema librarie... | Add `"additionalProperties": False`:
```
#!/usr/bin/python
from jsonschema import Validator
checker = Validator()
schema = {
"type" : "object",
"properties" : {
"source" : {
"type" : "object",
"properties" : {
"name" : {"type" : "string" }
},
... |
Error 429 when invoking Reddit api from Google App Engine | 8,963,485 | 8 | 2012-01-22T18:29:52Z | 12,300,001 | 11 | 2012-09-06T12:19:55Z | [
"python",
"google-app-engine",
"reddit"
] | I have been running a cron job on Google App Engine for over a month now without any issues. The job does a variety of things, one being that it uses urllib2 to make a call to retrieve a json response from Reddit as well as a few other sites. About two weeks ago I started seeing errors when invoking Reddit, but no erro... | Reddit rate limits the api pretty severely for the default user agent for the python shell. You need to set a unique user agent with your reddit username in it, like this:
> User-Agent: super happy flair bot by /u/spladug
More info about the reddit api here <https://github.com/reddit/reddit/wiki/API>. |
Test type of elements python tuple/list | 8,964,191 | 6 | 2012-01-22T19:59:00Z | 8,964,208 | 16 | 2012-01-22T20:00:34Z | [
"python"
] | How do you verify that the type of all elements in a list or a tuple are the same and of a certain type?
for example:
```
(1, 2, 3) # test for all int = True
(1, 3, 'a') # test for all int = False
``` | ```
all(isinstance(n, int) for n in lst)
```
Demo:
```
In [3]: lst = (1,2,3)
In [4]: all(isinstance(n, int) for n in lst)
Out[4]: True
In [5]: lst = (1,2,'3')
In [6]: all(isinstance(n, int) for n in lst)
Out[6]: False
```
Instead of `isinstance(n, int)` you could also use `type(n) is int` |
Delete Duplicate Rows in Django DB | 8,965,391 | 5 | 2012-01-22T22:44:22Z | 8,965,461 | 12 | 2012-01-22T22:53:57Z | [
"python",
"django"
] | I have a model where because of a code bug, there are duplicate rows. I now need to delete any duplicates from the database.
Every row should have a unique photo\_id. Is there a simple way to remove them? Or do I need to do something like this:
```
rows = MyModel.objects.all()
for row in rows:
try:
MyMode... | The simplest way is the simplest way! Especially for one off scripts where performance doesn't even matter (unless it does). Since it's not core code, I'd just write the first thing that comes to mind and *works*.
```
# assuming which duplicate is removed doesn't matter...
for row in MyModel.objects.all():
if MyMo... |
Delete Duplicate Rows in Django DB | 8,965,391 | 5 | 2012-01-22T22:44:22Z | 10,290,420 | 9 | 2012-04-24T01:01:15Z | [
"python",
"django"
] | I have a model where because of a code bug, there are duplicate rows. I now need to delete any duplicates from the database.
Every row should have a unique photo\_id. Is there a simple way to remove them? Or do I need to do something like this:
```
rows = MyModel.objects.all()
for row in rows:
try:
MyMode... | This may be faster because it avoids the inner filter for each row in MyModel.
Since the ids are unique, if the models are sorted by them in increasing order, we can keep track of the last id we saw and as we walk over the rows if we see a model with the same id, it must be a duplicate, so we can delete it.
```
lastS... |
Syntax behind sorted(key=lambda :) | 8,966,538 | 64 | 2012-01-23T02:09:18Z | 8,966,555 | 18 | 2012-01-23T02:11:35Z | [
"python",
"sorting",
"lambda"
] | I don't quite understand the syntax behind the `sorted()` argument:
```
key=lambda variable: variable[0]
```
Isn't `lambda` arbitrary? Why is `variable` stated twice in what looks like a `dict`? | `lambda` is a Python keyword that is used to [generate anonymous functions](http://docs.python.org/reference/expressions.html#lambda).
```
>>> (lambda x: x+2)(3)
5
``` |
Syntax behind sorted(key=lambda :) | 8,966,538 | 64 | 2012-01-23T02:09:18Z | 8,966,557 | 8 | 2012-01-23T02:11:49Z | [
"python",
"sorting",
"lambda"
] | I don't quite understand the syntax behind the `sorted()` argument:
```
key=lambda variable: variable[0]
```
Isn't `lambda` arbitrary? Why is `variable` stated twice in what looks like a `dict`? | The `variable` left of the `:` is a parameter name. The use of `variable` on the right is making use of the parameter.
Means almost exactly the same as:
```
def some_method(variable):
return variable[0]
``` |
Syntax behind sorted(key=lambda :) | 8,966,538 | 64 | 2012-01-23T02:09:18Z | 8,966,627 | 67 | 2012-01-23T02:26:36Z | [
"python",
"sorting",
"lambda"
] | I don't quite understand the syntax behind the `sorted()` argument:
```
key=lambda variable: variable[0]
```
Isn't `lambda` arbitrary? Why is `variable` stated twice in what looks like a `dict`? | `key` is a function that will be called to transform the collection's items before they are compared. The parameter passed to `key` must be something that is callable.
The use of `lambda` creates an anonymous function (which is callable). In the case of `sorted` the callable only takes one parameters. Python's `lambda... |
Function closure vs. callable class | 8,966,785 | 6 | 2012-01-23T03:04:38Z | 8,966,965 | 8 | 2012-01-23T03:44:54Z | [
"python",
"performance",
"design",
"python-3.x",
"closures"
] | In many cases, there are two implementation choices: a closure and a callable class. For example,
```
class F:
def __init__(self, op):
self.op = op
def __call__(self, arg1, arg2):
if (self.op == 'mult'):
return arg1 * arg2
if (self.op == 'add'):
return arg1 + arg2
raise InvalidOp(op)
f... | Closures are faster. Classes are more flexible (i.e. more methods available than just \_\_call\_\_). |
Python data structure similar to dictionary where key is two values? | 8,967,163 | 2 | 2012-01-23T04:23:13Z | 8,967,179 | 11 | 2012-01-23T04:26:42Z | [
"python"
] | I am looking for a data structure in Python that is similar to a dictionary. The difference is that there is two keys. I want to be able to access the value in constant time.
Like:
```
dict.get(dog, smurf)
{(dog, smurf): 40}
```
Is this possible?
If this doesn't exist, I would just do a dictionary in a dictionary. B... | What's stopping you?
```
d = {(dog, smurf): 40}
print d[(dog, smurf)] # 40
``` |
Flask with a webserver breaks all sessions? | 8,967,216 | 4 | 2012-01-23T04:33:06Z | 8,983,526 | 14 | 2012-01-24T07:48:45Z | [
"python",
"session",
"flask",
"lighttpd"
] | For example, this code:
```
from flask import session
@app.route('/is_logged_in/')
def is_logged_in():
return 'user' in session
```
It runs fine for me when running Flask's development server, but it throws a `500` error with *any* webserver setup (FastCGI, uWSGI, etc.) on any server (Apache, nginx, Lighttpd).
An... | I finally tried [Tornado](http://www.tornadoweb.org/), thinking it would help with my problems (it's written in Python, after all).
Lo and behold, a readable traceback:
```
RuntimeError: the session is unavailable because no secret key was set.
Set the secret_key on the application to something unique and secret.
```... |
How to install Oauth2.0 for python in Ubuntu | 8,967,494 | 6 | 2012-01-23T05:21:22Z | 8,967,508 | 12 | 2012-01-23T05:23:25Z | [
"python",
"ubuntu"
] | Hi I have ownloaded simplegeo-python-oauth2-debian-1.5.211-0-ga83f4a2.tar.gz .I do not know how to install it for python in ubuntu. can anyone help? | Extract it and run:
```
python setup.py build
sudo python setup.py install
``` |
Run 4 concurrent instances of a python script on a folder of data files | 8,968,373 | 5 | 2012-01-23T07:30:03Z | 8,968,406 | 7 | 2012-01-23T07:34:35Z | [
"python",
"multithreading",
"bash",
"xargs"
] | We have a folder with 50 datafiles (next-gen DNA sequences) that need to be converted by running a python script on each one. The script takes 5 hours per file and it is single threaded and is largely CPU bound (the CPU core runs at 99% with minimal disk IO).
Since I have a 4 core machine, I'd like to run 4 instances ... | You can use the [`multiprocessing`](http://docs.python.org/library/multiprocessing.html)-module. I suppose you have a list of files to process and a function to call for each file. Then you could simply use a worker-pool like this:
```
from multiprocessing import Pool, cpu_count
pool = Pool(processes=cpu_count)
pool.... |
Python serialization - Why pickle? | 8,968,884 | 46 | 2012-01-23T08:35:01Z | 8,968,969 | 60 | 2012-01-23T08:45:07Z | [
"python",
"serialization",
"pickle"
] | I understood that Python pickling is a way to 'store' a Python Object in a way that does respect Object programming - different from an output written in txt file or DB.
Do you have more details or references on the following points:
* where are pickled objects 'stored'?
* why is pickling preserving object representa... | Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.
As for where the pickled information is stored, usually one would do:
```
with open('filename', 'wb... |
Python serialization - Why pickle? | 8,968,884 | 46 | 2012-01-23T08:35:01Z | 19,360,828 | 21 | 2013-10-14T13:00:45Z | [
"python",
"serialization",
"pickle"
] | I understood that Python pickling is a way to 'store' a Python Object in a way that does respect Object programming - different from an output written in txt file or DB.
Do you have more details or references on the following points:
* where are pickled objects 'stored'?
* why is pickling preserving object representa... | Pickling is absolutely necessary for distributed and parallel computing.
Say you wanted to do a parallel map-reduce with `multiprocessing` (or across cluster nodes with [pyina](http://pythonhosted.org/pyina)), then you need to make sure the function you want to have mapped across the parallel resources will pickle. If... |
Python regex search AND split | 8,970,524 | 7 | 2012-01-23T10:56:51Z | 8,970,565 | 12 | 2012-01-23T11:01:02Z | [
"python",
"regex"
] | In PHP one can use the function `preg_match` with the flag `PREG_OFFSET_CAPTURE` in order to search a regex patter within a string and know what follows and what comes first. For example, given the string `aaa bbb ccc ddd eee fff`, I'd like to match-split `r'ddd'` and have:
```
before = 'aaa bbb ccc '
match = 'ddd'
af... | You can use `re.split()` but you need to put parentheses around the pattern so as to save the match:
```
>>> re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)
['aaa bbb ccc ', 'ddd', ' eee fff']
```
but in this case you don't need a regex at all:
```
>>> 'aaa bbb ccc ddd eee fff'.partition('ddd')
('aaa bbb ccc ', 'ddd... |
Should I use Python in stead of VBA? | 8,971,163 | 4 | 2012-01-23T11:52:21Z | 8,973,935 | 8 | 2012-01-23T15:20:16Z | [
"python",
"excel",
"vba",
"ms-access-2007"
] | I am been building a demo (and potentially a small application) for a financial accounting model. I am using VBA/Excel for data input (eg with forms), calculations and presentation of results and I am also running SQL-questions to MS Access database from the VBA program. In principle, the functionality of these compone... | If you decide to use Python to drive automation of Office applications, look into [Python Win32 Extensions](http://starship.python.net/~skippy/win32/Downloads.html)
However, I'm skeptical that is advisable. It would require you to install and learn Python. And if this is an application you distribute to users, they wo... |
Matplotlib 3D scatter color lost after redraw | 8,971,309 | 11 | 2012-01-23T12:05:13Z | 8,974,087 | 10 | 2012-01-23T15:29:39Z | [
"python",
"matplotlib"
] | Related to [this question](http://stackoverflow.com/questions/8891994/matplotlib-3d-scatter-plot-with-color-gradient), I want a 3D scatter plot with prescribed colors for each point. The example posted in the question works on my system, but after the first redraw (for instance after saving or if I rotate the image) th... | It's not clear why this is happening, and it certainly is a bug. Here I provide a hack to get the result you want, though it is not *as* automatic as one would want.
For some reason, the `Patch3DCollection` representing the scatter points is not updated after the first rendering. This update is essential, because it i... |
how to set foreign key during form completion (python/django) | 8,971,606 | 3 | 2012-01-23T12:29:19Z | 8,971,799 | 16 | 2012-01-23T12:43:12Z | [
"python",
"django",
"forms",
"foreign-keys"
] | During form processing I'd like to be able to set a foreign key field on a model object without the user having to select the key from a dropdown.
For instance:
```
#models.py
class AAA(models.Model):
some_field = models.TextField()
class BBB(models.Model):
another_field = models.TextField()
key_field =... | You can exclude the `key_field` from your model form, save with `commit=False`, then set `key_field` in your view before saving to the database.
```
class BBBForm(forms.ModelForm):
class Meta:
model = BBB
exclude = ("key_field",)
def create_view(request, **kwargs):
if request.method == "POST":... |
Matplotlib savefig with a legend outside the plot | 8,971,834 | 24 | 2012-01-23T12:46:21Z | 8,972,020 | 21 | 2012-01-23T13:00:57Z | [
"python",
"matplotlib",
"legend"
] | Reading the following article, I managed to put a legend outside plot.
* [How to put the legend out of the plot](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot)
code:
```
import matplotlib.pyplot as pyplot
x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]
fig = pyplot.figure()
ax = fig... | The problem is that when you plot dinamically, matplotlib determines the borders automatically to fit all your objects.
When you save a file, things are not being done automagically, so you need to specify
the size of your figure, and then the bounding box of your axes object.
Here is how to correct your code:
```
imp... |
Matplotlib savefig with a legend outside the plot | 8,971,834 | 24 | 2012-01-23T12:46:21Z | 18,179,374 | 7 | 2013-08-12T04:00:59Z | [
"python",
"matplotlib",
"legend"
] | Reading the following article, I managed to put a legend outside plot.
* [How to put the legend out of the plot](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot)
code:
```
import matplotlib.pyplot as pyplot
x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]
fig = pyplot.figure()
ax = fig... | Although this method works with legend, it seems not to be working well with figlegend when there are multiple subplots and we want a single overall legend. figlegend still get cropped when savefig. I just pasted my temporary solution below in case someone faces such a case.
```
import matplotlib.pyplot as plt
para =... |
Flask partial view like MVC 3 | 8,971,887 | 16 | 2012-01-23T12:51:19Z | 8,976,838 | 22 | 2012-01-23T18:40:30Z | [
"python",
"flask"
] | Is there something like .net MVC 3's partial view in flask?
I want to embed a widget in one view page,and that widget has its own logic. | There are several ways to include content in a Jinja2 template:
The [`include`](http://jinja.pocoo.org/docs/templates/#include) statement will render the supplied view (with the current context by default):
```
{# In your_view_template.jinja #}
{# ... your code ... #}
{% include "widgets/your_widget.jinja" %}
{# ... ... |
Why python isn't handling very large numbers in all areas? | 8,972,002 | 4 | 2012-01-23T12:59:04Z | 8,972,104 | 9 | 2012-01-23T13:06:06Z | [
"python",
"largenumber"
] | I am doing a puzzle where I have to deal with numbers of order 10^18. However, I find python isn't able to handle very large numbers in all areas.
To be specific, if we assign a = 1000000000000000000 (10^18) and do basic arithmetic calculations (+, -, /, \*), its responding. However, its showing OverflowError when I u... | In Python 2.x, `range` and `xrange` are limited to working with C `long` and your large integers are just too big for that. This limitation is simply due to the implementation choices made for `range` and `xrange`.
In Python 3.x the limitation has been removed and you can perform `range()` with very large integers.
`... |
Remove duplicates from the list of dictionaries | 8,972,076 | 4 | 2012-01-23T13:04:27Z | 8,972,181 | 12 | 2012-01-23T13:12:03Z | [
"python",
"list",
"dictionary"
] | I have following list of dictionaries:
```
d = [
{ 'name': 'test', 'regions': [{'country': 'UK'}] },
{ 'name': 'test', 'regions': [{'country': 'US'}, {'country': 'DE'}] },
{ 'name': 'test 1', 'regions': [{'country': 'UK'}], 'clients': ['1', '2', '5'] },
{ 'name': 'test', 'regions': [{'country': 'UK'}] },
]
```
What i... | How about this:
```
new_d = []
for x in d:
if x not in new_d:
new_d.append(x)
``` |
correct way to use super (argument passing) | 8,972,866 | 33 | 2012-01-23T14:04:35Z | 8,973,101 | 10 | 2012-01-23T14:24:15Z | [
"python"
] | So I was following [Python's Super Considered Harmful](http://fuhm.net/super-harmful/), and went to test out his examples.
However, [Example 1-3](http://fuhm.net/super-harmful/example1-3.py), which is supposed to show the correct way of calling `super` when handling `__init__` methods that expect different arguments, ... | If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using `**kwargs`, and then `pop` them right after you use them (unless you need them in upper classes).
```
class First(object):
def __init__(self, *args, **kwargs):
self.first_arg = kwargs.pop('first_a... |
correct way to use super (argument passing) | 8,972,866 | 33 | 2012-01-23T14:04:35Z | 8,973,302 | 31 | 2012-01-23T14:39:05Z | [
"python"
] | So I was following [Python's Super Considered Harmful](http://fuhm.net/super-harmful/), and went to test out his examples.
However, [Example 1-3](http://fuhm.net/super-harmful/example1-3.py), which is supposed to show the correct way of calling `super` when handling `__init__` methods that expect different arguments, ... | Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of `**kwargs` or remove them from `*args`. Instead, you can define a `Base` class which unlike `object`, absorbs/ignores arguments:
```
class Base(object):
def __init__(self, *args, **kwargs): pass
c... |
draw random element in numpy | 8,973,350 | 5 | 2012-01-23T14:42:07Z | 8,973,412 | 9 | 2012-01-23T14:45:57Z | [
"python",
"arrays",
"numpy",
"cumsum"
] | I have an array of element probabilities, let's say `[0.1, 0.2, 0.5, 0.2]`. The array sums up to 1.0.
Using plain Python or numpy, I want to draw elements proportional to their probability: the first element about 10% of the time, second 20%, third 50% etc. The "draw" should return index of the element drawn.
I came ... | ```
import numpy as np
def random_pick(choices, probs):
'''
>>> a = ['Hit', 'Out']
>>> b = [.3, .7]
>>> random_pick(a,b)
'''
cutoffs = np.cumsum(probs)
idx = cutoffs.searchsorted(np.random.uniform(0, cutoffs[-1]))
return choices[idx]
```
---
**How it works:**
```
In [22]: import numpy... |
Django/ python validate JSON | 8,975,124 | 4 | 2012-01-23T16:37:15Z | 8,975,289 | 7 | 2012-01-23T16:47:27Z | [
"python",
"django",
"json",
"django-models",
"django-forms"
] | what is the best way to validate JSON data in Django/python.
Is it best to create a bunch of classes like the Django FormMixin classes that can validate the data/ parameters being passed in?
What's the best DRY way of doing this? Are there existing apps that I can leverage?
I'd like to take in JSON data and perform ... | I just instantiate a model object from the json data and call full\_clean() on the model to validate: <https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean>
```
m = myModel(**jsondata)
m.full_clean()
``` |
Understanding django admin readonly_fields | 8,976,086 | 3 | 2012-01-23T17:41:15Z | 8,977,206 | 11 | 2012-01-23T19:10:02Z | [
"python",
"django",
"django-admin"
] | I created some code to differentiate between two usergroups in Django admin, resulting in showing all fields readonly or only some of them, which are set directly in the ModelAdmin class.
At first here is the code:
```
class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('created_at','created_by',)
def get_fo... | The ModelAdmin is only instantiated once for all requests that it receives. So when you define the readonly fields like that, you're setting it across the board permanently.
As long as you're running Django 1.2+, there's a `get_readonly_fields` method you can use instead for exactly this purpose:
```
class MyModelAdm... |
How is lazy evaluation implemented (in ORMs for example) | 8,976,103 | 2 | 2012-01-23T17:42:43Z | 8,977,321 | 7 | 2012-01-23T19:18:46Z | [
"python",
"activerecord",
"orm"
] | Im curious to know how lazy evaluation is implemented at higher levels, ie in libraries, etc. For example, how does the Django ORM or ActiveRecord defer evaluation of query until it is actually used? | Let's have a look at some methods for django's [`django.db.models.query.QuerySet`](https://code.djangoproject.com/browser/django/trunk/django/db/models/query.py) class:
```
class QuerySet(object):
"""
Represents a lazy database lookup for a set of objects.
"""
def __init__(self, model=None, query=None,... |
Percentage sign not working | 8,976,535 | 4 | 2012-01-23T18:16:54Z | 8,976,760 | 7 | 2012-01-23T18:33:46Z | [
"python",
"html"
] | I am working with a HTML application with Python. I usually use the `%` sign to indicate that I'm using a Python element, and never had a problem with that before.
Now, I am using some tables which I'm trying to control their size bye the percentage using the `%` sign. So now the Python does not show the Python elemen... | You need to escape '%' as '%%' in python strings. The error message you're getting probably is about the other percent signs. If you put only single percent sign in a string python thinks it will be followed by a format character and will try to do a variable substitution there.
In your case you should have:
```
'''
... |
Jinja2 escape all HTML but img, b, etc | 8,976,683 | 12 | 2012-01-23T18:28:29Z | 8,976,872 | 11 | 2012-01-23T18:42:56Z | [
"python",
"escaping",
"flask",
"jinja2"
] | Jinja2 automatically escapes all HTML tags, but I want to not escape some tags (like `img`, `b`, and some others). How can I do it? | You can write your own filter. The [*scrubber* library](http://pypi.python.org/pypi/scrubber) is pretty good at cleaning up HTML. The filter will need to wrap the returned string in `jinja2.Markup` so the template will not re-escape it.
Edit: a code example
```
import jinja2
import scrubber
def sanitize_html(text):
... |
Jinja2 escape all HTML but img, b, etc | 8,976,683 | 12 | 2012-01-23T18:28:29Z | 8,977,028 | 11 | 2012-01-23T18:55:35Z | [
"python",
"escaping",
"flask",
"jinja2"
] | Jinja2 automatically escapes all HTML tags, but I want to not escape some tags (like `img`, `b`, and some others). How can I do it? | You'll want to parse the input on submission using a white list approach - there are several good examples [in this question](http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter) and [viable options](http://pypi.python.org/pypi/bleach) out there.
Once you have done that, you can mark any va... |
Is there any way to pass 'stdin' as an argument to another process in python? | 8,976,962 | 11 | 2012-01-23T18:50:35Z | 8,981,813 | 7 | 2012-01-24T03:54:33Z | [
"python",
"multiprocessing",
"stdin"
] | I'm trying to create a script which is using multiprocessing module with python. The script (lets call it myscript.py) will get the input from another script with pipe.
Assume that I call the scripts like this;
```
$ python writer.py | python myscript.py
```
And here is the codes;
```
// writer.py
import time, sys
... | The simplest thing is to swap `get_input()` and `do_more_things()` i.e., read `sys.stdin` in the parent process:
```
def get_input(stdin):
for line in iter(stdin.readline, ''):
print("hello", line, end='')
stdin.close()
if __name__ == '__main__':
p1 = mp.Process(target=do_more_things)
p1.start... |
In Python, what determines the order while iterating through kwargs? | 8,977,594 | 10 | 2012-01-23T19:42:01Z | 8,977,623 | 22 | 2012-01-23T19:43:57Z | [
"python"
] | In python, I wrote this function to teach myself how `**kwargs` works in Python:
```
def fxn(a1, **kwargs):
print a1
for k in kwargs:
print k, " : ", kwargs[k]
```
I then called this function with
```
fxn(3, a2=2, a3=3, a4=4)
```
Here was the output that my Python interpreter printed:
```
3
a3 : ... | `kwargs` is a dictionary. Dictionaries are unordered - simply put, the order is unspecified and an implementation detail. Peeking under the hood will show that the order varies wildly depending on the hash values of the items, the order of insertion, etc. so you better don't rely on anything related to it. |
In Python, what determines the order while iterating through kwargs? | 8,977,594 | 10 | 2012-01-23T19:42:01Z | 8,977,630 | 10 | 2012-01-23T19:44:25Z | [
"python"
] | In python, I wrote this function to teach myself how `**kwargs` works in Python:
```
def fxn(a1, **kwargs):
print a1
for k in kwargs:
print k, " : ", kwargs[k]
```
I then called this function with
```
fxn(3, a2=2, a3=3, a4=4)
```
Here was the output that my Python interpreter printed:
```
3
a3 : ... | This is a dictionary. And, as mentioned in documentation, **dictionary has no order** (from <http://docs.python.org/tutorial/datastructures.html#dictionaries>):
> It is best to think of a dictionary as an **unordered set of key: value pairs**, with the requirement that the keys are unique (within one dictionary).
But... |
How to get subprocess' stdout data asynchronously? | 8,977,679 | 9 | 2012-01-23T19:49:08Z | 8,977,796 | 11 | 2012-01-23T19:58:54Z | [
"python",
"asynchronous",
"stdout",
"subprocess"
] | I wrote a simple python script for my application and predefined some fast commands like make etc.
I've written a function for running system commands (linux):
```
def runCommand(commandLine):
print('############## Running command: ' + commandLine)
p = subprocess.Popen(commandLine, shell = True, stdout = subp... | I'm not sure about colors, but here's how to poll the subprocess's stdout one line at a time:
```
import subprocess
proc = subprocess.Popen('cmake', shell=True, stdout=subprocess.PIPE)
while proc.poll() is None:
output = proc.stdout.readline()
print output
```
Don't forget to read from stderr as well, as I'm ... |
Raising builtin exception with default message in python | 8,978,057 | 11 | 2012-01-23T20:24:20Z | 8,978,153 | 13 | 2012-01-23T20:32:17Z | [
"python",
"exception"
] | I'm trying to implement a method that returns an error whenever a certain directory does not exist.
Rather than doing `raise OSError("Directory does not exist.")`, however, I want to use the builtint error message from OSError: `OSError: [Errno 2] No such file or directory:`. This is because I am raising the exception... | ```
import os
try:
open('foo')
except IOError as err:
print(err)
print(err.args)
print(err.filename)
```
produces
```
[Errno 2] No such file or directory: 'foo'
(2, 'No such file or directory')
foo
```
So, to generate an OSError with a similar message use
```
raise OSError(2, 'No such file or direc... |
Raising builtin exception with default message in python | 8,978,057 | 11 | 2012-01-23T20:24:20Z | 8,978,171 | 8 | 2012-01-23T20:34:18Z | [
"python",
"exception"
] | I'm trying to implement a method that returns an error whenever a certain directory does not exist.
Rather than doing `raise OSError("Directory does not exist.")`, however, I want to use the builtint error message from OSError: `OSError: [Errno 2] No such file or directory:`. This is because I am raising the exception... | To get the error message for a given error code, you might want to use [`os.strerror`](http://docs.python.org/library/os.html#os.strerror):
```
>>> os.strerror(2)
'No such file or directory'
```
Also, you might want to use [`errno`](http://docs.python.org/library/errno.html) module to use the standard abbreviations f... |
How can I create a 3d object/class in Python? | 8,978,147 | 2 | 2012-01-23T20:31:45Z | 8,978,215 | 7 | 2012-01-23T20:38:52Z | [
"python",
"3d"
] | My end goal right now is to take points that are read from a text file, and turn them into 3d objects. They do not need to be visualized, but they need to be stored in objects instead of just a string containing the x, y, and z values. The file gives me six numbers, two of each x, y, and z, and I was wondering how I wo... | Just define a `Point` and a `Line` class:
```
class Point(object):
def __init__(self, x=0, y=0 ,z=0):
self.x = x
self.y = y
self.z = z
class Line(object):
def __init__(self, point1=None, point2=None):
self.point1 = point1 or Point() # (0,0,0) by default
self.point2 = po... |
Can python figure out the most up to date directory? | 8,978,417 | 2 | 2012-01-23T20:55:01Z | 8,978,456 | 10 | 2012-01-23T20:58:58Z | [
"python"
] | I have six directories the follow the format
```
\home\mydir\myproject\2012-01-23_03-01-34
\home\mydir\myproject\2012-01-11_01-00-57
\home\mydir\myproject\2010-01-11_01-00-57
\home\mydir\myproject\2010-01-11_01-00-54
\home\mydir\myproject\2010-01-08_01-00-54
```
Note, the datetime as the final directory. It is *exact... | If you have those directory names in a list `dirs`, then `max(dirs)` will give you the latest. |
Iterate over 2d array in an expanding circular spiral | 8,979,214 | 19 | 2012-01-23T21:59:34Z | 9,591,896 | 8 | 2012-03-06T21:04:29Z | [
"python",
"matrix",
"loops",
"circle",
"spiral"
] | Given an `n` by `n` matrix `M`, at row `i` and column `j`, I'd like to iterate over all the neighboring values in a circular spiral.
The point of doing this is to test some function, `f`, which depends on M, to find the radius away from `(i, j)` in which `f` returns `True`. So, `f` looks like this:
```
def f(x, y):
... | Since it was mentioned that the order of the points do not matter, I've simply ordered them by the angle (`arctan2`) in which they appear at a given radius. Change `N` to get more points.
```
from numpy import *
N = 8
# Find the unique distances
X,Y = meshgrid(arange(N),arange(N))
G = sqrt(X**2+Y**2)
U = unique(G)
#... |
How do I run non query sql commands using cx_Oracle? | 8,979,257 | 2 | 2012-01-23T22:02:42Z | 8,979,504 | 7 | 2012-01-23T22:25:06Z | [
"python",
"sql",
"cx-oracle"
] | I am trying to run these commands using cx\_oracle:
```
begin
add_command_pkg.add_command
( command_id => 7,
expiry_time => sysdate + 7
);
add_command_pkg.add_command
( command_id => 12,
expiry_time => sysdate + 7
);
commit;
end;
```
So this is my Python code:
```
dsn = cx_Oracle.makedsn(hostnam... | The best way is to call the procedure directly using [`callproc`](http://cx-oracle.sourceforge.net/html/cursor.html#cursorobj).
```
curs.callproc['add_command_pkg.add_command',['7', 'sysdate + 7']]
orcl.commit()
```
or if you need to use keyword arguments directly use a dictionary not a list.
```
curs.callproc['add_... |
passing x- and y-data as keyword arguments in matplotlib? | 8,979,258 | 3 | 2012-01-23T22:02:44Z | 8,979,940 | 8 | 2012-01-23T23:07:00Z | [
"python",
"plot",
"ipython",
"matplotlib"
] | Or, why doesn't
```
import numpy
import matplotlib.pyplot as plt
plt.plot(xdata = numpy.array([1]), ydata = numpy.array(1), color = 'red', marker = 'o')
```
work? c.f.
```
> In [21]: import numpy
> In [22]: import matplotlib.pyplot as plt
> In [23]: plt.plot(xdata = numpy.array([1]), ydata = numpy.array(1), color ... | Just to expand on what @Yann already said:
To understand why this happens, you need to understand a bit more about matplotlib's structure. To allow "matlab-isms" like `plt.setp`, and to maintain compatibility with older versions of python, matplotlib avoid properties and relies heavily on getters and setters. (`plot` ... |
Persistent python subprocess | 8,980,050 | 9 | 2012-01-23T23:20:56Z | 8,980,466 | 21 | 2012-01-24T00:15:55Z | [
"python",
"subprocess"
] | Is there a way to make a subprocess call in python "persistent"? I'm calling a program that takes a while to load multiple times. So it would be great if I could just leave that program open and communicate with it without killing it.
The cartoon version of my python script looks like this:
```
for text in textcollec... | You can use `myprocess.stdin.write()` and `myprocess.stdout.read()` to communicate with your subprocess, you just need to be careful to make sure you handle buffering correctly to prevent your calls from blocking.
If the output from your subprocess is well-defined, you should be able to reliably communicate with it us... |
How can I verify Column data types in the SQLAlchemy ORM? | 8,980,735 | 11 | 2012-01-24T00:46:53Z | 8,980,982 | 20 | 2012-01-24T01:22:05Z | [
"python",
"database",
"orm",
"sqlalchemy"
] | Using the SQLAlchemy ORM, I want to make sure values are the right type for their columns.
For example, say I have an Integer column. I try to insert the value âhelloâ, which is not a valid integer. SQLAlchemy will allow me to do this. Only later, when I execute `session.commit()`, does it raise an exception: `sql... | SQLAlchemy doesn't build this in as it defers to the DBAPI/database as the best and most efficient source of validation and coercion of values.
To build your own validation, usually TypeDecorator or ORM-level validation is used. TypeDecorator has the advantage that it operates at the core and can be pretty transparent... |
On Heroku, locale.getdefaultlocale() is returning (None, None), breaking Django createsuperuser â how to fix? | 8,981,065 | 4 | 2012-01-24T01:37:15Z | 8,981,094 | 17 | 2012-01-24T01:40:54Z | [
"python",
"django",
"heroku"
] | Trying to do a `heroku python manage.py createsuperuser` gave me an error that ended roughly:
```
File "/usr/local/www/site-python/lib/django-trunk/django/contrib/auth/management/__init__.py", line 85, in get_system_username
return getpass.getuser().decode(locale.getdefaultlocale()[1])
TypeError: decode() argument 1 ... | To answer my own question: it turns out this can be fixed by the setting a heroku configuration variable, which results in an environment variable that python can pick up, which returns usable values from locale.getdefaultlocale().
In my case the heroku setting I used was:
```
heroku config:add LANG=en_US.UTF-8
```
... |
array in php and dict in python are the same? | 8,981,282 | 6 | 2012-01-24T02:14:26Z | 8,981,292 | 11 | 2012-01-24T02:16:28Z | [
"php",
"python",
"arrays"
] | I have a project using python and i want to convert the php to python. I have confused in the array of php in converting it to python...
in the old code of the php... it looks like this,
```
array(
"Code" => 122,
"Reference" => 1311,
"Type" => 'NT',
"Amount" => 100... | Your conversion is essentially correct (though I wouldn't use *dict* as a variable name since that masks a built-in class constructor of the same name). That being said, [PHP arrays](http://php.net/manual/en/language.types.array.php) are *ordered mappings*, so you should use a [Python OrderedDict](http://docs.python.or... |
How do I tell Python to convert integers into words | 8,982,163 | 24 | 2012-01-24T04:55:20Z | 8,982,414 | 24 | 2012-01-24T05:30:01Z | [
"python"
] | I'm trying to tell Python to convert integers into words.
**Example:** (using the song 99 bottles of beer on the wall)
I used this code to write the program:
```
for i in range(99,0,-1):
print i, "Bottles of beer on the wall,"
print i, "bottles of beer."
print "Take one down and pass it around,"
prin... | Use [pynum2word](http://sourceforge.net/projects/pynum2word/) module that can be found at sourceforge
```
>>> import num2word
>>> num2word.to_card(15)
'fifteen'
>>> num2word.to_card(55)
'fifty-five'
>>> num2word.to_card(1555)
'one thousand, five hundred and fifty-five'
``` |
How do I tell Python to convert integers into words | 8,982,163 | 24 | 2012-01-24T04:55:20Z | 19,193,721 | 10 | 2013-10-05T03:45:25Z | [
"python"
] | I'm trying to tell Python to convert integers into words.
**Example:** (using the song 99 bottles of beer on the wall)
I used this code to write the program:
```
for i in range(99,0,-1):
print i, "Bottles of beer on the wall,"
print i, "bottles of beer."
print "Take one down and pass it around,"
prin... | We adapted an existing nice solution [(ref)](http://www.daniweb.com/software-development/python/code/216839/number-to-word-converter-python) for converting numbers to words as follows:
```
def numToWords(num,join=True):
'''words = {} convert an integer number into words'''
units = ['','one','two','three','four... |
How do I tell Python to convert integers into words | 8,982,163 | 24 | 2012-01-24T04:55:20Z | 25,026,089 | 26 | 2014-07-29T22:32:44Z | [
"python"
] | I'm trying to tell Python to convert integers into words.
**Example:** (using the song 99 bottles of beer on the wall)
I used this code to write the program:
```
for i in range(99,0,-1):
print i, "Bottles of beer on the wall,"
print i, "bottles of beer."
print "Take one down and pass it around,"
prin... | The inflect package can do this.
<https://pypi.python.org/pypi/inflect>
```
$ pip install inflect
```
and then:
```
>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine
``` |
How to Uninstall setuptools python | 8,982,227 | 6 | 2012-01-24T05:03:26Z | 8,982,267 | 7 | 2012-01-24T05:08:47Z | [
"python",
"ubuntu"
] | Hi recently i installed setup tools module and google app engine gives me errors . Is there a way to uninstall setuptool? can any one tell me step by step because i tried hard | The answer depends on how it was installed.
If it was installed using the ubuntu (debian) package manager, try:
```
sudo apt-get remove --purge python-setuptools
```
[updated]
If you installed manually, probably the setuptools final location will be something like (adjust for your environment/python version):
```
... |
How to Uninstall setuptools python | 8,982,227 | 6 | 2012-01-24T05:03:26Z | 8,982,486 | 10 | 2012-01-24T05:38:25Z | [
"python",
"ubuntu"
] | Hi recently i installed setup tools module and google app engine gives me errors . Is there a way to uninstall setuptool? can any one tell me step by step because i tried hard | ```
easy_install pip
pip uninstall pip setuptools
```
(pip and setuptools both use the same package formats, but pip has uninstall support. kinda hilarious that installing something is the easiest way to uninstall.) |
Python custom sorting, by the difference in two elements of a tuple | 8,982,900 | 3 | 2012-01-24T06:34:44Z | 8,982,940 | 7 | 2012-01-24T06:39:17Z | [
"python",
"list",
"sorting",
"integer",
"tuples"
] | I'm new to Python's custom sorting capabilities, but I'm sure the following can be done. I have a list of tuples, and each tuple looks like this:
```
(some_int, some_int2, string)
```
I want to sort the list by the descending difference between some\_int and some\_int2, i.e. the largest difference between these two i... | ```
mylist.sort(key=lambda t: t[0] - t[1])
```
Note I'm subtracting them in the "wrong" order, which means that the differences will all come out negative and thereby sort the largest in magnitude to the beginning of the list. If you wanted, you could also subtract them in the "right" order and set `reverse=True`:
``... |
Saving XML files using ElementTree | 8,983,041 | 22 | 2012-01-24T06:53:03Z | 8,998,773 | 42 | 2012-01-25T06:35:03Z | [
"python",
"elementtree"
] | I'm trying to develop simple Python (3.2) code to read XML files, do some *corrections* and store them back. However, during the storage step ElementTree adds this namespace nomenclature. For example:
```
<ns0:trk>
<ns0:name>ACTIVE LOG</ns0:name>
<ns0:trkseg>
<ns0:trkpt lat="38.5" lon="-120.2">
<ns0:ele>6.385864</... | In order to avoid the `ns0` prefix the default namespace should be set *before* reading the XML data.
```
ET.register_namespace('', "http://www.topografix.com/GPX/1/1")
ET.register_namespace('', "http://www.topografix.com/GPX/1/0")
``` |
Split list of datetimes into days | 8,983,150 | 10 | 2012-01-24T07:05:38Z | 8,983,196 | 10 | 2012-01-24T07:10:20Z | [
"python",
"datetime",
"date",
"grouping"
] | I've got a sorted list of datetimes: (with day gaps)
```
list_of_dts = [
datetime.datetime(2012,1,1,0,0,0),
datetime.datetime(2012,1,1,1,0,0),
datetime.datetime(2012,1,2,0,0,0),
datetime.datetime(2012,1,3,0,0,0),
datetime.datetime(2012,1,5,0,0,0)... | The easiest way to go is to use [dict.setdefault](http://docs.python.org/library/stdtypes.html#dict.setdefault) to group entries falling on the same day and then loop over the lowest day to the highest:
```
>>> import datetime
>>> list_of_dts = [
datetime.datetime(2012,1,1,0,0,0),
datetime.... |
Execute php code in Python | 8,984,287 | 14 | 2012-01-24T09:12:55Z | 8,984,492 | 22 | 2012-01-24T09:29:49Z | [
"php",
"python"
] | For some reason, I have to run a php script to get an image from Python. Because the php script is very big and it is not mine, it will takes me days to find out the right algorithm used and translate it into python.
I am wonder if there is any way to run php script, with few parameters, which returns a image, in pyth... | Example code:
```
import subprocess
# if the script don't need output.
subprocess.call("php /path/to/your/script.php")
# if you want output
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
``` |
Creating and managing multiple connections in Redis Python | 8,984,870 | 7 | 2012-01-24T10:01:42Z | 8,986,285 | 9 | 2012-01-24T11:46:10Z | [
"python",
"redis",
"connection-pooling"
] | I am using Redis to store two databases : 0 and 1 via the [Redis-py](https://github.com/andymccurdy/redis-py) client library. I would like to create two connections for each database. Currently, I am doing this :
```
>>> connection0 = redis.Connection(host = 'localhost', port = 6379, db = 0)
>>> connection1 = redis.Co... | You really shouldn't create connections like that. Let me quote the redis-py documentation.
> Behind the scenes, redis-py uses a connection pool to manage
> connections to a Redis server. By default, each Redis instance you
> create will in turn create its own connection pool. You can override
> this behavior and use ... |
Python constructors and __init__ | 8,985,806 | 29 | 2012-01-24T11:11:09Z | 8,985,839 | 37 | 2012-01-24T11:13:46Z | [
"python"
] | Why are constructors indeed called "Constructors"? What is their purpose and how are they different from methods in a class?
Also, can there be more that one `__init__` in a class? I tried something like the following, can someone please explain the result?
```
>>> class test:
def __init__(self):
print "i... | There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.
In your code example, you're not *overloading* `__init__()`. What happens is that the second definition *rebinds* the name `__init__` to the new method, rendering the first method inac... |
Python constructors and __init__ | 8,985,806 | 29 | 2012-01-24T11:11:09Z | 8,986,413 | 27 | 2012-01-24T11:56:36Z | [
"python"
] | Why are constructors indeed called "Constructors"? What is their purpose and how are they different from methods in a class?
Also, can there be more that one `__init__` in a class? I tried something like the following, can someone please explain the result?
```
>>> class test:
def __init__(self):
print "i... | **Why are constructors indeed called "Constructors" ?**
Because `__init__` builds your object.
**How are they different from methods in a class ?**
As stated in the [official documentation](http://docs.python.org/reference/datamodel.html#object.__init__) `__init__` is *called when the instance is created*, other met... |
Python the Hard Way - exercise 6 - %r versus %s | 8,986,179 | 28 | 2012-01-24T11:37:38Z | 8,986,206 | 18 | 2012-01-24T11:39:32Z | [
"python"
] | <http://learnpythonthehardway.org/book/ex6.html>
Zed seems to use `%r` and `%s` interchangeably here, is there any difference between the two? Why not just use `%s` all the time?
Also, I wasn't sure what to search for in the documentation to find more info on this. What are `%r` and `%s` called exactly? Formatting st... | `%r` calls `repr`, while `%s` calls `str`. These may behave differently for some types, but not for others: [`repr`](http://docs.python.org/library/functions.html#repr) returns "a printable representation of an object", while [`str`](http://docs.python.org/library/functions.html#str) returns "a *nicely* printable repre... |
Python the Hard Way - exercise 6 - %r versus %s | 8,986,179 | 28 | 2012-01-24T11:37:38Z | 8,986,284 | 42 | 2012-01-24T11:46:09Z | [
"python"
] | <http://learnpythonthehardway.org/book/ex6.html>
Zed seems to use `%r` and `%s` interchangeably here, is there any difference between the two? Why not just use `%s` all the time?
Also, I wasn't sure what to search for in the documentation to find more info on this. What are `%r` and `%s` called exactly? Formatting st... | They are called [string formatting operations](https://docs.python.org/2.7/library/stdtypes.html#string-formatting-operations).
The difference between %s and %r is that %s uses the `str` function and %r uses the `repr` function. You can read about the differences between `str` and `repr` in [this answer](http://stacko... |
How to install lessc and nodejs in a Python virtualenv? | 8,986,709 | 13 | 2012-01-24T12:21:54Z | 8,987,444 | 13 | 2012-01-24T13:15:45Z | [
"python",
"node.js",
"virtualenv",
"less"
] | I would like to install a nodejs script (lessc) into a virtualenv.
How can I do that ?
Thanks
Natim | Here is what I used so far, but it may be optimized I think.
**Install nodejs**
```
wget http://nodejs.org/dist/v0.6.8/node-v0.6.8.tar.gz
tar zxf node-v0.6.8.tar.gz
cd node-v0.6.8/
./configure --prefix=/absolute/path/to/the/virtualenv/
make
make install
```
**Install npm (Node Package Manager)**
```
/absolute/path/... |
How to install lessc and nodejs in a Python virtualenv? | 8,986,709 | 13 | 2012-01-24T12:21:54Z | 11,616,583 | 10 | 2012-07-23T16:27:36Z | [
"python",
"node.js",
"virtualenv",
"less"
] | I would like to install a nodejs script (lessc) into a virtualenv.
How can I do that ?
Thanks
Natim | I created a bash script to automate Natim's solution.
Makes sure your Python virtualenv is active and just run the script. NodeJS, NPM and lessc will be downloaded and installed into your virtualenv.
<http://pastebin.com/wKLWgatq>
```
#!/bin/sh
#
# This script will download NodeJS, NPM and lessc, and install them in... |
How to install lessc and nodejs in a Python virtualenv? | 8,986,709 | 13 | 2012-01-24T12:21:54Z | 20,167,406 | 12 | 2013-11-23T20:22:41Z | [
"python",
"node.js",
"virtualenv",
"less"
] | I would like to install a nodejs script (lessc) into a virtualenv.
How can I do that ?
Thanks
Natim | I like shorrty's answer, he recommended using nodeenv, see:
[is there an virtual environment for node.js?](http://stackoverflow.com/questions/3653495/is-there-an-virtual-environment-for-node-js)
I followed this guide:
<http://calvinx.com/2013/07/11/python-virtualenv-with-node-environment-via-nodeenv/>
All I had to do... |
Convert JSON to XML in Python | 8,988,775 | 27 | 2012-01-24T14:45:47Z | 8,991,155 | 10 | 2012-01-24T17:18:44Z | [
"python",
"xml",
"json"
] | I see a number of questions on SO asking about ways to convert XML to JSON, but I'm interested in going the other way. Is there a python library for converting JSON to XML?
---
**Edit:** Nothing came back right away, so I went ahead and wrote a script that solves this problem.
Python already allows you to convert fr... | Load it into a dict using json.loads then use anything from this question...
[Serialize Python dictionary to XML](http://stackoverflow.com/questions/1019895/serialize-python-dictionary-to-xml) |
Convert JSON to XML in Python | 8,988,775 | 27 | 2012-01-24T14:45:47Z | 8,996,104 | 22 | 2012-01-24T23:56:55Z | [
"python",
"xml",
"json"
] | I see a number of questions on SO asking about ways to convert XML to JSON, but I'm interested in going the other way. Is there a python library for converting JSON to XML?
---
**Edit:** Nothing came back right away, so I went ahead and wrote a script that solves this problem.
Python already allows you to convert fr... | Nothing came back right away, so I went ahead and wrote a script that solves this problem.
Python already allows you to convert from JSON into a native dict (using `json` or, in versions < 2.6, `simplejson`), so I wrote a library that converts native dicts into an XML string.
<https://github.com/quandyfactory/dict2xm... |
Convert JSON to XML in Python | 8,988,775 | 27 | 2012-01-24T14:45:47Z | 19,474,571 | 8 | 2013-10-20T06:30:42Z | [
"python",
"xml",
"json"
] | I see a number of questions on SO asking about ways to convert XML to JSON, but I'm interested in going the other way. Is there a python library for converting JSON to XML?
---
**Edit:** Nothing came back right away, so I went ahead and wrote a script that solves this problem.
Python already allows you to convert fr... | If you don't have such a package, you can try:
```
def json2xml(json_obj, line_padding=""):
result_list = list()
json_obj_type = type(json_obj)
if json_obj_type is list:
for sub_elem in json_obj:
result_list.append(json2xml(sub_elem, line_padding))
return "\n".join(result_lis... |
Dnspython: Setting query timeout/lifetime | 8,989,457 | 4 | 2012-01-24T15:31:35Z | 8,989,817 | 10 | 2012-01-24T15:53:51Z | [
"python",
"timeout",
"lifetime",
"dnspython"
] | I have a small script that checks a large list of domains for their MX records, everything works fine but when the script finds a domain with no record, it takes quite a long time to skip to the next one.
I have tried adding:
```
query.lifetime = 1.0
or
query.timeout = 1.0
```
but this doesn't seem to do anything. D... | You're setting the timeout *after* you've already performed the query. So that's not gonna do anything!
What you want to do instead is create a `Resolver` object, set *its* timeout, and then call its `query()` method. `dns.resolver.query()` is just a convenience function that instantiates a default `Resolver` object a... |
can os.path.join (or other python method) append a '/' automatically for the case of the directory? | 8,989,988 | 2 | 2012-01-24T16:04:34Z | 8,990,026 | 12 | 2012-01-24T16:06:53Z | [
"python"
] | The `os.path.join(a, b)` method will generate a string ending without '/' no matter it is a file or directory. Now, is there any way (or any other `os.path` method) to get a '/' automatically for the case of the directory? | There is no such function in `os.path`. It's easy to code up yourself, though:
```
if os.path.isdir(path):
path = os.path.join(path, "")
```
This will add a `/` if there isn't already one at the end of `path` in case it points to a directory. |
Close all open files in ipython | 8,990,387 | 8 | 2012-01-24T16:27:38Z | 8,990,597 | 7 | 2012-01-24T16:42:40Z | [
"python",
"ipython",
"filehandle"
] | Sometimes when using ipython you might hit an exception in a function which has opened a file in write mode. This means that the next time you run the function you get a value error,
> ValueError: The file 'filename' is already opened. Please close it before reopening in write mode.
However since the function bugged ... | You should try to always use the `with` statement when working with files. For example, use something like
```
with open("x.txt") as fh:
...do something with the file handle fh
```
This ensures that if something goes wrong during the execution of the `with` block, and an exception is raised, the file is guarantee... |
Python conditional 'module object has no attribute' error with personal package distinct from circular import issue | 8,991,520 | 8 | 2012-01-24T17:45:22Z | 8,992,850 | 8 | 2012-01-24T19:29:12Z | [
"python",
"python-import"
] | I'm getting a 'module object has no attribute ..." error when trying to use a package heirarchy I created. The error is reminiscant of the error you get when there is a circular import (i.e. module a imports b and module b imports a), but I can't see that issue here. I've gone through many posts with a similar error, b... | # Here's the why
(This is, I believe, mostly supported by the explanation at <http://docs.python.org/faq/programming.html#how-can-i-have-modules-that-mutually-import-each-other>)
When the Python interpreter encounters a line of the form `import a.b.c`, it runs through the following steps. In pseudo-python:
```
for m... |
Why are pandas merges in python faster than data.table merges in R? | 8,991,709 | 118 | 2012-01-24T17:59:53Z | 8,992,714 | 177 | 2012-01-24T19:17:34Z | [
"python",
"join",
"data.table",
"pandas"
] | I recently came across the [pandas](http://pandas.sourceforge.net/) library for python, which according to [this benchmark](http://wesmckinney.com/blog/some-pandas-database-join-merge-benchmarks-vs-r-basemerge/) performs very fast in-memory merges. It's even faster than the [data.table](http://cran.r-project.org/web/pa... | The reason pandas is faster is because I came up with a better algorithm, which is implemented very carefully using [a fast hash table implementation - klib](https://github.com/attractivechaos/klib) and in C/[Cython](http://cython.org/) to avoid the Python interpreter overhead for the non-vectorizable parts. The algori... |
Why are pandas merges in python faster than data.table merges in R? | 8,991,709 | 118 | 2012-01-24T17:59:53Z | 8,997,908 | 84 | 2012-01-25T04:42:42Z | [
"python",
"join",
"data.table",
"pandas"
] | I recently came across the [pandas](http://pandas.sourceforge.net/) library for python, which according to [this benchmark](http://wesmckinney.com/blog/some-pandas-database-join-merge-benchmarks-vs-r-basemerge/) performs very fast in-memory merges. It's even faster than the [data.table](http://cran.r-project.org/web/pa... | It looks like Wes may have discovered a known issue in `data.table` when the number of unique strings (*levels*) is large: 10,000.
Does `Rprof()` reveal most of the time spent in the call `sortedmatch(levels(i[[lc]]), levels(x[[rc]])`? This isn't really the join itself (the algorithm), but a preliminary step.
Recent ... |
Why are pandas merges in python faster than data.table merges in R? | 8,991,709 | 118 | 2012-01-24T17:59:53Z | 32,489,918 | 12 | 2015-09-09T22:09:14Z | [
"python",
"join",
"data.table",
"pandas"
] | I recently came across the [pandas](http://pandas.sourceforge.net/) library for python, which according to [this benchmark](http://wesmckinney.com/blog/some-pandas-database-join-merge-benchmarks-vs-r-basemerge/) performs very fast in-memory merges. It's even faster than the [data.table](http://cran.r-project.org/web/pa... | This topic is two years old but seems like a probable place for people to land when they search for comparisons of Pandas and data.table
Since both of these have evolved over time, I want to post a relatively newer comparison (from 2014) here for the interested users: <https://github.com/Rdatatable/data.table/wiki/Ben... |
Recursion using yield | 8,991,840 | 24 | 2012-01-24T18:11:49Z | 8,991,864 | 54 | 2012-01-24T18:14:08Z | [
"python",
"python-2.7",
"recursion",
"yield"
] | Is there any way to mix recursion and the `yield` statement? For instance, a infinite number generator (using recursion) would be something like:
```
def infinity(start):
yield start
# recursion here ...
>>> it = infinity(1)
>>> next(it)
1
>>> next(it)
2
```
I tried:
```
def infinity(start):
yield start... | Yes, you can do this:
```
def infinity(start):
yield start
for x in infinity(start + 1):
yield x
```
This will error out once the maximum recursion depth is reached, though.
Starting from Python 3.3, you'll be able to use
```
def infinity(start):
yield start
yield from infinity(start + 1)
``... |
App Engine: Is there a good general-purpose tool for caching datastore objects? | 8,992,235 | 3 | 2012-01-24T18:42:42Z | 8,993,885 | 9 | 2012-01-24T20:45:26Z | [
"python",
"google-app-engine"
] | I'm looking at writing a super-class for all my Google App Engine datastore classes that looks something like this:
```
class MemcacheMixin(object):
@classmethod
def cache_get_by_id(cls, id, parent=None):
if memcache.has_key(...):
...
...
class MyEntity(db.Model, MemcacheMixin):
..... | [NDB](http://code.google.com/p/appengine-ndb-experiment/) (the new datastore library developer by Guido and included in the App Engine 1.6.1 SDK ) has builtin (memcache and memory) caching facilites.
See the [documentation](https://developers.google.com/appengine/docs/python/ndb/cache) for more details. |
How can I get the length of a single unit on an axis in matplotlib, in pixels? | 8,992,944 | 7 | 2012-01-24T19:35:51Z | 8,998,541 | 7 | 2012-01-25T06:04:40Z | [
"python",
"matlab",
"plot",
"matplotlib"
] | I want to make [`markersize`](http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.Line2D.set_markersize) equal to a single unit in height. It seems that `markersize` is in pixels. How can I get at how large "1 unit" (along a given axis) is, in pixels? | Have a look at the [Transformations tutorial](http://matplotlib.sourceforge.net/users/transforms_tutorial.html) (wow, that took a lot of digging to find -- !)
In particular, `axes.transData.transform(points)` returns pixel coordinates where (0,0) is the bottom-left of the viewport.
```
import matplotlib.pyplot as plt... |
How do I fix vim to properly indent folds containing Python comment lines? | 8,993,455 | 9 | 2012-01-24T20:14:08Z | 8,993,692 | 13 | 2012-01-24T20:31:20Z | [
"python",
"vim"
] | I set vim's foldmethod to indent which works very well when writing Python except when I have a comment line. For example, if I have this bit of code:
```
def myFunction():
# here is my comment
myString = "hello"
myInt = 2
```
If I have my cursor on the comment line and type "za" I get get an error saying... | You have to set foldignore to nothing.
```
:set foldignore=
```
From `:help foldignore`:
```
'foldignore' 'fdi' string (default: "#")
Used only when 'foldmethod' is "indent". Lines starting with
characters in 'foldignore' will get their fold level from surrounding
lines. White space is skipped before... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.