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 |
|---|---|---|---|---|---|---|---|---|---|
Programmatically generate video or animated GIF in Python? | 753,190 | 83 | 2009-04-15T18:57:14Z | 1,204,455 | 17 | 2009-07-30T04:29:45Z | [
"python",
"video",
"wxpython",
"animated-gif"
] | I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either... | To create a video, you could use [opencv](http://sourceforge.net/projects/opencvlibrary/),
```
#load your frames
frames = ...
#create a video writer
writer = cvCreateVideoWriter(filename, -1, fps, frame_size, is_color=1)
#and write your frames in a loop if you want
cvWriteFrame(writer, frames[i])
``` |
Programmatically generate video or animated GIF in Python? | 753,190 | 83 | 2009-04-15T18:57:14Z | 2,376,032 | 38 | 2010-03-04T00:13:13Z | [
"python",
"video",
"wxpython",
"animated-gif"
] | I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either... | As of June 2009 the originally cited blog post has a method to create animated GIFs [in the comments](http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/#comment-197921). Download the script [images2gif.py](https://pypi.python.org/pypi/images2gif) (formerly [images2gif.py](h... |
Programmatically generate video or animated GIF in Python? | 753,190 | 83 | 2009-04-15T18:57:14Z | 10,376,713 | 23 | 2012-04-29T22:51:44Z | [
"python",
"video",
"wxpython",
"animated-gif"
] | I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either... | I used [images2gif.py](http://sites.google.com/site/almarklein/files-1/images2gif.py) which was easy to use. It did seem to double the file size though..
26 110kb PNG files, I expected 26\*110kb = 2860kb, but my\_gif.GIF was 5.7mb
Also because the GIF was 8bit, the nice png's became a little fuzzy in the GIF
Here is... |
Programmatically generate video or animated GIF in Python? | 753,190 | 83 | 2009-04-15T18:57:14Z | 35,943,809 | 23 | 2016-03-11T15:19:07Z | [
"python",
"video",
"wxpython",
"animated-gif"
] | I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either... | I'd recommend not using images2gif from visvis because it has problems with PIL/Pillow and is not actively maintained (I should know, because I am the author).
Instead, please use [imageio](http://imageio.github.io), which was developed to solve this problem and more, and is intended to stay.
Quick and dirty solution... |
Inheritance and Overriding __init__ in python | 753,640 | 84 | 2009-04-15T20:45:46Z | 753,657 | 108 | 2009-04-15T20:49:52Z | [
"python",
"override",
"superclass"
] | I was reading 'Dive Into Python' and in the chapter on classes it gives this example:
```
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
```
The author then says that if you want to override the `__init__` meth... | The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclass built-in classes.
It looks like this nowadays.
```
class FileInfo(dict):
"""store file metadata"""
def __init__(self, filename=None):
super( FileInfo, self ).__init__()
self["... |
Inheritance and Overriding __init__ in python | 753,640 | 84 | 2009-04-15T20:45:46Z | 753,705 | 8 | 2009-04-15T21:00:40Z | [
"python",
"override",
"superclass"
] | I was reading 'Dive Into Python' and in the chapter on classes it gives this example:
```
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
```
The author then says that if you want to override the `__init__` meth... | You don't really *have* to call the `__init__` methods of the base class(es), but you usually *want* to do it because the base classes will do some important initializations there that are needed for rest of the classes methods to work.
For other methods it depends on your intentions. If you just want to add something... |
Inheritance and Overriding __init__ in python | 753,640 | 84 | 2009-04-15T20:45:46Z | 11,055,691 | 14 | 2012-06-15T17:43:42Z | [
"python",
"override",
"superclass"
] | I was reading 'Dive Into Python' and in the chapter on classes it gives this example:
```
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
```
The author then says that if you want to override the `__init__` meth... | In each class that you need to inherit from, you can run a loop of each class that needs init'd upon initiation of the child class...an example that can copied might be better understood...
```
class Female_Grandparent:
def __init__(self):
self.grandma_name = 'Grandma'
class Male_Grandparent:
def __in... |
Is there a more pythonic way to build this dictionary? | 753,986 | 6 | 2009-04-15T22:26:44Z | 754,002 | 18 | 2009-04-15T22:30:23Z | [
"python"
] | What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: `values` is a list that is not related to any dictionary.
```
for value in values:
new_d... | At least it's shorter:
```
dict((key_from_value(value), value) for value in values)
``` |
Is there a more pythonic way to build this dictionary? | 753,986 | 6 | 2009-04-15T22:26:44Z | 754,024 | 15 | 2009-04-15T22:36:49Z | [
"python"
] | What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: `values` is a list that is not related to any dictionary.
```
for value in values:
new_d... | ```
>>> l = [ 1, 2, 3, 4 ]
>>> dict( ( v, v**2 ) for v in l )
{1: 1, 2: 4, 3: 9, 4: 16}
```
In Python 3.0 you can use a "dict comprehension" which is basically a shorthand for the above:
```
{ v : v**2 for v in l }
``` |
How to know when to manage resources in Python | 754,187 | 4 | 2009-04-15T23:39:48Z | 754,215 | 11 | 2009-04-15T23:47:26Z | [
"python",
"garbage-collection"
] | I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this:
```
for file in os.listdir(dir):
y=open(dir+'\\'+file,... | Python will close open files when they get garbage-collected, so generally you can forget about it -- particularly when reading.
That said, if you want to close explicitely, you could do this:
```
for file in os.listdir(dir):
f = open(dir+'\\'+file,'r')
y = f.readlines()
for line in y:
pass
f.... |
Some Basic Python Questions | 754,468 | 5 | 2009-04-16T01:41:41Z | 754,503 | 20 | 2009-04-16T02:10:31Z | [
"php",
"python",
"unicode",
"replace",
"html-entities"
] | I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible.
My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Python waters... | First of all, those aren't Microsoft Word entitiesâthey **are** UTF-8. You're converting them to HTML entities.
The Pythonic way to write something like:
```
chr(0xe2) . chr(0x80) . chr(0x98)
```
would be:
```
'\xe2\x80\x98'
```
But Python already has built-in functionality for the type of conversion you want to... |
What is the purpose of the sub-interpreter API in CPython? | 755,070 | 14 | 2009-04-16T07:20:45Z | 755,125 | 14 | 2009-04-16T07:45:18Z | [
"mod-wsgi",
"python"
] | I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod\_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other purpose... | I imagine the purpose is to create separate python execution environments. For instance, [mod\_wsgi](https://code.google.com/p/modwsgi/) (Apache Python module) hosts a single python interpreter and then hosts multiple applications within sub-interpreters (in the default configuration).
Some key points from the [docume... |
Default value for field in Django model | 755,857 | 57 | 2009-04-16T12:13:34Z | 755,863 | 84 | 2009-04-16T12:16:41Z | [
"python",
"django",
"django-models",
"django-admin"
] | Suppose I have a model:
```
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
```
Currently I am using the default admin to create/edit objects of this type.
How do I remove the field **`b`** from the admin so that... | Set `editable` to `False` and `default` to your default value.
<http://docs.djangoproject.com/en/dev/ref/models/fields/#editable>
```
b = models.CharField(max_length=7, default='0000000', editable=False)
```
Also, your `id` field is unnecessary. Django will add it automatically. |
Default value for field in Django model | 755,857 | 57 | 2009-04-16T12:13:34Z | 755,872 | 17 | 2009-04-16T12:20:38Z | [
"python",
"django",
"django-models",
"django-admin"
] | Suppose I have a model:
```
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
```
Currently I am using the default admin to create/edit objects of this type.
How do I remove the field **`b`** from the admin so that... | You can set the default like this:
```
b = models.CharField(max_length=7,default="foobar")
```
and then you can hide the field with your model's Admin class like this:
```
class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
``` |
Default value for field in Django model | 755,857 | 57 | 2009-04-16T12:13:34Z | 7,969,092 | 12 | 2011-11-01T15:53:42Z | [
"python",
"django",
"django-models",
"django-admin"
] | Suppose I have a model:
```
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
```
Currently I am using the default admin to create/edit objects of this type.
How do I remove the field **`b`** from the admin so that... | You can also use a callable in the default field, such as:
```
b = models.CharField(max_length=7, default=foo)
```
And then define the callable:
```
def foo():
return 'bar'
``` |
Listing all permutations of a string/integer | 756,055 | 96 | 2009-04-16T13:13:39Z | 756,083 | 106 | 2009-04-16T13:22:28Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] | A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and ... | First of all: it smells like *recursion* of course!
Since you also wanted to know the principle, I did my best to explain it human language. I think recursion is very easy most of the times. You only have to grasp two steps:
1. The first step
2. All the other steps (all with the same logic)
In **human language**:
>... |
Listing all permutations of a string/integer | 756,055 | 96 | 2009-04-16T13:13:39Z | 756,102 | 9 | 2009-04-16T13:25:08Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] | A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and ... | First of all, sets have permutations, not strings or integers, so I'll just assume you mean "the set of characters in a string."
Note that a set of size n has n! n-permutations.
The following pseudocode (from Wikipedia), called with k = 1...n! will give all the permutations:
```
function permutation(k, s) {
for ... |
Listing all permutations of a string/integer | 756,055 | 96 | 2009-04-16T13:13:39Z | 1,447,183 | 11 | 2009-09-18T23:08:27Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] | A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and ... | ```
void permute (char *str, int ptr) {
int i, len;
len = strlen(str);
if (ptr == len) {
printf ("%s\n", str);
return;
}
for (i = ptr ; i < len ; i++) {
swap (&str[ptr], &str[i]);
permute (str, ptr + 1);
swap (&str[ptr], &str[i]);
}
}
```
You can write your swap function to swap charac... |
Listing all permutations of a string/integer | 756,055 | 96 | 2009-04-16T13:13:39Z | 10,630,026 | 40 | 2012-05-17T04:54:32Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] | A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and ... | It's just two lines of code if LINQ is allowed to use. Please see my answer [here](http://stackoverflow.com/a/10629938/1251423).
**EDIT**
Here is my generic function which can return all the permutations (not combinations) from a list of T:
```
static IEnumerable<IEnumerable<T>>
GetPermutations<T>(IEnumerable<T>... |
Listing all permutations of a string/integer | 756,055 | 96 | 2009-04-16T13:13:39Z | 21,843,611 | 17 | 2014-02-18T03:11:27Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] | A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and ... | Here I have found the solution. It was written in Java, but I have converted it to C#. I hope it will help you.

Here's the code in C#:
```
static void Main(string[] args)
{
string str = "ABC";
char[] charArry = str.ToCharArray();
permute... |
Listing all permutations of a string/integer | 756,055 | 96 | 2009-04-16T13:13:39Z | 32,544,916 | 8 | 2015-09-12T23:47:19Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] | A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and ... | **Recursion** is not necessary, [here](http://stackoverflow.com/a/1506337/1486443) is good information about this solution.
```
var values1 = new[] { 1, 2, 3, 4, 5 };
foreach (var permutation in values1.GetPermutations())
{
Console.WriteLine(string.Join(", ", permutation));
}
var values2 = new[] { 'a', 'b', 'c',... |
pylint warning on 'except Exception:' | 756,180 | 10 | 2009-04-16T13:42:24Z | 756,183 | 18 | 2009-04-16T13:44:45Z | [
"python",
"pylint"
] | For a block like this:
```
try:
#some stuff
except Exception:
pass
```
pylint raises warning W0703 'Catch "Exception"'. Why? | It's considered good practice to not normally catch the root Exception object, but instead to catch more specific ones - for example IOException.
Consider if an out of memory exception occurred - simply using "pass" isn't going to leave your programme in a good state.
Pretty much the only time you should catch Except... |
pylint warning on 'except Exception:' | 756,180 | 10 | 2009-04-16T13:42:24Z | 1,114,833 | 14 | 2009-07-11T22:37:07Z | [
"python",
"pylint"
] | For a block like this:
```
try:
#some stuff
except Exception:
pass
```
pylint raises warning W0703 'Catch "Exception"'. Why? | It's good practice to catch only a very narrow range of types. 'Exception' is too general - you will end up catching not just the errors you planned for, but other errors too, which may mask bugs in your code that would be quicker to diagnose if they weren't caught at all, or possibly would be better dealt with by a si... |
Can you write a permutation function just as elegantly in C#? | 756,223 | 5 | 2009-04-16T13:53:49Z | 756,308 | 12 | 2009-04-16T14:13:01Z | [
"c#",
"python",
"algorithm"
] | I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:
```
def permute(xs, pre=[]):
if len(xs) == 0:
yield pre
for i, x in enumerate(xs):
for y in permute(xs[:i] + xs[i+1:], pre + [x]):
yield y
``` | Well, it probably isn't how I'd write it, but:
```
static IEnumerable<T[]> Permute<T>(this T[] xs, params T[] pre) {
if (xs.Length == 0) yield return pre;
for (int i = 0; i < xs.Length; i++) {
foreach (T[] y in Permute(xs.Take(i).Union(xs.Skip(i+1)).ToArray(), pre.Union(new[] { xs[i] }).ToArray())) {
... |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | 11 | 2009-04-16T15:02:38Z | 756,580 | 15 | 2009-04-16T15:07:24Z | [
"python",
"data-structures",
"tuples"
] | What is the nicest way of splitting this:
```
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
```
into this:
```
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
```
Assuming that the input always has an even number of values. | ```
[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]
``` |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | 11 | 2009-04-16T15:02:38Z | 756,602 | 36 | 2009-04-16T15:10:52Z | [
"python",
"data-structures",
"tuples"
] | What is the nicest way of splitting this:
```
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
```
into this:
```
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
```
Assuming that the input always has an even number of values. | `zip()` is your friend:
```
t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
``` |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | 11 | 2009-04-16T15:02:38Z | 756,704 | 7 | 2009-04-16T15:36:04Z | [
"python",
"data-structures",
"tuples"
] | What is the nicest way of splitting this:
```
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
```
into this:
```
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
```
Assuming that the input always has an even number of values. | Or, using `itertools` (see the [recipe](http://docs.python.org/library/itertools.html#recipes) for `grouper`):
```
from itertools import izip
def group2(iterable):
args = [iter(iterable)] * 2
return izip(*args)
tuples = [ab for ab in group2(tuple)]
``` |
Using multiple listboxes in python tkinter | 756,662 | 12 | 2009-04-16T15:24:17Z | 756,875 | 19 | 2009-04-16T16:11:42Z | [
"python",
"listbox",
"tkinter"
] | ```
from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox2 = Listbox(master)
listbox2.pack()
listbox2.insert(END, "a list entry")
for item in ["one", "two", "three", "four... | Short answer: set the value of the `exportselection` attribute of all listbox widgets to False or zero.
From [a pythonware overview](http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/TkIntro/introduction/listbox.htm) of the listbox widget:
> By default, the selection is exported
> to the X selection mech... |
How do you serialize a model instance in Django? | 757,022 | 93 | 2009-04-16T16:47:31Z | 757,233 | 9 | 2009-04-16T17:36:47Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] | There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance? | It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset ... |
How do you serialize a model instance in Django? | 757,022 | 93 | 2009-04-16T16:47:31Z | 3,289,057 | 150 | 2010-07-20T10:31:13Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] | There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance? | You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:
```
from django.core import serializers
# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])
``` |
How do you serialize a model instance in Django? | 757,022 | 93 | 2009-04-16T16:47:31Z | 13,884,771 | 31 | 2012-12-14T19:05:17Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] | There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance? | To avoid the array wrapper, remove it before you return the response:
```
import json
from django.core import serializers
def getObject(request, id):
obj = MyModel.objects.get(pk=id)
data = serializers.serialize('json', [obj,])
struct = json.loads(data)
data = json.dumps(struct[0])
return HttpResp... |
How do you serialize a model instance in Django? | 757,022 | 93 | 2009-04-16T16:47:31Z | 35,612,936 | 9 | 2016-02-24T20:57:09Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] | There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance? | If you're dealing with a list of model instances the best you can do is using `serializers.serialize()`, it gonna fit your need perfectly.
However, you are to face an issue with trying to serialize a *single* object, not a `list` of objects. That way, in order to get rid of different hacks, just use Django's `model_to... |
Converting tree list to hierarchy dict | 757,244 | 6 | 2009-04-16T17:40:18Z | 757,582 | 9 | 2009-04-16T19:02:37Z | [
"python",
"tree",
"hierarchical-trees"
] | I have a list of elements with attrs: parent, level, is\_leaf\_node, is\_root\_node, is\_child\_node.
I want to convert this list to hierarchy dict.
Example of output dict:
```
{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
{
... | Here's a less sophisticated, recursive version like chmod700 described. Completely untested of course:
```
def build_tree(nodes):
# create empty tree to fill
tree = {}
# fill in tree starting with roots (those with no parent)
build_tree_recursive(tree, None, nodes)
return tree
def build_tree_rec... |
Difference in regex behavior between Perl and Python? | 757,476 | 3 | 2009-04-16T18:35:40Z | 757,521 | 7 | 2009-04-16T18:46:12Z | [
"python",
"regex",
"perl"
] | I have a couple email addresses, `'[email protected]'` and `'[email protected]'`.
In perl, I could take the `To:` line of a raw email and find either of the above addresses with
```
/\w+@(tickets\.)?company\.com/i
```
In python, I simply wrote the above regex as `'\w+@(tickets\.)?company\.com'` expecting... | The documentation for `re.findall`:
> ```
> findall(pattern, string, flags=0)
> Return a list of all non-overlapping matches in the string.
>
> If one or more groups are present in the pattern, return a
> list of groups; this will be a list of tuples if the pattern
> has more than one group.
>
> Em... |
Shell: insert a blank/new line two lines above pattern | 757,532 | 6 | 2009-04-16T18:48:13Z | 758,010 | 7 | 2009-04-16T20:55:45Z | [
"python",
"perl",
"text",
"sed",
"awk"
] | To add a blank line above every line that matches your regexp, you can use:
```
sed '/regexp/{x;p;x;}'
```
But I want to add a blank line, not *one* line above, but *two* lines above the line which matches my regexp.
The pattern I'll be matching is a postal code in the address line.
Here is a snippet of the text's ... | More readable Perl, and handles multiple files sanely.
```
#!/usr/bin/env perl
use constant LINES => 2;
my @buffer = ();
while (<>) {
/pattern/ and unshift @buffer, "\n";
push @buffer, $_;
print splice @buffer, 0, -LINES;
}
continue {
if (eof(ARGV)) {
print @buffer;
@buffer = ();
}
... |
Make function definition in a python file order independent | 758,188 | 22 | 2009-04-16T21:48:53Z | 758,197 | 31 | 2009-04-16T21:53:03Z | [
"python"
] | I use Python CGI. I cannot call a function before it is defined.
In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.
Is there such a trick in Python as well?
example:
```
def do_something(ds_parameter):
helper_function(d... | All functions must be defined before any are used.
However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.
You don't need "forward declaration" because all declarations are completely independent of each other. As long as all declarations come before ... |
Make function definition in a python file order independent | 758,188 | 22 | 2009-04-16T21:48:53Z | 11,898,838 | 9 | 2012-08-10T09:26:29Z | [
"python"
] | I use Python CGI. I cannot call a function before it is defined.
In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.
Is there such a trick in Python as well?
example:
```
def do_something(ds_parameter):
helper_function(d... | An even better illustration of your point would be:
```
def main():
print_something()
....
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
def helper_function(hf_parameter):
....
main()
```
In other words, you can ke... |
PyQt4 Minimize to Tray | 758,256 | 20 | 2009-04-16T22:16:37Z | 758,352 | 26 | 2009-04-16T22:53:20Z | [
"python",
"pyqt4",
"system-tray",
"minimize"
] | Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.
Has anybody done this? Any direction would be appreciated.
Using Python 2.5.4 and PyQt4 on Window XP Pro | It's pretty straightforward once you remember that there's no way to actually minimize to the [system tray](http://blogs.msdn.com/oldnewthing/archive/2003/09/10/54831.aspx).
Instead, you fake it by doing this:
1. Catch the minimize event on your window
2. In the minimize event handler, create and show a QSystemTrayIc... |
PyQt4 Minimize to Tray | 758,256 | 20 | 2009-04-16T22:16:37Z | 758,422 | 10 | 2009-04-16T23:17:59Z | [
"python",
"pyqt4",
"system-tray",
"minimize"
] | Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.
Has anybody done this? Any direction would be appreciated.
Using Python 2.5.4 and PyQt4 on Window XP Pro | Code helps, so here's something I wrote for an application, except for the closeEvent instead of the minimize event.
Notes:
"closeEvent(event)" is an overridden Qt event, so it must be put in the class that implements the window you want to hide.
"okayToClose()" is a function you might consider implementing (or a bo... |
Python Sort Collections.DefaultDict in Descending order | 758,792 | 8 | 2009-04-17T02:41:58Z | 758,803 | 12 | 2009-04-17T02:49:30Z | [
"python"
] | I have this bit of code:
```
visits = defaultdict(int)
for t in tweetsSQL:
visits[t.user.from_user] += 1
```
I looked at some examples online that used the sorted method like so:
`sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True)`
but it is giving me:
`"TypeError: 'builtin_functio... | iteritems is a method. You need parenthesis to call it: `visits.iteritems()`.
As it stands now, you are passing the iteritems method itself to `sorted` which is why it is complaining that it can't iterate over a function or method. |
Python: MySQLdb Connection Problems | 758,819 | 10 | 2009-04-17T02:55:57Z | 834,431 | 8 | 2009-05-07T12:41:01Z | [
"python",
"mysql",
"connection"
] | I'm having trouble with the MySQLdb module.
```
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
```
(I'm using a custom port)
the error I get is:
```
Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (... | add `unix_socket='path_to_socket'` where `path_to_socket` should be the path of the MySQL socket, e.g. `/var/run/mysqld/mysqld2.sock` |
Python: MySQLdb Connection Problems | 758,819 | 10 | 2009-04-17T02:55:57Z | 6,482,408 | 36 | 2011-06-26T05:57:38Z | [
"python",
"mysql",
"connection"
] | I'm having trouble with the MySQLdb module.
```
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
```
(I'm using a custom port)
the error I get is:
```
Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (... | Changing `localhost` to `127.0.0.1` solved my problem using `MySQLdb`:
```
db = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
```
Using `127.0.0.1` forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If ... |
How to use cherrypy as a web server for static files? | 759,627 | 13 | 2009-04-17T08:54:26Z | 760,115 | 29 | 2009-04-17T11:53:00Z | [
"python",
"cherrypy"
] | Is it any easy way to use CherryPy as an web server that will display `.html` files in some folder? All CherryPy introductory documentation states that content is dynamically generated:
```
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.qu... | This simple code will serve files on current directory.
```
import os
import cherrypy
PATH = os.path.abspath(os.path.dirname(__file__))
class Root(object): pass
cherrypy.tree.mount(Root(), '/', config={
'/': {
'tools.staticdir.on': True,
'tools.staticdir.dir': PATH,
... |
Unexpected result from sys.getrefcount | 759,740 | 5 | 2009-04-17T09:29:39Z | 759,782 | 7 | 2009-04-17T09:45:43Z | [
"python",
"garbage-collection"
] | When I typed:
```
>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
```
I am not getting where is `astrd` used 3 times ? | It's not `astrd` that is referenced three times, but the value `123`. `astrd` is simply a name for the (immutable) number 123, which can be referenced however many times. Additionally to that, small integers are usually shared:
```
>>> astrd = 123
>>> sys.getrefcount(astrd)
4
>>> j = 123
>>> sys.getrefcount(astrd)
5
`... |
Investigating python process to see what's eating CPU | 760,039 | 6 | 2009-04-17T11:17:34Z | 760,048 | 7 | 2009-04-17T11:22:27Z | [
"python",
"multithreading",
"debugging",
"monitoring",
"pylons"
] | I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc?
**Update:**
* configured access log... | [Profiling](http://docs.python.org/library/profile.html#instant-user-s-manual) might help you learn a bit of what it's doing. If your sort the output by "time" you will see which functions are chowing up cpu time, which should give you some good hints. |
Iterate over a python sequence in multiples of n? | 760,753 | 17 | 2009-04-17T15:01:35Z | 760,829 | 7 | 2009-04-17T15:13:44Z | [
"iteration",
"python"
] | How do I process the elements of a sequence in batches, idiomatically?
For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:
```
for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
```
Of course, this doesn't work because it is expecting a single eleme... | I am sure someone is going to come up with some more "Pythonic" but how about:
```
for y in range(0, len(x), 2):
print "%s%s" % (x[y], x[y+1])
```
Note that this would only work if you know that `len(x) % 2 == 0;` |
Iterate over a python sequence in multiples of n? | 760,753 | 17 | 2009-04-17T15:01:35Z | 760,857 | 39 | 2009-04-17T15:20:36Z | [
"iteration",
"python"
] | How do I process the elements of a sequence in batches, idiomatically?
For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:
```
for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
```
Of course, this doesn't work because it is expecting a single eleme... | A generator function would be neat:
```
def batch_gen(data, batch_size):
for i in range(0, len(data), batch_size):
yield data[i:i+batch_size]
```
Example use:
```
a = "abcdef"
for i in batch_gen(a, 2): print i
```
prints:
```
ab
cd
ef
``` |
Iterate over a python sequence in multiples of n? | 760,753 | 17 | 2009-04-17T15:01:35Z | 760,887 | 10 | 2009-04-17T15:28:48Z | [
"iteration",
"python"
] | How do I process the elements of a sequence in batches, idiomatically?
For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:
```
for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
```
Of course, this doesn't work because it is expecting a single eleme... | Don't forget about the zip() function:
```
a = 'abcdef'
for x,y in zip(a[::2], a[1::2]):
print '%s%s' % (x,y)
``` |
Iterate over a python sequence in multiples of n? | 760,753 | 17 | 2009-04-17T15:01:35Z | 761,125 | 13 | 2009-04-17T16:24:48Z | [
"iteration",
"python"
] | How do I process the elements of a sequence in batches, idiomatically?
For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:
```
for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
```
Of course, this doesn't work because it is expecting a single eleme... | I've got an alternative approach, that works for iterables that don't have a known length.
```
def groupsgen(seq, size):
it = iter(seq)
while True:
values = ()
for n in xrange(size):
values += (it.next(),)
yield values
```
It works by iterating over the sequ... |
Long-running ssh commands in python paramiko module (and how to end them) | 760,978 | 17 | 2009-04-17T15:51:20Z | 766,255 | 20 | 2009-04-19T22:27:05Z | [
"python",
"ssh",
"paramiko"
] | I want to run a `tail -f logfile` command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:
```
interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print... | Instead of calling exec\_command on the client, get hold of the transport and generate your own channel. The [channel](http://www.lag.net/paramiko/docs/paramiko.Channel-class.html) can be used to execute a command, and you can use it in a select statement to find out when data can be read:
```
#!/usr/bin/env python
im... |
Long-running ssh commands in python paramiko module (and how to end them) | 760,978 | 17 | 2009-04-17T15:51:20Z | 836,069 | 12 | 2009-05-07T17:43:22Z | [
"python",
"ssh",
"paramiko"
] | I want to run a `tail -f logfile` command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:
```
interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print... | 1) You can just close the client if you wish. The server on the other end will kill the tail process.
2) If you need to do this in a non-blocking way, you will have to use the channel object directly. You can then watch for both stdout and stderr with channel.recv\_ready() and channel.recv\_stderr\_ready(), or use sel... |
Suppress the u'prefix indicating unicode' in python strings | 761,361 | 30 | 2009-04-17T17:22:04Z | 761,459 | 30 | 2009-04-17T17:42:38Z | [
"python",
"string",
"unicode",
"printing"
] | Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off? | You could use Python 3.0.. The default string type is unicode, so the `u''` prefix is no longer required..
In short, no. You cannot turn this off.
The `u` comes from the `unicode.__repr__` method, which is used to display stuff in REPL:
```
>>> print repr(unicode('a'))
u'a'
>>> unicode('a')
u'a'
```
If I'm not mist... |
Suppress the u'prefix indicating unicode' in python strings | 761,361 | 30 | 2009-04-17T17:22:04Z | 13,246,056 | 13 | 2012-11-06T07:05:49Z | [
"python",
"string",
"unicode",
"printing"
] | Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off? | I had a case where I needed drop the u prefix because I was setting up some javascript with python as part of an html template. A simple output left the u prefix in for the dict keys e.g.
```
var turns = [{u'armies':2...];
```
which breaks javascript.
In order to get the output javascript needed, I used the json pyt... |
Why csv.reader is not pythonic? | 761,430 | 7 | 2009-04-17T17:35:38Z | 761,449 | 14 | 2009-04-17T17:40:42Z | [
"python",
"csv"
] | I started to use the [csv.reader](https://docs.python.org/2/library/csv.html#csv.reader) in Python 2.6 but you can't use `len` on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.
Or is this just an abandoned module in later versions? | I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.
```
import csv
r = csv.reader(...)
lines = [line for line in r]
print len(lines) #number of lines
for odd in lines[1::2]: print odd # print odd lines
``` |
Is it ok to use dashes in Python files when trying to import them? | 761,519 | 65 | 2009-04-17T17:58:59Z | 761,529 | 19 | 2009-04-17T18:01:05Z | [
"python",
"naming"
] | Basically when I have a python file like:
```
python-code.py
```
and use:
```
import (python-code)
```
the interpreter gives me syntax error.
Any ideas on how to fix it? Are dashes illegal in python file names? | The problem is that `python-code` is not an identifier. The parser sees this as `python` minus `code`. Of course this won't do what you're asking. You will need to use a filename that is also a valid python identifier. Try replacing the `-` with an underscore. |
Is it ok to use dashes in Python files when trying to import them? | 761,519 | 65 | 2009-04-17T17:58:59Z | 761,531 | 84 | 2009-04-17T18:01:46Z | [
"python",
"naming"
] | Basically when I have a python file like:
```
python-code.py
```
and use:
```
import (python-code)
```
the interpreter gives me syntax error.
Any ideas on how to fix it? Are dashes illegal in python file names? | You should check out [PEP 8](http://www.python.org/dev/peps/pep-0008/), the Style Guide for Python Code:
> Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, althoug... |
Is it ok to use dashes in Python files when trying to import them? | 761,519 | 65 | 2009-04-17T17:58:59Z | 762,693 | 74 | 2009-04-18T01:06:18Z | [
"python",
"naming"
] | Basically when I have a python file like:
```
python-code.py
```
and use:
```
import (python-code)
```
the interpreter gives me syntax error.
Any ideas on how to fix it? Are dashes illegal in python file names? | One other thing to note in your code is that import is not a function. So `import(python-code)` should be `import python-code` which, as some have already mentioned, is interpreted as "import python minus code", not what you intended. If you really need to import a file with a dash in its name, you can do the following... |
Overriding 'to boolean' operator in python? | 761,586 | 19 | 2009-04-17T18:15:27Z | 761,605 | 33 | 2009-04-17T18:21:14Z | [
"python"
] | I'm using a class that is inherited from list as a data structure:
```
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
```
All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying the list has no elements. Since my class ... | In 2.x: override [`__nonzero__()`](https://docs.python.org/2/reference/datamodel.html#object.__nonzero__). In 3.x, override [`__bool__()`](https://docs.python.org/3/reference/datamodel.html?highlight=__bool__#object.__bool__). |
How to get the label of a choice in a Django forms ChoiceField? | 761,698 | 41 | 2009-04-17T18:43:52Z | 762,830 | 90 | 2009-04-18T03:28:26Z | [
"python",
"django",
"choicefield"
] | I have a ChoiceField, now how do I get the "label" when I need it?
```
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
```
`form.cleaned_data["re... | See the docs on [Model.get\_FOO\_display()](http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get%5FFOO%5Fdisplay). So, should be something like :
```
ContactForm.get_reason_display()
```
In a template, use like this:
```
{{ OBJNAME.get_FIELDNAME_display }}
``` |
How to get the label of a choice in a Django forms ChoiceField? | 761,698 | 41 | 2009-04-17T18:43:52Z | 7,600,927 | 51 | 2011-09-29T17:14:51Z | [
"python",
"django",
"choicefield"
] | I have a ChoiceField, now how do I get the "label" when I need it?
```
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
```
`form.cleaned_data["re... | This may help:
```
reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]
``` |
How to get the label of a choice in a Django forms ChoiceField? | 761,698 | 41 | 2009-04-17T18:43:52Z | 9,574,425 | 11 | 2012-03-05T21:40:16Z | [
"python",
"django",
"choicefield"
] | I have a ChoiceField, now how do I get the "label" when I need it?
```
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
```
`form.cleaned_data["re... | This the easiest way to do this: [Model instance reference: Model.get\_FOO\_display()](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display)
You can use this function which will return the display name: `ObjectName.get_FieldName_display()`
Replace `ObjectName` with your c... |
Trimming a string in Python | 761,804 | 610 | 2009-04-17T19:16:06Z | 761,816 | 33 | 2009-04-17T19:19:12Z | [
"python",
"string",
"trim"
] | How do I remove leading and trailing whitespace from a string in Python?
For example:
```
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
``` | ```
myString.strip()
``` |
Trimming a string in Python | 761,804 | 610 | 2009-04-17T19:16:06Z | 761,822 | 18 | 2009-04-17T19:21:14Z | [
"python",
"string",
"trim"
] | How do I remove leading and trailing whitespace from a string in Python?
For example:
```
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
``` | You want strip():
```
myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ]
for phrase in myphrases:
print phrase.strip()
``` |
Trimming a string in Python | 761,804 | 610 | 2009-04-17T19:16:06Z | 761,825 | 932 | 2009-04-17T19:21:29Z | [
"python",
"string",
"trim"
] | How do I remove leading and trailing whitespace from a string in Python?
For example:
```
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
``` | Just one space, or all such spaces? If the second, then strings already have a `.strip()` method:
```
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL spaces at ends removed
'Hello'
```
If you need only to remove one sp... |
Trimming a string in Python | 761,804 | 610 | 2009-04-17T19:16:06Z | 6,039,813 | 163 | 2011-05-18T04:16:47Z | [
"python",
"string",
"trim"
] | How do I remove leading and trailing whitespace from a string in Python?
For example:
```
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
``` | As pointed out in answers above
```
myString.strip()
```
will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space.
For more flexibility use the following
* Removes only **leading** whitespace chars: `myString.lstrip()`
* Removes only **trailing** whitespace chars: `myString.rstri... |
Trimming a string in Python | 761,804 | 610 | 2009-04-17T19:16:06Z | 10,192,113 | 68 | 2012-04-17T13:22:23Z | [
"python",
"string",
"trim"
] | How do I remove leading and trailing whitespace from a string in Python?
For example:
```
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
``` | `strip` is not limited to whitespace characters either:
```
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
``` |
Python : How to convert markdown formatted text to text | 761,824 | 16 | 2009-04-17T19:21:18Z | 761,847 | 25 | 2009-04-17T19:27:32Z | [
"python",
"parsing",
"markdown"
] | I need to convert markdown text to plain text format to display summary in my website. I want the code in python. | This module will help do what you describe:
[http://www.freewisdom.org/projects/python-markdown/Using\_as\_a\_Module](http://www.freewisdom.org/projects/python-markdown/Using%5Fas%5Fa%5FModule)
Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.
Your code might look s... |
Importing In Python | 762,111 | 3 | 2009-04-17T20:37:07Z | 762,125 | 9 | 2009-04-17T20:41:04Z | [
"python",
"import"
] | Is it possible to import modules based on location?
(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)
I'd like to import a module that's local to the current script. | You can extend the path at runtime like this:
```
sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))
``` |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h' | 762,292 | 23 | 2009-04-17T21:36:22Z | 762,957 | 13 | 2009-04-18T05:27:41Z | [
"python",
"build",
"matplotlib",
"freetype"
] | **ft2build.h** is located here:
**C:\Program Files\GnuWin32\include**
Initially, I made the same mistake as here:
<http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director>
but since then, I've corrected that particular error (I've added the above direct... | Have you installed freetype properly? If you have, there should be a file named `ft2build.h` somewhere under the installation directory, and the directory where that file is found is the one that you should specify with `-I`. The string "GnuWin32" does not appear anywhere in the output of your build command, so it look... |
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h' | 762,292 | 23 | 2009-04-17T21:36:22Z | 5,206,094 | 57 | 2011-03-05T19:02:47Z | [
"python",
"build",
"matplotlib",
"freetype"
] | **ft2build.h** is located here:
**C:\Program Files\GnuWin32\include**
Initially, I made the same mistake as here:
<http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director>
but since then, I've corrected that particular error (I've added the above direct... | This error comes about when building matplotlib on Ubuntu 10.10 also. The solution is to do:
```
sudo apt-get install python-dev libfreetype6-dev
``` |
How do i convert WMD markdown syntax to HTML on my site? | 763,087 | 3 | 2009-04-18T07:21:39Z | 763,102 | 7 | 2009-04-18T07:47:21Z | [
"python",
"html",
"django",
"markdown",
"wmd"
] | Am using django and am implementing WMD on my site, am just wondering how do i convert the markdown syntax to HTML for display purposes, is there some sort of function i should call to do this conversion?
What is the best way to handle markdown ie. do i save the markdown as is to the database then parse it when displa... | Check out the [markup](http://docs.djangoproject.com/en/1.0/ref/contrib/#markup) add-on which comes with Django. That is what you are looking for.
> To activate these filters, add 'django.contrib.markup' to your INSTALLED\_APPS setting. Once youâve done that, use {% load markup %} in a template, and youâll have ac... |
python, "a in b" keyword, how about multiple a's? | 763,944 | 15 | 2009-04-18T18:53:11Z | 763,947 | 7 | 2009-04-18T18:57:12Z | [
"python"
] | My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:
```
if "a" in "abrakadabra" :
print "it is definitely here"
```
But is it possible to test if more than one item is in the list (any one)?... | `any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))` |
python, "a in b" keyword, how about multiple a's? | 763,944 | 15 | 2009-04-18T18:53:11Z | 763,951 | 45 | 2009-04-18T18:58:14Z | [
"python"
] | My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:
```
if "a" in "abrakadabra" :
print "it is definitely here"
```
But is it possible to test if more than one item is in the list (any one)?... | ```
alternatives = ("// @in ", "// @out ", "// @ret ")
if any(a in sTxT for a in alternatives):
print "found"
if all(a in sTxT for a in alternatives):
print "found all"
```
[`any()`](http://docs.python.org/library/functions.html#any) and [`all()`](http://docs.python.org/library/functions.html#all) takes an ite... |
Determine if a function is available in a Python module | 763,971 | 14 | 2009-04-18T19:06:00Z | 763,975 | 17 | 2009-04-18T19:09:31Z | [
"python"
] | I am working on some Python socket code that's using the [`socket.fromfd()`](http://docs.python.org/library/socket.html#socket.fromfd) function.
However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.
**What's the best way to determine if ... | [`hasattr()`](http://docs.python.org/library/functions.html#hasattr) is the best choice. Go with that. :)
```
if hasattr(socket, 'fromfd'):
pass
else:
pass
```
**EDIT**: Actually, according to the docs all hasattr is doing is calling getattr and catching the exception. So if you want to cut out the middle man... |
Determine if a function is available in a Python module | 763,971 | 14 | 2009-04-18T19:06:00Z | 763,977 | 17 | 2009-04-18T19:11:40Z | [
"python"
] | I am working on some Python socket code that's using the [`socket.fromfd()`](http://docs.python.org/library/socket.html#socket.fromfd) function.
However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.
**What's the best way to determine if ... | Or simply use a try..except block:
```
try:
sock = socket.fromfd(...)
except AttributeError:
sock = socket.socket(...)
``` |
Python: How do I get time from a datetime.timedelta object? | 764,184 | 16 | 2009-04-18T20:55:48Z | 764,198 | 22 | 2009-04-18T21:04:40Z | [
"python",
"mysql",
"timedelta"
] | A mysql database table has a column whose datatype is time ( <http://dev.mysql.com/doc/refman/5.0/en/time.html> ). When the table data is accessed, Python returns the value of this column as a datetime.timedelta object. How do I extract the time out of this? (I didn't really understand what timedelta is for from the py... | It's strange that Python returns the value as a `datetime.timedelta`. It probably should return a `datetime.time`. Anyway, it looks like it's returning the elapsed time since midnight (assuming the column in the table is 6:00 PM). In order to convert to a `datetime.time`, you can do the following::
```
value = datetim... |
Dictionary to lowercase in Python | 764,235 | 27 | 2009-04-18T21:23:14Z | 764,244 | 53 | 2009-04-18T21:31:02Z | [
"python"
] | I wish to do this but for a dictionary:
```
"My string".lower()
```
Is there a built in function or should I use a loop? | You will need to use either a loop or a list/generator comprehension. If you want to lowercase all the keys and values, you can do this::
```
dict((k.lower(), v.lower()) for k,v in {'My Key':'My Value'}.iteritems())
```
If you want to lowercase just the keys, you can do this::
```
dict((k.lower(), v) for k,v in {'My... |
Dictionary to lowercase in Python | 764,235 | 27 | 2009-04-18T21:23:14Z | 765,409 | 13 | 2009-04-19T13:25:52Z | [
"python"
] | I wish to do this but for a dictionary:
```
"My string".lower()
```
Is there a built in function or should I use a loop? | The following is identical to Rick Copeland's answer, just written without a using generator expression:
```
outdict = {}
for k, v in {'My Key': 'My Value'}.iteritems():
outdict[k.lower()] = v.lower()
```
Generator-expressions, list comprehension's and (in Python 2.7 and higher) dict comprehension's are basically... |
A list of string replacements in Python | 764,360 | 17 | 2009-04-18T22:28:06Z | 764,374 | 33 | 2009-04-18T22:36:06Z | [
"python",
"string",
"replace"
] | Is there a far shorter way to write the following code?
```
my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')
```
Note that I don't need those exact values replaced; I'... | Looks like a good opportunity to use a loop:
```
mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
my_string = my_string.replace(k, v)
```
A faster approach if you don't mind the parentheses would be:
```
mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5... |
A list of string replacements in Python | 764,360 | 17 | 2009-04-18T22:28:06Z | 764,385 | 15 | 2009-04-18T22:43:25Z | [
"python",
"string",
"replace"
] | Is there a far shorter way to write the following code?
```
my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')
```
Note that I don't need those exact values replaced; I'... | Also look into [`str.translate()`](http://docs.python.org/library/stdtypes.html#str.translate). It replaces characters according to a mapping you provide for Unicode strings, or otherwise must be told what to replace each character from chr(0) to chr(255) with. |
A list of string replacements in Python | 764,360 | 17 | 2009-04-18T22:28:06Z | 764,591 | 29 | 2009-04-19T00:59:10Z | [
"python",
"string",
"replace"
] | Is there a far shorter way to write the following code?
```
my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')
```
Note that I don't need those exact values replaced; I'... | You can easily use string.maketrans() to create the mapping string to pass to str.translate():
```
import string
trans = string.maketrans("ABCDE","12345")
my_string = my_string.translate(trans)
``` |
A list of string replacements in Python | 764,360 | 17 | 2009-04-18T22:28:06Z | 765,835 | 9 | 2009-04-19T18:20:59Z | [
"python",
"string",
"replace"
] | Is there a far shorter way to write the following code?
```
my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')
```
Note that I don't need those exact values replaced; I'... | If you want to get the wrong answer, slowly, then use string.replace in a loop. (Though it does work in this case of no overlap among the patterns and replacements.)
For the general case with possible overlaps or a long subject string, use re.sub:
```
import re
def multisub(subs, subject):
"Simultaneously perfor... |
Python Macros: Use Cases? | 764,412 | 20 | 2009-04-18T22:56:16Z | 764,425 | 14 | 2009-04-18T23:05:46Z | [
"python",
"macros",
"lisp",
"scheme"
] | If Python had a macro facility similar to Lisp/Scheme (something like [MetaPython](https://code.google.com/p/metapython/)), how would you use it?
If you are a Lisp/Scheme programmer, what sorts of things do you use macros for (other than things that have a clear syntactic parallel in Python such as a while loop)? | I believe that macros run counter to Python's culture. Macros in Lisp allow the [big ball of mud](http://en.wikipedia.org/wiki/Big%5Fball%5Fof%5Fmud) approach; you get to redefine the language to become more suited to your problem domain. Conversely Pythonic code uses the most natural built in feature of Python to solv... |
Python Macros: Use Cases? | 764,412 | 20 | 2009-04-18T22:56:16Z | 764,906 | 12 | 2009-04-19T05:45:58Z | [
"python",
"macros",
"lisp",
"scheme"
] | If Python had a macro facility similar to Lisp/Scheme (something like [MetaPython](https://code.google.com/p/metapython/)), how would you use it?
If you are a Lisp/Scheme programmer, what sorts of things do you use macros for (other than things that have a clear syntactic parallel in Python such as a while loop)? | Some examples of lisp macros:
* [ITERATE](http://common-lisp.net/project/iterate) which is a funny and extensible loop facility
* [CL-YACC](http://www.pps.jussieu.fr/~jch/software/cl-yacc/)/[FUCC](http://common-lisp.net/project/fucc) that are parser generators that generate parsers at compile time
* [CL-WHO](http://ww... |
Python Macros: Use Cases? | 764,412 | 20 | 2009-04-18T22:56:16Z | 16,493,714 | 13 | 2013-05-11T04:19:22Z | [
"python",
"macros",
"lisp",
"scheme"
] | If Python had a macro facility similar to Lisp/Scheme (something like [MetaPython](https://code.google.com/p/metapython/)), how would you use it?
If you are a Lisp/Scheme programmer, what sorts of things do you use macros for (other than things that have a clear syntactic parallel in Python such as a while loop)? | This is a somewhat late answer, but [MacroPy](https://github.com/lihaoyi/macropy) is a new project of mine to bring macros to Python. We have a pretty substantial list of demos, all of which are use cases which require macros to implement, for example providing an extremely concise way of declaring classes:
```
@case
... |
How to hide console window in python? | 764,631 | 33 | 2009-04-19T01:35:30Z | 764,642 | 13 | 2009-04-19T01:44:08Z | [
"python",
"console",
"hide"
] | I am writing an IRC bot in Python.
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that? | In linux, just run it, no problem. In Windows, you want to use the pythonw executable.
### Update
Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?
* UNIX (Linux)
> $ nohup mypythonprog &
* Wind... |
How to hide console window in python? | 764,631 | 33 | 2009-04-19T01:35:30Z | 764,654 | 54 | 2009-04-19T01:51:12Z | [
"python",
"console",
"hide"
] | I am writing an IRC bot in Python.
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that? | Simply save it with a `.pyw` extension. This will prevent the console window from opening.
> On Windows systems, there is no notion of an âexecutable modeâ. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. **The extension can a... |
How to hide console window in python? | 764,631 | 33 | 2009-04-19T01:35:30Z | 15,148,338 | 7 | 2013-03-01T00:30:37Z | [
"python",
"console",
"hide"
] | I am writing an IRC bot in Python.
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that? | Save it with a `.pyw` extension and will open with `pythonw.exe`. Double click it, and Python will start without a window.
For example, if you have the following script name:
```
foo.py
```
Rename it to:
```
foo.pyw
``` |
SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk? | 764,710 | 37 | 2009-04-19T02:33:43Z | 764,743 | 32 | 2009-04-19T02:57:03Z | [
"python",
"database",
"sqlite",
"memory",
"benchmarking"
] | ## Why is :memory: in sqlite so slow?
I've been trying to see if there are any performance improvements gained by using in-memory sqlite vs. disk based sqlite. Basically I'd like to trade startup time and memory to get extremely rapid queries which do *not* hit disk during the course of the application.
However, the ... | It has to do with the fact that SQLite has a page cache. According to the [Documentation](http://www.sqlite.org/compile.html), the default page cache is 2000 1K pages or about 2Mb. Since this is about 75% to 90% of your data, it isn't surprising that the two number are very similar. My guess is that in addition to the ... |
SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk? | 764,710 | 37 | 2009-04-19T02:33:43Z | 765,136 | 7 | 2009-04-19T09:38:08Z | [
"python",
"database",
"sqlite",
"memory",
"benchmarking"
] | ## Why is :memory: in sqlite so slow?
I've been trying to see if there are any performance improvements gained by using in-memory sqlite vs. disk based sqlite. Basically I'd like to trade startup time and memory to get extremely rapid queries which do *not* hit disk during the course of the application.
However, the ... | You're doing SELECTs, you're using memory cache. Try to interleave SELECTs with UPDATEs. |
SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk? | 764,710 | 37 | 2009-04-19T02:33:43Z | 1,056,148 | 17 | 2009-06-29T00:45:03Z | [
"python",
"database",
"sqlite",
"memory",
"benchmarking"
] | ## Why is :memory: in sqlite so slow?
I've been trying to see if there are any performance improvements gained by using in-memory sqlite vs. disk based sqlite. Basically I'd like to trade startup time and memory to get extremely rapid queries which do *not* hit disk during the course of the application.
However, the ... | My question to you is, What are you trying to benchmark?
As already mentioned, SQLite's :memory: DB is just the same as the disk-based one, i.e. paged, and the only difference is that the pages are never written to disk. So the only difference between the two are the disk writes :memory: doesn't need to do (it also do... |
How's Python Multiprocessing Implemented on Windows? | 765,129 | 12 | 2009-04-19T09:32:46Z | 765,207 | 29 | 2009-04-19T10:41:44Z | [
"python",
"multithreading",
"fork"
] | Given the absence of a Windows fork() call, how's the multiprocessing package in Python 2.6 implemented under Windows? On top of Win32 threads or some sort of fake fork or just compatibility on top of the existing multithreading? | It's done using a subprocess call to sys.executable (i.e. start a new Python process) followed by serializing all of the globals, and sending those over the pipe. A poor man's cloning of the current process. This is the cause of the [extra restrictions](http://docs.python.org/library/multiprocessing.html#windows) found... |
Proxy Check in python | 765,305 | 8 | 2009-04-19T12:01:51Z | 765,436 | 11 | 2009-04-19T13:41:40Z | [
"python",
"http",
"proxy"
] | I have written a script in python that uses cookies and POST/GET. I also included proxy support in my script. However, when one enters a dead proxy proxy, the script crashes. Is there any way to check if a proxy is dead/alive before running the rest of my script?
Furthermore, I noticed that some proxies don't handle c... | The simplest was is to simply catch the IOError exception from urllib:
```
try:
urllib.urlopen(
"http://example.com",
proxies={'http':'http://example.com:8080'}
)
except IOError:
print "Connection error! (Check proxy)"
else:
print "All was fine"
```
Also, from [this blog post - "check ... |
Using PIL to make all white pixels transparent? | 765,736 | 28 | 2009-04-19T17:13:27Z | 765,774 | 34 | 2009-04-19T17:38:26Z | [
"python",
"image",
"python-imaging-library"
] | I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle)
I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code
```
img = Im... | You need to make the following changes:
* append a tuple `(255, 255, 255, 0)` and not a list `[255, 255, 255, 0]`
* use `img.putdata(newData)`
This is the working code:
```
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[... |
Using PIL to make all white pixels transparent? | 765,736 | 28 | 2009-04-19T17:13:27Z | 765,829 | 24 | 2009-04-19T18:17:14Z | [
"python",
"image",
"python-imaging-library"
] | I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle)
I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code
```
img = Im... | You can also use pixel access mode to modify the image in-place:
```
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
pixdata = img.load()
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y] == (255, 255, 255, 255):
pixdata[x, y] = (255, 25... |
Python timedelta in years | 765,797 | 79 | 2009-04-19T18:00:40Z | 765,812 | 7 | 2009-04-19T18:08:08Z | [
"python",
"datetime",
"timedelta"
] | I need to check if some number of years have been since some date. Currently I've got `timedelta` from `datetime` module and I don't know how to convert it to years. | First off, at the most detailed level, the problem can't be solved exactly. Years vary in length, and there isn't a clear "right choice" for year length.
That said, get the difference in whatever units are "natural" (probably seconds) and divide by the ratio between that and years. E.g.
```
delta_in_days / (365.25)
d... |
Python timedelta in years | 765,797 | 79 | 2009-04-19T18:00:40Z | 765,862 | 39 | 2009-04-19T18:36:03Z | [
"python",
"datetime",
"timedelta"
] | I need to check if some number of years have been since some date. Currently I've got `timedelta` from `datetime` module and I don't know how to convert it to years. | If you're trying to check if someone is 18 years of age, using `timedelta` will not work correctly on some edge cases because of leap years. For example, someone born on January 1, 2000, will turn 18 exactly 6575 days later on January 1, 2018 (5 leap years included), but someone born on January 1, 2001, will turn 18 ex... |
Python timedelta in years | 765,797 | 79 | 2009-04-19T18:00:40Z | 765,990 | 85 | 2009-04-19T20:05:15Z | [
"python",
"datetime",
"timedelta"
] | I need to check if some number of years have been since some date. Currently I've got `timedelta` from `datetime` module and I don't know how to convert it to years. | You need more than a `timedelta` to tell how many years have passed; you also need to know the beginning (or ending) date. (It's a leap year thing.)
Your best bet is to use the `dateutil.relativedelta` [object](http://labix.org/python-dateutil), but that's a 3rd party module. If you want to know the `datetime` that wa... |
Amazon S3 permissions | 765,964 | 10 | 2009-04-19T19:51:07Z | 768,050 | 14 | 2009-04-20T12:28:03Z | [
"python",
"django",
"amazon-web-services",
"amazon-s3"
] | Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for... | There are various ways to control access to the S3 objects:
1. Use the query string auth - but as you noted this does require an expiration date. You could make it far in the future, which has been good enough for most things I have done.
2. Use the S3 ACLS - but this requires the user to have an AWS account and authe... |
Amazon S3 permissions | 765,964 | 10 | 2009-04-19T19:51:07Z | 768,090 | 8 | 2009-04-20T12:43:17Z | [
"python",
"django",
"amazon-web-services",
"amazon-s3"
] | Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for... | 1. Have the user hit your server
2. Have the server set up a query-string authentication with a short expiration (minutes, hours?)
3. Have your server redirect to #2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.