title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python tool that builds a dependency diagram for methods of a class
798,389
<p>I'm digging into a huge legacy Python class that has a lot of methods. I eventually break complex ones into smaller pieces so the amount of methods increases even more. I wonder if there is a tool that can scan the Python code and build some kind of dependency diagram for its methods.</p> <p>I define method <code>x()</code> to be a dependency of method <code>y()</code> if <code>x()</code> is called at least once in <code>y()</code>.</p> <p>I could use such a tool to isolate (if possible) subsets of class methods that have no external dependencies (all their dependencies are methods from the same subset).</p> <p>I'm planning to move some functionality into other classes and I think that such an approach would help me to decide which parts to extract from the initial huge class.</p> <p>Edit: I would really like a command-line tool.</p>
16
2009-04-28T14:54:26Z
800,083
<p>Have you looked at <a href="http://furius.ca/snakefood/" rel="nofollow">Snakefood</a> yet? It looks like it's exactly what you're looking for.</p>
3
2009-04-28T22:24:17Z
[ "python", "refactoring" ]
Python tool that builds a dependency diagram for methods of a class
798,389
<p>I'm digging into a huge legacy Python class that has a lot of methods. I eventually break complex ones into smaller pieces so the amount of methods increases even more. I wonder if there is a tool that can scan the Python code and build some kind of dependency diagram for its methods.</p> <p>I define method <code>x()</code> to be a dependency of method <code>y()</code> if <code>x()</code> is called at least once in <code>y()</code>.</p> <p>I could use such a tool to isolate (if possible) subsets of class methods that have no external dependencies (all their dependencies are methods from the same subset).</p> <p>I'm planning to move some functionality into other classes and I think that such an approach would help me to decide which parts to extract from the initial huge class.</p> <p>Edit: I would really like a command-line tool.</p>
16
2009-04-28T14:54:26Z
2,398,941
<p>i was confuse in this question too,i have found a search helper help me to find the call hierarchy in another way. not very good but better than donot have. sorry about my english.</p> <p>ps.IDE eclipse+pydev</p>
0
2010-03-08T02:20:36Z
[ "python", "refactoring" ]
Python tool that builds a dependency diagram for methods of a class
798,389
<p>I'm digging into a huge legacy Python class that has a lot of methods. I eventually break complex ones into smaller pieces so the amount of methods increases even more. I wonder if there is a tool that can scan the Python code and build some kind of dependency diagram for its methods.</p> <p>I define method <code>x()</code> to be a dependency of method <code>y()</code> if <code>x()</code> is called at least once in <code>y()</code>.</p> <p>I could use such a tool to isolate (if possible) subsets of class methods that have no external dependencies (all their dependencies are methods from the same subset).</p> <p>I'm planning to move some functionality into other classes and I think that such an approach would help me to decide which parts to extract from the initial huge class.</p> <p>Edit: I would really like a command-line tool.</p>
16
2009-04-28T14:54:26Z
17,953,557
<p><a href="http://pycallgraph.slowchop.com/" rel="nofollow">Pycallgraph</a> should do what you are looking for.</p>
0
2013-07-30T17:30:15Z
[ "python", "refactoring" ]
How to call a Perl script from Python, piping input to it?
798,413
<p>I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.</p> <p>What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like <code>os.system</code> for this, but piping a variable to the perl script is something that seems to elude me.</p> <p>In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?</p> <p>EDIT: I forgot to include that the system I'm working with only has python v2.3</p>
6
2009-04-28T14:58:34Z
798,425
<p><a href="http://docs.python.org/library/os.html#os.popen" rel="nofollow">os.popen()</a> will return a tuple with the stdin and stdout of the subprocess.</p>
9
2009-04-28T15:00:49Z
[ "python", "perl", "domainkeys", "dkim" ]
How to call a Perl script from Python, piping input to it?
798,413
<p>I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.</p> <p>What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like <code>os.system</code> for this, but piping a variable to the perl script is something that seems to elude me.</p> <p>In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?</p> <p>EDIT: I forgot to include that the system I'm working with only has python v2.3</p>
6
2009-04-28T14:58:34Z
798,432
<p>"I'm pretty sure I can use something like os.system for this, but piping a variable to the perl script is something that seems to elude me."</p> <p>Correct. The <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module is like os.system, but provides the piping features you're looking for.</p>
2
2009-04-28T15:01:48Z
[ "python", "perl", "domainkeys", "dkim" ]
How to call a Perl script from Python, piping input to it?
798,413
<p>I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.</p> <p>What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like <code>os.system</code> for this, but piping a variable to the perl script is something that seems to elude me.</p> <p>In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?</p> <p>EDIT: I forgot to include that the system I'm working with only has python v2.3</p>
6
2009-04-28T14:58:34Z
798,485
<pre><code>from subprocess import Popen, PIPE p = Popen(['./foo.pl'], stdin=PIPE, stdout=PIPE) p.stdin.write(the_input) p.stdin.close() the_output = p.stdout.read() </code></pre>
6
2009-04-28T15:12:26Z
[ "python", "perl", "domainkeys", "dkim" ]
How to call a Perl script from Python, piping input to it?
798,413
<p>I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.</p> <p>What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like <code>os.system</code> for this, but piping a variable to the perl script is something that seems to elude me.</p> <p>In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?</p> <p>EDIT: I forgot to include that the system I'm working with only has python v2.3</p>
6
2009-04-28T14:58:34Z
798,508
<p>I'm sure there's a reason you're going down the route you've chosen, but why not just do the signing in Python?</p> <p>How are you signing it? Maybe we could provide some assitance in writing a python implementation?</p>
2
2009-04-28T15:18:12Z
[ "python", "perl", "domainkeys", "dkim" ]
How to call a Perl script from Python, piping input to it?
798,413
<p>I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.</p> <p>What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like <code>os.system</code> for this, but piping a variable to the perl script is something that seems to elude me.</p> <p>In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?</p> <p>EDIT: I forgot to include that the system I'm working with only has python v2.3</p>
6
2009-04-28T14:58:34Z
798,534
<p>Use <a href="http://docs.python.org/library/subprocess.html">subprocess</a>. Here is the Python script:</p> <pre><code>#!/usr/bin/python import subprocess var = "world" pipe = subprocess.Popen(["./x.pl", var], stdout=subprocess.PIPE) result = pipe.stdout.read() print result </code></pre> <p>And here is the Perl script:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; my $name = shift; print "Hello $name!\n"; </code></pre>
10
2009-04-28T15:25:57Z
[ "python", "perl", "domainkeys", "dkim" ]
How to call a Perl script from Python, piping input to it?
798,413
<p>I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.</p> <p>What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like <code>os.system</code> for this, but piping a variable to the perl script is something that seems to elude me.</p> <p>In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?</p> <p>EDIT: I forgot to include that the system I'm working with only has python v2.3</p>
6
2009-04-28T14:58:34Z
14,704,170
<p>I tried also to do that only configure how to make it work as</p> <pre><code>pipe = subprocess.Popen( ['someperlfile.perl', 'param(s)'], stdin=subprocess.PIPE ) response = pipe.communicate()[0] </code></pre> <p>I wish this will assist u to make it work.</p>
1
2013-02-05T09:34:12Z
[ "python", "perl", "domainkeys", "dkim" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
798,548
<p><code>set1 | set2</code> is an operation that won't modify either existing <code>set</code>, but return a new <code>set</code> instead. The new <code>set</code> is created and returned. There is no way to make it automatically copy arbritary attributes from one or both of the <code>set</code>s to the newly created <code>set</code>, without customizing the <code>|</code> operator yourself by <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5For%5F%5F" rel="nofollow">defining the <code>__or__</code> method</a>.</p> <pre><code>class MySet(set): def __init__(self, *args, **kwds): super(MySet, self).__init__(*args, **kwds) self.foo = 'nothing' def __or__(self, other): result = super(MySet, self).__or__(other) result.foo = self.foo + "|" + other.foo return result r = MySet('abc') r.foo = 'bar' s = MySet('cde') s.foo = 'baz' t = r | s print r, s, t print r.foo, s.foo, t.foo </code></pre> <p>Prints:</p> <pre><code>MySet(['a', 'c', 'b']) MySet(['c', 'e', 'd']) MySet(['a', 'c', 'b', 'e', 'd']) bar baz bar|baz </code></pre>
2
2009-04-28T15:29:24Z
[ "python", "subclass", "set", "instance-variables" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
798,595
<p>For me this works perfectly using Python 2.5.2 on Win32. Using you class definition and the following test:</p> <pre><code>f = Fooset([1,2,4]) s = sets.Set((5,6,7)) print f, f.foo f.foo = 'bar' print f, f.foo g = f | s print g, g.foo assert( (f | f).foo == 'bar') </code></pre> <p>I get this output, which is what I expect:</p> <pre><code>Fooset([1, 2, 4]) default Fooset([1, 2, 4]) bar Fooset([1, 2, 4, 5, 6, 7]) bar </code></pre>
-2
2009-04-28T15:39:34Z
[ "python", "subclass", "set", "instance-variables" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
798,676
<p>It looks like set bypasses <code>__init__</code> in the <a href="http://svn.python.org/view/python/trunk/Objects/setobject.c?view=markup" rel="nofollow">c code</a>. However you will end an instance of <code>Fooset</code>, it just won't have had a chance to copy the field.</p> <p>Apart from overriding the methods that return new sets I'm not sure you can do too much in this case. Set is clearly built for a certain amount of speed, so does a lot of work in c.</p>
2
2009-04-28T15:59:59Z
[ "python", "subclass", "set", "instance-variables" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
798,794
<p>Assuming the other answers are correct, and overriding all the methods is the only way to do this, here's my attempt at a moderately elegant way of doing this. If more instance variables are added, only one piece of code needs to change. Unfortunately if a new binary operator is added to the set object, this code will break, but I don't think there's a way to avoid that. Comments welcome!</p> <pre><code>def foocopy(f): def cf(self, new): r = f(self, new) r.foo = self.foo return r return cf class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' def copy(self): x = set.copy(self) x.foo = self.foo return x @foocopy def __and__(self, x): return set.__and__(self, x) @foocopy def __or__(self, x): return set.__or__(self, x) @foocopy def __rand__(self, x): return set.__rand__(self, x) @foocopy def __ror__(self, x): return set.__ror__(self, x) @foocopy def __rsub__(self, x): return set.__rsub__(self, x) @foocopy def __rxor__(self, x): return set.__rxor__(self, x) @foocopy def __sub__(self, x): return set.__sub__(self, x) @foocopy def __xor__(self, x): return set.__xor__(self, x) @foocopy def difference(self, x): return set.difference(self, x) @foocopy def intersection(self, x): return set.intersection(self, x) @foocopy def symmetric_difference(self, x): return set.symmetric_difference(self, x) @foocopy def union(self, x): return set.union(self, x) f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre>
0
2009-04-28T16:31:30Z
[ "python", "subclass", "set", "instance-variables" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
804,973
<p>My favorite way to wrap methods of a built-in collection:</p> <pre><code>class Fooset(set): def __init__(self, s=(), foo=None): super(Fooset,self).__init__(s) if foo is None and hasattr(s, 'foo'): foo = s.foo self.foo = foo @classmethod def _wrap_methods(cls, names): def wrap_method_closure(name): def inner(self, *args): result = getattr(super(cls, self), name)(*args) if isinstance(result, set) and not hasattr(result, 'foo'): result = cls(result, foo=self.foo) return result inner.fn_name = name setattr(cls, name, inner) for name in names: wrap_method_closure(name) Fooset._wrap_methods(['__ror__', 'difference_update', '__isub__', 'symmetric_difference', '__rsub__', '__and__', '__rand__', 'intersection', 'difference', '__iand__', 'union', '__ixor__', 'symmetric_difference_update', '__or__', 'copy', '__rxor__', 'intersection_update', '__xor__', '__ior__', '__sub__', ]) </code></pre> <p>Essentially the same thing you're doing in your own answer, but with fewer loc. It's also easy to put in a metaclass if you want to do the same thing with lists and dicts as well.</p>
11
2009-04-30T01:01:00Z
[ "python", "subclass", "set", "instance-variables" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
6,698,723
<p>I think that the recommended way to do this is not to subclass directly from the built-in <code>set</code>, but rather to make use of the <a href="http://docs.python.org/library/collections.html#collections.Set" rel="nofollow">Abstract Base Class <code>Set</code></a> available in <a href="http://docs.python.org/library/collections.html#abcs-abstract-base-classes" rel="nofollow">collections</a>.</p> <p>Using the ABC Set gives you some methods for free as a mix-in so you can have a minimal Set class by defining only <code>__contains__()</code>, <code>__len__()</code> and <code>__iter__()</code>. If you want some of the nicer set methods like <code>intersection()</code> and <code>difference()</code>, you probably do have to wrap them.</p> <p>Here's my attempt (this one happens to be a frozenset-like, but you can inherit from <code>MutableSet</code> to get a mutable version):</p> <pre><code>from collections import Set, Hashable class CustomSet(Set, Hashable): """An example of a custom frozenset-like object using Abstract Base Classes. """ ___hash__ = Set._hash wrapped_methods = ('difference', 'intersection', 'symetric_difference', 'union', 'copy') def __repr__(self): return "CustomSet({0})".format(list(self._set)) def __new__(cls, iterable): selfobj = super(CustomSet, cls).__new__(CustomSet) selfobj._set = frozenset(iterable) for method_name in cls.wrapped_methods: setattr(selfobj, method_name, cls._wrap_method(method_name, selfobj)) return selfobj @classmethod def _wrap_method(cls, method_name, obj): def method(*args, **kwargs): result = getattr(obj._set, method_name)(*args, **kwargs) return CustomSet(result) return method def __getattr__(self, attr): """Make sure that we get things like issuperset() that aren't provided by the mix-in, but don't need to return a new set.""" return getattr(self._set, attr) def __contains__(self, item): return item in self._set def __len__(self): return len(self._set) def __iter__(self): return iter(self._set) </code></pre>
3
2011-07-14T19:15:53Z
[ "python", "subclass", "set", "instance-variables" ]
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
<p>I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?</p> <p>Using the old sets module, the following code worked perfectly:</p> <pre><code>import sets class Fooset(sets.Set): def __init__(self, s = []): sets.Set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>but this does not work using the built-in set module.</p> <p>The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?</p> <p>(To clarify, the following code does <em>not</em> work (the assertion fails):</p> <pre><code>class Fooset(set): def __init__(self, s = []): set.__init__(self, s) if isinstance(s, Fooset): self.foo = s.foo else: self.foo = 'default' f = Fooset([1,2,4]) f.foo = 'bar' assert( (f | f).foo == 'bar') </code></pre> <p>)</p>
5
2009-04-28T15:05:21Z
12,319,510
<p>Sadly, set does not follow the rules and <code>__new__</code> is not called to make new <code>set</code> objects, even though they keep the type. This is clearly a bug in Python (issue #1721812, which will not be fixed in the 2.x sequence). You should never be able to get an object of type X without calling the <code>type</code> object that creates X objects! If <code>set.__or__</code> is not going to call <code>__new__</code> it is formally obligated to return <code>set</code> objects instead of subclass objects.</p> <p>But actually, noting the post by <em>nosklo</em> above, your original behavior does not make any sense. The <code>Set.__or__</code> operator should not be reusing either of the source objects to construct its result, it should be whipping up a new one, in which case its <code>foo</code> should be <code>"default"</code>!</p> <p>So, practically, anyone doing this <strong>should</strong> have to overload those operators so that they would know which copy of <code>foo</code> gets used. If it is not dependent on the Foosets being combined, you can make it a class default, in which case it will get honored, because the new object thinks it is of the subclass type.</p> <p>What I mean is, your example would work, sort of, if you did this:</p> <pre><code>class Fooset(set): foo = 'default' def __init__(self, s = []): if isinstance(s, Fooset): self.foo = s.foo f = Fooset([1,2,5]) assert (f|f).foo == 'default' </code></pre>
2
2012-09-07T13:53:11Z
[ "python", "subclass", "set", "instance-variables" ]
All combinations of a list of lists
798,854
<p>I'm basically looking for a python version of <a href="http://stackoverflow.com/questions/545703/combination-of-listlistint">Combination of <code>List&lt;List&lt;int&gt;&gt;</code></a></p> <p>Given a list of lists, I need a new list that gives all the possible combinations of items between the lists.</p> <pre><code>[[1,2,3],[4,5,6],[7,8,9,10]] -&gt; [[1,4,7],[1,4,8],...,[3,6,10]] </code></pre> <p>The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance!</p>
95
2009-04-28T16:44:47Z
798,893
<p>you need <a href="https://docs.python.org/2/library/itertools.html#itertools.product"><code>itertools.product</code></a>:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; a = [[1,2,3],[4,5,6],[7,8,9,10]] &gt;&gt;&gt; list(itertools.product(*a)) [(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)] </code></pre>
168
2009-04-28T16:54:56Z
[ "python", "combinations" ]
All combinations of a list of lists
798,854
<p>I'm basically looking for a python version of <a href="http://stackoverflow.com/questions/545703/combination-of-listlistint">Combination of <code>List&lt;List&lt;int&gt;&gt;</code></a></p> <p>Given a list of lists, I need a new list that gives all the possible combinations of items between the lists.</p> <pre><code>[[1,2,3],[4,5,6],[7,8,9,10]] -&gt; [[1,4,7],[1,4,8],...,[3,6,10]] </code></pre> <p>The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance!</p>
95
2009-04-28T16:44:47Z
798,894
<p>The most elegant solution is to use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a> in python 2.6.</p> <p>If you aren't using Python 2.6, the docs for itertools.product actually show an equivalent function to do the product the "manual" way:</p> <pre><code>def product(*args, **kwds): # product('ABCD', 'xy') --&gt; Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --&gt; 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) </code></pre>
17
2009-04-28T16:55:04Z
[ "python", "combinations" ]
All combinations of a list of lists
798,854
<p>I'm basically looking for a python version of <a href="http://stackoverflow.com/questions/545703/combination-of-listlistint">Combination of <code>List&lt;List&lt;int&gt;&gt;</code></a></p> <p>Given a list of lists, I need a new list that gives all the possible combinations of items between the lists.</p> <pre><code>[[1,2,3],[4,5,6],[7,8,9,10]] -&gt; [[1,4,7],[1,4,8],...,[3,6,10]] </code></pre> <p>The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance!</p>
95
2009-04-28T16:44:47Z
798,908
<pre><code>listOLists = [[1,2,3],[4,5,6],[7,8,9,10]] for list in itertools.product(*listOLists): print list; </code></pre> <p>I hope you find that as elegant as I did when I first encountered it.</p>
10
2009-04-28T16:58:13Z
[ "python", "combinations" ]
Python exceptions: call same function for any Exception
799,293
<p>Notice in the code below that <code>foobar()</code> is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception?</p> <pre><code>try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() except: foobar() </code></pre>
4
2009-04-28T18:35:33Z
799,315
<pre><code>success = False try: foo() success = True except(A): bar() except(B): baz() except(C): bay() finally: if not success: foobar() </code></pre>
15
2009-04-28T18:42:01Z
[ "python", "exception" ]
Python exceptions: call same function for any Exception
799,293
<p>Notice in the code below that <code>foobar()</code> is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception?</p> <pre><code>try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() except: foobar() </code></pre>
4
2009-04-28T18:35:33Z
799,323
<p>You can use a dictionary to map exceptions against functions to call:</p> <pre><code>exception_map = { ErrorTypeA : bar, ErrorTypeB : baz } try: try: somthing() except tuple(exception_map), e: # this catches only the exceptions in the map exception_map[type(e)]() # calls the related function raise # raise the Excetion again and the next line catches it except Exception, e: # every Exception ends here foobar() </code></pre>
11
2009-04-28T18:43:22Z
[ "python", "exception" ]
Configure Apache to use Python just like CGI PHP
799,354
<p>I think one commonly known way of adding PHP to an Apache webserver is to configure it like this:</p> <pre><code>ScriptAlias /php5.3 /usr/local/php5.3/bin Action application/php5.3 /php5.3/php-cgi AddType application/php5.3 .php </code></pre> <p>Now I tried to write a similar configuration for Python:</p> <pre><code>ScriptAlias /python /usr/bin Action application/python /python/python AddType application/python .py </code></pre> <p>I have a small test script that looks like this:</p> <pre><code>print "Content-Type: text/html\n\n" print "Test" </code></pre> <p>But something seems to be wrong since the apache error log says the following:</p> <pre><code>Premature end of script headers: python </code></pre> <p>So my first though was that my python response is not right. But there is the Content-Type and also both linebreaks. Also the output of a similar PHP script called with <code>php-cgi</code> gives exactly the same output.</p> <p>Also I haven't found a tutorial that shows how to get python working this way. So maybe it is not possible, but then I'm curious why this is the case? Or am I missing something?</p>
0
2009-04-28T18:51:59Z
799,432
<p>" So maybe it is not possible, but then I'm curious why this is the case?"</p> <p>Correct. It's not possible. It was never intended, either.</p> <p>Reason 1 - Python is not PHP. PHP -- as a whole -- expects to be a CGI. Python does not.</p> <p>Reason 2 - Python is not inherently a CGI. It's an interpreter that has (almost) no environmental expectations.</p> <p>Reason 3 - Python was never designed to be a CGI. That's why Python is generally embedded into small wrappers (mod_python, mod_wsgi, mod_fastcgi) which can encapsulate the CGI environment in a form that makes more sense to a running Python program.</p>
5
2009-04-28T19:11:46Z
[ "python", "apache", "cgi" ]
Configure Apache to use Python just like CGI PHP
799,354
<p>I think one commonly known way of adding PHP to an Apache webserver is to configure it like this:</p> <pre><code>ScriptAlias /php5.3 /usr/local/php5.3/bin Action application/php5.3 /php5.3/php-cgi AddType application/php5.3 .php </code></pre> <p>Now I tried to write a similar configuration for Python:</p> <pre><code>ScriptAlias /python /usr/bin Action application/python /python/python AddType application/python .py </code></pre> <p>I have a small test script that looks like this:</p> <pre><code>print "Content-Type: text/html\n\n" print "Test" </code></pre> <p>But something seems to be wrong since the apache error log says the following:</p> <pre><code>Premature end of script headers: python </code></pre> <p>So my first though was that my python response is not right. But there is the Content-Type and also both linebreaks. Also the output of a similar PHP script called with <code>php-cgi</code> gives exactly the same output.</p> <p>Also I haven't found a tutorial that shows how to get python working this way. So maybe it is not possible, but then I'm curious why this is the case? Or am I missing something?</p>
0
2009-04-28T18:51:59Z
799,630
<p>You can use <em>any</em> type of executable as cgi. Your problem is in your apache config, which looks like you just made it up. Check the apache docs for more details, but you don't need the Action and AddType.</p> <pre><code>ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" </code></pre> <p>Then drop the following into your cgi-bin:</p> <pre><code>#!/usr/bin/python # test.py print "Content-Type: text/html\n\n" print "Test" </code></pre> <p>Make sure it's executable, and see the result at /cgi-bin/test.py</p>
12
2009-04-28T20:13:58Z
[ "python", "apache", "cgi" ]
Configure Apache to use Python just like CGI PHP
799,354
<p>I think one commonly known way of adding PHP to an Apache webserver is to configure it like this:</p> <pre><code>ScriptAlias /php5.3 /usr/local/php5.3/bin Action application/php5.3 /php5.3/php-cgi AddType application/php5.3 .php </code></pre> <p>Now I tried to write a similar configuration for Python:</p> <pre><code>ScriptAlias /python /usr/bin Action application/python /python/python AddType application/python .py </code></pre> <p>I have a small test script that looks like this:</p> <pre><code>print "Content-Type: text/html\n\n" print "Test" </code></pre> <p>But something seems to be wrong since the apache error log says the following:</p> <pre><code>Premature end of script headers: python </code></pre> <p>So my first though was that my python response is not right. But there is the Content-Type and also both linebreaks. Also the output of a similar PHP script called with <code>php-cgi</code> gives exactly the same output.</p> <p>Also I haven't found a tutorial that shows how to get python working this way. So maybe it is not possible, but then I'm curious why this is the case? Or am I missing something?</p>
0
2009-04-28T18:51:59Z
11,747,828
<p>The error "Premature end of script headers:" can occur if the .py file was edited in a Windows program that uses CRLF characters for line breaks instead of the Unix LF.</p> <p>Some programs like Dreamweaver have line-break-type in preferences. Notepad also uses CRLF.</p> <p>If your host has a file editor, you could test by backspacing the current linebreaks and reentering them through that editor which would change any CRLF to LF only. Notepad++ can use LF only.</p>
1
2012-07-31T19:45:54Z
[ "python", "apache", "cgi" ]
Configure Apache to use Python just like CGI PHP
799,354
<p>I think one commonly known way of adding PHP to an Apache webserver is to configure it like this:</p> <pre><code>ScriptAlias /php5.3 /usr/local/php5.3/bin Action application/php5.3 /php5.3/php-cgi AddType application/php5.3 .php </code></pre> <p>Now I tried to write a similar configuration for Python:</p> <pre><code>ScriptAlias /python /usr/bin Action application/python /python/python AddType application/python .py </code></pre> <p>I have a small test script that looks like this:</p> <pre><code>print "Content-Type: text/html\n\n" print "Test" </code></pre> <p>But something seems to be wrong since the apache error log says the following:</p> <pre><code>Premature end of script headers: python </code></pre> <p>So my first though was that my python response is not right. But there is the Content-Type and also both linebreaks. Also the output of a similar PHP script called with <code>php-cgi</code> gives exactly the same output.</p> <p>Also I haven't found a tutorial that shows how to get python working this way. So maybe it is not possible, but then I'm curious why this is the case? Or am I missing something?</p>
0
2009-04-28T18:51:59Z
24,783,017
<p>When you open for example <code>http://localhost/test.py</code> you expect that Apache will somehow start process <code>/usr/bin/python /var/www/test.py</code> (i.e the interpreter with single command line argument). But this is not what happens because Apache calls the cgi script with <em>no</em> arguments. Instead it provides all the information through environment variables which are standardized by CGI.</p> <p>As others have pointed out using python as plain cgi is inefficient but if for educational reasons you would still like to do it you can try this.</p> <p>Assuming that the default Apache cgi-bin settings are active you can create a simple wrapper named <code>python</code> (or whatever you choose) in your <code>/usr/lib/cgi-bin</code> with the following contents:</p> <pre><code>#!/usr/bin/python import os execfile(os.environ['PATH_TRANSLATED']) </code></pre> <p>Don't forget to make it executable: <code>chmod a+x /usr/lib/cgi-bin/python</code></p> <p>Put these in you Apache config:</p> <pre><code>AddType application/python .py Action application/python /cgi-bin/python </code></pre> <p>Now when you open <code>http://localhost/test.py</code> Apache will execute /cgi-bin/python with no arguments but with filled in CGI environment variables. In this case we use <code>PATH_TRANSLATED</code> since it points directly to the file in the webroot.<br> Calling <code>execfile</code> interprets that script inside the already opened python process.</p>
0
2014-07-16T14:09:37Z
[ "python", "apache", "cgi" ]
Print long integers in python
799,434
<p>If I run this where vote.created_on is a python datetime:</p> <pre><code>import calendar created_on_timestamp = calendar.timegm(vote.created_on.timetuple())*1000 created_on_timestamp = str(created_on_timestamp) </code></pre> <p>created_on_timestamp will be printed with encapsulating tick marks ('). If I do int() or something like that, I'll get something like 1240832864000L which isn't a number as far as JavaScript is concerned (which is where I need to use these datetimes).</p> <p>Does anybody know the best way to handle this situation? Should I cast the long as a string and strip the tick marks? That seems crazy.</p> <p>=== Edited Addendum ===</p> <p>The larger problem was that Django was converting " into it's HTML encoded equivalent &39; (or similar). The best way to deal with this is to convert the long into a string and when the template parses the string, use {{ created_on_timestamp|safe }} to render the quote marks as quote marks.</p>
3
2009-04-28T19:12:27Z
799,447
<pre><code>&gt;&gt;&gt; i = 1240832864000L &gt;&gt;&gt; i 1240832864000L &gt;&gt;&gt; print i 1240832864000 &gt;&gt;&gt; &gt;&gt;&gt; '&lt;script type="text/javascript"&gt; var num = %s; &lt;/script&gt;' % i '&lt;script type="text/javascript"&gt; var num = 1240832864000; &lt;/script&gt;' </code></pre> <p>The L only shows up when you trigger the object's <a href="http://docs.python.org/library/functions.html#repr"><code>__repr__</code></a></p> <p>When and how are you sending this data to JavaScript? If you send it as JSON, you shouldn't have to worry about long literals or how Python displays its objects within Python.</p>
5
2009-04-28T19:16:07Z
[ "python", "django", "datetime" ]
Print long integers in python
799,434
<p>If I run this where vote.created_on is a python datetime:</p> <pre><code>import calendar created_on_timestamp = calendar.timegm(vote.created_on.timetuple())*1000 created_on_timestamp = str(created_on_timestamp) </code></pre> <p>created_on_timestamp will be printed with encapsulating tick marks ('). If I do int() or something like that, I'll get something like 1240832864000L which isn't a number as far as JavaScript is concerned (which is where I need to use these datetimes).</p> <p>Does anybody know the best way to handle this situation? Should I cast the long as a string and strip the tick marks? That seems crazy.</p> <p>=== Edited Addendum ===</p> <p>The larger problem was that Django was converting " into it's HTML encoded equivalent &39; (or similar). The best way to deal with this is to convert the long into a string and when the template parses the string, use {{ created_on_timestamp|safe }} to render the quote marks as quote marks.</p>
3
2009-04-28T19:12:27Z
799,492
<p>With the line:</p> <pre><code>created_on_timestamp = str(created_on_timestamp) </code></pre> <p>You are converting something into a string. The python console represents strings with single-quotes (is this what you mean by tick marks?) The string data, of course, does not include the quotes. </p> <p>When you use <code>int()</code> to re-convert it to a number, <code>int()</code> knows it's long because it's too big, and returns a long integer. </p> <p>The python console represents this long number with a trailing <code>L</code>. but the numeric content, of course, does not include the <code>L</code>. </p> <pre><code>&gt;&gt;&gt; l = 42000000000 &gt;&gt;&gt; str(l) '42000000000' &gt;&gt;&gt; l 42000000000L &gt;&gt;&gt; int(str(l)) 42000000000L &gt;&gt;&gt; type( int(str(l)) ) &lt;type 'long'&gt; </code></pre> <p>Although the python console is representing numbers and strings this way (in python syntax), you should be able to use them normally. Are you anticipating a problem or have you actually run into one at this point?</p>
3
2009-04-28T19:30:36Z
[ "python", "django", "datetime" ]
Python html output (first attempt), several questions (code included)
799,479
<p>While I have been playing with python for a few months now (just a hobbyist), I know very little about web programming (a little html, zero javascript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask:</p> <p><a href="http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web">http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web</a></p> <p>Thx to the answers, I made some progress. For now, I'm just using python and html. I can't post my project code, so I wrote a small example using twitter search (pls see below).</p> <p>My questions are:</p> <p>(1) am I doing anything terribly stupid? I feel like WebOutput() is clear but inefficient. If I used javascript, I'm assuming I could write a html template file and then just update the data. yes? better way to do this?</p> <p>(2) at what point would a framework be appropriate for an app like this? overkill?</p> <p>Sorry for the basic questions - but I don't want to spend too much time going down the wrong path.</p> <pre><code>import simplejson, urllib, time #query, results per page query = "swineflu" rpp = 25 jsonURL = "http://search.twitter.com/search.json?q=" + query + "&amp;rpp=" + str(rpp) #currently storing all search results, really only need most recent but want the data avail for other stuff data = [] #iterate over search results def SearchResults(): jsonResults = simplejson.load(urllib.urlopen(jsonURL)) for tweet in jsonResults["results"]: try: #terminal output feed = tweet["from_user"] + " | " + tweet["text"] print feed data.append(feed) except: print "exception??" # writes latest tweets to file/web def WebOutput(): f = open("outw.html", "w") f.write("&lt;html&gt;\n") f.write("&lt;title&gt;python newb's twitter search&lt;/title&gt;\n") f.write("&lt;head&gt;&lt;meta http-equiv='refresh' content='60'&gt;&lt;/head&gt;\n") f.write("&lt;body&gt;\n") f.write("&lt;h1 style='font-size:150%'&gt;Python Newb's Twitter Search&lt;/h1&gt;") f.write("&lt;h2 style='font-size:125%'&gt;Searching Twitter for: " + query + "&lt;/h2&gt;\n") f.write("&lt;h2 style='font-size:125%'&gt;" + time.ctime() + " (updates every 60 seconds)&lt;/h2&gt;\n") for i in range(1,rpp): try: f.write("&lt;p style='font-size:90%'&gt;" + data[-i] + "&lt;/p&gt;\n") except: continue f.write("&lt;/body&gt;\n") f.write("&lt;/html&gt;\n") f.close() while True: print "" print "\nSearching Twitter for: " + query + " | current date/time is: " + time.ctime() print "" SearchResults() WebOutput() time.sleep(60) </code></pre>
2
2009-04-28T19:27:29Z
799,513
<p>The issue that you will run into is that you will need to change the python whenever you want to change the html. For this case, that might be fine, but it can lead to trouble. I think using something with a template system makes a lot of sense. I would suggest looking at Django. The <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01" rel="nofollow">tutorial</a> is very good.</p>
1
2009-04-28T19:35:34Z
[ "javascript", "python" ]
Python html output (first attempt), several questions (code included)
799,479
<p>While I have been playing with python for a few months now (just a hobbyist), I know very little about web programming (a little html, zero javascript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask:</p> <p><a href="http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web">http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web</a></p> <p>Thx to the answers, I made some progress. For now, I'm just using python and html. I can't post my project code, so I wrote a small example using twitter search (pls see below).</p> <p>My questions are:</p> <p>(1) am I doing anything terribly stupid? I feel like WebOutput() is clear but inefficient. If I used javascript, I'm assuming I could write a html template file and then just update the data. yes? better way to do this?</p> <p>(2) at what point would a framework be appropriate for an app like this? overkill?</p> <p>Sorry for the basic questions - but I don't want to spend too much time going down the wrong path.</p> <pre><code>import simplejson, urllib, time #query, results per page query = "swineflu" rpp = 25 jsonURL = "http://search.twitter.com/search.json?q=" + query + "&amp;rpp=" + str(rpp) #currently storing all search results, really only need most recent but want the data avail for other stuff data = [] #iterate over search results def SearchResults(): jsonResults = simplejson.load(urllib.urlopen(jsonURL)) for tweet in jsonResults["results"]: try: #terminal output feed = tweet["from_user"] + " | " + tweet["text"] print feed data.append(feed) except: print "exception??" # writes latest tweets to file/web def WebOutput(): f = open("outw.html", "w") f.write("&lt;html&gt;\n") f.write("&lt;title&gt;python newb's twitter search&lt;/title&gt;\n") f.write("&lt;head&gt;&lt;meta http-equiv='refresh' content='60'&gt;&lt;/head&gt;\n") f.write("&lt;body&gt;\n") f.write("&lt;h1 style='font-size:150%'&gt;Python Newb's Twitter Search&lt;/h1&gt;") f.write("&lt;h2 style='font-size:125%'&gt;Searching Twitter for: " + query + "&lt;/h2&gt;\n") f.write("&lt;h2 style='font-size:125%'&gt;" + time.ctime() + " (updates every 60 seconds)&lt;/h2&gt;\n") for i in range(1,rpp): try: f.write("&lt;p style='font-size:90%'&gt;" + data[-i] + "&lt;/p&gt;\n") except: continue f.write("&lt;/body&gt;\n") f.write("&lt;/html&gt;\n") f.close() while True: print "" print "\nSearching Twitter for: " + query + " | current date/time is: " + time.ctime() print "" SearchResults() WebOutput() time.sleep(60) </code></pre>
2
2009-04-28T19:27:29Z
799,528
<p>I'd suggest using a template to generate the output, you can start with the buildin <a href="http://docs.python.org/library/string.html#template-strings" rel="nofollow">string.Template</a> or try something fancier, for example <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a> (or Cheetah, Genshi, Jinja, Kid, etc). </p> <p>Python has many nice web frameworks, the smallest of them would be <a href="http://webpy.org/" rel="nofollow">web.py</a> or <a href="http://werkzeug.pocoo.org/" rel="nofollow">werkzeug</a></p> <p>If you want a fullblown framework, look at <a href="http://pylonshq.com/" rel="nofollow">Pylons</a> or <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> but these are really overkill for a project like that.</p>
4
2009-04-28T19:40:57Z
[ "javascript", "python" ]
Python html output (first attempt), several questions (code included)
799,479
<p>While I have been playing with python for a few months now (just a hobbyist), I know very little about web programming (a little html, zero javascript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask:</p> <p><a href="http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web">http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web</a></p> <p>Thx to the answers, I made some progress. For now, I'm just using python and html. I can't post my project code, so I wrote a small example using twitter search (pls see below).</p> <p>My questions are:</p> <p>(1) am I doing anything terribly stupid? I feel like WebOutput() is clear but inefficient. If I used javascript, I'm assuming I could write a html template file and then just update the data. yes? better way to do this?</p> <p>(2) at what point would a framework be appropriate for an app like this? overkill?</p> <p>Sorry for the basic questions - but I don't want to spend too much time going down the wrong path.</p> <pre><code>import simplejson, urllib, time #query, results per page query = "swineflu" rpp = 25 jsonURL = "http://search.twitter.com/search.json?q=" + query + "&amp;rpp=" + str(rpp) #currently storing all search results, really only need most recent but want the data avail for other stuff data = [] #iterate over search results def SearchResults(): jsonResults = simplejson.load(urllib.urlopen(jsonURL)) for tweet in jsonResults["results"]: try: #terminal output feed = tweet["from_user"] + " | " + tweet["text"] print feed data.append(feed) except: print "exception??" # writes latest tweets to file/web def WebOutput(): f = open("outw.html", "w") f.write("&lt;html&gt;\n") f.write("&lt;title&gt;python newb's twitter search&lt;/title&gt;\n") f.write("&lt;head&gt;&lt;meta http-equiv='refresh' content='60'&gt;&lt;/head&gt;\n") f.write("&lt;body&gt;\n") f.write("&lt;h1 style='font-size:150%'&gt;Python Newb's Twitter Search&lt;/h1&gt;") f.write("&lt;h2 style='font-size:125%'&gt;Searching Twitter for: " + query + "&lt;/h2&gt;\n") f.write("&lt;h2 style='font-size:125%'&gt;" + time.ctime() + " (updates every 60 seconds)&lt;/h2&gt;\n") for i in range(1,rpp): try: f.write("&lt;p style='font-size:90%'&gt;" + data[-i] + "&lt;/p&gt;\n") except: continue f.write("&lt;/body&gt;\n") f.write("&lt;/html&gt;\n") f.close() while True: print "" print "\nSearching Twitter for: " + query + " | current date/time is: " + time.ctime() print "" SearchResults() WebOutput() time.sleep(60) </code></pre>
2
2009-04-28T19:27:29Z
799,586
<p>It would not be overkill to use a framework for something like this; python frameworks tend to be very light and easy to work with, and would make it much easier for you to add features to your tiny site. But neither is it required; I'll assume you're doing this for learning purposes and talk about how I would change the code.</p> <p>You're doing templating without a template engine in your WebOutput function; there are all kinds of neat template languages for python, my favorite of which is <a href="http://www.makotemplates.org/" rel="nofollow">mako</a>. If the code in that function ever gets hairier than it is currently, I would break it out into a template; I'll show you what that would look like in a moment. But first, I'd use multiline strings to replace all those f.write's, and string substitution instead of adding strings:</p> <pre><code>f.write("""&lt;html&gt; &lt;title&gt;python newb's twitter search&lt;/title&gt; &lt;head&gt;&lt;meta http-equiv='refresh' content='60'&gt;&lt;/head&gt; &lt;body&gt; &lt;h1 style='font-size:150%'&gt;Python Newb's Twitter Search&lt;/h1&gt; &lt;h2 style='font-size:125%'&gt;Searching Twitter for: %s&lt;/h2&gt; &lt;h2 style='font-size:125%'&gt;%s (updates every 60 seconds)&lt;/h2&gt;""" % (query, time.ctime())) for datum in reversed(data): f.write("&lt;p style='font-size:90%'&gt;%s&lt;/p&gt;" % (datum)) f.write("&lt;/body&gt;&lt;/html&gt;") </code></pre> <p>Also note that I simplified your for loop a bit; I'll explain further if what I put doesn't make sense.</p> <p>If you were to convert your WebOutput function to Mako, you would first import mako at the top of your file with:</p> <pre><code>import mako </code></pre> <p>Then you would replace the whole body of WebOutput() with:</p> <pre><code>f = file("outw.html", "w") data = reversed(data) t = Template(filename='/path/to/mytmpl.txt').render({"query":query, "time":time.ctime(), "data":data}) f.write(t) </code></pre> <p>Finally, you would make a file /path/to/mytmpl.txt that looks like this:</p> <pre><code>&lt;html&gt; &lt;title&gt;python newb's twitter search&lt;/title&gt; &lt;head&gt;&lt;meta http-equiv='refresh' content='60'&gt;&lt;/head&gt; &lt;body&gt; &lt;h1 style='font-size:150%'&gt;Python Newb's Twitter Search&lt;/h1&gt; &lt;h2 style='font-size:125%'&gt;Searching Twitter for: ${query}&lt;/h2&gt; &lt;h2 style='font-size:125%'&gt;${time} (updates every 60 seconds)&lt;/h2&gt; % for datum in data: &lt;p style'font-size:90%'&gt;${datum}&lt;/p&gt; % endfor &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And you can see that the nice thing you've accomplished is separating the output (or "view layer" in web terms) from the code that grabs and formats the data (the "model layer" and "controller layer"). This will make it much easier for you to change the output of your script in the future.</p> <p>(Note: I didn't test the code I've presented here; apologies if it isn't quite right. It should basically work though)</p>
8
2009-04-28T20:00:40Z
[ "javascript", "python" ]
Python html output (first attempt), several questions (code included)
799,479
<p>While I have been playing with python for a few months now (just a hobbyist), I know very little about web programming (a little html, zero javascript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask:</p> <p><a href="http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web">http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web</a></p> <p>Thx to the answers, I made some progress. For now, I'm just using python and html. I can't post my project code, so I wrote a small example using twitter search (pls see below).</p> <p>My questions are:</p> <p>(1) am I doing anything terribly stupid? I feel like WebOutput() is clear but inefficient. If I used javascript, I'm assuming I could write a html template file and then just update the data. yes? better way to do this?</p> <p>(2) at what point would a framework be appropriate for an app like this? overkill?</p> <p>Sorry for the basic questions - but I don't want to spend too much time going down the wrong path.</p> <pre><code>import simplejson, urllib, time #query, results per page query = "swineflu" rpp = 25 jsonURL = "http://search.twitter.com/search.json?q=" + query + "&amp;rpp=" + str(rpp) #currently storing all search results, really only need most recent but want the data avail for other stuff data = [] #iterate over search results def SearchResults(): jsonResults = simplejson.load(urllib.urlopen(jsonURL)) for tweet in jsonResults["results"]: try: #terminal output feed = tweet["from_user"] + " | " + tweet["text"] print feed data.append(feed) except: print "exception??" # writes latest tweets to file/web def WebOutput(): f = open("outw.html", "w") f.write("&lt;html&gt;\n") f.write("&lt;title&gt;python newb's twitter search&lt;/title&gt;\n") f.write("&lt;head&gt;&lt;meta http-equiv='refresh' content='60'&gt;&lt;/head&gt;\n") f.write("&lt;body&gt;\n") f.write("&lt;h1 style='font-size:150%'&gt;Python Newb's Twitter Search&lt;/h1&gt;") f.write("&lt;h2 style='font-size:125%'&gt;Searching Twitter for: " + query + "&lt;/h2&gt;\n") f.write("&lt;h2 style='font-size:125%'&gt;" + time.ctime() + " (updates every 60 seconds)&lt;/h2&gt;\n") for i in range(1,rpp): try: f.write("&lt;p style='font-size:90%'&gt;" + data[-i] + "&lt;/p&gt;\n") except: continue f.write("&lt;/body&gt;\n") f.write("&lt;/html&gt;\n") f.close() while True: print "" print "\nSearching Twitter for: " + query + " | current date/time is: " + time.ctime() print "" SearchResults() WebOutput() time.sleep(60) </code></pre>
2
2009-04-28T19:27:29Z
799,739
<p><a href="http://www.python.org/doc/2.5.2/lib/typesseq-strings.html" rel="nofollow">String formatting</a> can make things a lot neater, and less error-prone.</p> <p>Simple example, <code>%s</code> is replaced by <code>a title</code>:</p> <pre><code>my_html = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;%s&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;" % ("a title") </code></pre> <p>Or multiple times (title is the same, and now "my content" is displayed where the second <code>%s</code> is:</p> <pre><code>my_html = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;%s&lt;/h1&gt;%s&lt;/body&gt;&lt;/html&gt;" % ("a title", "my content") </code></pre> <p>You can also use named keys when doing <code>%s</code>, like <code>%(thekey)s</code>, which means you don't have to keep track of which order the <code>%s</code> are in. Instead of a <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="nofollow">list</a>, you use a <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a>, which maps the key to a value:</p> <pre><code>my_html = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;%(title)s&lt;/h1&gt;%(content)s&lt;/body&gt;&lt;/html&gt;" % { "title": "a title", "content":"my content" } </code></pre> <p>The biggest issue with your script is, you are using a global variable (<code>data</code>). A <em>much</em> better way would be:</p> <ul> <li>call search_results, with an argument of "swineflu"</li> <li>search_results returns a list of results, store the result in a variable</li> <li>call WebOutput, with the search results variable as the argument</li> <li>WebOutput returns a string, containing your HTML</li> <li>write the returned HTML to your file</li> </ul> <p>WebOutput would return the HTML (as a string), and write it to a file. Something like:</p> <pre><code>results = SearchResults("swineflu", 25) html = WebOutput(results) f = open("outw.html", "w") f.write(html) f.close() </code></pre> <p>Finally, the twitterd module is only required if you are accessing data that requires a login. The public timeline is, well, public, and can be accessed without any authentication, so you can remove the twitterd import, and the <code>api = </code> line. If you did want to use twitterd, you would have to do something with the <code>api</code> variable, for example:</p> <pre><code>api = twitterd.Api(username='username', password='password') statuses = api.GetPublicTimeline() </code></pre> <p>So, the way I might have written the script is:</p> <pre><code>import time import urllib import simplejson def search_results(query, rpp = 25): # 25 is default value for rpp url = "http://search.twitter.com/search.json?q=%s&amp;%s" % (query, rpp) jsonResults = simplejson.load(urllib.urlopen(url)) data = [] # setup empty list, within function scope for tweet in jsonResults["results"]: # Unicode! # And tweet is a dict, so we can use the string-formmating key thing data.append(u"%(from_user)s | %(text)s" % tweet) return data # instead of modifying the global data! def web_output(data, query): results_html = "" # loop over each index of data, storing the item in "result" for result in data: # append to string results_html += " &lt;p style='font-size:90%%'&gt;%s&lt;/p&gt;\n" % (result) html = """&lt;html&gt; &lt;head&gt; &lt;meta http-equiv='refresh' content='60'&gt; &lt;title&gt;python newb's twitter search&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 style='font-size:150%%'&gt;Python Newb's Twitter Search&lt;/h1&gt; &lt;h2 style='font-size:125%%'&gt;Searching Twitter for: %(query)s&lt;/h2&gt; &lt;h2 style='font-size:125%%'&gt; %(ctime)s (updates every 60 seconds)&lt;/h2&gt; %(results_html)s &lt;/body&gt; &lt;/html&gt; """ % { 'query': query, 'ctime': time.ctime(), 'results_html': results_html } return html def main(): query_string = "swineflu" results = search_results(query_string) # second value defaults to 25 html = web_output(results, query_string) # Moved the file writing stuff to main, so WebOutput is reusable f = open("outw.html", "w") f.write(html) f.close() # Once the file is written, display the output to the terminal: for formatted_tweet in results: # the .encode() turns the unicode string into an ASCII one, ignoring # characters it cannot display correctly print formatted_tweet.encode('ascii', 'ignore') if __name__ == '__main__': main() # Common Python idiom, only runs main if directly run (not imported). # Then means you can do.. # import myscript # myscript.search_results("#python") # without your "main" function being run </code></pre> <p><hr /></p> <blockquote> <p>(2) at what point would a framework be appropriate for an app like this? overkill?</p> </blockquote> <p>I would say always use a web-framework (with a few exceptions)</p> <p>Now, that might seem strange, given all time I just spent explaining fixes to your script.. but, with the above modifications to your script, it's incredibly easy to do, since everything has been nicely function'ified!</p> <p>Using <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a>, which is a really simple HTTP framework for Python, you can easily send data to the browser, rather than constantly writing a file.</p> <p>This assumes the above script is saved as <code>twitter_searcher.py</code>.</p> <p>Note I've never used CherryPy before, this is just the HelloWorld example on the CherryPy homepage, with a few lines copied from the above script's main() function!</p> <pre><code>import cherrypy # import the twitter_searcher.py script import twitter_searcher # you can now call the the functions in that script, for example: # twitter_searcher.search_results("something") class TwitterSearcher(object): def index(self): query_string = "swineflu" results = twitter_searcher.search_results(query_string) # second value defaults to 25 html = twitter_searcher.web_output(results, query_string) return html index.exposed = True cherrypy.quickstart(TwitterSearcher()) </code></pre> <p>Save and run that script, then browse to <code>http://0.0.0.0:8080/</code> and it'll show your page!</p> <p>The problem with this, on every page load it will query the Twitter API. This will not be a problem if it's just you using it, but with hundreds (or even tens) of people looking at the page, it would start to slow down (and you could get rate-limited/blocked by the twitter API, eventually)</p> <p>The solution is basically back to the start.. You would write (cache) the search result to disc, re-searching twitter if the data is more than ~60 seconds old. You could also look into <a href="http://www.cherrypy.org/wiki/Caching" rel="nofollow">CherryPy's caching options</a>.. but this answer is getting rather absurdly long..</p>
5
2009-04-28T20:44:15Z
[ "javascript", "python" ]
Getting name of windows computer running python script?
799,767
<p>Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. </p> <p>How would I get that computer name in the python script?</p> <p>Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:</p> <pre><code>&gt;&gt;&gt; python.library.getComputerName() 'DARK-TOWER' </code></pre> <p>Is there a standard or third party library I can use?</p>
45
2009-04-28T20:49:11Z
799,775
<p>I bet <a href="http://pydoc.org/1.6/socket.html#-gethostname" rel="nofollow">gethostname</a> will work beautifully.</p>
2
2009-04-28T20:51:15Z
[ "python", "windows", "networking" ]
Getting name of windows computer running python script?
799,767
<p>Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. </p> <p>How would I get that computer name in the python script?</p> <p>Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:</p> <pre><code>&gt;&gt;&gt; python.library.getComputerName() 'DARK-TOWER' </code></pre> <p>Is there a standard or third party library I can use?</p>
45
2009-04-28T20:49:11Z
799,779
<p>Since the python scrips are for sure running on a windows system, you should use the Win32 API <a href="http://msdn.microsoft.com/en-us/library/ms724295%28VS.85%29.aspx" rel="nofollow">GetComputerName</a> or <a href="http://msdn.microsoft.com/en-us/library/ms724301%28VS.85%29.aspx" rel="nofollow">GetComputerNameEx</a></p> <p>You can get the fully qualified DNS name, or NETBIOS name, or a variety of different things.</p> <pre><code>import win32api win32api.GetComputerName() &gt;&gt;'MYNAME' </code></pre> <p>Or:</p> <pre><code>import win32api WIN32_ComputerNameDnsHostname = 1 win32api.GetComputerNameEx(WIN32_ComputerNameDnsHostname) &gt;&gt; u'MYNAME' </code></pre>
4
2009-04-28T20:52:31Z
[ "python", "windows", "networking" ]
Getting name of windows computer running python script?
799,767
<p>Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. </p> <p>How would I get that computer name in the python script?</p> <p>Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:</p> <pre><code>&gt;&gt;&gt; python.library.getComputerName() 'DARK-TOWER' </code></pre> <p>Is there a standard or third party library I can use?</p>
45
2009-04-28T20:49:11Z
799,782
<p>From <a href="https://mail.python.org/pipermail/python-list/2006-April/397494.html" rel="nofollow">https://mail.python.org/pipermail/python-list/2006-April/397494.html</a></p> <pre><code>import os os.getenv('COMPUTERNAME') </code></pre>
9
2009-04-28T20:53:12Z
[ "python", "windows", "networking" ]
Getting name of windows computer running python script?
799,767
<p>Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. </p> <p>How would I get that computer name in the python script?</p> <p>Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:</p> <pre><code>&gt;&gt;&gt; python.library.getComputerName() 'DARK-TOWER' </code></pre> <p>Is there a standard or third party library I can use?</p>
45
2009-04-28T20:49:11Z
799,783
<pre><code>import socket socket.gethostname() </code></pre>
15
2009-04-28T20:53:25Z
[ "python", "windows", "networking" ]
Getting name of windows computer running python script?
799,767
<p>Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. </p> <p>How would I get that computer name in the python script?</p> <p>Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:</p> <pre><code>&gt;&gt;&gt; python.library.getComputerName() 'DARK-TOWER' </code></pre> <p>Is there a standard or third party library I can use?</p>
45
2009-04-28T20:49:11Z
799,799
<p>It turns out there are three options (including the two already answered earlier):</p> <pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; import socket &gt;&gt;&gt; import os &gt;&gt;&gt; platform.node() 'DARK-TOWER' &gt;&gt;&gt; socket.gethostname() 'DARK-TOWER' &gt;&gt;&gt; os.environ['COMPUTERNAME'] 'DARK-TOWER' </code></pre>
83
2009-04-28T20:57:22Z
[ "python", "windows", "networking" ]
Getting name of windows computer running python script?
799,767
<p>Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. </p> <p>How would I get that computer name in the python script?</p> <p>Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:</p> <pre><code>&gt;&gt;&gt; python.library.getComputerName() 'DARK-TOWER' </code></pre> <p>Is there a standard or third party library I can use?</p>
45
2009-04-28T20:49:11Z
34,773,209
<p>As Eric Carr said you could use these three variants.</p> <p>I prefer using them together:</p> <pre><code>def getpcname(): n1 = platform.node() n2 = socket.gethostname() n3 = os.environ["COMPUTERNAME"] if n1 == n2 == n3: return n1 elif n1 == n2: return n1 elif n1 == n3: return n1 elif n2 == n3: return n2 else: raise Exception("Computernames are not equal to each other") </code></pre> <p>I prefer it when developing cross patform applications to be sure ;)</p>
2
2016-01-13T17:29:57Z
[ "python", "windows", "networking" ]
How to get last inserted item's key in google app engine
799,803
<p>I am working with google app engine and python.<br /> I have a model with Items.<br /> Immediately after I insert an item with item.put()<br /> I want to get it's key and redirect to a page using this key</p> <p>something like,</p> <pre><code>redirectUrl = "/view/key/%s/" % item.key self.redirect(redirectUrl) </code></pre>
1
2009-04-28T20:58:22Z
799,926
<p>After you did you <code>put()</code> you can run</p> <pre><code>item.key().id() </code></pre> <p>Getting the <code>id()</code> is slightly safer than just using <code>key()</code> directly, since you'd be indirectly calling <code>__str__()</code>, which may not happen in a non strincg context.</p> <p>The other options is to call <code>id_or_name()</code>, but then you probably would already know what the name is in that case.</p>
1
2009-04-28T21:36:37Z
[ "python", "google-app-engine" ]
How to get last inserted item's key in google app engine
799,803
<p>I am working with google app engine and python.<br /> I have a model with Items.<br /> Immediately after I insert an item with item.put()<br /> I want to get it's key and redirect to a page using this key</p> <p>something like,</p> <pre><code>redirectUrl = "/view/key/%s/" % item.key self.redirect(redirectUrl) </code></pre>
1
2009-04-28T20:58:22Z
799,967
<p>Thanks for the initiative Scott Kirkwood. I was actually missing the ()</p> <pre><code>redirectUrl = "/view/key/%s/" % item.key() self.redirect(redirectUrl) </code></pre> <p>Good to know that in google datastore you don't need to use anything like Scope_identity, but you can just get the item.key() just after item.put()..</p>
1
2009-04-28T21:47:53Z
[ "python", "google-app-engine" ]
How to get last inserted item's key in google app engine
799,803
<p>I am working with google app engine and python.<br /> I have a model with Items.<br /> Immediately after I insert an item with item.put()<br /> I want to get it's key and redirect to a page using this key</p> <p>something like,</p> <pre><code>redirectUrl = "/view/key/%s/" % item.key self.redirect(redirectUrl) </code></pre>
1
2009-04-28T20:58:22Z
804,324
<p>Also, item.put() returns the key as the result, so it's hardly ever necessary to fetch that key immediately again -- just change your sequence, e.g</p> <pre><code> item.put() redirectUrl = "/view/key/%s/" % item.key() </code></pre> <p>into</p> <pre><code> k = item.put() redirectUrl = "/view/key/%s/" % k </code></pre>
4
2009-04-29T21:18:38Z
[ "python", "google-app-engine" ]
keeping same formatting for floating point values
800,015
<p>I have a python program that reads floating point values using the following regular expression</p> <pre><code> (-?\d+\.\d+) </code></pre> <p>once I extract the value using float(match.group(1)), I get the actual floating point number. However, I am not able to distinguish if the number was 1.2345678 or 1.234 or 1.2340000.</p> <p>The problem I am facing is to print out the floating point value again, with the exact same formatting. An easy solution is to "split and count" the floating point value when still a string, <em>eg</em> splitting at the decimal point, and counting the integer part length and the fractional part length, then create the formatter as </p> <pre><code>print "%"+str(total_len)+"."+str(fractional_len)+"f" % value </code></pre> <p>but maybe you know a standard way to achieve the same result ?</p>
1
2009-04-28T22:01:29Z
800,035
<p>If you want to keep a fixed precision, avoid using <code>float</code>s and use <code>Decimal</code> instead:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; d = Decimal('-1.2345') &gt;&gt;&gt; str(d) '-1.2345' &gt;&gt;&gt; float(d) -1.2344999999999999 </code></pre>
8
2009-04-28T22:07:44Z
[ "python", "formatting", "floating-point" ]
keeping same formatting for floating point values
800,015
<p>I have a python program that reads floating point values using the following regular expression</p> <pre><code> (-?\d+\.\d+) </code></pre> <p>once I extract the value using float(match.group(1)), I get the actual floating point number. However, I am not able to distinguish if the number was 1.2345678 or 1.234 or 1.2340000.</p> <p>The problem I am facing is to print out the floating point value again, with the exact same formatting. An easy solution is to "split and count" the floating point value when still a string, <em>eg</em> splitting at the decimal point, and counting the integer part length and the fractional part length, then create the formatter as </p> <pre><code>print "%"+str(total_len)+"."+str(fractional_len)+"f" % value </code></pre> <p>but maybe you know a standard way to achieve the same result ?</p>
1
2009-04-28T22:01:29Z
800,041
<pre><code>&gt;&gt;&gt; from decimal import Decimal as d &gt;&gt;&gt; d('1.13200000') Decimal('1.13200000') &gt;&gt;&gt; print d('1.13200000') 1.13200000 </code></pre>
1
2009-04-28T22:09:09Z
[ "python", "formatting", "floating-point" ]
keeping same formatting for floating point values
800,015
<p>I have a python program that reads floating point values using the following regular expression</p> <pre><code> (-?\d+\.\d+) </code></pre> <p>once I extract the value using float(match.group(1)), I get the actual floating point number. However, I am not able to distinguish if the number was 1.2345678 or 1.234 or 1.2340000.</p> <p>The problem I am facing is to print out the floating point value again, with the exact same formatting. An easy solution is to "split and count" the floating point value when still a string, <em>eg</em> splitting at the decimal point, and counting the integer part length and the fractional part length, then create the formatter as </p> <pre><code>print "%"+str(total_len)+"."+str(fractional_len)+"f" % value </code></pre> <p>but maybe you know a standard way to achieve the same result ?</p>
1
2009-04-28T22:01:29Z
800,329
<p>You method is basically correct. String formatting has a less often used <code>*</code> operator you can put for the formatting sizes, here's some code:</p> <pre><code>import re def parse_float(str): re_float = re.compile(r'(-?)(\d+)\.(\d+)') grps = re_float.search(str) sign, decimal, fraction = grps.groups() float_val = float('%s%s.%s' % (sign, decimal, fraction)) total_len = len(grps.group(0)) print '%*.*f' % (total_len, len(fraction), float_val) parse_float('1.2345678') parse_float('1.234') parse_float('1.2340000') </code></pre> <p>and it outputs</p> <pre><code>1.2345678 1.234 1.2340000 </code></pre>
3
2009-04-28T23:54:10Z
[ "python", "formatting", "floating-point" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
800,201
<pre><code>import os def get_immediate_subdirectories(a_dir): return [name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))] </code></pre>
115
2009-04-28T23:02:06Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
800,203
<p><a href="http://www.python.org/doc/2.5.4/lib/os-file-dir.html" rel="nofollow"><code>os.walk</code></a> is your friend in this situation.</p> <p>Straight from the documentation:</p> <blockquote> <p>walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). </p> </blockquote>
7
2009-04-28T23:02:46Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
800,206
<p>Using Twisted's FilePath module:</p> <pre><code>from twisted.python.filepath import FilePath def subdirs(pathObj): for subpath in pathObj.walk(): if subpath.isdir(): yield subpath if __name__ == '__main__': for subdir in subdirs(FilePath(".")): print "Subdirectory:", subdir </code></pre> <p>Since some commenters have asked what the advantages of using Twisted's libraries for this is, I'll go a bit beyond the original question here.</p> <p><hr /></p> <p>There's <a href="http://twistedmatrix.com/trac/browser/branches/filepath-setcontent-2931-3/twisted/python/filepath.py#L6" rel="nofollow">some improved documentation</a> in a branch that explains the advantages of FilePath; you might want to read that.</p> <p>More specifically in this example: unlike the standard library version, this function can be implemented with <em>no imports</em>. The "subdirs" function is totally generic, in that it operates on nothing but its argument. In order to copy and move the files using the standard library, you need to depend on the "<code>open</code>" builtin, "<code>listdir</code>", perhaps "<code>isdir</code>" or "<code>os.walk</code>" or "<code>shutil.copy</code>". Maybe "<code>os.path.join</code>" too. Not to mention the fact that you need a string passed an argument to identify the actual file. Let's take a look at the full implementation which will copy each directory's "index.tpl" to "index.html":</p> <pre><code>def copyTemplates(topdir): for subdir in subdirs(topdir): tpl = subdir.child("index.tpl") if tpl.exists(): tpl.copyTo(subdir.child("index.html")) </code></pre> <p>The "subdirs" function above can work on any <code>FilePath</code>-like object. Which means, among other things, <code>ZipPath</code> objects. Unfortunately <code>ZipPath</code> is read-only right now, but it could be extended to support writing.</p> <p>You can also pass your own objects for testing purposes. In order to test the os.path-using APIs suggested here, you have to monkey with imported names and implicit dependencies and generally perform black magic to get your tests to work. With FilePath, you do something like this:</p> <pre><code>class MyFakePath: def child(self, name): "Return an appropriate child object" def walk(self): "Return an iterable of MyFakePath objects" def exists(self): "Return true or false, as appropriate to the test" def isdir(self): "Return true or false, as appropriate to the test" ... subdirs(MyFakePath(...)) </code></pre>
5
2009-04-28T23:03:54Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
800,299
<p>Here's one way:</p> <pre><code>import os import shutil def copy_over(path, from_name, to_name): for path, dirname, fnames in os.walk(path): for fname in fnames: if fname == from_name: shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name)) copy_over('.', 'index.tpl', 'index.html') </code></pre>
0
2009-04-28T23:42:09Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
800,539
<p>I just wrote some code to move vmware virtual machines around, and ended up using <code>os.path</code> and <code>shutil</code> to accomplish file copying between sub-directories.</p> <pre><code>def copy_client_files (file_src, file_dst): for file in os.listdir(file_src): print "Copying file: %s" % file shutil.copy(os.path.join(file_src, file), os.path.join(file_dst, file)) </code></pre> <p>It's not terribly elegant, but it does work.</p>
1
2009-04-29T01:38:14Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
17,460,317
<pre><code>import os, os.path </code></pre> <p><strong>To get (full-path) immediate sub-directories in a directory:</strong></p> <pre><code>def SubDirPath (d): return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)]) </code></pre> <p><strong>To get the latest (newest) sub-directory:</strong></p> <pre><code>def LatestDirectory (d): return max(SubDirPath(d), key=os.path.getmtime) </code></pre>
11
2013-07-04T00:47:48Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
18,278,257
<p>Why has no one mentioned <a href="https://docs.python.org/2/library/glob.html"><code>glob</code></a>? <code>glob</code> lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:</p> <pre><code>from glob import glob paths = glob('*/') </code></pre> <p>Note that <code>glob</code> will return the directory with the final slash (as unix would) while most <code>path</code> based solutions will omit the final slash.</p>
23
2013-08-16T16:41:50Z
[ "python", "file" ]
How to get all of the immediate subdirectories in Python
800,197
<p>I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). </p> <p>I'm getting bogged down by trying to get the list of subdirectories.</p>
63
2009-04-28T22:59:11Z
25,705,093
<p>Check "<a href="http://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory/973488#973488">Getting a list of all subdirectories in the current directory</a>".</p> <p>Here's a Python 3 version:</p> <pre><code>import os dir_list = next(os.walk('.'))[1] print(dir_list) </code></pre>
5
2014-09-06T21:50:37Z
[ "python", "file" ]
How to initialize variables to None/Undefined and compare to other variables in Python?
800,248
<p>Basically I have some variables that I don't want to preinitialize:</p> <pre><code>originalTime = None recentTime = None postTime = None def DoSomething ( ) : if originalTime == None or (postTime - recentTime).seconds &gt; 5 : ... </code></pre> <p>I get compile error on the if:</p> <pre><code>UnboundLocalError: local variable 'originalTime' referenced before assignment </code></pre> <p>As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.</p> <p>Any ideas?</p>
1
2009-04-28T23:22:37Z
800,267
<p>I just tried your code in the shell and I didn't get an error. It should work. Maybe post the entire code? You can also use try/catch.</p> <p>Or maybe locals().has_key('originalTime') ?</p>
-2
2009-04-28T23:30:25Z
[ "python" ]
How to initialize variables to None/Undefined and compare to other variables in Python?
800,248
<p>Basically I have some variables that I don't want to preinitialize:</p> <pre><code>originalTime = None recentTime = None postTime = None def DoSomething ( ) : if originalTime == None or (postTime - recentTime).seconds &gt; 5 : ... </code></pre> <p>I get compile error on the if:</p> <pre><code>UnboundLocalError: local variable 'originalTime' referenced before assignment </code></pre> <p>As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.</p> <p>Any ideas?</p>
1
2009-04-28T23:22:37Z
800,280
<p>Your code should have worked, I'm guessing that it's inside a function but originalTime is defined somewhere else. Also it's a bit better to say <code>originalTime is None</code> if that's what you really want or even better, <code>not originalTime</code>.</p>
5
2009-04-28T23:34:18Z
[ "python" ]
How to initialize variables to None/Undefined and compare to other variables in Python?
800,248
<p>Basically I have some variables that I don't want to preinitialize:</p> <pre><code>originalTime = None recentTime = None postTime = None def DoSomething ( ) : if originalTime == None or (postTime - recentTime).seconds &gt; 5 : ... </code></pre> <p>I get compile error on the if:</p> <pre><code>UnboundLocalError: local variable 'originalTime' referenced before assignment </code></pre> <p>As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.</p> <p>Any ideas?</p>
1
2009-04-28T23:22:37Z
800,330
<p>If the <code>if</code> statement is inside a function, but the <code>= None</code> declarations are at the module-level, then the variables are out of scope inside the function. The simplest fix is to explicitly indicate that the variable identifiers are to be found in the global scope:</p> <pre><code>def doSomething(): global originalTime if originalTime: print "originalTime exists and does not evaluate to False" </code></pre> <p>Many folks regard this as poor Python design, btw. If you agree with that assessment, and your architecture permits, you may wish to refactor your function so that it receives external dependencies as function arguments. </p>
0
2009-04-28T23:54:33Z
[ "python" ]
How to initialize variables to None/Undefined and compare to other variables in Python?
800,248
<p>Basically I have some variables that I don't want to preinitialize:</p> <pre><code>originalTime = None recentTime = None postTime = None def DoSomething ( ) : if originalTime == None or (postTime - recentTime).seconds &gt; 5 : ... </code></pre> <p>I get compile error on the if:</p> <pre><code>UnboundLocalError: local variable 'originalTime' referenced before assignment </code></pre> <p>As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.</p> <p>Any ideas?</p>
1
2009-04-28T23:22:37Z
800,389
<p>There's not really any "pretty" way around this. Just based on the variable names that you've given, my first instinct is to create an object:</p> <pre><code>class SomeTimeClass(object): def __init__(self, recentTime=None, originalTime=None, postTime=None): self.recentTime = recentTime self.originalTime = originalTime self.postTime = postTime time = SomeTimeClass() if not time.recentTime:: ... </code></pre> <p>This might work because it sounds like the variables are correlated. A couple of other options:</p> <p>Wrap the procedure in a function:</p> <pre><code>def SomeFunc(recentTime=None, originalTime=None, postTime=None): if not recentTime: ... </code></pre> <p>Use a dict:</p> <pre><code>some_dict = {} if not some_dict.get('originalTime', None): #return None if key doesn't exist ... </code></pre>
-2
2009-04-29T00:24:53Z
[ "python" ]
How to initialize variables to None/Undefined and compare to other variables in Python?
800,248
<p>Basically I have some variables that I don't want to preinitialize:</p> <pre><code>originalTime = None recentTime = None postTime = None def DoSomething ( ) : if originalTime == None or (postTime - recentTime).seconds &gt; 5 : ... </code></pre> <p>I get compile error on the if:</p> <pre><code>UnboundLocalError: local variable 'originalTime' referenced before assignment </code></pre> <p>As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.</p> <p>Any ideas?</p>
1
2009-04-28T23:22:37Z
802,450
<p>I need to correct Jarret Hardie, and since I don't have enough rep to comment.</p> <p>The global scope is not an issue. Python will automatically look up variable names in enclosing scopes. The only issue is when you want to change the value. If you simply redefine the variable, Python will create a new local variable, unless you use the global keyword. So</p> <pre><code>originalTime = None def doSomething(): if originalTime: print "originalTime is not None and does not evaluate to False" else: print "originalTime is None or evaluates to False" def doSomethingElse(): originalTime = True def doSomethingCompletelyDifferent() global originalTime originalTime = True doSomething() doSomethingElse() doSomething() doSomethingCompletelyDifferent() doSomething() </code></pre> <p>Should output:</p> <pre><code>originalTime is None or evaluates to False originalTime is None or evaluates to False originalTime is not None and does not evaluate to False </code></pre> <p>I second his warning that this is bad design.</p>
8
2009-04-29T13:50:16Z
[ "python" ]
About GUI editor that would be compatible with Python 3.0
800,769
<p>I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use with Python 3.0? Any suggestions are welcomed. Thanks!</p>
3
2009-04-29T03:37:44Z
800,794
<p>Just use whichever editor you are most comfortable with.</p> <p>The "leading space as logic" and duck typing mean that there is a limited amount of syntax checking and re-factoring an editor can reasonably do (or is required!) with python source.</p> <p>If you dont have a favorite editor then just use the "idle" editor which comes with most python distributions.</p> <p>If you were talking about a GUI design tool then you need to choose among the several supported GUIs (Tk, WxWindows etc. etc.) before you choose your design tool.</p>
0
2009-04-29T03:49:55Z
[ "python", "user-interface", "python-3.x" ]
About GUI editor that would be compatible with Python 3.0
800,769
<p>I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use with Python 3.0? Any suggestions are welcomed. Thanks!</p>
3
2009-04-29T03:37:44Z
800,824
<p>There are many useful libraries (not to mention educational material, cookbook snippets, etc.) that have yet to be ported to Python 3.0, so I recommend using Python 2.x for now (where, currently, 5 &lt;= x &lt;= 6). Doubly so if you're a beginner to Python. Triply so if you're actually planning on releasing some software--many systems do not ship with Python 3.0.</p> <p>Python 3.0 is not radically different from the Python 2.x series; what you learn in Python 2 will very much still apply to Python 3. Searching Python 3.0 here on SO reveals many threads in which the majority declare that they're not moving to Python 3.0 anytime soon.</p>
1
2009-04-29T04:03:50Z
[ "python", "user-interface", "python-3.x" ]
About GUI editor that would be compatible with Python 3.0
800,769
<p>I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use with Python 3.0? Any suggestions are welcomed. Thanks!</p>
3
2009-04-29T03:37:44Z
800,918
<p>The only GUI toolkit currently available in Python3.0 is Tkinter, and I don't think there are any Python3.0 GUI-builders available yet.</p>
0
2009-04-29T04:47:19Z
[ "python", "user-interface", "python-3.x" ]
About GUI editor that would be compatible with Python 3.0
800,769
<p>I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use with Python 3.0? Any suggestions are welcomed. Thanks!</p>
3
2009-04-29T03:37:44Z
800,941
<p>WING 3.2 beta work in python 3.</p> <p>ricnar</p>
0
2009-04-29T05:00:23Z
[ "python", "user-interface", "python-3.x" ]
About GUI editor that would be compatible with Python 3.0
800,769
<p>I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use with Python 3.0? Any suggestions are welcomed. Thanks!</p>
3
2009-04-29T03:37:44Z
801,121
<p>If your looking for a GUI editor, have a look at these:</p> <ul> <li><a href="http://wxformbuilder.org" rel="nofollow">wxFormBuilder</a> can generate .XRC files for wxpython.</li> <li>XRCed ships with wxpython and could do this as well.</li> </ul> <p>.XRC files are xml file which describes your GUI and are not language specific. You could load these files from a Python 2.6 and a Python 3.0 without any change.</p> <p>WxPython is currently available only for Python 2.6 though. I would not worry too much about converting a python 2.6 to 3.0. This is the matter of a few lines to change.</p> <p>The problem with the .XRC approach is that you still need to glue these xml files with Python code. If you're a beginner this might be as tricky as writing the GUI by hand. That's the problem with WxPython anyway: I don't know any real good editor for it, have a look at this <a href="http://stackoverflow.com/questions/800849/nice-ide-for-wxpython-or-tkinter-gui-development">discussion</a></p>
1
2009-04-29T06:31:22Z
[ "python", "user-interface", "python-3.x" ]
About GUI editor that would be compatible with Python 3.0
800,769
<p>I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use with Python 3.0? Any suggestions are welcomed. Thanks!</p>
3
2009-04-29T03:37:44Z
972,835
<p><a href="http://www.riverbankcomputing.co.uk/software/pyqt/download" rel="nofollow">PyQt 4.5</a> (released a couple of days ago) added support for Python 3</p> <p>That doesn't of course devaluate gotgenes answer: most of the 3rd party libraries are just not ready yet for Python 3.</p>
0
2009-06-09T22:34:28Z
[ "python", "user-interface", "python-3.x" ]
C# Nmath to Python SciPy
801,128
<p>I need to port some functions from C# to Python, but i can't implement next code right:</p> <pre><code>[SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)] public static SqlDouble LogNormDist(double probability, double mean, double stddev) { LognormalDistribution lnd = new LognormalDistribution(mean,stddev); return (SqlDouble)lnd.CDF(probability); } </code></pre> <p>This code uses CenterSpace Nmath library.</p> <p>Anyone can help me to write a right function in python, which will be similar to this code?</p> <p>Sorry for my English.</p> <p><strong>UPD</strong> Actually, i don't understand which scipy.stats.lognorm.cdf attrs are simillar to C# probability, mean, stddev</p> <p>If just copy existing order to python, like in answer below, i get wrong number.</p>
1
2009-04-29T06:33:05Z
801,435
<p>Maybe you can use Python.NET (this is <em>NOT</em> IronPython), it allows to access .NET components and services:</p> <p><a href="http://pythonnet.sourceforge.net/" rel="nofollow">http://pythonnet.sourceforge.net/</a></p>
0
2009-04-29T08:29:43Z
[ "c#", "python", "scipy", "nmath" ]
C# Nmath to Python SciPy
801,128
<p>I need to port some functions from C# to Python, but i can't implement next code right:</p> <pre><code>[SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)] public static SqlDouble LogNormDist(double probability, double mean, double stddev) { LognormalDistribution lnd = new LognormalDistribution(mean,stddev); return (SqlDouble)lnd.CDF(probability); } </code></pre> <p>This code uses CenterSpace Nmath library.</p> <p>Anyone can help me to write a right function in python, which will be similar to this code?</p> <p>Sorry for my English.</p> <p><strong>UPD</strong> Actually, i don't understand which scipy.stats.lognorm.cdf attrs are simillar to C# probability, mean, stddev</p> <p>If just copy existing order to python, like in answer below, i get wrong number.</p>
1
2009-04-29T06:33:05Z
801,457
<p>Scipy has a bunch of distributions defined in the scipy.stats package</p> <pre><code>import scipy.stats def LogNormDist(prob, mean=0, stddev=1): return scipy.stats.lognorm.cdf(prob,stddev,mean) </code></pre> <h3>Update</h3> <p>Okay, it looks like Scipy's stat definitions are a little nonstandard. Here's the end of the docstring for <code>scipy.stats.lognormal</code></p> <blockquote> <p>Lognormal distribution</p> <p>lognorm.pdf(x,s) = 1/(s*x*sqrt(2*pi)) * exp(-1/2*(log(x)/s)**2) for x > 0, s > 0.</p> <p>If log x is normally distributed with mean mu and variance sigma**2, then x is log-normally distributed with shape paramter sigma and scale parameter exp(mu).</p> </blockquote> <p>So maybe try</p> <pre><code>return scipy.stats.lognorm.cdf(prob,stddev,scipy.exp(mean)) </code></pre> <p>If that still doesn't work, try getting a few sample points and I'll see if I can find a working relationship.</p> <h3>Udpate 2</h3> <p>Oops, I didn't realize that the scale param is a keyword. This one should now work:</p> <pre><code>import scipy.stats def LogNormDist(prob, mean=0, stddev=1): return scipy.stats.lognorm.cdf(prob,stddev,scale=scipy.exp(mean)) </code></pre> <p>Cheers and good luck with your project!</p>
3
2009-04-29T08:39:10Z
[ "c#", "python", "scipy", "nmath" ]
C# Nmath to Python SciPy
801,128
<p>I need to port some functions from C# to Python, but i can't implement next code right:</p> <pre><code>[SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)] public static SqlDouble LogNormDist(double probability, double mean, double stddev) { LognormalDistribution lnd = new LognormalDistribution(mean,stddev); return (SqlDouble)lnd.CDF(probability); } </code></pre> <p>This code uses CenterSpace Nmath library.</p> <p>Anyone can help me to write a right function in python, which will be similar to this code?</p> <p>Sorry for my English.</p> <p><strong>UPD</strong> Actually, i don't understand which scipy.stats.lognorm.cdf attrs are simillar to C# probability, mean, stddev</p> <p>If just copy existing order to python, like in answer below, i get wrong number.</p>
1
2009-04-29T06:33:05Z
801,643
<p>The Python docs describe a method random.lognormvariate(mu, sigma):</p> <p><a href="http://docs.python.org/library/random.html" rel="nofollow">http://docs.python.org/library/random.html</a></p> <p>Maybe that's what you want.</p>
2
2009-04-29T09:46:48Z
[ "c#", "python", "scipy", "nmath" ]
C# Nmath to Python SciPy
801,128
<p>I need to port some functions from C# to Python, but i can't implement next code right:</p> <pre><code>[SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)] public static SqlDouble LogNormDist(double probability, double mean, double stddev) { LognormalDistribution lnd = new LognormalDistribution(mean,stddev); return (SqlDouble)lnd.CDF(probability); } </code></pre> <p>This code uses CenterSpace Nmath library.</p> <p>Anyone can help me to write a right function in python, which will be similar to this code?</p> <p>Sorry for my English.</p> <p><strong>UPD</strong> Actually, i don't understand which scipy.stats.lognorm.cdf attrs are simillar to C# probability, mean, stddev</p> <p>If just copy existing order to python, like in answer below, i get wrong number.</p>
1
2009-04-29T06:33:05Z
19,847,809
<p>Ivan,</p> <p>We've got no interest in keeping people locked into NMath. Here's what we're doing in NMath.</p> <pre><code> double t = ( Math.Log( x ) - mu_ ) / sigmaRoot2_; return ( 0.5 + 0.5 * Erf( t ) ); </code></pre> <p>where</p> <pre><code>private static double Erf( double x ) { return ( x &lt; 0.0 ? -StatsFunctions.IncompleteGamma( 0.5, x * x ) : StatsFunctions.IncompleteGamma( 0.5, x * x ) ); } </code></pre> <p>That should help...</p> <ul> <li>Trevor</li> </ul>
0
2013-11-07T22:16:32Z
[ "c#", "python", "scipy", "nmath" ]
Django equivalent of PHP's form value array/associative array
801,354
<p>In PHP, I would do this to get <code>name</code> as an array.</p> <pre><code>&lt;input type"text" name="name[]" /&gt; &lt;input type"text" name="name[]" /&gt; </code></pre> <p>Or if I wanted to get <code>name</code> as an associative array:</p> <pre><code>&lt;input type"text" name="name[first]" /&gt; &lt;input type"text" name="name[last]" /&gt; </code></pre> <p>What is the Django equivalent for such things?</p>
42
2009-04-29T08:04:10Z
802,053
<p><a href="http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects">Check out the QueryDict documentation</a>, particularly the usage of <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.getlist"><code>QueryDict.getlist(key)</code></a>.</p> <p>Since request.POST and request.GET in the view are instances of QueryDict, you could do this:</p> <pre><code>&lt;form action='/my/path/' method='POST'&gt; &lt;input type='text' name='hi' value='heya1'&gt; &lt;input type='text' name='hi' value='heya2'&gt; &lt;input type='submit' value='Go'&gt; &lt;/form&gt; </code></pre> <p>Then something like this:</p> <pre><code>def mypath(request): if request.method == 'POST': greetings = request.POST.getlist('hi') # will be ['heya1','heya2'] </code></pre>
57
2009-04-29T12:03:36Z
[ "python", "django", "forms", "html-form" ]
Django equivalent of PHP's form value array/associative array
801,354
<p>In PHP, I would do this to get <code>name</code> as an array.</p> <pre><code>&lt;input type"text" name="name[]" /&gt; &lt;input type"text" name="name[]" /&gt; </code></pre> <p>Or if I wanted to get <code>name</code> as an associative array:</p> <pre><code>&lt;input type"text" name="name[first]" /&gt; &lt;input type"text" name="name[last]" /&gt; </code></pre> <p>What is the Django equivalent for such things?</p>
42
2009-04-29T08:04:10Z
804,798
<p>Django does not provide a way to get associative arrays (dictionaries in Python) from the request object. As the first answer pointed out, you can use <code>.getlist()</code> as needed, or write a function that can take a <code>QueryDict</code> and reorganize it to your liking (pulling out key/value pairs if the key matches some <code>key[*]</code> pattern, for example).</p>
4
2009-04-29T23:40:42Z
[ "python", "django", "forms", "html-form" ]
Django equivalent of PHP's form value array/associative array
801,354
<p>In PHP, I would do this to get <code>name</code> as an array.</p> <pre><code>&lt;input type"text" name="name[]" /&gt; &lt;input type"text" name="name[]" /&gt; </code></pre> <p>Or if I wanted to get <code>name</code> as an associative array:</p> <pre><code>&lt;input type"text" name="name[first]" /&gt; &lt;input type"text" name="name[last]" /&gt; </code></pre> <p>What is the Django equivalent for such things?</p>
42
2009-04-29T08:04:10Z
4,746,016
<p>Sorry for digging this up, but Django has an utils.datastructures.DotExpandedDict. Here's a piece of it's docs:</p> <pre><code>&gt;&gt;&gt; d = DotExpandedDict({'person.1.firstname': ['Simon'], \ 'person.1.lastname': ['Willison'], \ 'person.2.firstname': ['Adrian'], \ 'person.2.lastname': ['Holovaty']}) &gt;&gt;&gt; d {'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}} </code></pre> <p>The only difference being you use dot's instead of brackets. I think it's now conceptually replaced with prefixed forms in formsets, but the class is left in the codebase.</p>
17
2011-01-20T10:34:39Z
[ "python", "django", "forms", "html-form" ]
Updating data in google app engine
801,477
<p>I'm attempting my first google app engine project – a simple player stats database for a sports team I'm involved with. Given this model:</p> <pre><code>class Player(db.Model): """ Represents a player in the club. """ first_name = db.StringProperty() surname = db.StringProperty() gender = db.StringProperty() </code></pre> <p>I want to make a basic web interface for creating and modifying players. My code structure looks something like this:</p> <pre><code>class PlayersPage(webapp.RequestHandler): def get(self): # Get all the current players, and store the list. # We need to store the list so that we can update # if necessary in post(). self.shown_players = list(Player.all()) # omitted: html-building using django template </code></pre> <p>This code produces a very basic HTML page consisting of a form and a table. The table has one row for each Player, looking like something like this:</p> <pre><code> &lt;tr&gt; &lt;td&gt;&lt;input type=text name="first_name0" value="Test"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=text name="surname0" value="Guy"&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="gender0"&gt; &lt;option value="Male" selected&gt;Male&lt;/option&gt; &lt;option value="Female" &gt;Female&lt;/option&gt; &lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;!-- next row: first_name1, etc. --&gt; </code></pre> <p>My idea is that I would store the Player instances that I used in self.shown_players, so that I could later update Players if necessary in my <code>post()</code> method (of the same class) by doing: </p> <pre><code>def post(self): # some code skipped for i, player in enumerate(self.shown_players): fn = self.request.get('first_name'+str(i)).strip() sn = self.request.get('surname'+str(i)).strip() gd = self.request.get('gender'+str(i)).strip() if any([fn != player.first_name, sn != player.surname, gd != player.gender]): player.first_name = fn player.surname = sn player.gender = gd player.put() </code></pre> <p>However, this doesn't work because <code>self.shown_players</code> does not exist when the <code>post()</code> method is called. I guess the app engine creates a new instance of the class every time the page is accessed.</p> <p>I experimented with the same idea but putting <code>shown_players</code> at the class or module level (and calling it <code>global</code>) but this didn't work for reasons that I cannot divine. For example:</p> <pre><code>shown_players = [] class PlayersPage(webapp.RequestHandler): def get(self): # Get all the current players, and store the list. # We need to store the list so that we can update # if necessary in post(). global shown_players shown_players[:] = list(Player.all()) </code></pre> <p><code>shown_players</code> appears to have the right value within <code>get()</code> because the HTML generates correctly, but it is empty within <code>post()</code>.</p> <p>What should I do?</p> <p>EDIT: Thanks, all. The answer ("Just retrieve the players again!") should have been obvious :-) Maybe I'll look at memcache one day, but I'm not expecting the player list to get beyond 30 in the near future..</p>
0
2009-04-29T08:47:56Z
801,491
<p>On each request you are working on a new instance of the same class. That's why you can't create a varable in <code>get()</code> and use its value in <code>post()</code>. What you could do is either retrieve the values again in your <code>post()</code>-method or store the data in the <code>memcache</code>.</p> <p>Refer to the documentation of memcache here:</p> <p><a href="http://code.google.com/intl/de-DE/appengine/docs/python/memcache/" rel="nofollow">http://code.google.com/intl/de-DE/appengine/docs/python/memcache/</a></p>
2
2009-04-29T08:54:58Z
[ "python", "google-app-engine" ]
Updating data in google app engine
801,477
<p>I'm attempting my first google app engine project – a simple player stats database for a sports team I'm involved with. Given this model:</p> <pre><code>class Player(db.Model): """ Represents a player in the club. """ first_name = db.StringProperty() surname = db.StringProperty() gender = db.StringProperty() </code></pre> <p>I want to make a basic web interface for creating and modifying players. My code structure looks something like this:</p> <pre><code>class PlayersPage(webapp.RequestHandler): def get(self): # Get all the current players, and store the list. # We need to store the list so that we can update # if necessary in post(). self.shown_players = list(Player.all()) # omitted: html-building using django template </code></pre> <p>This code produces a very basic HTML page consisting of a form and a table. The table has one row for each Player, looking like something like this:</p> <pre><code> &lt;tr&gt; &lt;td&gt;&lt;input type=text name="first_name0" value="Test"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=text name="surname0" value="Guy"&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="gender0"&gt; &lt;option value="Male" selected&gt;Male&lt;/option&gt; &lt;option value="Female" &gt;Female&lt;/option&gt; &lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;!-- next row: first_name1, etc. --&gt; </code></pre> <p>My idea is that I would store the Player instances that I used in self.shown_players, so that I could later update Players if necessary in my <code>post()</code> method (of the same class) by doing: </p> <pre><code>def post(self): # some code skipped for i, player in enumerate(self.shown_players): fn = self.request.get('first_name'+str(i)).strip() sn = self.request.get('surname'+str(i)).strip() gd = self.request.get('gender'+str(i)).strip() if any([fn != player.first_name, sn != player.surname, gd != player.gender]): player.first_name = fn player.surname = sn player.gender = gd player.put() </code></pre> <p>However, this doesn't work because <code>self.shown_players</code> does not exist when the <code>post()</code> method is called. I guess the app engine creates a new instance of the class every time the page is accessed.</p> <p>I experimented with the same idea but putting <code>shown_players</code> at the class or module level (and calling it <code>global</code>) but this didn't work for reasons that I cannot divine. For example:</p> <pre><code>shown_players = [] class PlayersPage(webapp.RequestHandler): def get(self): # Get all the current players, and store the list. # We need to store the list so that we can update # if necessary in post(). global shown_players shown_players[:] = list(Player.all()) </code></pre> <p><code>shown_players</code> appears to have the right value within <code>get()</code> because the HTML generates correctly, but it is empty within <code>post()</code>.</p> <p>What should I do?</p> <p>EDIT: Thanks, all. The answer ("Just retrieve the players again!") should have been obvious :-) Maybe I'll look at memcache one day, but I'm not expecting the player list to get beyond 30 in the near future..</p>
0
2009-04-29T08:47:56Z
801,526
<p>I've never tried building a google app engine app, but I understand it's somewhat similar to Django in it's handling of databases etc.</p> <p>I don't think you should be storing things in global variables and instead should be treating each transaction seperately. The get request works because you're doing what you ought to be doing and re-requesting the information from the db.</p> <p>If you want to update a player in your post function, you probably want to pass in the details, <em>[look up players with those details again]</em>, modify them as you please. The bit in brackets is the step you're missing.</p>
1
2009-04-29T09:05:18Z
[ "python", "google-app-engine" ]
Updating data in google app engine
801,477
<p>I'm attempting my first google app engine project – a simple player stats database for a sports team I'm involved with. Given this model:</p> <pre><code>class Player(db.Model): """ Represents a player in the club. """ first_name = db.StringProperty() surname = db.StringProperty() gender = db.StringProperty() </code></pre> <p>I want to make a basic web interface for creating and modifying players. My code structure looks something like this:</p> <pre><code>class PlayersPage(webapp.RequestHandler): def get(self): # Get all the current players, and store the list. # We need to store the list so that we can update # if necessary in post(). self.shown_players = list(Player.all()) # omitted: html-building using django template </code></pre> <p>This code produces a very basic HTML page consisting of a form and a table. The table has one row for each Player, looking like something like this:</p> <pre><code> &lt;tr&gt; &lt;td&gt;&lt;input type=text name="first_name0" value="Test"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=text name="surname0" value="Guy"&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="gender0"&gt; &lt;option value="Male" selected&gt;Male&lt;/option&gt; &lt;option value="Female" &gt;Female&lt;/option&gt; &lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;!-- next row: first_name1, etc. --&gt; </code></pre> <p>My idea is that I would store the Player instances that I used in self.shown_players, so that I could later update Players if necessary in my <code>post()</code> method (of the same class) by doing: </p> <pre><code>def post(self): # some code skipped for i, player in enumerate(self.shown_players): fn = self.request.get('first_name'+str(i)).strip() sn = self.request.get('surname'+str(i)).strip() gd = self.request.get('gender'+str(i)).strip() if any([fn != player.first_name, sn != player.surname, gd != player.gender]): player.first_name = fn player.surname = sn player.gender = gd player.put() </code></pre> <p>However, this doesn't work because <code>self.shown_players</code> does not exist when the <code>post()</code> method is called. I guess the app engine creates a new instance of the class every time the page is accessed.</p> <p>I experimented with the same idea but putting <code>shown_players</code> at the class or module level (and calling it <code>global</code>) but this didn't work for reasons that I cannot divine. For example:</p> <pre><code>shown_players = [] class PlayersPage(webapp.RequestHandler): def get(self): # Get all the current players, and store the list. # We need to store the list so that we can update # if necessary in post(). global shown_players shown_players[:] = list(Player.all()) </code></pre> <p><code>shown_players</code> appears to have the right value within <code>get()</code> because the HTML generates correctly, but it is empty within <code>post()</code>.</p> <p>What should I do?</p> <p>EDIT: Thanks, all. The answer ("Just retrieve the players again!") should have been obvious :-) Maybe I'll look at memcache one day, but I'm not expecting the player list to get beyond 30 in the near future..</p>
0
2009-04-29T08:47:56Z
801,535
<p>In your post method, just before the "for" clause, retrieve the players list from where it is stored:</p> <pre><code>def post(self): # some code skipped self.shown_players = Player.all().fetch() for i, player in enumerate(self.shown_players): ... </code></pre>
2
2009-04-29T09:06:28Z
[ "python", "google-app-engine" ]
Why Python informixdb package is throwing an error!
801,515
<p>I have downloaded &amp; installed the latest Python InformixDB package, but when I try to import it from the shell, I am getting the following error in the form of a Windows dialog box!</p> <p><strong>"A procedure entry point sqli_describe_input_stmt could not be located in the dynamic link isqlit09a.dll"</strong></p> <p>Any ideas what's happening?</p> <p>Platform: Windows Vista (Biz Edition), Python 2.5.</p>
1
2009-04-29T09:01:20Z
803,958
<p>Which version of IBM Informix Connect (I-Connect) or IBM Informix ClientSDK (CSDK) are you using? The 'describe input' function is a more recent addition, but it is likely that you have it.</p> <p>Have you been able to connect to any Informix DBMS from the command shell? If not, then the suspicion must be that you don't have the correct environment. You would probably need to specify $INFORMIXDIR (or %INFORMIXDIR% - I'm going to omit '$' and '%' sigils from here on); you would need to set INFORMIXSERVER to connect successfully; you would need to have the correct directory (probably INFORMIXDIR/bin on Windows; on Unix, it would be INFORMIXDIR/lib and INFORMIXDIR/lib/esql or INFORMIXDIR/lib/odbc) on your PATH.</p>
1
2009-04-29T19:43:50Z
[ "python", "informix" ]
Why Python informixdb package is throwing an error!
801,515
<p>I have downloaded &amp; installed the latest Python InformixDB package, but when I try to import it from the shell, I am getting the following error in the form of a Windows dialog box!</p> <p><strong>"A procedure entry point sqli_describe_input_stmt could not be located in the dynamic link isqlit09a.dll"</strong></p> <p>Any ideas what's happening?</p> <p>Platform: Windows Vista (Biz Edition), Python 2.5.</p>
1
2009-04-29T09:01:20Z
823,474
<p>Does other way to connect to database work? Can you use (configure in control panel) ODBC? If ODBC works then you can use Python win32 extensions (ActiveState distribution comes with it) and there is ODBC support. You can also use Jython which can work with ODBC via JDBC-ODBC bridge or with Informix JDBC driver.</p>
0
2009-05-05T05:29:22Z
[ "python", "informix" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
801,933
<p>This link may be helpfull: <a href="http://www.djangosnippets.org/snippets/1060/" rel="nofollow">Timedelta Snippets</a></p>
2
2009-04-29T11:31:33Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
801,963
<p>You can trivially normalize a timedelta to a single floating-point number in days or seconds. </p> <p>Here's the "Normalize to Days" version.</p> <pre><code>float(timedelta.days) + float(timedelta.seconds) / float(86400) </code></pre> <p>You can trivially turn a floating-point number into a timedelta. </p> <pre><code>&gt;&gt;&gt; datetime.timedelta(2.5) datetime.timedelta(2, 43200) </code></pre> <p>So, store your timedelta as a float.</p> <p>Here's the "Normalize to Seconds" version.</p> <pre><code>timedelta.days*86400+timedelta.seconds </code></pre> <p>Here's the reverse (using seconds)</p> <pre><code>datetime.timedelta( someSeconds/86400 ) </code></pre>
27
2009-04-29T11:40:52Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
3,329,149
<p>For PostgreSQL, use django-pgsql-interval-field here: <a href="http://code.google.com/p/django-pgsql-interval-field/" rel="nofollow">http://code.google.com/p/django-pgsql-interval-field/</a></p>
3
2010-07-25T12:16:14Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
5,686,428
<p><a href="https://bitbucket.org/schinckel/django-timedelta-field/src">https://bitbucket.org/schinckel/django-timedelta-field/src</a></p>
5
2011-04-16T12:23:10Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
10,576,547
<p>First, define your model:</p> <pre><code>class TimeModel(models.Model): time = models.FloatField() </code></pre> <p>To store a timedelta object:</p> <pre><code># td is a timedelta object TimeModel.objects.create(time=td.total_seconds()) </code></pre> <p>To get the timedelta object out of the database:</p> <pre><code># Assume the previously created TimeModel object has an id of 1 td = timedelta(seconds=TimeModel.objects.get(id=1).time) </code></pre> <p><strong>Note:</strong> I'm using Python 2.7 for this example.</p>
7
2012-05-14T01:16:07Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
16,954,516
<p>There is a ticket which dates back to July 2006 relating to this: <a href="https://code.djangoproject.com/ticket/2443" rel="nofollow">https://code.djangoproject.com/ticket/2443</a></p> <p>Several patches were written but the one that was turned in to a project: <a href="https://github.com/johnpaulett/django-durationfield" rel="nofollow">https://github.com/johnpaulett/django-durationfield</a></p> <p>Compared to all the other answers here this project is mature and would have been merged to core except that its inclusion is currently considered to be "bloaty".</p> <p>Personally, I've just tried a bunch of solutions and this is the one that works beautifully.</p> <pre><code>from django.db import models from durationfield.db.models.fields.duration import DurationField class Event(models.Model): start = models.DateTimeField() duration = DurationField() @property def finish(self): return self.start + self.duration </code></pre> <p>Result:</p> <pre><code>$ evt = Event.objects.create(start=datetime.datetime.now(), duration='1 week') $ evt.finish Out[]: datetime.datetime(2013, 6, 13, 5, 29, 29, 404753) </code></pre> <p>And in admin:</p> <p><strong>Change event</strong></p> <p>Duration: <code>7 days, 0:00:00</code></p>
2
2013-06-06T05:47:58Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
28,830,179
<p>Putting this out there cause it might be another way to solve this problem. first install this library: <a href="https://pypi.python.org/pypi/django-timedeltafield" rel="nofollow">https://pypi.python.org/pypi/django-timedeltafield</a> </p> <p>Then:</p> <pre><code>import timedelta class ModelWithTimeDelta(models.Model): timedeltafield = timedelta.fields.TimedeltaField() </code></pre> <p>within the admin you will be asked to enter data into the field with the following format: 3 days, 4 hours, 2 minutes</p>
2
2015-03-03T11:03:20Z
[ "python", "django", "model" ]
How to put timedelta in django model?
801,912
<p>With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!</p> <p>Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...</p>
20
2009-04-29T11:26:47Z
29,516,197
<p>Since Django 1.8 you can use <a href="https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.DurationField">DurationField</a>.</p>
38
2015-04-08T13:35:20Z
[ "python", "django", "model" ]
Notifying container object: best practices
801,931
<p>I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well.</p> <p>I think of three alternatives on how to achieve this:</p> <p>1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references.</p> <p>2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement.</p> <p>3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.</p> <p>I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task?</p> <p>It would be great if you could point out snippets in Python.</p>
4
2009-04-29T11:31:06Z
802,031
<p>There is no "one-size-fits-all" solution for the Observer pattern. But usually, it's better to define an EventManager object where interested parties can register themselves for certain events and post these events whenever they happen. It simply creates less dependencies.</p> <p>Note that you need to use a global EventManager instance, which can be problematic during testing or from a general OO point of view (it's a global variable). I strongly advise against passing the EventManager around all the time because that will clutter your code.</p> <p>In my own code, the "key" for registering events is the class of the event. The EventManager uses a dictionary (event class -> list of observers) to know which event goes where. In the notification code, you can then use <code>dict.get(event.__class__, ())</code> to find your listeners.</p>
3
2009-04-29T12:00:25Z
[ "python", "architecture", "containers", "notifications" ]
Notifying container object: best practices
801,931
<p>I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well.</p> <p>I think of three alternatives on how to achieve this:</p> <p>1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references.</p> <p>2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement.</p> <p>3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.</p> <p>I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task?</p> <p>It would be great if you could point out snippets in Python.</p>
4
2009-04-29T11:31:06Z
802,083
<p>I would use event handling for this. You don't have to implement it yourself -- I use <a href="http://pydispatcher.sourceforge.net/" rel="nofollow">pydispatcher</a> for exactly this kind of event handling, and it's always worked very well (it uses weak references internally, to avoid the circular reference problem). </p> <p>Also, if you're using a gui framework, you might already have an event framework you can hook into, for example <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a> has signals and slots. </p>
3
2009-04-29T12:14:12Z
[ "python", "architecture", "containers", "notifications" ]
Notifying container object: best practices
801,931
<p>I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well.</p> <p>I think of three alternatives on how to achieve this:</p> <p>1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references.</p> <p>2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement.</p> <p>3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.</p> <p>I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task?</p> <p>It would be great if you could point out snippets in Python.</p>
4
2009-04-29T11:31:06Z
802,084
<p>You're over-thinking this. Seriously. Python isn't C++; your concerns are non-issues in Python. Just write what makes sense in your problem domain.</p> <p>" Not absolutely good because of circular references."</p> <p>Why not? Circularity is of no relevance here at all. Bidirectional relationships are great things. Use them. Python garbage collects them just fine without any thinking on your part.</p> <p>What possible problem do you have with mutual (birectional) relationships?</p> <p>"...operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators. "</p> <p>What? Your Operators are Python objects, pass all you want. All Python objects are (in effect) references, don't sweat it. </p> <p>What possible problem do you have with manipulating Operator objects?</p>
5
2009-04-29T12:15:23Z
[ "python", "architecture", "containers", "notifications" ]
Notifying container object: best practices
801,931
<p>I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well.</p> <p>I think of three alternatives on how to achieve this:</p> <p>1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references.</p> <p>2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement.</p> <p>3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.</p> <p>I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task?</p> <p>It would be great if you could point out snippets in Python.</p>
4
2009-04-29T11:31:06Z
802,088
<pre><code>&gt;&gt;&gt; class Account(object): ... def notify(self): ... print "Account notified" ... &gt;&gt;&gt; class Operator(object): ... def __init__(self, notifier): ... self.notifier = notifier ... &gt;&gt;&gt; A = Account() &gt;&gt;&gt; O = Operator(A.notify) &gt;&gt;&gt; O.notifier() Account notified &gt;&gt;&gt; import gc &gt;&gt;&gt; gc.garbage [] &gt;&gt;&gt; del A &gt;&gt;&gt; del O &gt;&gt;&gt; gc.garbage [] </code></pre> <p>One thing you may not know about instance methods is that they're bound when looked up when using the dot syntax. In other words saying <code>A.notify</code> automatically binds the self parameter of notify to A. You can then hold a reference to this function without creating uncollectable garbage.</p> <p>Lastly, you can always use <a href="http://www.kamaelia.org/Home" rel="nofollow">Kamaelia</a> for this type of thing.</p>
3
2009-04-29T12:15:39Z
[ "python", "architecture", "containers", "notifications" ]
Notifying container object: best practices
801,931
<p>I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well.</p> <p>I think of three alternatives on how to achieve this:</p> <p>1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references.</p> <p>2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement.</p> <p>3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.</p> <p>I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task?</p> <p>It would be great if you could point out snippets in Python.</p>
4
2009-04-29T11:31:06Z
802,261
<p>There are Observer pattern snippets all over the Web. A good source of reliable code is active state, E.G :</p> <p><a href="http://code.activestate.com/recipes/131499/" rel="nofollow">http://code.activestate.com/recipes/131499/</a></p>
0
2009-04-29T13:00:07Z
[ "python", "architecture", "containers", "notifications" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
802,146
<p><a href="http://www.diveintopython.net/http_web_services/user_agent.html">Setting the User-Agent</a> from everyone's favorite <a href="http://diveintopython.net/">Dive Into Python</a>.</p> <p>The short story: You can use <a href="http://docs.python.org/library/urllib2.html#urllib2.Request.add_header">Request.add_header</a> to do this.</p> <p>You can also pass the headers as a dictionary when creating the Request itself, <a href="http://docs.python.org/library/urllib2.html#urllib2.Request">as the docs note</a>:</p> <blockquote> <p><em>headers</em> should be a dictionary, and will be treated as if <code>add_header()</code> was called with each key and value as arguments. This is often used to “spoof” the <code>User-Agent</code> header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as <code>"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"</code>, while <code>urllib2</code>‘s default user agent string is <code>"Python-urllib/2.6"</code> (on Python 2.6).</p> </blockquote>
50
2009-04-29T12:34:30Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
802,246
<p>I <a href="http://stackoverflow.com/a/762007/3790126">answered</a> a <a href="http://stackoverflow.com/questions/761978/send-headers-along-in-python">similar question</a> a couple weeks ago.</p> <p>There is example code in that question, but basically you can do something like this: (Note the capitalization of <code>User-Agent</code> as of <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="nofollow">RFC 2616</a>, section 14.43.)</p> <pre><code>opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'Mozilla/5.0')] response = opener.open('http://www.stackoverflow.com') </code></pre>
89
2009-04-29T12:56:46Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
5,196,160
<pre><code>headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request('www.example.com', None, headers) html = urllib2.urlopen(req).read() </code></pre> <p>Or, a bit shorter:</p> <pre><code>req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' }) html = urllib2.urlopen(req).read() </code></pre>
72
2011-03-04T15:58:58Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
8,994,498
<p>All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header. If you don't try to send a User-agent header, it sends the default Python / urllib2 </p> <p>None of these methods seem to work for adding User-agent but they work for other headers:</p> <pre><code>opener = urllib2.build_opener(proxy) opener.addheaders = {'User-agent':'Custom user agent'} urllib2.install_opener(opener) request = urllib2.Request(url, headers={'User-agent':'Custom user agent'}) request.headers['User-agent'] = 'Custom user agent' request.add_header('User-agent', 'Custom user agent') </code></pre>
8
2012-01-24T21:32:26Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
10,468,884
<p>For python 3, urllib is split into 3 modules...</p> <pre><code>import urllib.request req = urllib.request.Request(url="http://localhost/",data=b'None',headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'}) handler = urllib.request.urlopen(req) </code></pre>
8
2012-05-06T07:19:05Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
14,324,710
<p>Another solution in <code>urllib2</code> and Python 2.7:</p> <pre><code>req = urllib2.Request('http://www.example.com/') req.add_unredirected_header('User-Agent', 'Custom User-Agent') urllib2.urlopen(req) </code></pre>
5
2013-01-14T18:54:25Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
29,161,951
<p>For urllib you can use:</p> <pre><code>from urllib import FancyURLopener class MyOpener(FancyURLopener, object): version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' myopener = MyOpener() myopener.retrieve('https://www.google.com/search?q=test', 'useragent.html') </code></pre>
2
2015-03-20T08:01:49Z
[ "python", "urllib2", "user-agent" ]
Changing user agent on urllib2.urlopen
802,134
<p>How can I download a webpage with a user agent other than the default one on urllib2.urlopen?</p>
75
2009-04-29T12:32:36Z
31,693,953
<p>Try this :</p> <pre><code>html_source_code = requests.get("http://www.example.com/", headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36','Upgrade-Insecure-Requests': '1','x-runtime': '148ms'}, allow_redirects=True).content </code></pre>
1
2015-07-29T07:30:42Z
[ "python", "urllib2", "user-agent" ]
Face-tracking libraries for Java or Python
802,243
<p>I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. </p> <p>We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll have a reasonably fast camera for the project, so I can probably use some logic for seeing if "face1 in frame00 == face1 in frame01".</p> <p>Ideally such a software would return a list of faces (as in x,y locations) and their sizes.</p>
8
2009-04-29T12:55:12Z
802,278
<p>"faint" (The Face Annotation Interface) might be what you're looking for.</p> <p><a href="http://faint.sourceforge.net/" rel="nofollow">http://faint.sourceforge.net/</a></p> <p><a href="http://technoroy.blogspot.com/2008/06/faint-search-for-faces.html" rel="nofollow">http://technoroy.blogspot.com/2008/06/faint-search-for-faces.html</a></p> <p>I never used it myself. However, I played with the application which bundles with faint.</p>
2
2009-04-29T13:04:58Z
[ "java", "python", "face-detection" ]
Face-tracking libraries for Java or Python
802,243
<p>I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. </p> <p>We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll have a reasonably fast camera for the project, so I can probably use some logic for seeing if "face1 in frame00 == face1 in frame01".</p> <p>Ideally such a software would return a list of faces (as in x,y locations) and their sizes.</p>
8
2009-04-29T12:55:12Z
802,289
<p>There was an <a href="http://www.linux-magazin.de/heft%5Fabo/ausgaben/2008/02/ins%5Fgesicht%5Fgeblickt" rel="nofollow">article about this</a> in the German "Linux Magazin".</p> <p>They used the <a href="http://sourceforge.net/projects/opencvlibrary/" rel="nofollow">Open Computer Vision Library</a> which offers a whole bunch of algorithms to process images in various ways.</p>
2
2009-04-29T13:07:05Z
[ "java", "python", "face-detection" ]
Face-tracking libraries for Java or Python
802,243
<p>I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. </p> <p>We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll have a reasonably fast camera for the project, so I can probably use some logic for seeing if "face1 in frame00 == face1 in frame01".</p> <p>Ideally such a software would return a list of faces (as in x,y locations) and their sizes.</p>
8
2009-04-29T12:55:12Z
802,381
<p>Checkout <a href="http://opencv.willowgarage.com/wiki/PythonInterface" rel="nofollow">OpenCV Python Interface</a></p>
7
2009-04-29T13:32:51Z
[ "java", "python", "face-detection" ]
Face-tracking libraries for Java or Python
802,243
<p>I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. </p> <p>We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll have a reasonably fast camera for the project, so I can probably use some logic for seeing if "face1 in frame00 == face1 in frame01".</p> <p>Ideally such a software would return a list of faces (as in x,y locations) and their sizes.</p>
8
2009-04-29T12:55:12Z
2,272,905
<p><a href="http://www.codeproject.com/info/search.aspx?artkw=face+recognition" rel="nofollow">CodeProject has a whole raft of articles in various languages.</a></p>
0
2010-02-16T12:44:44Z
[ "java", "python", "face-detection" ]
How can I enumerate/list all installed applications in Windows XP?
802,499
<p>When I say "installed application", I basically mean any application visible in [Control Panel]->[Add/Remove Programs]. </p> <p>I would prefer to do it in Python, but C or C++ is also fine.</p>
6
2009-04-29T14:02:12Z
802,510
<p>Check out the <a href="http://msdn.microsoft.com/en-us/library/aa394378%28VS.85%29.aspx">Win32_Product</a> WMI (Windows Management Instrumentation) class. <a href="http://timgolden.me.uk/python/wmi.html">Here's a tutorial</a> on using WMI in Python.</p>
10
2009-04-29T14:05:59Z
[ "c++", "python", "winapi", "enumeration" ]