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
sequence |
---|---|---|---|---|---|---|---|---|---|
Applying a common font scheme to multiple objects in wxPython | 171,694 | <p>Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a <strong>SetFont()</strong> call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and <em>wxPython In Action</em> book don't discuss this.</p>
<p>Is there a way to easily apply the same SetFont() method to all these text objects without making separate calls each time?</p>
| 3 | 2008-10-05T08:27:57Z | 184,571 | <p>You can do this by calling SetFont on the parent window (Frame, Dialog, etc) before adding any widgets. The child widgets will inherit the font.</p>
| 5 | 2008-10-08T19:55:40Z | [
"python",
"fonts",
"wxpython"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 171,779 | <p>To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do <code>n / i</code>, and this will cover the whole problem space.</p>
<p>As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.</p>
<p>Python code:</p>
<pre><code>import math
def divisorGenerator(n):
large_divisors = []
for i in xrange(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
print list(divisorGenerator(100))
</code></pre>
<p>Which should output a list like:</p>
<pre>
[1, 2, 4, 5, 10, 20, 25, 50, 100]
</pre>
| 19 | 2008-10-05T10:03:51Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 171,784 | <p>Given your factorGenerator function, here is a divisorGen that should work:</p>
<pre><code>def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
while True:
f[i] += 1
if f[i] <= factors[i][1]:
break
f[i] = 0
i += 1
if i >= nfactors:
return
</code></pre>
<p>The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator.</p>
| 62 | 2008-10-05T10:09:20Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 371,129 | <p>I like Greg solution, but I wish it was more python like.
I feel it would be faster and more readable;
so after some time of coding I came out with this.</p>
<p>The first two functions are needed to make the cartesian product of lists.
And can be reused whnever this problem arises.
By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.</p>
<p>"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime.
Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor.
We sort them, and return them.</p>
<p>I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.</p>
<p>Pietro Speroni (pietrosperoni dot it)</p>
<pre><code>from math import sqrt
##############################################################
### cartesian product of lists ##################################
##############################################################
def appendEs2Sequences(sequences,es):
result=[]
if not sequences:
for e in es:
result.append([e])
else:
for e in es:
result+=[seq+[e] for seq in sequences]
return result
def cartesianproduct(lists):
"""
given a list of lists,
returns all the possible combinations taking one element from each list
The list does not have to be of equal length
"""
return reduce(appendEs2Sequences,lists,[])
##############################################################
### prime factors of a natural ##################################
##############################################################
def primefactors(n):
'''lists prime factors, from greatest to smallest'''
i = 2
while i<=sqrt(n):
if n%i==0:
l = primefactors(n/i)
l.append(i)
return l
i+=1
return [n] # n is prime
##############################################################
### factorization of a natural ##################################
##############################################################
def factorGenerator(n):
p = primefactors(n)
factors={}
for p1 in p:
try:
factors[p1]+=1
except KeyError:
factors[p1]=1
return factors
def divisors(n):
factors = factorGenerator(n)
divisors=[]
listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
listfactors=cartesianproduct(listexponents)
for f in listfactors:
divisors.append(reduce(lambda x, y: x*y, f, 1))
divisors.sort()
return divisors
print divisors(60668796879)
</code></pre>
<p>P.S.
it is the first time I am posting to stackoverflow.
I am looking forward for any feedback.</p>
| 5 | 2008-12-16T12:17:12Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 15,025,068 | <p>Adapted from <a href="http://codereview.stackexchange.com/a/23015/8431">CodeReview</a>, here is a variant which works with <code>num=1</code> !</p>
<pre><code>from itertools import product
import operator
def prod(ls):
return reduce(operator.mul, ls, 1)
def powered(factors, powers):
return prod(f**p for (f,p) in zip(factors, powers))
def divisors(num) :
pf = dict(prime_factors(num))
primes = pf.keys()
#For each prime, possible exponents
exponents = [range(i+1) for i in pf.values()]
return (powered(primes,es) for es in product(*exponents))
</code></pre>
| 2 | 2013-02-22T13:11:56Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 18,366,032 | <p>Assuming that the <code>factors</code> function returns the factors of <em>n</em> (for instance, <code>factors(60)</code> returns the list [2, 2, 3, 5]), here is a function to compute the divisors of <em>n</em>:</p>
<pre><code>function divisors(n)
divs := [1]
for fact in factors(n)
temp := []
for div in divs
if fact * div not in divs
append fact * div to temp
divs := divs + temp
return divs
</code></pre>
| 0 | 2013-08-21T19:29:02Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 23,983,542 | <pre><code>return [x for x in range(n+1) if n/x==int(n/x)]
</code></pre>
| -1 | 2014-06-01T19:20:42Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 25,813,885 | <p>For me this works fine and is also clean (Python 3)</p>
<pre><code>def divisors(number):
n = 1
while(n<number):
if(number%n==0):
print(n)
else:
pass
n += 1
print(number)
</code></pre>
<p>Not very fast but returns divisors line by line as you wanted, also you can do list.append(n) and list.append(number) if you really want to</p>
| -1 | 2014-09-12T17:42:43Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 31,340,346 | <p>Here's my solution. It seems to be dumb but works well...and I was trying to find all proper divisors so the loop started from i = 2. </p>
<pre><code>import math as m
def findfac(n):
faclist = [1]
for i in range(2, int(m.sqrt(n) + 2)):
if n%i == 0:
if i not in faclist:
faclist.append(i)
if n/i not in faclist:
faclist.append(n/i)
return facts
</code></pre>
| 0 | 2015-07-10T12:05:26Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 36,070,582 | <p>Old question, but here is my take:</p>
<pre><code>def divs(n, m):
if m == 1: return [1]
if n % m == 0: return [m] + divs(n, m - 1)
return divs(n, m - 1)
</code></pre>
<p>You can proxy with:</p>
<pre><code>def divisorGenerator(n):
for x in reversed(divs(n, n)):
yield x
</code></pre>
<p>NOTE: For languages that support, this could be tail recursive.</p>
| 0 | 2016-03-17T20:01:32Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 36,700,288 | <p>I think you can stop at <code>math.sqrt(n)</code> instead of n/2. </p>
<p>I will give you example so that you can understand it easily. Now the <code>sqrt(28)</code> is <code>5.29</code> so <code>ceil(5.29)</code> will be 6. So I if I will stop at 6 then I will can get all the divisors. How?</p>
<p>First see the code and then see image:</p>
<pre><code>def divisors(n):
divs = [1]
for i in xrange(2,int(math.sqrt(n))+1):
if n%i == 0:
divs.extend([i,n/i])
return list(set(divs))
</code></pre>
<p>Now, See the image below:</p>
<p>Lets say I have already added <code>1</code> to my divisors list and I start with <code>i=2</code> so</p>
<p><a href="http://i.stack.imgur.com/jsBas.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/jsBas.jpg" alt="Divisors of a 28"></a></p>
<p>So at the end of all the iterations as I have added the quotient and the divisor to my list all the divisors of 28 are populated. </p>
<p>Hope this helps. If you have any doubt don't hesitate to ping back and I will be glad to help you :).</p>
<p>Source: <a href="http://www.wikihow.com/Determine-the-Number-of-Divisors-of-an-Integer" rel="nofollow">How to determine the divisors of a number</a><br />
<a href="http://radiusofcircle.blogspot.in/2016/04/problem-21-project-euler-solution-with-python.html" rel="nofollow">Radius of circle</a> - Both code and image</p>
| 0 | 2016-04-18T17:13:37Z | [
"python",
"algorithm",
"math"
] |
What is the best way to get all the divisors of a number? | 171,765 | <p>Here's the very dumb way:</p>
<pre><code>def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
</code></pre>
<p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p>
<p>I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:</p>
<p>(factor1, multiplicity1)<br />
(factor2, multiplicity2)<br />
(factor3, multiplicity3)<br />
and so on...</p>
<p>i.e. the output of </p>
<pre><code>for i in factorGenerator(100):
print i
</code></pre>
<p>is:</p>
<pre><code>(2, 2)
(5, 2)
</code></pre>
<p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p>
<pre><code>for i in divisorGen(100):
print i
</code></pre>
<p>output this:</p>
<pre><code>1
2
4
5
10
20
25
50
100
</code></pre>
<p><hr /></p>
<p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p>
<p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
| 62 | 2008-10-05T09:48:58Z | 37,058,745 | <p>Although there are already many solutions to this, I really have to post this :)</p>
<p>This one is:</p>
<ul>
<li>readable </li>
<li>short</li>
<li>self contained, copy & paste ready</li>
<li>quick (in cases with a lot of prime factors and divisors, > 10 times faster than Greg's solution)</li>
<li>python3, python2 and pypy compliant</li>
</ul>
<p>Code:</p>
<pre><code>def divisors(n):
# get factors and their counts
factors = {}
nn = n
i = 2
while i*i <= nn:
while nn % i == 0:
if not i in factors:
factors[i] = 0
factors[i] += 1
nn //= i
i += 1
if nn > 1:
factors[nn] = 1
primes = list(factors.keys())
# generates factors from primes[k:] subset
def generate(k):
if k == len(primes):
yield 1
else:
rest = generate(k+1)
prime = primes[k]
for factor in rest:
prime_to_i = 1
# prime_to_i iterates prime**i values, i being all possible exponents
for _ in range(factors[prime] + 1):
yield factor * prime_to_i
prime_to_i *= prime
# in python3, `yield from generate(0)` would also work
for factor in generate(0):
yield factor
</code></pre>
| 5 | 2016-05-05T19:25:54Z | [
"python",
"algorithm",
"math"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 172,053 | <p>I'm also looking into this. I too am working on a Django project that might utilize Open Id. For references, check out:</p>
<ul>
<li><a href="http://siege.org/projects/phpMyID/" rel="nofollow">PHPMyId</a></li>
<li><a href="http://openid.net/get/" rel="nofollow">OpenId's page</a></li>
</ul>
<p>Hopefully someone here has tackled this issue.</p>
| 3 | 2008-10-05T14:20:57Z | [
"python",
"django",
"openid"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 172,058 | <p>I'm using <a href="http://siege.org/projects/phpMyID/" rel="nofollow">phpMyID</a> to authenticate at StackOverflow right now. Generates a standard HTTP auth realm and works perfectly. It should be exactly what you need.</p>
| 3 | 2008-10-05T14:22:37Z | [
"python",
"django",
"openid"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 172,086 | <p>Why not run an OpenID provider from your local machine?</p>
<p>If you are a .Net developer there is an OpenID provider library for .Net at <a href="http://code.google.com/p/dotnetopenid/" rel="nofollow">Google Code</a>. This uses the standard .Net profile provider mechanism and wraps it with an OpenID layer. We are using it to add OpenID to our custom authentication engine.</p>
<p>If you are working in another language/platform there are a number of OpenID implementation avalaiable from the OpenID community site <a href="http://wiki.openid.net/Libraries" rel="nofollow">here</a>.</p>
| 1 | 2008-10-05T14:48:18Z | [
"python",
"django",
"openid"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 172,137 | <p>You could probably use the django OpenID library to write a provider to test against. Have one that always authenticates and one that always fails.</p>
| 3 | 2008-10-05T15:24:31Z | [
"python",
"django",
"openid"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 172,145 | <p>I have no problems testing with <a href="http://myopenid.com" rel="nofollow">myopenid.com</a>. I thought there would be a problem testing on my local machine but it just worked. (I'm using ASP.NET with DotNetOpenId library).</p>
<p>The 'realm' and return url must contain the port number like '<a href="http://localhost:93359" rel="nofollow">http://localhost:93359</a>'.</p>
<p>I assume it works OK because the provider does a client side redirect.</p>
| 9 | 2008-10-05T15:29:43Z | [
"python",
"django",
"openid"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 172,244 | <p>You shouldn't be having trouble developing against your own machine. What error are you getting?</p>
<p>An OpenID provider will ask you to give your site (in this case <a href="http://localhost:8000" rel="nofollow">http://localhost:8000</a> or similar) access to your identity. If you click ok then it will redirect you that url. I've never had problems with <a href="http://www.livejournal.com" rel="nofollow">livejournal</a> and I expect that <a href="http://myopenid.com" rel="nofollow">myopenid.com</a> will work too.</p>
<p>If you're having problems developing locally I suggest that the problem you're having is unrelated to the url being localhost, but something else. Without an error message or problem description it's impossible to say more.</p>
<p><strong>Edit</strong>: It turns out that Yahoo do things differently to other OpenID providers that I've come across and disallow redirections to ip address, sites without a correct tld in their domain name and those that run on ports other than 80 or 443. See <a href="http://openid.net/pipermail/general/2008-January/004024.html" rel="nofollow">here</a> for a post from a Yahoo developer on this subject. <a href="http://openid.net/pipermail/general/2008-January/004023.html" rel="nofollow">This post</a> offers a work around, but I would suggest that for development myopenid.com would be far simpler than working around Yahoo, or running your own provider.</p>
| 1 | 2008-10-05T16:40:16Z | [
"python",
"django",
"openid"
] |
How do you develop against OpenID locally | 172,040 | <p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p>
<p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
| 34 | 2008-10-05T14:08:42Z | 175,273 | <p>The libraries at <a href="http://openidenabled.com/" rel="nofollow">OpenID Enabled</a> ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of <a href="http://openidenabled.com/python-openid/trunk/examples/server/" rel="nofollow">this test provider</a>.</p>
| 13 | 2008-10-06T17:22:39Z | [
"python",
"django",
"openid"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 172,097 | <p>A <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users">user profile</a> (as returned by <code>django.contrib.auth.models.User.get_profile</code>) doesn't extend the User table - the model you specify as the profile model with the <code>AUTH_PROFILE_MODULE</code> setting is just a model which has a <code>ForeignKey</code> to <code>User</code>. <code>get_profile</code> and the setting are really just a convenience API for accessing an instance of a specific model which has a <code>ForeignKey</code> to a specific <code>User</code> instance.</p>
<p>As such, one option is to create a profile model in which the <code>ForeignKey</code> to <code>User</code> can be <code>null</code> and associate your <code>Photo</code> model with this profile model instead of the <code>User</code> model. This would allow you to create a profile for a non-existent user and attach a registered User to the profile at a later date.</p>
| 7 | 2008-10-05T14:53:46Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 172,099 | <p>From the documentation on <a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="nofollow">django auth</a>, if you want to use the User model, it's mandatory to have a username and password, there are no "anonymous accounts". I guess you could create accounts with a default password and then give the opportunity for people to enable a "real" account (by setting a password themselves).</p>
<p>To set up a "People" table that ties to the User table you just have to use a ForeignKey field (that's actually the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">recommended way</a> of adding additional info to the User model, and not inheritance)</p>
| 0 | 2008-10-05T14:56:24Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 172,464 | <p>Users that can't login? Just given them a totally random password.</p>
<pre><code>import random
user.set_password( str(random.random()) )
</code></pre>
<p>They'll never be able to log on.</p>
| 2 | 2008-10-05T18:57:26Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 176,472 | <p>Using a <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">model with a ForeignKey field linking to User</a> might not work as you want because you need anonymous access. I'm not sure if that's going to work, but you might try what happens if you let it have a ForeignKey to <a href="http://docs.djangoproject.com/en/dev/topics/auth/#anonymous-users" rel="nofollow">AnonymousUser</a> (whose id is always None!) instead.</p>
<p>If you try it, post your results here, I'd be curious.</p>
| 0 | 2008-10-06T22:31:06Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 176,825 | <p>Supply your own authentication routine, then you can check (or not check) anything you like. We do this so if they fail on normal username, we can also let them in on email/password (although that's not what I'm showing below).</p>
<p>in settings.py:</p>
<pre><code>AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'userprofile.my_authenticate.MyLoginBackend', # if they fail the normal test
)
</code></pre>
<p>in userprofile/my_authenticate.py:</p>
<pre><code>from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class MyLoginBackend(ModelBackend):
"""Return User record if username + (some test) is valid.
Return None if no match.
"""
def authenticate(self, username=None, password=None, request=None):
try:
user = User.objects.get(username=username)
# plus any other test of User/UserProfile, etc.
return user # indicates success
except User.DoesNotExist:
return None
# authenticate
# class MyLoginBackend
</code></pre>
| 3 | 2008-10-07T00:40:41Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 177,742 | <p>The django.contrib.auth.models.User exists solely for the purpose of using default authentication backend (database-based). If you write your own backend, you can make some accounts passwordless, while keeping <em>normal</em> accounts with passwords. Django documentation has a <a href="http://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources" rel="nofollow">chapter on this</a>.</p>
| 0 | 2008-10-07T09:23:25Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
Django UserProfile... without a password | 172,066 | <p>I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.</p>
<p>So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.</p>
| 1 | 2008-10-05T14:29:56Z | 180,657 | <p>Another upvote for <a href="http://stackoverflow.com/questions/172066/django-userprofile-without-a-password#172097">insin's answer</a>: handle this through a <code>UserProfile</code>. <a href="http://djangopeople.net/ubernostrum/" rel="nofollow">James Bennett</a> has a <a href="http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/" rel="nofollow">great article</a> about extending <code>django.contrib.auth.models.User</code>. He walks through a couple methods, explains their pros/cons and lands on the <code>UserProfile</code> way as ideal.</p>
| 0 | 2008-10-07T22:09:42Z | [
"python",
"database",
"django",
"django-authentication",
"django-users"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 172,313 | <p>Speaking as a library author:</p>
<p>I'm waiting for the final version to be released. My belief, like that of most of the Python community, is that 2.x will continue to be the dominant version for a period of weeks or months. That's plenty of time to release a nice, polished 3.x release.</p>
<p>I'll be maintaining separate 2.x and 3.x branches. 2.x will be backwards compatible to 2.4, so I can't use a lot of the fancy syntax or new features in 2.6 / 3.0. In contrast, the 3.x branch will use every one of those features that results in a nicer experience for the user. The test suite will be modified so that 2to3 will work upon it, and I'll maintain the same tests for both branches.</p>
| 3 | 2008-10-05T17:14:15Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 172,350 | <p>The main idea of 2.6 is to provide a migration path to 3.0. So you can use <code>from __future__ import X</code> slowly migrating one feature at a time until you get all of them nailed down and can move to 3.0. Many of the 3.0 features will flow into 2.6 as well, so you can make the language gap smaller gradually rather than having to migrate everything in one go.</p>
<p>At work, we plan to upgrade from 2.5 to 2.6 first. Then we begin enabling 3.0 features slowly one module at a time. At some point a whole subpart of the system will probably be ready for 3.x.</p>
<p>The only problem are libraries. If a library is never migrated, we are stuck with the old library. But I am pretty confident that we'll get a fine alternative in due time for that part.</p>
| 5 | 2008-10-05T17:50:42Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 174,305 | <p>Some of my more complex 2.x code is going to stay at 2.5 or 2.6.
I am moving onto 3.0 for all new development once some of the 3rd party libraries I use often have been updated for 3.</p>
| 0 | 2008-10-06T13:32:52Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 214,601 | <p>Here's the general plan for Twisted. I was originally going to blog this, but then I thought: why blog about it when I could get <em>points</em> for it?</p>
<ol>
<li><p><strong>Wait until somebody cares.</strong></p>
<p>Right now, nobody has Python 3. We're not going to spend a bunch of effort until at least one actual user has come forth and said "I need Python 3.0 support", and has a good reason for it aside from the fact that 3.0 looks shiny.</p></li>
<li><p><strong>Wait until our dependencies have migrated.</strong></p>
<p>A large system like Twisted has a number of dependencies. For starters, ours include:</p>
<ul>
<li><a href="http://www.zope.org/Products/%5AopeInterface">Zope Interface</a></li>
<li><a href="http://www.dlitz.net/software/pycrypto/">PyCrypto</a></li>
<li><a href="https://launchpad.net/pyopenssl/">PyOpenSSL</a></li>
<li><a href="http://sourceforge.net/projects/pywin32/">pywin32</a></li>
<li><a href="http://www.pygtk.org/">PyGTK</a> (though this dependency is sadly very light right now, by the time migration rolls around, I hope Twisted will have more GUI tools)</li>
<li><a href="http://pyasn1.sourceforge.net/">pyasn1</a></li>
<li><a href="http://www.pangalactic.org/PyPAM/">PyPAM</a></li>
<li><a href="http://gmpy.sourceforge.net/">gmpy</a></li>
</ul>
<p>Some of these projects have their own array of dependencies so we'll have to wait for those as well.</p></li>
<li><p><strong>Wait until somebody cares enough <em>to help</em>.</strong></p>
<p>There are, charitably, 5 people who work on Twisted - and I say "charitably" because that's counting me, and I haven't committed in months. We have <a href="http://twistedmatrix.com/trac/report/1">over 1000 open tickets</a> right now, and it would be nice to actually fix some of those â fix bugs, add features, and generally make Twisted a better product in its own right â before spending time on getting it ported over to a substantially new version of the language.</p>
<p>This potentially includes <a href="http://twistedmatrix.com/trac/wiki/TwistedSoftwareFoundation">sponsors</a> caring enough to pay for us to do it, but I hope that there will be an influx of volunteers who care about 3.0 support and want to help move the community forward.</p></li>
<li><p><strong>Follow Guido's advice.</strong></p>
<p>This means <strong><em><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=227041">we will not change our API incompatibly</a></em></strong>, and we will follow the <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208549">transitional development guidelines</a> that Guido posted last year. That starts with having unit tests, and running <a href="http://docs.python.org/library/2to3.html">the 2to3 conversion tool</a> over the Twisted codebase.</p></li>
<li><p><strong>Report bugs against, and file patches for, the 2to3 tool</strong>.</p>
<p>When we get to the point where we're actually using it, I anticipate that there will be a lot of problems with running <code>2to3</code> in the future. Running it over Twisted right now takes an extremely long time and (last I checked, which was quite a while ago) can't parse a few of the files in the Twisted repository, so the resulting output won't import. I think there will have to be a fair amount of success stories from small projects and a lot of hammering on the tool before it will actually work for us.</p>
<p>However, the Python development team has been very helpful in responding to our bug reports, and early responses to these problems have been encouraging, so I expect that all of these issues will be fixed in time.</p></li>
<li><p><strong>Maintain 2.x compatibility for several years.</strong></p>
<p>Right now, Twisted supports python 2.3 to 2.5. Currently, we're working on 2.6 support (which we'll obviously have to finish before 3.0!). Our plan is to we revise our supported versions of Python based on the long-term supported versions of <a href="http://en.wikipedia.org/wiki/Ubuntu">Ubuntu</a> - release 8.04, which includes Python 2.5, will be supported until 2013. According to Guido's advice we will need to drop support for 2.5 in order to support 3.0, but I am hoping we can find a way around that (we are pretty creative with version-compatibility hacks).</p>
<p>So, we are planning to support Python 2.5 until at least 2013. In two years, Ubuntu will release another long-term supported version of Ubuntu: if they still exist, and stay on schedule, that will be 10.04. Personally I am guessing that this will ship with Python 2.x, perhaps python 2.8, as <code>/usr/bin/python</code>, because there is a huge amount of Python software packaged with the distribution and it will take a long time to update it all. So, five years from <em>then</em>, in 2015, we can start looking at dropping 2.x support.</p>
<p>During this period, we will continue to follow Guido's advice about migration: running 2to3 over our 2.x codebase, and modifying the 2.x codebase to keep its tests passing in both versions.</p>
<p>The upshot of this is that Python 3.x will not be a <em>source</em> language for Twisted until well after my 35th birthday â it will be a target runtime (and a set of guidelines and restrictions) for my python 2.x code. I expect to be writing programs in Python 2.x for the next ten years or so.</p></li>
</ol>
<p>So, that's the plan. I'm hoping that it ends up looking laughably conservative in a year or so; that the 3.x transition is easy as pie, and everyone rapidly upgrades. Other things could happen, too: the 2.x and 3.x branches could converge, someone might end up writing a <code>3to2</code>, or another runtime (PyPy comes to mind) might allow for running 2.x and 3.x code in the same process directly, making our conversion process easier.</p>
<p>For the time being, however, we're assuming that, for many years, we will have people with large codebases they're maintaining (or people writing new code who want to use <em>other</em> libraries which have not yet been migrated) who still want new features and bug fixes in Twisted. Pretty soon I expect we will also have bleeding-edge users that want to use Twisted on python 3. I'd like to provide all of those people with a positive experience for as long as possible.</p>
| 88 | 2008-10-18T04:59:57Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 2,977,934 | <h2><strong>Support both</strong></h2>
<p>I wanted to make an attempt at converting the BeautifulSoup library to 3x for a project I'm working on but I can see how it would be a pain to maintain two different branches of the code.</p>
<p>The current model to handle this include:</p>
<ol>
<li>make a change to the 2x branch</li>
<li>run 2to3</li>
<li>pray that it does the conversion properly the first time</li>
<li>run the code</li>
<li>run unit tests to verify that everything works</li>
<li>copy the output to the 3x branch</li>
</ol>
<p>This model works but IMHO it sucks. For every change/release you have to go through these steps ::sigh::. Plus, it discourages developers from extending the 3x branch with new features that can only be supported in py3k because you're still essentially targeting all the code to 2x.</p>
<p><strong>The solution... use a preprocessor</strong></p>
<p>Since I couldn't find a decent c-style preprocessor with #define and #ifdef directives for python I wrote one. </p>
<p>It's called <a href="http://pypi.python.org/pypi?%3aaction=search&term=pypreprocessor&submit=search" rel="nofollow">pypreprocessor and can be found in the PYPI</a></p>
<p>Essentially, what you do is:</p>
<ol>
<li>import pypreprocessor</li>
<li>detect which version of python the script is running in</li>
<li>set a 'define' in the preprocessor for the version (ex 'python2' or 'python3')</li>
<li>sprinkle '#ifdef python2' and '#ifdef python3' directives where the code is version specific</li>
<li>run the code</li>
</ol>
<p>That's it. Now it'll work in both 2x and 3x. If you are worried about added performance hit of running a preprocessor there's also a mode that will strip out all of the metadata and output the post-processed source to a file.</p>
<p><strong>Best of all... you only have to do the 2to3 conversion once.</strong></p>
<p>Here's the a working example:</p>
<pre><code>#!/usr/bin/env python
# py2and3.py
import sys
from pypreprocessor import pypreprocessor
#exclude
if sys.version[:3].split('.')[0] == '2':
pypreprocessor.defines.append('python2')
if sys.version[:3].split('.')[0] == '3':
pypreprocessor.defines.append('python3')
pypreprocessor.parse()
#endexclude
#ifdef python2
print('You are using Python 2x')
#ifdef python3
print('You are using python 3x')
#else
print('Python version not supported')
#endif
</code></pre>
<p>These are the results in the terminal:</p>
<pre>
python py2and3.py
>>>You are using Python 2x
python3 py2and3.py
>>>You are using python 3x
</pre>
<p>If you want to output to a file and make clean version-specific source file with no extra meta-data, add these two lines somewhere before the pypreprocessor.parse() statement:</p>
<pre><code>pypreprocessor.output = outputFileName.py
pypreprocessor.removeMeta = True
</code></pre>
<p>Then:</p>
<pre>
python py2and3.py
</pre>
<p>Will create a file called outputFileName.py that is python 2x specific with no extra metadata.</p>
<pre>
python3 py2and3.py
</pre>
<p>Will create a file called outputFileName.py that is python 3x specific with no extra metadata.</p>
<p>For documentation and more examples see check out <a href="http://code.google.com/p/pypreprocessor/" rel="nofollow">pypreprocessor on GoogleCode</a>.</p>
<p>I sincerely hope this helps. I love writing code in python and I hope to see support progress into the 3x realm asap. I hate to see the language not progress. Especially, since the 3x version resolves a lot of the featured WTFs and makes the syntax look a little more friendly to users migrating from other languages.</p>
<p>The documentation at this point is complete but not extensive. I'll try to get the wiki up with some more extensive information soon.</p>
<p><strong>Update:</strong></p>
<p><strong>Although I designed pypreprocessor specifically to solve this issue, it doesn't work because the lexer does syntax checking on all of the code before any code is executed.</strong></p>
<p><strong>If python had real C preprocessor directive support it would allow developers to write both python2x and python3k code alongside each other in the same file but due to the bad reputation of the C preprocessor (abuse of macro replacement to change language keywords) I don't see legitimate C preprocessor support being added to python any time soon.</strong></p>
| 3 | 2010-06-04T21:32:10Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 5,324,553 | <p>The Zope Toolkit has been in a slow progress to Python 3 support. Slow mainly because many of these libraries are very complex. </p>
<p>For most libraries I use 2to3. Some libraries make do without it because they are simple or have most of the code in a C-extension. zc.buildout, which is a related package, will run the same code without 2to3 for Python 2 and 3 support.</p>
<p>We port the ZTK to Python 3 because many other libraries and frameworks depend on it, such as Twisted and the Pyramid framework.</p>
| 2 | 2011-03-16T11:22:43Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
How are you planning on handling the migration to Python 3? | 172,306 | <p>I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:</p>
<ol>
<li><p>Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?</p></li>
<li><p>Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?</p></li>
</ol>
| 49 | 2008-10-05T17:08:30Z | 13,095,022 | <p>The Django project uses the library <a href="http://packages.python.org/six"><code>six</code></a> to maintain a codebase that works simultaneously on Python 2 <em>and</em> Python 3 (<a href="https://www.djangoproject.com/weblog/2012/aug/19/experimental-python-3-support/">blog post</a>).</p>
<p><code>six</code> does this by providing a compatibility layer that intelligently redirects imports and functions to their respective locations (as well as unifying other incompatible changes).</p>
<h3>Obvious advantages:</h3>
<ul>
<li>No need for separate branches for Python 2 and Python 3</li>
<li>No conversion tools, such as 2to3.</li>
</ul>
| 8 | 2012-10-26T22:00:41Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 172,398 | <p>I'd probably go for <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard#Implementations" rel="nofollow">AES</a>.</p>
| 1 | 2008-10-05T18:26:22Z | [
"python",
"security",
"encryption"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 172,420 | <p>AES 256 is generally the preferred choice, but depending on your location (or your customers' location) you may have legal constraints, and will be forced to use something weaker.</p>
<p>Also note that you should use a random IV for each communication and pass it along with the message (this will also save the need for a timestamp).</p>
<p>If possible, try not to depend on the algorithm, and pass the algorithm along with the message. The node will then look at the header, and decide on the algorithm that will be used for decryption. That way you can easily switch algorithms when a certain deployment calls for it.</p>
| 3 | 2008-10-05T18:39:01Z | [
"python",
"security",
"encryption"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 172,430 | <p>Asymmetric encryption would work in this scenario as well. Simply have each node publish it's public key. Any node that wants to communicate with that node need only encrypt the message with that node's public key. One advantage of using asymmetric keys is that it becomes easier to change and distribute keys -- since the public keys can be distributed openly, each node need only update it's public-private key pair and republish. You don't need some protocol for the entire network (or each node pair) to agree on a new symmetric key.</p>
| 1 | 2008-10-05T18:42:31Z | [
"python",
"security",
"encryption"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 172,437 | <p>Assuming the use of symmetric crypto, then AES should be your default choice, unless you have a good very reason to select otherwise. </p>
<p>There was a long, involved competition to select AES, and the winner was carefully chosen. Even Bruce Schneier, crypto god, has said that the AES winner is a better choice than the algorithm (TwoFish) that he submitted to the competition.</p>
| 4 | 2008-10-05T18:46:12Z | [
"python",
"security",
"encryption"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 172,449 | <p>Why not create a VPN among the nodes that must communicate securely? </p>
<p>Then, you don't have to bother coding up your own security solution, and you're not restricted to a static, shared key (which, if compromised, will allow all captured traffic to be decrypted after the fact).</p>
| 1 | 2008-10-05T18:49:11Z | [
"python",
"security",
"encryption"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 172,458 | <p>Your first thought should be channel security - either SSL/TLS, or IPSec.<br />
Admittedly, these both have a certain amount of setup overhead, IPSec more than SSL/TLS, especially when it comes to PKI etc. - but it more than pays for itself in simplicity of development, reliability, security, and more. Just make sure you're using strong cipher suites, as appropriate to the protocol.</p>
<p>If neither SSL/TLS or IPSec fits your scenario/environment, your next choice should be <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">AES</a> (aka Rijndael).<br />
Use keys at least 256 bits long, if you want you can go longer.<br />
Keys should be randomly generated, by a cryptographically secure random number generator (and not a simple rnd() call).<br />
Set the cipher mode to <a href="http://en.wikipedia.org/wiki/Cipher_block_chaining">CBC</a>.<br />
Use PKCS7 padding.<br />
Generate a unique, crypto-random Initialization Vector (IV).
Don't forget to properly protect and manage your keys, and maybe consider periodic key rotations.</p>
<p>Depending on your data, you may want to also implement a keyed hash, to provide for message integrity - use <a href="http://en.wikipedia.org/wiki/SHA-256">SHA-256</a> for hashing.</p>
<p>There are also rare situations where you may want to go with a stream cipher, but thats usually more complicated and I would recommend you avoid it your first time out.</p>
<p>Now, I'm not familiar ezpycrypto (or really python in general), and cant really state that it supports all this; but everything here is pretty standard and recommended best practice, if your crypto library doesnt support it, I would suggest finding one that does ;-).</p>
| 7 | 2008-10-05T18:52:23Z | [
"python",
"security",
"encryption"
] |
What symmetric cypher to use for encrypting messages? | 172,392 | <p>I haven't a clue about encryption at all. But I need it. How?</p>
<p>Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).</p>
<p>Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that.</p>
<p>Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out.</p>
<p>So here is what I would like to do:</p>
<ul>
<li>messages are sent as UDP datagrams</li>
<li>each message contains a timestamp to make messages differ (counter replay attacks)</li>
<li>each message is encrypted with a shared secret symmetric key and sent over the network</li>
<li>other end can decrypt with shared secret symmetric key</li>
</ul>
<p>Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link.</p>
<p>What cypher should I use for this encryption? What key length?</p>
<p>I would prefer to use something supported by <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>.</p>
<p>Assuming, as most point out, I go with AES. What modes should I be using?</p>
<p>I couldn't figure out how to do it with ezPyCrypto, <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> seems to be hung on a moderator swap and googles <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> does not explain how to set this up - I fear if I don't just <em>get</em> it, then I run a risk of introducing insecurity. So barebones would be better. <a href="http://www.josh-davis.org/pythonAES" rel="nofollow">This guy</a> claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up?</p>
<p><strong>EDIT:</strong> I moved the search for the python implementation to <a href="http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption">another question</a> to stop clobber...</p>
| 5 | 2008-10-05T18:23:19Z | 179,023 | <blockquote>
<p>I haven't a clue about encryption at all. But I need it. How?</p>
</blockquote>
<p><strong>DANGER!</strong> If you don't know much about cryptography, don't try to implement it yourself. Cryptography is <em>hard to get right</em>. There are many, many different ways to break the security of a cryptographic system beyond actually cracking the key (which is usually very hard).</p>
<p>If you just slap a cipher on your streaming data, without careful key management and other understanding of the subtleties of cryptographic systems, you will likely open yourself up to all kinds of vulnerabilities. For example, the scheme you describe will be vulnerable to <a href="http://wikipedia.org/wiki/Man-in-the-middle_attack" rel="nofollow">man-in-the-middle attacks</a> without some specific plan for key distribution among the nodes, and may be vulnerable to <a href="http://wikipedia.org/wiki/Chosen-plaintext_attack" rel="nofollow">chosen-plaintext</a> and/or <a href="http://wikipedia.org/wiki/Known-plaintext_attack" rel="nofollow">known-plaintext attacks</a> depending on how your distributed system communicates with the outside world, and the exact choice of cipher and <a href="http://wikipedia.org/wiki/Block_cipher_mode" rel="nofollow">mode of operation</a>.</p>
<p>So... you will have to read up on crypto in general before you can use it securely.</p>
| 8 | 2008-10-07T15:24:37Z | [
"python",
"security",
"encryption"
] |
How do I split a multi-line string into multiple lines? | 172,439 | <p>I have a multi-line string literal that I want to do an operation on each line, like so:</p>
<pre><code>inputString = """Line 1
Line 2
Line 3"""
</code></pre>
<p>I want to do something like the following:</p>
<pre><code>for line in inputString:
doStuff()
</code></pre>
| 137 | 2008-10-05T18:46:27Z | 172,454 | <pre><code>inputString.splitlines()
</code></pre>
<p>Will give you a list with each item, the <a href="http://docs.python.org/2/library/stdtypes.html#str.splitlines"><code>splitlines()</code></a> method is designed to split each line into a list element.</p>
| 171 | 2008-10-05T18:50:59Z | [
"python",
"string"
] |
How do I split a multi-line string into multiple lines? | 172,439 | <p>I have a multi-line string literal that I want to do an operation on each line, like so:</p>
<pre><code>inputString = """Line 1
Line 2
Line 3"""
</code></pre>
<p>I want to do something like the following:</p>
<pre><code>for line in inputString:
doStuff()
</code></pre>
| 137 | 2008-10-05T18:46:27Z | 172,468 | <p>Like the others said:</p>
<pre><code>inputString.split('\n') # --> ['Line 1', 'Line 2', 'Line 3']
</code></pre>
<p>This is identical to the above, but the string module's functions are deprecated and should be avoided:</p>
<pre><code>import string
string.split(inputString, '\n') # --> ['Line 1', 'Line 2', 'Line 3']
</code></pre>
<p>Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the <code>splitlines</code> method with a <code>True</code> argument:</p>
<pre><code>inputString.splitlines(True) # --> ['Line 1\n', 'Line 2\n', 'Line 3']
</code></pre>
| 154 | 2008-10-05T18:58:44Z | [
"python",
"string"
] |
How do I split a multi-line string into multiple lines? | 172,439 | <p>I have a multi-line string literal that I want to do an operation on each line, like so:</p>
<pre><code>inputString = """Line 1
Line 2
Line 3"""
</code></pre>
<p>I want to do something like the following:</p>
<pre><code>for line in inputString:
doStuff()
</code></pre>
| 137 | 2008-10-05T18:46:27Z | 16,752,366 | <p>Might be overkill in this particular case but another option involves using <code>StringIO</code> to create a file-like object</p>
<pre><code>for line in StringIO.StringIO(inputString):
doStuff()
</code></pre>
| 14 | 2013-05-25T17:54:57Z | [
"python",
"string"
] |
How do I split a multi-line string into multiple lines? | 172,439 | <p>I have a multi-line string literal that I want to do an operation on each line, like so:</p>
<pre><code>inputString = """Line 1
Line 2
Line 3"""
</code></pre>
<p>I want to do something like the following:</p>
<pre><code>for line in inputString:
doStuff()
</code></pre>
| 137 | 2008-10-05T18:46:27Z | 22,233,816 | <p>The best way to do this is to simply use <code>str.splitlines</code>.</p>
<p>Besides the advantage mentioned by @efotinis of optionally including the newline character in the split result when called with a <code>True</code> argument, <code>splitlines()</code> handles newlines properly, unlike <code>split("\n")</code>.</p>
<hr>
<p><code>\n</code>, in Python, represents a Unix line-break (ASCII decimal code 10), independently from the platform where you run it. However, <a href="https://en.wikipedia.org/wiki/Newline#Representations" rel="nofollow">the linebreak representation is platform-dependent</a>. On Windows, <code>\n</code> is two characters, <code>CR</code> and <code>LF</code> (ASCII decimal codes 13 and 10, AKA <code>\r</code> and <code>\n</code>), while on any modern Unix (including OS X), it's the single character <code>LF</code>.</p>
<p><code>print</code>, for example, works correctly even if you have a string with line endings that don't match your platform:</p>
<pre><code>>>> print " a \n b \r\n c "
a
b
c
</code></pre>
<p>However, explicitly splitting on "\n", will yield platform-dependent behaviour:</p>
<pre><code>>>> " a \n b \r\n c ".split("\n")
[' a ', ' b \r', ' c ']
</code></pre>
<p>Even if you use <code>os.linesep</code>, it will only split according to the newline separator on your platform, and will fail if you're processing text created in other platforms, or with a bare <code>\n</code>:</p>
<pre><code>>>> " a \n b \r\n c ".split(os.linesep)
[' a \n b ', ' c ']
</code></pre>
<p><code>splitlines</code> solves all these problems:</p>
<pre><code>>>> " a \n b \r\n c ".splitlines()
[' a ', ' b ', ' c ']
</code></pre>
<hr>
<p><a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">Reading files in text mode</a> partially mitigates the newline representation problem, as it converts Python's <code>\n</code> into the platform's newline representation.
However, text mode only exists on Windows. On Unix systems, all files are opened in binary mode, so <code>split('\n')</code> on a Windows file will lead to undesired behaviour. Also, it's not unusual to process strings with potentially different newlines from other sources, such as from a socket.</p>
| 24 | 2014-03-06T19:13:57Z | [
"python",
"string"
] |
How do I split a multi-line string into multiple lines? | 172,439 | <p>I have a multi-line string literal that I want to do an operation on each line, like so:</p>
<pre><code>inputString = """Line 1
Line 2
Line 3"""
</code></pre>
<p>I want to do something like the following:</p>
<pre><code>for line in inputString:
doStuff()
</code></pre>
| 137 | 2008-10-05T18:46:27Z | 30,873,284 | <p>I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are <strong>not the same</strong>, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):</p>
<pre><code>try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
for line in StringIO.StringIO(variable_with_multiline_string):
pass
print line.strip()
</code></pre>
| 1 | 2015-06-16T16:34:00Z | [
"python",
"string"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,726 | <p>First thing that comes to mind: <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a>. It runs only on x86, for the time being.</p>
<p>Then, <a href="http://code.activestate.com/recipes/277940/" rel="nofollow">constant binding</a>. That is, make all global references (and <em>global.attr</em>, <em>global.attr.attr</em>â¦) be local names inside of functions and methods. This isn't always successful, but in general it works. It can be done by hand, but obviously is tedious.</p>
<p>You said apart from in-code optimization, so I won't delve into this, but keep your mind open for typical mistakes (<code>for i in range(10000000)</code> comes to mind) that people do.</p>
| 16 | 2008-10-05T21:51:10Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,734 | <p>This won't necessarily speed up any of your code, but is critical knowledge when programming in Python if you want to avoid slowing your code down. The "Global Interpreter Lock" (GIL), has the potential to drastically reduce the speed of your multi-threaded program if its behavior is not understood (yes, this bit me ... I had a nice 4 processor machine that wouldn't use more than 1.2 processors at a time). There's an introductory article with some links to get you started at <a href="http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/" rel="nofollow">SmoothSpan</a>.</p>
| 4 | 2008-10-05T21:59:06Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,737 | <p>Run your app through the Python profiler.
Find a serious bottleneck.
Rewrite that bottleneck in C.
Repeat.</p>
| 4 | 2008-10-05T22:02:52Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,740 | <p>Cython and pyrex can be used to generate c code using a python-like syntax. Psyco is also fantastic for appropriate projects (sometimes you'll not notice much speed boost, sometimes it'll be as much as 50x as fast).
I still reckon the best way is to profile your code (cProfile, etc.) and then just code the bottlenecks as c functions for python.</p>
| 9 | 2008-10-05T22:03:44Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,744 | <p>The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions.</p>
<p>In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this:</p>
<pre><code>result = u""
for item in my_list:
result += unicode (item)
</code></pre>
<p>will copy the <em>entire</em> string twice per iteration. This has been well-covered, and the solution is to use <code>"".join</code>:</p>
<pre><code>result = "".join (unicode (item) for item in my_list)
</code></pre>
<p>Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list.</p>
<p>Finally, <strong>don't be afraid to rewrite bits in C!</strong> Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module.</p>
<p>My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.</p>
| 22 | 2008-10-05T22:09:25Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,766 | <p>People have given some good advice, but you have to be aware that when high performance is needed, the python model is: punt to c. Efforts like psyco may in the future help a bit, but python just isn't a fast language, and it isn't designed to be. Very few languages have the ability to do the dynamic stuff really well and still generate very fast code; at least for the forseeable future (and some of the design works against fast compilation) that will be the case.</p>
<p>So, if you really find yourself in this bind, your best bet will be to isolate the parts of your system that are unacceptable slow in (good) python, and design around the idea that you'll rewrite those bits in C. Sorry. Good design can help make this less painful. Prototype it in python first though, then you've easily got a sanity check on your c, as well.</p>
<p>This works well enough for things like numpy, after all. I can't emphasize enough how much good design will help you though. If you just iteratively poke at your python bits and replace the slowest ones with C, you may end up with a big mess. Think about exactly where the C bits are needed, and how they can be minimized and encapsulated sensibly.</p>
| 4 | 2008-10-05T22:27:08Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,782 | <p>Just a note on using psyco: In some cases it can actually produce slower run-times. Especially when trying to use psyco with code that was written in C. I can't remember the the article I read this, but the <code>map()</code> and <code>reduce()</code> functions were mentioned specifically. Luckily you can tell psyco not to handle specified functions and/or modules.</p>
| 3 | 2008-10-05T22:45:13Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,784 | <p>Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"</p>
<p>Remember the Jackson rules of optimization: </p>
<ul>
<li>Rule 1: Don't do it.</li>
<li>Rule 2 (for experts only): Don't do it yet.</li>
</ul>
<p>And the Knuth rule:</p>
<ul>
<li>"Premature optimization is the root of all evil."</li>
</ul>
<p>The more useful rules are in the <a href="http://www.cs.cmu.edu/~jch/java/rules.html">General Rules for Optimization</a>.</p>
<ol>
<li><p>Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.</p></li>
<li><p>Remember the 80/20 rule.</p></li>
<li><p>Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%.</p></li>
<li><p>Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.</p></li>
</ol>
<p><strong>Bottom Line</strong></p>
<p>You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.</p>
| 40 | 2008-10-05T22:46:37Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,794 | <p>I'm surprised no one mentioned ShedSkin: <a href="http://code.google.com/p/shedskin/">http://code.google.com/p/shedskin/</a>, it automagically converts your python program to C++ and in some benchmarks yields better improvements than psyco in speed. </p>
<p>Plus anecdotal stories on the simplicity: <a href="http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin.html">http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin.html</a></p>
<p>There are limitations though, please see: <a href="http://tinyurl.com/shedskin-limitations">http://tinyurl.com/shedskin-limitations</a></p>
| 7 | 2008-10-05T22:54:57Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 172,991 | <p>This is the procedure that I try to follow:<br></p>
<ul>
<li> import psyco; psyco.full()
<li> If it's not fast enough, run the code through a profiler, see where the bottlenecks are. (DISABLE psyco for this step!)
<li> Try to do things such as other people have mentioned to get the code at those bottlenecks as fast as possible.
<ul><li>Stuff like [str(x) for x in l] or [x.strip() for x in l] is much, much slower than map(str, x) or map(str.strip, x). </ul>
<li> After this, if I still need more speed, it's actually really easy to get PyRex up and running. I first copy a section of python code, put it directly in the pyrex code, and see what happens. Then I twiddle with it until it gets faster and faster.
</ul>
| 3 | 2008-10-06T01:38:57Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 173,055 | <p>Rather than just punting to C, I'd suggest:</p>
<p>Make your code count. Do more with fewer executions of lines:</p>
<ul>
<li>Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.</li>
<li>Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable</li>
<li>Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1).</li>
<li>Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops.</li>
<li>If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance.</li>
<li>Need to crunch numbers? You might want to check <code>numpy</code> out.</li>
<li>Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the <code>Twisted</code> framework.</li>
<li>Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter.</li>
</ul>
<p>If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.</p>
| 26 | 2008-10-06T02:28:52Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 175,283 | <p>If using psyco, I'd recommend <code>psyco.profile()</code> instead of <code>psyco.full()</code>. For a larger project it will be smarter about the functions that got optimized and use a ton less memory.</p>
<p>I would also recommend looking at iterators and generators. If your application is using large data sets this will save you many copies of containers.</p>
| 1 | 2008-10-06T17:24:16Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 247,612 | <p>It's often possible to achieve near-C speeds (close enough for any project using Python in the first place!) by replacing explicit algorithms written out longhand in Python with an implicit algorithm using a built-in Python call. This works because most Python built-ins are written in C anyway. Well, in CPython of course ;-) <a href="https://www.python.org/doc/essays/list2str/" rel="nofollow">https://www.python.org/doc/essays/list2str/</a> </p>
| 3 | 2008-10-29T17:06:02Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 247,641 | <p>The canonical reference to how to improve Python code is here: <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips" rel="nofollow">PerformanceTips</a>. I'd recommend against optimizing in C unless you really need to though. For most applications, you can get the performance you need by following the rules posted in that link.</p>
| 2 | 2008-10-29T17:16:39Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 364,373 | <p>I hope you've read: <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips">http://wiki.python.org/moin/PythonSpeed/PerformanceTips</a></p>
<p>Resuming what's already there are usualy 3 principles:</p>
<ul>
<li>write code that gets transformed in better bytecode, like, use locals, avoid unnecessary lookups/calls, use idiomatic constructs (if there's natural syntax for what you want, use it - usually faster. eg: don't do: "for key in some_dict.keys()", do "for key in some_dict")</li>
<li>whatever is written in C is considerably faster, abuse whatever C functions/modules you have available</li>
<li>when in doubt, import timeit, profile</li>
</ul>
| 5 | 2008-12-12T22:27:19Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 863,670 | <p>Besides the (great) <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a> and the (nice) <a href="http://code.google.com/p/shedskin/" rel="nofollow">shedskin</a>, I'd recommend trying <a href="http://www.cython.org/" rel="nofollow">cython</a> a great fork of <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">pyrex</a>. </p>
<p>Or, if you are not in a hurry, I recommend to just wait. Newer python virtual machines are coming, and <a href="http://code.google.com/p/unladen-swallow/" rel="nofollow">unladen-swallow</a> will find its way into the mainstream.</p>
| 1 | 2009-05-14T14:32:27Z | [
"python",
"optimization",
"performance"
] |
Speeding Up Python | 172,720 | <p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li>
</ul>
<p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
| 39 | 2008-10-05T21:46:00Z | 18,849,701 | <p>A couple of ways to speed up Python code were introduced after this question was asked:</p>
<ul>
<li><strong>Pypy</strong> has a JIT-compiler, which makes it a lot faster for CPU-bound code.</li>
<li>Pypy is written in <a href="https://code.google.com/p/rpython/" rel="nofollow"><strong>Rpython</strong></a>, a subset of Python that compiles to native code, leveraging the LLVM tool-chain.</li>
</ul>
| 0 | 2013-09-17T12:20:41Z | [
"python",
"optimization",
"performance"
] |
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx) | 173,246 | <p>I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.</p>
<p>The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I must. We use Apache 2.2 but will be switching over to Nginx once it goes live. </p>
<p>What are my options? Anyone had experience with this?</p>
| 12 | 2008-10-06T05:07:19Z | 173,292 | <p>You can probably check the code for <a href="http://www.sphider.eu/" rel="nofollow">Sphider</a>. They docs and pdfs, so I'm sure they can read them. Might also lead you in the right direction for other Office formats.</p>
| 2 | 2008-10-06T05:56:07Z | [
"php",
"python",
"perl",
"parsing",
"office-2007"
] |
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx) | 173,246 | <p>I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.</p>
<p>The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I must. We use Apache 2.2 but will be switching over to Nginx once it goes live. </p>
<p>What are my options? Anyone had experience with this?</p>
| 12 | 2008-10-06T05:07:19Z | 173,306 | <p>The Office 2007 file formats are open and <a href="http://msdn.microsoft.com/en-us/library/aa338205.aspx">well documented</a>. Roughly speaking, all of the new file formats ending in "x" are zip compressed XML documents. For example:</p>
<blockquote>
<p>To open a Word 2007 XML file Create a
temporary folder in which to store the
file and its parts.</p>
<p>Save a Word 2007 document, containing
text, pictures, and other elements, as
a .docx file.</p>
<p>Add a .zip extension to the end of the
file name.</p>
<p>Double-click the file. It will open in
the ZIP application. You can see the
parts that comprise the file.</p>
<p>Extract the parts to the folder that
you created previously.</p>
</blockquote>
<p>The other file formats are roughly similar. I don't know of any open source libraries for interacting with them as yet - but depending on your exact requirements, it doesn't look too difficult to read and write simple documents. Certainly it should be a lot easier than with the older formats.</p>
<p>If you need to read the older formats, OpenOffice has an API and can read and write Office 2003 and older documents with more or less success.</p>
| 16 | 2008-10-06T06:10:41Z | [
"php",
"python",
"perl",
"parsing",
"office-2007"
] |
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx) | 173,246 | <p>I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.</p>
<p>The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I must. We use Apache 2.2 but will be switching over to Nginx once it goes live. </p>
<p>What are my options? Anyone had experience with this?</p>
| 12 | 2008-10-06T05:07:19Z | 173,340 | <p>I have successfully used the <a href="http://msdn.microsoft.com/en-us/library/bb448854.aspx" rel="nofollow">OpenXML Format SDK</a> in a project to modify an Excel spreadsheet via code. This would require .NET and I'm not sure about how well it would work under Mono.</p>
| 3 | 2008-10-06T06:30:25Z | [
"php",
"python",
"perl",
"parsing",
"office-2007"
] |
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx) | 173,246 | <p>I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.</p>
<p>The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I must. We use Apache 2.2 but will be switching over to Nginx once it goes live. </p>
<p>What are my options? Anyone had experience with this?</p>
| 12 | 2008-10-06T05:07:19Z | 1,979,887 | <p>The python docx module can generate formatted Microsoft office docx files from pure Python. Out of the box, it does headers, paragraphs, tables, and bullets, but the makeelement() module can be extended to do arbitrary elements like images.</p>
<pre><code>from docx import *
document = newdocument()
# This location is where most document content lives
docbody = document.xpath('/w:document/w:body',namespaces=wordnamespaces)[0]
# Append two headings
docbody.append(heading('Heading',1) )
docbody.append(heading('Subheading',2))
docbody.append(paragraph('Some text')
</code></pre>
| 6 | 2009-12-30T12:13:58Z | [
"php",
"python",
"perl",
"parsing",
"office-2007"
] |
Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught? | 173,278 | <p>The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.</p>
<p>The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.</p>
| 33 | 2008-10-06T05:40:13Z | 173,323 | <p>You can call <a href="https://docs.python.org/2/library/os.html#os._exit">os._exit()</a> to directly exit, without throwing an exception:</p>
<pre><code> import os
os._exit(1)
</code></pre>
<p>This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be returned by the process.</p>
| 45 | 2008-10-06T06:24:53Z | [
"python",
"exception",
"exit",
"systemexit"
] |
Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught? | 173,278 | <p>The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.</p>
<p>The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.</p>
| 33 | 2008-10-06T05:40:13Z | 13,723,190 | <p>As Jerub said, <code>os._exit(1)</code> is your answer. But, considering it bypasses <em>all</em> cleanup procedures, including <code>finally:</code> blocks, closing files, etc, and should really be avoided at all costs, may I present a "safer-ish" way of using it?</p>
<p>If you problem is <code>SystemExit</code> being caught at outer levels (ie, unittest), then <strong><em>be the outer level yourself!</em></strong> Wrap your main code in a try/except block, catch SystemExit, and call os._exit there, <em>and <strong>only</strong> there!</em> This way you may call <code>sys.exit</code> normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and <em>then</em> calling os._exit.</p>
<p>You can even choose which exits are the "emergency" ones. The code below is an example of such approach:</p>
<pre><code>import sys, os
EMERGENCY = 255 # can be any number actually
try:
# wrap your whole code here ...
# ... some code
if x: sys.exit()
# ... some more code
if y: sys.exit(EMERGENCY) # use only for emergency exits
# ...
except SystemExit as e:
if e.code != EMERGENCY:
raise # normal exit, let unittest catch it
else:
os._exit(EMERGENCY) # try to stop *that*, sucker!
</code></pre>
| 29 | 2012-12-05T12:23:15Z | [
"python",
"exception",
"exit",
"systemexit"
] |
python dictionary update method | 173,290 | <p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
| 17 | 2008-10-06T05:53:32Z | 173,299 | <p>You actually want to do this:</p>
<pre><code>for i, tag in enumerate(tag):
tagDict[tag] = i
</code></pre>
<p>The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.</p>
| 44 | 2008-10-06T06:05:00Z | [
"python",
"dictionary",
"variables"
] |
python dictionary update method | 173,290 | <p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
| 17 | 2008-10-06T05:53:32Z | 173,300 | <p>I think this is what you want to do:</p>
<pre><code>d = {}
for i, tag in enumerate(ithTag):
d[tag] = i
</code></pre>
| 2 | 2008-10-06T06:05:05Z | [
"python",
"dictionary",
"variables"
] |
python dictionary update method | 173,290 | <p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
| 17 | 2008-10-06T05:53:32Z | 173,301 | <p>Try</p>
<pre><code>tagDict[ithTag] = i
</code></pre>
| 2 | 2008-10-06T06:05:28Z | [
"python",
"dictionary",
"variables"
] |
python dictionary update method | 173,290 | <p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
| 17 | 2008-10-06T05:53:32Z | 173,369 | <p>If you want to be clever:</p>
<pre><code>tagDict.update(map(reversed, enumerate(tag)))
</code></pre>
<p>Thanks to Brian for the update. This is apparently ~5% faster than the iterative version.</p>
<p>(EDIT: Thanks saverio for pointing out my answer was incorrect (now fixed). Probably the most efficient/Pythonic way would be Torsten Marek's answer, slightly modified:</p>
<pre><code>tagDict.update((t, i) for (i,t) in enumerate(tag))
</code></pre>
<p>)</p>
| 17 | 2008-10-06T06:41:44Z | [
"python",
"dictionary",
"variables"
] |
python dictionary update method | 173,290 | <p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
| 17 | 2008-10-06T05:53:32Z | 179,005 | <p>It's a one-liner:</p>
<pre><code>tagDict = dict((t, i) for i, t in enumerate(tag))
</code></pre>
| 12 | 2008-10-07T15:22:22Z | [
"python",
"dictionary",
"variables"
] |
python dictionary update method | 173,290 | <p>I have a list string tag.</p>
<p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
</code></pre>
<p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p>
<p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p>
<p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p>
<p>Thanks!</p>
| 17 | 2008-10-06T05:53:32Z | 13,350,988 | <p>I think what you want is this:</p>
<pre><code>for i, ithTag in enumerate(tag):
tagDict.update({ithTag: i})
</code></pre>
| 2 | 2012-11-12T20:24:27Z | [
"python",
"dictionary",
"variables"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 173,774 | <p>Have you checked out the <a href="http://www.mobilepythonbook.com/" rel="nofollow">Mobile Python Book</a>?</p>
<blockquote>
<p>This practical hands-on book effectively teaches how to program your own powerful and fun applications easily on Nokia smartphones based on Symbian OS and the S60 platform.</p>
</blockquote>
<p><img src="http://www.mobilenin.com/mobilepythonbook/book-cover.png" alt="Mobile Python Book cover" /></p>
| 3 | 2008-10-06T10:06:13Z | [
"python",
"mobile",
"pys60"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 174,358 | <p>I've just started to look into this myself. I've purchased the Mobile Python book above. It looks good so far. </p>
<p>This site has a few tutorials as well:
<a href="http://croozeus.com/tutorials.htm" rel="nofollow">http://croozeus.com/tutorials.htm</a></p>
<p>I'm using putools to code/sync over bluetooth from linux:
<a href="http://people.csail.mit.edu/kapu/symbian/python.html" rel="nofollow">http://people.csail.mit.edu/kapu/symbian/python.html</a></p>
<p>There are advantages/disadvantages to the python dev on S60. Obviously, using Python is a major plus. There are some extra tricks you need in order to get your app built into a distributed form where you don't need to require the end user to first go download the python runtime for their phone. </p>
<p>The other disadvantage is simply in UI. You have three forms of ui available via the appuifw API. Let's say you want to draw images on the screen as well as have a text entry field in the ui, you really can't. You'll have to split the ui into parts that fit what the python api gives you. </p>
<p>As for IDE/Emulator, I'm just using VIM on Ubuntu with the bluetooth sync tools in putools. I've seen that you can get the C++ or Java environments, and then use the emulators in them, but not seen how it works since it seems to be a windows only option at this point.</p>
| 3 | 2008-10-06T13:49:52Z | [
"python",
"mobile",
"pys60"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 330,298 | <h2>PyS60 -- its cool :)</h2>
<p>I worked quite a lot on PyS60 ver 1.3 FP2. It is a great language to port your apps on
Symbian Mobiles and Powerful too. I did my Major project in PyS60, which was a <a href="http://sourceforge.net/projects/gsmlocator" rel="nofollow">GSM locator</a>(its not the latest version) app for Symbian phones. </p>
<p>There is also a very neat py2sis utility which converts your py apps to portabble sis apps that can be installed on any Sumbian phones. The ease of use of Python scripting laanguage and a good set of warapped APIs for Mobile functions just enables you to do anything very neatly and quickly.</p>
<p>The latest Video and Camera APIs let you do neary everything that can be done with the phone. I'd suggest you few very good resources to start with</p>
<ol>
<li><a href="http://www.forum.nokia.com/Resources_and_Information/Tools/Runtimes/Python_for_S60/" rel="nofollow">Forum Nokia</a></li>
<li><a href="http://opensource.nokia.com/projects/pythonfors60/" rel="nofollow">Nokia OpenSource Resource
center</a></li>
<li><a href="http://www.mobilenin.com/pys60/menu.htm" rel="nofollow">A very good tutorial (for beginners)</a></li>
</ol>
<p>Just access these, download the Emulator, and TAKE OFF for a ride with PyS60. M sure you'll love it.</p>
<p>P.S. : as the post is so old, I believe u must already be either loving it or finished off with it. But I just cudn't resist answering. :)</p>
| 8 | 2008-12-01T08:50:45Z | [
"python",
"mobile",
"pys60"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 489,368 | <p>I've written a calculator, that I'd like to have, and made a simple game.
I wrote it right on the phone. I was writing in text editor then switched to Python and ran a script. It is not very comfortable, but it's ok. Moreover, I was writing all this when I hadn't PC nearby.</p>
<p>It was a great experience!</p>
| 0 | 2009-01-28T21:06:11Z | [
"python",
"mobile",
"pys60"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 1,195,831 | <p>I have some J2ME experience and now I decided to write a couple of useful apps for my phone so I decided to use PyS60 to study Python by the way:)</p>
<p>Some things I don't like about the platform are:</p>
<ol>
<li>You can't invoke any graphical functions (module appuifw) from non-main thread.</li>
<li>Python script model is not well-suited for ui applications because the script must contain explicit while loop or semaphore to prevent main thread from exit</li>
<li>There function sys.exit() is not available.</li>
</ol>
<p>Again, I'm a newbie to PyS60 so if the issues given above do have nice workarounds don't hesitate to write them as comments. I would be very grateful.</p>
| 0 | 2009-07-28T18:22:38Z | [
"python",
"mobile",
"pys60"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 1,201,939 | <p>There is a nice little IDE called <a href="http://code.google.com/p/ped-s60/" rel="nofollow">PED</a> for S60 phones which gives you some extra features and makes it easier to code. It's not really that advanced yet, but it's better than manually switching between text editor and python all the time.</p>
<p>HTH</p>
<p>Kage</p>
| 0 | 2009-07-29T17:49:54Z | [
"python",
"mobile",
"pys60"
] |
Does anyone have experience with PyS60 mobile development | 173,484 | <p>I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.</p>
<p>Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.</p>
| 10 | 2008-10-06T07:37:30Z | 4,553,278 | <p>I've seen here a mobile IDE for pyS60..</p>
<p><a href="http://circuitdesolator.blogspot.com/2010/12/ped-mobile-phyton-ide-for-pys60.html" rel="nofollow">http://circuitdesolator.blogspot.com/2010/12/ped-mobile-phyton-ide-for-pys60.html</a></p>
<p>It's called PED and i've been using it in the past months..</p>
| 1 | 2010-12-29T10:25:53Z | [
"python",
"mobile",
"pys60"
] |
Is it possible to pass arguments into event bindings? | 173,687 | <p>I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.</p>
<p>When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:</p>
<pre><code>b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
self.log.write("Click! (%d)\n" % event.GetId())
</code></pre>
<p>But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value? </p>
<p>It would greatly reduce copy & pasting the same code but with different callers.</p>
| 23 | 2008-10-06T09:31:40Z | 173,694 | <p>You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.</p>
<pre><code>b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
self.log.write("Click! (%d)\n" % event.GetId())
</code></pre>
<p>If you're out to reduce the amount of code to type, you might also try a little automatism like:</p>
<pre><code>class foo(whateverwxobject):
def better_bind(self, type, instance, handler, *args, **kwargs):
self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)
def __init__(self):
self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')
</code></pre>
| 37 | 2008-10-06T09:38:08Z | [
"python",
"events",
"wxpython"
] |
Is it possible to pass arguments into event bindings? | 173,687 | <p>I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.</p>
<p>When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:</p>
<pre><code>b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
self.log.write("Click! (%d)\n" % event.GetId())
</code></pre>
<p>But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value? </p>
<p>It would greatly reduce copy & pasting the same code but with different callers.</p>
| 23 | 2008-10-06T09:31:40Z | 173,826 | <p>The nicest way would be to make a generator of event handlers, e.g.:</p>
<pre><code>def getOnClick(self, additionalArgument):
def OnClick(self, event):
self.log.write("Click! (%d), arg: %s\n"
% (event.GetId(), additionalArgument))
return OnClick
</code></pre>
<p>Now you bind it with:</p>
<pre><code>b = wx.Button(self, 10, "Default Button", (20, 20))
b.Bind(wx.EVT_BUTTON, self.getOnClick('my additional data'))
</code></pre>
| 11 | 2008-10-06T10:33:33Z | [
"python",
"events",
"wxpython"
] |
How do I blink/control Macbook keyboard LEDs programmatically? | 173,905 | <p>Do you know how I can switch on/off (blink) Macbook keyboard led (caps lock,numlock) under Mac OS X (preferably Tiger)?</p>
<p>I've googled for this, but have got no results, so I am asking for help.</p>
<p>I would like to add this feature as notifications (eg. new message received on Adium, new mail received).</p>
<p>I would prefer applescript, python, but if it's impossible, any code would be just fine.</p>
<p>I will appreciate any kind of guidance.</p>
| 4 | 2008-10-06T11:11:05Z | 173,914 | <p><a href="http://googlemac.blogspot.com/2008/04/manipulating-keyboard-leds-through.html" rel="nofollow">http://googlemac.blogspot.com/2008/04/manipulating-keyboard-leds-through.html</a></p>
| 5 | 2008-10-06T11:15:02Z | [
"python",
"osx",
"keyboard",
"blink"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 174,184 | <p>Have a look at this question <a href="http://stackoverflow.com/questions/169897/how-to-package-twisted-program-with-py2exe">how-to-package-twisted-program-with-py2exe</a> it seems to be the same problem.</p>
<p>The answer given there is to explicitly include the modules on the command line to py2exe.</p>
| 4 | 2008-10-06T13:05:01Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 174,203 | <p>If you don't have to work with py2exe, bbfreeze works better, and I've tried it with the email module. <a href="http://pypi.python.org/pypi/bbfreeze/0.95.4" rel="nofollow">http://pypi.python.org/pypi/bbfreeze/0.95.4</a></p>
| 1 | 2008-10-06T13:09:26Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 174,769 | <p>Use the "includes" option. See: <a href="http://www.py2exe.org/index.cgi/ListOfOptions" rel="nofollow">http://www.py2exe.org/index.cgi/ListOfOptions</a></p>
| 2 | 2008-10-06T15:31:13Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 176,305 | <p>What version of Python are you using? If you are using 2.5 or 2.6, then you should be doing your import like:</p>
<pre><code>import string,time,sys,os,smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import Encoders
</code></pre>
<p>I'm pretty certain that py2exe's modulefinder can correctly find the email package if you use it correctly (i.e. use the above names in Python 2.5+, or use the old names in Python 2.4-). Certainly the SpamBayes setup script does not need to explicitly include the email package, and it includes the email modules without problem.</p>
<p>The other answers are correct in that if you do need to specifically include a module, you use the "includes" option, either via the command-line, or passing them in when you call setup.</p>
| 4 | 2008-10-06T21:38:17Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 1,194,697 | <p>while porting my app from py24 to 26 I had the same problem.</p>
<p>After reading <a href="http://www.py2exe.org/index.cgi/ExeWithEggs" rel="nofollow">http://www.py2exe.org/index.cgi/ExeWithEggs</a>
if found finaly following solution:</p>
<h2>in my application.py:</h2>
<pre><code>import email
import email.mime.text
import email.mime.base
import email.mime.multipart
import email.iterators
import email.generator
import email.utils
try:
from email.MIMEText import MIMEText
except:
from email.mime import text as MIMEText
</code></pre>
<h2>in setup.py:</h2>
<pre><code>import modulefinder
modulefinder.AddPackagePath("mail.mime", "base")
modulefinder.AddPackagePath("mail.mime", "multipart")
modulefinder.AddPackagePath("mail.mime", "nonmultipart")
modulefinder.AddPackagePath("mail.mime", "audio")
modulefinder.AddPackagePath("mail.mime", "image")
modulefinder.AddPackagePath("mail.mime", "message")
modulefinder.AddPackagePath("mail.mime", "application")
</code></pre>
<p>For py2exe to work with packages loaded during runtime, the main thing seems to be that u explicitly import the modules needed by your app somewhere in your app.
And then give py2exe in setup.py with moudlefinder.AddPackagePath( , ) the hint, where to search for modules it couldn't find by std. introspection.
in the app</p>
| 0 | 2009-07-28T14:56:32Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 18,602,374 | <p>This solve my problem:
in setup.py edit</p>
<pre><code>includes = ["email"]
</code></pre>
| 0 | 2013-09-03T22:16:01Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 25,947,245 | <p>Please try this. This works on my py2exe build. Just replace "project_name.py" with your main script. The EXTRA_INCLUDES are packages that you need to include in your build like email package. I this works with you also. </p>
<pre><code>from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
EXTRA_INCLUDES = [
"email.iterators", "email.generator", "email.utils", "email.base64mime", "email", "email.mime",
"email.mime.multipart", "email.mime.text", "email.mime.base",
"lxml.etree", "lxml._elementpath", "gzip"
]
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True, 'includes': EXTRA_INCLUDES,
'dll_excludes': ['w9xpopen.exe','MSVCR71.dll']}},
console = [{'script': "project_name.py"}],
zipfile = None,
)
</code></pre>
| 0 | 2014-09-20T09:20:36Z | [
"python",
"winapi",
"py2exe"
] |
Python - Py2exe can't build .exe using the 'email' module | 174,170 | <p>py2exe does not work with the standard email module</p>
<p>Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this:</p>
<p><hr /></p>
<p>The following modules appear to be missing</p>
<h2>['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME']</h2>
<p>The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help?</p>
<p>Thank you,</p>
<p>P.S.
Imports in the script look like this:</p>
<p>Code: Select all
import string,time,sys,os,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders</p>
| 7 | 2008-10-06T13:02:03Z | 31,598,698 | <p>I got it working by explicitly including missing modules in setup.py:</p>
<p>OLD setup.py:</p>
<pre><code>setup(console = ['main.py'])
</code></pre>
<p>New setup.py:</p>
<pre><code>setup(console = ['main.py'],
options={"py2exe":{"includes":["email.mime.multipart","email.mime.text"]}})
</code></pre>
| 1 | 2015-07-23T21:52:10Z | [
"python",
"winapi",
"py2exe"
] |
What is the best way to run multiple subprocesses via fork()? | 174,853 | <p>A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script after all kids are collected.</p>
<p>What is the best way to work it out? Thanks. </p>
| 8 | 2008-10-06T15:47:59Z | 174,984 | <p>Have you looked at the <a href="http://pyprocessing.berlios.de/" rel="nofollow">pyprocessing</a> module?</p>
| 2 | 2008-10-06T16:16:41Z | [
"python",
"linux"
] |
What is the best way to run multiple subprocesses via fork()? | 174,853 | <p>A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script after all kids are collected.</p>
<p>What is the best way to work it out? Thanks. </p>
| 8 | 2008-10-06T15:47:59Z | 174,989 | <p>The traditional, UNIX-y way to communicate with sub-processes is to open pipes to their standard input/output, and use the <code>select()</code> system call to multiplex the communications in the parent process (available in Python via... the <code>select</code> module).</p>
<p>If you need to kill a slow-running child process, you can just save its process ID (returned by the <code>os.fork()</code> call) and then use <code>os.kill()</code> to kill it when not needed anymore. Of course, it would probably be cleaner to be able to communicate with the child process explicitly and <em>tell it</em> to shut itself down.</p>
| 1 | 2008-10-06T16:17:28Z | [
"python",
"linux"
] |
What is the best way to run multiple subprocesses via fork()? | 174,853 | <p>A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script after all kids are collected.</p>
<p>What is the best way to work it out? Thanks. </p>
| 8 | 2008-10-06T15:47:59Z | 175,038 | <p>Simple example:</p>
<pre><code>import os
chidren = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
pass # really should exec the job
for child in children:
os.waitpid(child, 0)
</code></pre>
<p>Timing out a slow child is a little more work; you can use <code>wait</code> instead of <code>waitpid</code>, and cull the returned values from the list of children, instead of waiting on each one in turn (as here). If you set up an <code>alarm</code> with a <code>SIGALRM</code> handler, you can terminate the waiting after a specified delay. This is all standard UNIX stuff, not Python-specific...</p>
| 10 | 2008-10-06T16:26:25Z | [
"python",
"linux"
] |
What is the best way to run multiple subprocesses via fork()? | 174,853 | <p>A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script after all kids are collected.</p>
<p>What is the best way to work it out? Thanks. </p>
| 8 | 2008-10-06T15:47:59Z | 177,237 | <p><em>Ephemient</em>: each child in your code will stay in the for loop after his job ends. He will fork again and again. Moreover, the children that start when children[] is not empty will try to wait for some of their brothers at the end of the loop. Eventually someone will crash. This is a workaround:</p>
<pre><code>import os, time
def doTheJob(job):
for i in xrange(10):
print job, i
time.sleep(0.01*ord(os.urandom(1)))
# random.random() would be the same for each process
jobs = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
imTheFather = True
children = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
imTheFather = False
doTheJob(job)
break
# in the meanwhile
# ps aux|grep python|grep -v grep|wc -l == 11 == 10 children + the father
if imTheFather:
for child in children:
os.waitpid(child, 0)
</code></pre>
| 4 | 2008-10-07T04:31:40Z | [
"python",
"linux"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 175,016 | <p>It's not possible AFAIK... which is a pity. Basically, ElementTree modules assume that the reader is 100% XML compliant, so it shouldn't matter if they output a section as CDATA or some other format that generates the equivalent text.</p>
<p>See <a href="https://mail.python.org/pipermail/python-list/2005-June/304602.html" rel="nofollow">this thread</a> on the Python mailing list for more info. Basically, they recommend some kind of DOM-based XML library instead.</p>
| 6 | 2008-10-06T16:21:58Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 175,101 | <p>After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular elements.</p>
<pre><code>def Comment(text=None):
element = Element(Comment)
element.text = text
return element
</code></pre>
<p>Then in the <code>_write</code> function of ElementTree that actually outputs the XML, there's a special case handling for comments:</p>
<pre><code>if tag is Comment:
file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
</code></pre>
<p>In order to support CDATA sections, I create a factory function called <code>CDATA</code>, extended the ElementTree class and changed the <code>_write</code> function to handle the CDATA elements.</p>
<p>This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do.</p>
<p>The implementation seems to work with both ElementTree and cElementTree.</p>
<pre><code>import elementtree.ElementTree as etree
#~ import cElementTree as etree
def CDATA(text=None):
element = etree.Element(CDATA)
element.text = text
return element
class ElementTreeCDATA(etree.ElementTree):
def _write(self, file, node, encoding, namespaces):
if node.tag is CDATA:
text = node.text.encode(encoding)
file.write("\n<![CDATA[%s]]>\n" % text)
else:
etree.ElementTree._write(self, file, node, encoding, namespaces)
if __name__ == "__main__":
import sys
text = """
<?xml version='1.0' encoding='utf-8'?>
<text>
This is just some sample text.
</text>
"""
e = etree.Element("data")
cdata = CDATA(text)
e.append(cdata)
et = ElementTreeCDATA(e)
et.write(sys.stdout, "utf-8")
</code></pre>
| 21 | 2008-10-06T16:41:48Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 202,122 | <p><a href="http://lxml.de/">lxml</a> has support for <a href="http://lxml.de/api.html#cdata">CDATA</a> and API like ElementTree.</p>
| 10 | 2008-10-14T17:43:57Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 320,876 | <p>Actually this code has a bug, since you don't catch <code>]]></code> appearing in the data you are inserting as CDATA</p>
<p>as per <a href="http://stackoverflow.com/questions/223652/is-there-a-way-to-escape-a-cdata-end-token-in-xml">Is there a way to escape a CDATA end token in xml?</a></p>
<p>you should break it into two CDATA's in that case, splitting the <code>]]></code> between the two.</p>
<p>basically <code>data = data.replace("]]>", "]]]]><![CDATA[>")</code><br>
(not necessarily correct, please verify)</p>
| 5 | 2008-11-26T14:28:21Z | [
"python",
"xml"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.