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
listlengths
1
5
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
1,429,154
<p>Another way:</p> <pre><code>import math def hextobinary(hex_string): s = int(hex_string, 16) num_digits = int(math.ceil(math.log(s) / math.log(2))) digit_lst = ['0'] * num_digits idx = num_digits while s &gt; 0: idx -= 1 if s % 2 == 1: digit_lst[idx] = '1' s = s / 2 return '...
2
2009-09-15T19:24:01Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
1,519,418
<p>hex --> decimal then decimal --> binary</p> <pre><code>#decimal to binary def d2b(n): bStr = '' if n &lt; 0: raise ValueError, "must be a positive integer" if n == 0: return '0' while n &gt; 0: bStr = str(n % 2) + bStr n = n &gt;&gt; 1 return bStr #hex to binary def h2b(hex...
3
2009-10-05T11:00:55Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
4,859,937
<p>For solving the left-side trailing zero problem:</p> <hr> <pre><code>my_hexdata = "1a" scale = 16 ## equals to hexadecimal num_of_bits = 8 bin(int(my_hexdata, scale))[2:].zfill(num_of_bits) </code></pre> <hr> <p>It will give 00011010 instead of the trimmed version.</p>
58
2011-02-01T07:17:53Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
7,373,476
<p>This is a slight touch up to Glen Maynard's solution, which I think is the right way to do it. It just adds the padding element.</p> <pre><code> def hextobin(self, hexval): ''' Takes a string representation of hex data with arbitrary length and converts to string representation ...
5
2011-09-10T17:44:44Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
9,486,791
<pre><code>"{0:020b}".format(int('ABC123EFFF', 16)) </code></pre>
11
2012-02-28T17:28:51Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
9,686,905
<pre><code>no=raw_input("Enter your number in hexa decimal :") def convert(a): if a=="0": c="0000" elif a=="1": c="0001" elif a=="2": c="0010" elif a=="3": c="0011" elif a=="4": c="0100" elif a=="5": c="0101" elif a=="6": c="0110" e...
-10
2012-03-13T15:21:11Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
25,016,156
<pre><code>&gt;&gt;&gt; bin( 0xABC123EFFF ) </code></pre> <p>'0b1010101111000001001000111110111111111111'</p>
13
2014-07-29T13:10:58Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
28,407,262
<pre><code>a = raw_input('hex number\n') length = len(a) ab = bin(int(a, 16))[2:] while len(ab)&lt;(length * 4): ab = '0' + ab print ab </code></pre>
-1
2015-02-09T10:09:57Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
28,913,296
<p>I added the calculation for the number of bits to fill to Onedinkenedi's solution. Here is the resulting function:</p> <pre><code>def hextobin(h): return bin(int(h, 16))[2:].zfill(len(h) * 4) </code></pre> <p>Where 16 is the base you're converting from (hexadecimal), and 4 is how many bits you need to represent...
0
2015-03-07T09:21:39Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
32,916,352
<pre><code>import binascii hexa_input = input('Enter hex String to convert to Binary: ') pad_bits=len(hexa_input)*4 Integer_output=int(hexa_input,16) Binary_output= bin(Integer_output)[2:]. zfill(pad_bits) print(Binary_output) """zfill(x) i.e. x no of 0 s to be padded left - Integers will overwrite 0 s starting from ri...
-1
2015-10-02T21:48:08Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
34,574,391
<pre><code> def conversion(): e=raw_input("enter hexadecimal no.:") e1=("a","b","c","d","e","f") e2=(10,11,12,13,14,15) e3=1 e4=len(e) e5=() while e3&lt;=e4: e5=e5+(e[e3-1],) e3=e3+1 print e5 e6=1 e8=() while e6&lt;=e4: e7=e5[e6-1] if e7=="A": ...
-1
2016-01-03T07:42:54Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
36,884,411
<p>i have a short snipped hope that helps :-)</p> <pre><code>input = 'ABC123EFFF' for index, value in enumerate(input): print(value) print(bin(int(value,16)+16)[3:]) string = ''.join([bin(int(x,16)+16)[3:] for y,x in enumerate(input)]) print(string) </code></pre> <p>first i use your input and enumerate it to...
0
2016-04-27T08:31:51Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
37,221,884
<blockquote> <h1>Convert hex to binary, 42 digits and leading zeros?</h1> </blockquote> <p>We have several direct ways to accomplish this goal, without hacks using slices.</p> <p>First, before we can do any binary manipulation at all, convert to int (I presume this is in a string format, not as a literal):</p> <pr...
2
2016-05-14T02:34:52Z
[ "python", "string", "binary", "hex", "string-formatting" ]
How do you mix old-style and new-style Python classes?
1,425,714
<p>I've seen a few questions on this topic, but I haven't been able to find a definitive answer. </p> <p>I would like to know the proper way to use old-style classes in a new Python code base. Let's say for example that I have two fixed classes, <strong>A</strong> and <strong>B</strong>. If I want to subclass <strong>...
6
2009-09-15T07:41:44Z
1,425,998
<p>This is not a issue of mixing old and new style classes. super() does not call <em>all</em> base classes functions, it calls the first one it finds according the method resolution order. In this case A2, which in turn calls A.</p> <p>If you want to call both, do so explicitly:</p> <pre><code>class C(A2, B2): de...
6
2009-09-15T08:55:16Z
[ "python", "class", "multiple-inheritance", "instantiation" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
1,425,733
<p>If you want a new list:</p> <pre><code>a = ["Python", "Java", "Microsoft"] b = a[::-1] # b is now ["Microsoft", "Java", "Python"] </code></pre> <p>or</p> <pre><code>a = ["Python", "Java", "Microsoft"] b = list(reversed(a)) # b is now ["Microsoft", "Java", "Python"] </code></pre> <p>If you want to modify an exist...
25
2009-09-15T07:44:45Z
[ "python" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
1,425,740
<pre><code>&gt;&gt;&gt; l = ["Microsoft", "Java", "Python"] &gt;&gt;&gt; l.reverse() &gt;&gt;&gt; l ['Python', 'Java', 'Microsoft'] &gt;&gt;&gt; </code></pre>
1
2009-09-15T07:46:23Z
[ "python" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
1,425,744
<p>the most comprehensible option for sequences is to use "reversed", but the result is always a list, so for a string you could either use it and convert it to a string again by joining the elements, or use a slice with negative index (this later being more efficient, I guess):</p> <pre><code>s = "abcd" reversed(s) #...
1
2009-09-15T07:48:33Z
[ "python" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
38,784,593
<pre><code>public class StringRev { public static void main(String[] args) { // text is containing dummy/ Test string String text="ReverseToString"; //StringBuilder sb=new StringBuilder(); // In this line I am creating the object of StringBuffer StringBuffer sb=new StringBuffer(); // using a fo...
-1
2016-08-05T08:25:40Z
[ "python" ]
Problem configparser in python
1,426,241
<p>Actually I am stuck in my work. I want to import a txt file into my python program which should have two lists of intergers.</p> <p>The following program is working fine but I need to import the list 'a' and 'b' with the help of configparser. </p> <p>It will be so nice if some one help me with it!</p> <p>I am a b...
0
2009-09-15T09:57:38Z
1,426,255
<p>Seems like ConfigParser is not the best tool for the job. You may implement the parsing logic youself something like:</p> <pre><code>a, b = [], [] with open('myfile', 'r') as f: for num, line in enumerate(f.readlines()): if num &gt;= 10: b.push(line) else: a.push(line) <...
0
2009-09-15T10:01:27Z
[ "python", "configparser" ]
Problem configparser in python
1,426,241
<p>Actually I am stuck in my work. I want to import a txt file into my python program which should have two lists of intergers.</p> <p>The following program is working fine but I need to import the list 'a' and 'b' with the help of configparser. </p> <p>It will be so nice if some one help me with it!</p> <p>I am a b...
0
2009-09-15T09:57:38Z
1,426,477
<p>The <a href="http://docs.python.org/library/json.html#module-json" rel="nofollow"><code>json</code> module</a> provides better support for lists in configuration files. Instead of the ConfigParser (no list support) format, try using <a href="http://json.org/" rel="nofollow"><code>JSON</code></a> for this purpose.</p...
0
2009-09-15T11:00:58Z
[ "python", "configparser" ]
Problem configparser in python
1,426,241
<p>Actually I am stuck in my work. I want to import a txt file into my python program which should have two lists of intergers.</p> <p>The following program is working fine but I need to import the list 'a' and 'b' with the help of configparser. </p> <p>It will be so nice if some one help me with it!</p> <p>I am a b...
0
2009-09-15T09:57:38Z
1,426,520
<p>Yea, the config parser probably isn't the best choice...but if you really want to, try this:</p> <pre><code>import unittest from ConfigParser import SafeConfigParser from cStringIO import StringIO def _parse_float_list(string_value): return [float(v.strip()) for v in string_value.split(',')] def _generate_flo...
0
2009-09-15T11:09:39Z
[ "python", "configparser" ]
Live UI update of model changes when the model contains plain data structures only
1,426,272
<p>Please consult me with your opinions on the following topic:</p> <p>I have a model - a structure of the objects. Such as:</p> <ul> <li><p>Event, containing participants</p></li> <li><p>Current task</p></li> <li><p>Assignee of each task</p></li> </ul> <p>The model is going to be pickled on the server and transferr...
2
2009-09-15T10:05:36Z
1,426,368
<p>You may be operating under a mis-conception: pickles don't include the code from classes that are pickled. You can add methods to your data structures, and it will not increase the size of your pickles.</p> <p>This is a common misunderstanding about pickles. They don't include code.</p>
0
2009-09-15T10:36:43Z
[ "python", "design-patterns", "architecture" ]
Live UI update of model changes when the model contains plain data structures only
1,426,272
<p>Please consult me with your opinions on the following topic:</p> <p>I have a model - a structure of the objects. Such as:</p> <ul> <li><p>Event, containing participants</p></li> <li><p>Current task</p></li> <li><p>Assignee of each task</p></li> </ul> <p>The model is going to be pickled on the server and transferr...
2
2009-09-15T10:05:36Z
2,977,996
<p>You may add a flag, e.g. self.isOnClientSide, and check it in every update handler, so that you can use different logic in either case.</p> <pre><code>def onUpdateFoo(self): if self.isOnClientSide: return self.onUpdateFooOnClient() else: return self.onUpdateFooOnServer() </code></pre> <p>Change this fl...
0
2010-06-04T21:41:56Z
[ "python", "design-patterns", "architecture" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="h...
0
2009-09-15T12:51:00Z
1,427,076
<p>You can just write an script that is continuously in a while block waiting for the connection to happen and waits for a signal to close it.</p> <p><a href="http://docs.python.org/library/signal.html" rel="nofollow">http://docs.python.org/library/signal.html</a></p> <p>Then to stop it you just need to run another s...
1
2009-09-15T13:08:09Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="h...
0
2009-09-15T12:51:00Z
1,427,086
<p>I think <a href="http://en.wikipedia.org/wiki/Comet%5F%28programming%29" rel="nofollow">Comet</a> is what you're looking for. Make sure to take a look at Tornado too.</p>
0
2009-09-15T13:09:04Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="h...
0
2009-09-15T12:51:00Z
1,427,125
<p>You can use a ‘double fork’ to run your code in a new background process unbound to the old one. See eg <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">this</a> recipe with more explanatory comments than you could possibly want.</p> <p>I wouldn't recommend this as a primary way of running b...
1
2009-09-15T13:17:21Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="h...
0
2009-09-15T12:51:00Z
1,429,758
<p>You may want to look at FastCGI, it sounds exactly like what you are looking for, but I'm not sure if it's under current development. It uses a CGI daemon and a special apache module to communicate with it. Since the daemon is long running, you don't have the fork/exec cost. But as a cost of managing your own res...
0
2009-09-15T21:38:08Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="h...
0
2009-09-15T12:51:00Z
1,431,519
<p>If you are using twisted then it has a whole infrastructure for starting and stopping daemons.</p> <p><a href="http://twistedmatrix.com/projects/core/documentation/howto/application.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/application.html</a></p> <blockquote> <p>How would ...
3
2009-09-16T07:36:21Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
Calling Py_Finalize() from C
1,427,002
<p>This is a follow up to <a href="http://stackoverflow.com/questions/1417473/call-python-from-c">http://stackoverflow.com/questions/1417473/call-python-from-c</a></p> <p>At the startup of the programm I call the following function to initialize the interpreter:</p> <pre><code>void initPython(){ PyEval_InitThread...
9
2009-09-15T12:51:46Z
1,432,160
<p>Have you tried commenting out all the 'work' done in your threads? Replace it with a busy loop or a sleep or something. That will help pinpoint whether it is your initialisation/shutdown code, or something you're actually doing to Python in between. Perhaps you're not setting up the threads properly - there are a lo...
1
2009-09-16T10:25:06Z
[ "c++", "python", "c" ]
Calling Py_Finalize() from C
1,427,002
<p>This is a follow up to <a href="http://stackoverflow.com/questions/1417473/call-python-from-c">http://stackoverflow.com/questions/1417473/call-python-from-c</a></p> <p>At the startup of the programm I call the following function to initialize the interpreter:</p> <pre><code>void initPython(){ PyEval_InitThread...
9
2009-09-15T12:51:46Z
1,434,508
<p>Yeah the whole section is rather dubious but I think I've got my mistake.</p> <p>I've got to save the PyThreadState when initializing the interpreter and swap this state back in when I finish it (no idea why I need a specific ThreadState to call Finalize - shouldn't every State work as well?)</p> <p>Anyways the ex...
7
2009-09-16T17:48:38Z
[ "c++", "python", "c" ]
Calling Py_Finalize() from C
1,427,002
<p>This is a follow up to <a href="http://stackoverflow.com/questions/1417473/call-python-from-c">http://stackoverflow.com/questions/1417473/call-python-from-c</a></p> <p>At the startup of the programm I call the following function to initialize the interpreter:</p> <pre><code>void initPython(){ PyEval_InitThread...
9
2009-09-15T12:51:46Z
28,080,794
<p>I am also getting similar problem while running scripts containing <code>pyxhook</code> from different threads through embedded interpreter. </p> <p>There is no problem if one script running at a time. The hook is released properly but if two or more script ran in parallel the hooking is not stopped. Though my scri...
0
2015-01-22T03:27:15Z
[ "c++", "python", "c" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work...
4
2009-09-15T13:01:56Z
1,427,212
<p>Don't use <code>map</code>. It generates a big list in memory.</p> <p>Don't use <code>xrange</code>. It is limited to short integers.</p> <p>Use generators instead.</p> <pre><code># No changes on `ceil()`, `func()` and `calculate()` def generate_sequence(start, stop): while start &lt; stop: yield st...
4
2009-09-15T13:34:59Z
[ "python" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work...
4
2009-09-15T13:01:56Z
1,428,255
<p>90,000,000,000,000 is a lot of numbers to check, I tried checking every millionth number and thought the average would be close enough, but to no avail.</p>
0
2009-09-15T16:35:40Z
[ "python" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work...
4
2009-09-15T13:01:56Z
1,546,544
<p>Even a very fast calculation for each number will take too long. To satisfy the 1 minute rule you'd need to solve/add 1.5 Trillion numbers per second.</p> <p>I think there must be a way to compute the result more directly.</p>
1
2009-10-09T23:35:21Z
[ "python" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work...
4
2009-09-15T13:01:56Z
1,549,435
<p><a href="http://python.org/doc/2.5.2/lib/typesseq-xrange.html" rel="nofollow">3.6.3 XRange Type</a> :</p> <blockquote> <p>"3.6.3 XRange Type</p> <p>The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take t...
0
2009-10-11T00:07:56Z
[ "python" ]
Managing object instances
1,427,479
<p>I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.</p> <p>Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.</p> <pr...
1
2009-09-15T14:18:36Z
1,427,506
<p><strong>"I could use an associative array"</strong> Correct.</p> <p><strong>"the array is the only method I know for doing this."</strong></p> <p>Learn about "Mappings" or "Dictionaries" as soon as you can. You will find that it does exactly what you're asking for.</p> <p>What language are you using? If you pro...
3
2009-09-15T14:22:52Z
[ "javascript", "python", "actionscript-3", "oop" ]
Managing object instances
1,427,479
<p>I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.</p> <p>Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.</p> <pr...
1
2009-09-15T14:18:36Z
1,427,512
<p>This what collection classes (lists, dictionaries/maps, sets) are for; to collect a number of instances. For the above case I would probably use a map (class name varies depending on language) from name to object. </p>
2
2009-09-15T14:23:56Z
[ "javascript", "python", "actionscript-3", "oop" ]
Managing object instances
1,427,479
<p>I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.</p> <p>Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.</p> <pr...
1
2009-09-15T14:18:36Z
1,429,344
<pre><code>#!/usr/bin/env python """Playing with pets. """ class Pet(object): """A pet with a name.""" def __init__(self, name): """Create a pet with a `name`. """ self._name = name @property def name(self): # name is read-only return self._name def __repr__...
0
2009-09-15T20:06:13Z
[ "javascript", "python", "actionscript-3", "oop" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks ...
0
2009-09-15T15:24:20Z
1,427,881
<p>why are you importing from <code>XWinInfos</code>? you should be importing from <code>SomeUtils</code>. Not to mention that <code>*</code>-style imports are discouraged.</p> <p><strong>Edit</strong>: your error</p> <blockquote> <p>ImportError: cannot import name MyClass1</p> </blockquote> <p>basically tells you...
2
2009-09-15T15:28:46Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks ...
0
2009-09-15T15:24:20Z
1,427,899
<p>You may want to rewrite main.py as follows:</p> <pre><code>import SomeUtils as util def main(): util.funct1() # Use funct1 without problem; aMyObj1 = util.MyClass1() # Use MyClass1 with error if __name__ == "__main__": main() </code></pre> <p>A few quick notes:</p> <ul> <li>There i...
1
2009-09-15T15:31:25Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks ...
0
2009-09-15T15:24:20Z
1,427,902
<p>I suppose you mean </p> <pre><code>from SomeUtils import * </code></pre> <p>however, that does not trigger the error for me. This works fine for me:</p> <p>SomeUtils.py</p> <pre><code>def funct1(): print 4 class MyClass1: def __init__(self): print 8 </code></pre> <p>main.py</p> <pre><code>from...
1
2009-09-15T15:31:57Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks ...
0
2009-09-15T15:24:20Z
1,427,920
<p>Hmm... there's several typos in your example, so I wonder if your actual code has some typos as well. Here's the complete source from a quick test that does work fine without import errors.</p> <p>SomeUtils.py:</p> <pre><code>def funct1(): print('Function 1') def funct2(): print('Function 2') class MyCl...
3
2009-09-15T15:34:44Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks ...
0
2009-09-15T15:24:20Z
1,428,131
<p>Your question is naturally linked to a lot of SO older one. See, just for reference, <a href="http://stackoverflow.com/questions/1342128/problem-with-python-and-import">SO1342128</a> and <a href="http://stackoverflow.com/questions/1057843/python-import-problem">SO1057843</a></p>
0
2009-09-15T16:12:13Z
[ "python", "import" ]
Encoding issues with python's etree.tostring
1,428,172
<p>I'm using python 2.6.2's xml.etree.cElementTree to create an xml document:</p> <pre><code>import xml.etree.cElementTree as etree elem = etree.Element('tag') elem.text = (u"Würth Elektronik Midcom").encode('utf-8') xml = etree.tostring(elem,encoding='UTF-8') </code></pre> <p>At the end of the day, xml looks like:<...
7
2009-09-15T16:20:37Z
1,428,220
<p>You're encoding the text twice. Try this:</p> <pre><code>import xml.etree.cElementTree as etree elem = etree.Element('tag') elem.text = u"Würth Elektronik Midcom" xml = etree.tostring(elem,encoding='UTF-8') </code></pre>
16
2009-09-15T16:30:15Z
[ "python", "xml", "utf-8", "tostring" ]
python html integration
1,428,260
<p>this is a complete n00b question and i understand i may get voted down for asking this but i am totally confused over python's html integration. as i understand one way to integrate python with html code is by using mod_python. now, is there any other way or method that is more effective for using python with html?<...
0
2009-09-15T16:37:27Z
1,428,306
<p>You can read a tutorial on how to use Python in the web.</p> <p><a href="http://docs.python.org/howto/webservers.html" rel="nofollow">http://docs.python.org/howto/webservers.html</a></p> <p>In few words, mod_python keeps python interpreter in memory ready to execute python scripts, which is faster than launching i...
2
2009-09-15T16:44:34Z
[ "python", "html" ]
python html integration
1,428,260
<p>this is a complete n00b question and i understand i may get voted down for asking this but i am totally confused over python's html integration. as i understand one way to integrate python with html code is by using mod_python. now, is there any other way or method that is more effective for using python with html?<...
0
2009-09-15T16:37:27Z
1,428,314
<p>I would suggest you to start with <a href="http://webpy.org/tutorial3.en" rel="nofollow">web.py</a></p>
3
2009-09-15T16:46:04Z
[ "python", "html" ]
python html integration
1,428,260
<p>this is a complete n00b question and i understand i may get voted down for asking this but i am totally confused over python's html integration. as i understand one way to integrate python with html code is by using mod_python. now, is there any other way or method that is more effective for using python with html?<...
0
2009-09-15T16:37:27Z
1,428,475
<p>The standard way for Python web apps to talk to a webserver is WSGI. Also check out WebOb.</p> <ul> <li><a href="http://www.wsgi.org/wsgi/" rel="nofollow">http://www.wsgi.org/wsgi/</a></li> <li><a href="http://pythonpaste.org/webob/" rel="nofollow">http://pythonpaste.org/webob/</a></li> </ul> <p>But for a complete...
1
2009-09-15T17:13:28Z
[ "python", "html" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,588
<p>I'd go for:</p> <pre><code>s="abcdefgh" print "".join(b+a for a,b in zip(s[::2],s[1::2])) </code></pre> <p>s[start:end:step] takes every step'th letter, zip matches them up pairwise, the loop swaps them, and the join gives you back a string.</p>
13
2009-09-15T17:39:11Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,604
<p>Since in Python, every string is also an iterable, <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools</a> comes in handy here.</p> <p>In addition to the functions itertools provides, the documentation also supplies lots of recipes.</p> <pre><code>from itertools import izip_longest # ...
1
2009-09-15T17:42:05Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,609
<pre><code>''.join(s[i+1] + s[i] for i in range(0,len(s),2)) </code></pre> <p>Yes, I know it's less pythonic for using range, but it's short, and I probably don't have to explain it for you to figure out what it does.</p>
5
2009-09-15T17:42:45Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,761
<p>my personal favorite to do stuff pairwise:</p> <pre><code>def pairwise( iterable ): it = iter(iterable) return zip(it, it) # zipping the same iterator twice produces pairs output = ''.join( b+a for a,b in pairwise(input)) </code></pre>
6
2009-09-15T18:04:19Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,429,170
<p>I just noticed that <em>none</em> of the existing answers work if the length of the input is odd. Most of the answers lose the last character. My previous answer throws an exception.</p> <p>If you just want the last character tacked onto the end, you could do something like this:</p> <pre><code>print "".join(map(l...
2
2009-09-15T19:28:13Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,429,303
<p>This may look a little scary, but I think you'd learn a lot deciphering the following idiom:</p> <pre><code>s = "abcdefgh" print ''.join(b+a for a,b in zip(*[iter(s)]*2)) </code></pre>
0
2009-09-15T19:55:16Z
[ "python" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say...
3
2009-09-15T18:07:11Z
1,428,802
<p>You can use a reluctant qualifier in your pattern (for more details, reference the <a href="http://docs.python.org/library/re.html">python documentation</a> on the <code>*?</code>, <code>+?</code>, and <code>??</code> operators):</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*?&lt;/blabla&gt;&lt;bla&gt; </code></pr...
10
2009-09-15T18:11:28Z
[ "python", "regex" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say...
3
2009-09-15T18:07:11Z
1,428,805
<p>Um... there is a way to tell re to find the smallest match, and it's precisely by using <em>non-greedy</em> quantifiers.</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*?&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>I can't imagine why you would want to do it while using greedy quantifiers.</p>
0
2009-09-15T18:11:59Z
[ "python", "regex" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say...
3
2009-09-15T18:07:11Z
1,428,808
<p>The Python re module supports nongreedy matching. You just add a <code>?</code> to the end of the wildcard pattern, such as <code>.*?</code>. You can learn more at <a href="http://www.amk.ca/python/howto/regex/regex.html#SECTION000730000000000000000" rel="nofollow">this HOWTO</a>.</p>
1
2009-09-15T18:12:44Z
[ "python", "regex" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say...
3
2009-09-15T18:07:11Z
1,429,209
<pre><code>I believe the regex &lt;bla&gt;&lt;blabla&gt;87765.*?&lt;/blabla&gt;&lt;bla&gt; can produce catastrophic backtracking. Instead, use: &lt;bla&gt;&lt;blabla&gt;87765[^&lt;]*&lt;/blabla&gt;&lt;bla&gt; Using atomic grouping (I'm not sure Python supports this), the above regex becomes &lt;bla&gt;&lt;blabla&gt...
1
2009-09-15T19:34:40Z
[ "python", "regex" ]
In Django, how to call a subprocess with a slow start-up time
1,428,900
<p>Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called <strong><em>cmd</em></strong> that operates on a file that the view creates, for example likeso:</p> <pre><code> def call_subprocess(request): response = HttpResponse() with t...
4
2009-09-15T18:29:06Z
1,430,277
<p>How about "daemonizing" the subprocess call using <a href="http://www.clapper.org/software/python/daemon/" rel="nofollow">python-daemon</a> or its successor, <a href="http://www.clapper.org/software/python/grizzled/" rel="nofollow">grizzled</a>. </p>
0
2009-09-16T00:15:06Z
[ "python", "django", "multithreading", "fork", "subprocess" ]
In Django, how to call a subprocess with a slow start-up time
1,428,900
<p>Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called <strong><em>cmd</em></strong> that operates on a file that the view creates, for example likeso:</p> <pre><code> def call_subprocess(request): response = HttpResponse() with t...
4
2009-09-15T18:29:06Z
1,431,761
<p>It may seem like i am punting this product as this is the second time i have responded with a recommendation of this.</p> <p>But it seems like you need a Message Queing service, in particular a distributed message queue.</p> <p>ere is how it will work:</p> <ol> <li>Your Django App requests CMD</li> <li>CMD gets a...
3
2009-09-16T08:48:24Z
[ "python", "django", "multithreading", "fork", "subprocess" ]
In Django, how to call a subprocess with a slow start-up time
1,428,900
<p>Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called <strong><em>cmd</em></strong> that operates on a file that the view creates, for example likeso:</p> <pre><code> def call_subprocess(request): response = HttpResponse() with t...
4
2009-09-15T18:29:06Z
1,445,760
<p>Issy already mentioned Celery, but since comments doesn't work well with code samples, I'll reply as an answer instead.</p> <p>You should try to use Celery synchronously with the AMQP result store. You could distribute the actual execution to another process or even another machine. Executing synchronously in celer...
3
2009-09-18T17:05:58Z
[ "python", "django", "multithreading", "fork", "subprocess" ]
Python 3 smtplib send with unicode characters
1,429,147
<p>I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:</p> <pre><code> import smtplib from email.mime.text import MIMEText sender = to = 'ABC@DEF.com' server = 'smtp.DEF.com' msg = MIMEText('€10') msg['Subject'] = 'Hello' msg['From'] = s...
7
2009-09-15T19:22:08Z
1,429,232
<p><code>_charset</code> parameter of <code>MIMEText</code> defaults to <code>us-ascii</code> according to the <a href="http://docs.python.org/library/email.mime.html#email.mime.text.MIMEText" rel="nofollow">docs</a>. Since <code>€</code> is not from us-ascii set it isn't working.</p> <p>example in the docs that you...
2
2009-09-15T19:39:43Z
[ "python", "email", "unicode", "python-3.x", "smtplib" ]
Python 3 smtplib send with unicode characters
1,429,147
<p>I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:</p> <pre><code> import smtplib from email.mime.text import MIMEText sender = to = 'ABC@DEF.com' server = 'smtp.DEF.com' msg = MIMEText('€10') msg['Subject'] = 'Hello' msg['From'] = s...
7
2009-09-15T19:22:08Z
1,430,542
<p>The key is in <a href="http://docs.python.org/3.1/library/email.mime.html#email.mime.text.MIMEText" rel="nofollow">the docs</a>:</p> <pre><code>class email.mime.text.MIMEText(_text, _subtype='plain', _charset='us-ascii') </code></pre> <blockquote> <p>A subclass of MIMENonMultipart, the MIMEText class is used t...
8
2009-09-16T02:00:56Z
[ "python", "email", "unicode", "python-3.x", "smtplib" ]
Python 3 smtplib send with unicode characters
1,429,147
<p>I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:</p> <pre><code> import smtplib from email.mime.text import MIMEText sender = to = 'ABC@DEF.com' server = 'smtp.DEF.com' msg = MIMEText('€10') msg['Subject'] = 'Hello' msg['From'] = s...
7
2009-09-15T19:22:08Z
2,262,800
<p>Gus Mueller had a similar issue: <a href="http://bugs.python.org/issue4403" rel="nofollow">http://bugs.python.org/issue4403</a></p>
1
2010-02-14T21:12:34Z
[ "python", "email", "unicode", "python-3.x", "smtplib" ]
Using GetExtendedTcpTable in Python
1,429,403
<p>I am trying to use GetExtendedTcpTable via a Python program. Basically I am trying to convert "ActiveState Code Recipe 392572: Using the Win32 IPHelper API" to <a href="http://www.codeproject.com/KB/IP/iphlpapi2.aspx" rel="nofollow">"Getting the active TCP/UDP connections using the GetExtendedTcpTable function"</a>...
0
2009-09-15T20:20:34Z
1,429,449
<p>The TCP_TABLE_CLASS is an enum</p> <pre> typedef enum { TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS, TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER, TCP_TABLE_OWNER_PID_CONNECTIONS, TCP_TABLE_OWNER_PID_ALL, TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS, TCP_TABL...
1
2009-09-15T20:30:19Z
[ "python", "winapi" ]
Using GetExtendedTcpTable in Python
1,429,403
<p>I am trying to use GetExtendedTcpTable via a Python program. Basically I am trying to convert "ActiveState Code Recipe 392572: Using the Win32 IPHelper API" to <a href="http://www.codeproject.com/KB/IP/iphlpapi2.aspx" rel="nofollow">"Getting the active TCP/UDP connections using the GetExtendedTcpTable function"</a>...
0
2009-09-15T20:20:34Z
1,429,480
<p>In this case, since: </p> <blockquote> <p>typedef enum { TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS, TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER, TCP_TABLE_OWNER_PID_CONNECTIONS, <strong>TCP_TABLE_OWNER_PID_ALL</strong>, TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_...
0
2009-09-15T20:37:03Z
[ "python", "winapi" ]
Does Python have an equivalent to 'switch'?
1,429,505
<p>I am trying to check each index in an 8 digit binary string. If it is <code>'0'</code> then it is <code>'OFF'</code> otherwise its <code>'ON'</code>.</p> <p>Is there a more concise way to write this code with a switch-like feature.?</p>
13
2009-09-15T20:41:33Z
1,429,518
<p><a href="http://docs.python.org/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python">"Why isn't there a switch or case statement in Python?"</a></p>
27
2009-09-15T20:43:18Z
[ "python", "syntax", "switch-statement" ]
Does Python have an equivalent to 'switch'?
1,429,505
<p>I am trying to check each index in an 8 digit binary string. If it is <code>'0'</code> then it is <code>'OFF'</code> otherwise its <code>'ON'</code>.</p> <p>Is there a more concise way to write this code with a switch-like feature.?</p>
13
2009-09-15T20:41:33Z
1,429,537
<p>No it doesn't. In the Python core language, one of the rules is to only have one way to do something. The switch is redundant to:</p> <pre><code>if x == 1: pass elif x == 5: pass elif x == 10: pass </code></pre> <p>(without the fall-through, of course).</p> <p>The switch was originally introduced as...
15
2009-09-15T20:48:50Z
[ "python", "syntax", "switch-statement" ]
Does Python have an equivalent to 'switch'?
1,429,505
<p>I am trying to check each index in an 8 digit binary string. If it is <code>'0'</code> then it is <code>'OFF'</code> otherwise its <code>'ON'</code>.</p> <p>Is there a more concise way to write this code with a switch-like feature.?</p>
13
2009-09-15T20:41:33Z
1,429,546
<p>Try this instead:</p> <pre><code>def on_function(*args, **kwargs): # do something def off_function(*args, **kwargs): # do something function_dict = { '0' : off_function, '1' : on_function } for ch in binary_string: function_dict[ch]() </code></pre> <p>Or you could use a list comprehension or generato...
6
2009-09-15T20:50:47Z
[ "python", "syntax", "switch-statement" ]
How to programmatically set a global (module) variable?
1,429,814
<p>I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for definition in definitions.items(): exec("%s = %r" % definition) # a = 1, etc. </code></pre> <p>Specifically, I want to create a module <code>f...
22
2009-09-15T21:50:47Z
1,429,835
<p>You can set globals in the dictionary returned by globals():</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for name, value in definitions.items(): globals()[name] = value </code></pre>
26
2009-09-15T21:56:13Z
[ "python", "module", "global-variables" ]
How to programmatically set a global (module) variable?
1,429,814
<p>I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for definition in definitions.items(): exec("%s = %r" % definition) # a = 1, etc. </code></pre> <p>Specifically, I want to create a module <code>f...
22
2009-09-15T21:50:47Z
1,430,039
<p>You're right, <code>exec</code> is usually a bad idea and it certainly isn't needed in this case.</p> <p>Ned's answer is fine. Another possible way to do it if you're a module is to import yourself:</p> <p>fundamentalconstants.py:</p> <pre><code>import fundamentalconstants fundamentalconstants.life_meaning= 42 ...
3
2009-09-15T22:49:04Z
[ "python", "module", "global-variables" ]
How to programmatically set a global (module) variable?
1,429,814
<p>I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for definition in definitions.items(): exec("%s = %r" % definition) # a = 1, etc. </code></pre> <p>Specifically, I want to create a module <code>f...
22
2009-09-15T21:50:47Z
1,430,178
<p>Here is a better way to do it:</p> <pre><code>import sys definitions = {'a': 1, 'b': 2, 'c': 123.4} module = sys.modules[__name__] for name, value in definitions.iteritems(): setattr(module, name, value) </code></pre>
33
2009-09-15T23:37:45Z
[ "python", "module", "global-variables" ]
Configuring Roundup with Apache
1,430,364
<p>I think I just need a bit more guidance than what the documentation gives, and it's quite hard to find anything relating to Roundup and Apache specifically.</p> <p>All i'm trying to do currently is to have Apache display what the stand-alone server does when running roundup-server support=C:/Roundup/</p> <p>Runnin...
2
2009-09-16T00:52:31Z
1,430,601
<p>It is fairly easy to run roundup under Apache if you use <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a>.</p> <p>Unfortunately I've since moved away from roundup and no longer have a copy of my wsgi script to show you, but you should be able to figure it out from this <a href="http://markmai...
1
2009-09-16T02:19:33Z
[ "python", "apache", "roundup" ]
Configuring Roundup with Apache
1,430,364
<p>I think I just need a bit more guidance than what the documentation gives, and it's quite hard to find anything relating to Roundup and Apache specifically.</p> <p>All i'm trying to do currently is to have Apache display what the stand-alone server does when running roundup-server support=C:/Roundup/</p> <p>Runnin...
2
2009-09-16T00:52:31Z
1,431,346
<p>First, requires the following modules enabled:</p> <pre><code>LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule proxy_ftp_module modu...
3
2009-09-16T06:46:30Z
[ "python", "apache", "roundup" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a...
21
2009-09-16T01:16:58Z
1,430,484
<p>How about using</p> <pre><code>d = mkdtemp() t = os.path.join(d, 'fifo') </code></pre>
3
2009-09-16T01:36:12Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a...
21
2009-09-16T01:16:58Z
1,430,486
<p>Why not just use <a href="http://docs.python.org/library/tempfile.html#tempfile.mkstemp" rel="nofollow">mkstemp()</a>?</p> <p>For example:</p> <pre><code>import tempfile import os handle, filename = tempfile.mkstemp() os.mkfifo(filename) writer = open(filename, os.O_WRONLY) reader = open(filename, os.O_RDONLY) os...
-1
2009-09-16T01:37:37Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a...
21
2009-09-16T01:16:58Z
1,430,494
<p>If it's for use within your program, and not with any externals, have a look at the <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue module</a>. As an added benefit, python queues are thread-safe.</p>
3
2009-09-16T01:42:29Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a...
21
2009-09-16T01:16:58Z
1,430,566
<p><code>os.mkfifo()</code> will fail with exception <code>OSError: [Errno 17] File exists</code> if the file already exists, so there is no security issue here. The security issue with using <code>tempfile.mktemp()</code> is the race condition where it is possible for an attacker to create a file with the same name be...
19
2009-09-16T02:09:15Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a...
21
2009-09-16T01:16:58Z
32,597,858
<p>Effectively, all that <code>mkstemp</code> does is run <code>mktemp</code> in a loop and keeps attempting to exclusively create until it succeeds (see stdlib source code <a href="https://hg.python.org/cpython/file/2.7/Lib/tempfile.py#l235" rel="nofollow">here</a>). You can do the same with <code>os.mkfifo</code>:</p...
0
2015-09-16T00:34:37Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Application to generate installers for Linux, Windows and MacOSX from a single configuration
1,430,497
<p>Here's what I want:</p> <p>Given a set of definitions (preferably in Python) on what files to install where and what post-install script to run, etc.. I would like this program to generate installers for the three major platforms:</p> <ul> <li>MSI on Windows</li> <li>dmg on MacOSX</li> <li>Tarball w/ install.sh (a...
2
2009-09-16T01:43:44Z
1,430,520
<p>Your requirements are probably such that hand-rolling a make script to do these things is the order of the day. Or write it in python if you don't like make. It will be more flexible and probably faster than trying to learn some proprietary scripting language from some installer creator. Anything with a fancy gui an...
0
2009-09-16T01:52:54Z
[ "python", "installer", "cross-platform", "wix", "dmg" ]
Application to generate installers for Linux, Windows and MacOSX from a single configuration
1,430,497
<p>Here's what I want:</p> <p>Given a set of definitions (preferably in Python) on what files to install where and what post-install script to run, etc.. I would like this program to generate installers for the three major platforms:</p> <ul> <li>MSI on Windows</li> <li>dmg on MacOSX</li> <li>Tarball w/ install.sh (a...
2
2009-09-16T01:43:44Z
1,430,619
<p>perhaps <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">paver</a> can be made to meet your needs? you'd have to add the msi, dmg, tgz, etc parts as tasks using some external library, but i believe it can be done.</p>
0
2009-09-16T02:25:11Z
[ "python", "installer", "cross-platform", "wix", "dmg" ]
Application to generate installers for Linux, Windows and MacOSX from a single configuration
1,430,497
<p>Here's what I want:</p> <p>Given a set of definitions (preferably in Python) on what files to install where and what post-install script to run, etc.. I would like this program to generate installers for the three major platforms:</p> <ul> <li>MSI on Windows</li> <li>dmg on MacOSX</li> <li>Tarball w/ install.sh (a...
2
2009-09-16T01:43:44Z
1,430,658
<p>Look into <a href="http://www.cmake.org/Wiki/CMake%3APackaging%5FWith%5FCPack" rel="nofollow">CPack</a>. It works very well with CMake, if you use that for your build system, but it also works without it. This uses CMake-type syntax, not Python, but it can generate NSIS installers, ZIP archives, binary executables o...
2
2009-09-16T02:38:18Z
[ "python", "installer", "cross-platform", "wix", "dmg" ]
Kill sub-threads when Django restarts?
1,430,517
<p>I'm running Django, and I'm creating threads that run in parallel while Django runs. Those threads sometimes run external processes that block while waiting for external input.</p> <p>When I restart Django, those threads that are blocking while awaiting external input sometimes persist through the restart, and furt...
0
2009-09-16T01:51:58Z
1,430,541
<p>What are you using to restart django? I'd put something in that script to look for process id's in the socket file(s) and kill those before starting django.</p> <p>Alternatively, you could be very heavy handed and just run something like 'pkill -9 *django*' before your django startup sequence.</p>
0
2009-09-16T02:00:45Z
[ "python", "django", "multithreading" ]
Kill sub-threads when Django restarts?
1,430,517
<p>I'm running Django, and I'm creating threads that run in parallel while Django runs. Those threads sometimes run external processes that block while waiting for external input.</p> <p>When I restart Django, those threads that are blocking while awaiting external input sometimes persist through the restart, and furt...
0
2009-09-16T01:51:58Z
1,430,786
<p>It's not easy for a Python process to kill its own threads -- even harder (nearly impossible) to kill the threads of <em>another</em> process, and I suspect the latter is the case you have... the "restart" is presumably happening on a different process, so those threads are more or less out of bounds for you!</p> <...
1
2009-09-16T03:26:38Z
[ "python", "django", "multithreading" ]
Load an existing many-to-many table relation with sqlalchemy
1,430,584
<p>I'm using SqlAlchemy to interact with an existing PostgreSQL database. </p> <p>I need to access data organized in a many-to-many relationship. The documentation describes how to create relationships, but I cannot find an example for neatly loading and query an existing one.</p>
1
2009-09-16T02:12:36Z
1,433,074
<p>Querying an existing relation is not really different than creating a new one. You pretty much write the same code but specify the table and column names that are already there, and of course you won't need SQLAlchemy to issue the <code>CREATE TABLE</code> statements.</p> <p>See <a href="http://www.sqlalchemy.org/d...
1
2009-09-16T13:47:02Z
[ "python", "sqlalchemy" ]
Python: Traversing a string, checking its element, and inputting dictionary key-value pairs
1,430,957
<p>I have a function that returns an 8 digit long binary string for given parameter:</p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) return rule </code></pre> <p>I want to traverse each index of this string and check if it is a zero or a one. I tried to write a code like this: </p> <pre><code>def rule(x): ...
0
2009-09-16T04:34:57Z
1,430,984
<p>Here's a much more Pythonic version of the code you've written - hopefully the comments explain the code well enough to understand.</p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) ruleDict = {} # create an empty dictionary for i,c in enumerate(rule): # i = index, c = character at index, for each ...
0
2009-09-16T04:44:47Z
[ "python" ]
Python: Traversing a string, checking its element, and inputting dictionary key-value pairs
1,430,957
<p>I have a function that returns an 8 digit long binary string for given parameter:</p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) return rule </code></pre> <p>I want to traverse each index of this string and check if it is a zero or a one. I tried to write a code like this: </p> <pre><code>def rule(x): ...
0
2009-09-16T04:34:57Z
1,431,036
<p>Is this what you want?</p> <pre><code>def rule(x) : rule = bin(x)[2:].zfill(8) return dict((index, 'ON' if int(i) else 'OFF') for index, i in enumerate(rule)) </code></pre>
2
2009-09-16T05:04:45Z
[ "python" ]
Accessing Plist items in a dict
1,431,424
<p>I have a class in a module I that reads a plist (XML) file and returns a dict. This is extremely convenient because I can say something like:</p> <pre><code>Data.ServerNow.Property().DefaultChart </code></pre> <p>This returns a property dictionary, specifically the value for <code>DefaultChart</code>. Very elegant...
0
2009-09-16T07:10:04Z
1,431,776
<p>It doesn't work because the dot operator is not proper accessor syntax for python dictionaries. You;re trying to treat it as an object and access a property, rather than accessing a data member of the data structure.</p>
2
2009-09-16T08:51:00Z
[ "python", "xml", "namespaces", "plist" ]
Accessing Plist items in a dict
1,431,424
<p>I have a class in a module I that reads a plist (XML) file and returns a dict. This is extremely convenient because I can say something like:</p> <pre><code>Data.ServerNow.Property().DefaultChart </code></pre> <p>This returns a property dictionary, specifically the value for <code>DefaultChart</code>. Very elegant...
0
2009-09-16T07:10:04Z
1,431,828
<p>You can use getattr redefinition to treat dictionary keys as attributes, e.g.:</p> <pre><code>class xmldict(dict): def __getattr__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: if attr in self: return self[attr] ...
1
2009-09-16T09:05:03Z
[ "python", "xml", "namespaces", "plist" ]
What is the keycode for control+z key in python?
1,431,495
<p>I want to send some modem AT commands using python code, and am wondering what is the keycode for the key combination <strong>control+z</strong></p> <p>Gath</p>
2
2009-09-16T07:30:23Z
1,431,524
<p>Key code? If you send AT commands you are probably sending strings with ascii text and control codes, right? Ctrl-Z is usually 26 (decimal). So chr(26) should work, or if it's a part of a string, '\x1a' as 26 decimal is 1A hex.</p> <p>That said, Ctrl-Z is not usually a part of the AT command set... so if this doesn...
5
2009-09-16T07:38:03Z
[ "python" ]
Is it possible to run pydev connected to a virtualbox instance?
1,431,936
<p>At the moment I'm developing using a simple editor, putty, and a VirtualBox instance of a linux server. I've heard good things about pydev and would like to try it, but I'd like to use the python install &amp; terminal from my VirtualBox guest OS.</p> <p>I'm already using a Shared Folder with VirtualBox so my Guest...
0
2009-09-16T09:26:45Z
1,432,066
<p>UPDATE: Let me understand the situation, Windows is hosting the virtualBox which host the linux. You connect to the linux using putty. Python files are on the linux machine and you wish to edit them from your Windows using pydev. So either do that using the sharing features of virtual box (which can work for you in ...
0
2009-09-16T10:00:47Z
[ "python", "linux", "virtualbox", "pydev" ]
Is it possible to run pydev connected to a virtualbox instance?
1,431,936
<p>At the moment I'm developing using a simple editor, putty, and a VirtualBox instance of a linux server. I've heard good things about pydev and would like to try it, but I'd like to use the python install &amp; terminal from my VirtualBox guest OS.</p> <p>I'm already using a Shared Folder with VirtualBox so my Guest...
0
2009-09-16T09:26:45Z
1,432,475
<p>I assume your host box is windows.</p> <p>I also assume that pydev will run under linux (since it's eclipse based). Are you ok installing the dev environment on your linux server?</p> <p>In which case:</p> <ol> <li>install and run <a href="http://sourceforge.net/projects/xming/" rel="nofollow">xming</a> on your w...
1
2009-09-16T11:45:59Z
[ "python", "linux", "virtualbox", "pydev" ]
Add an "empty" option to a ChoiceField based on model datas
1,431,966
<p>I'm defining a ChoiceField based on a model's datas.</p> <pre><code>field = forms.ChoiceField(choices=[[r.id, r.name] for r in Model.objects.all()]) </code></pre> <p>However I'd like to prepend my options with an empty one to select "no" objects. But I can't find a nice way to prepend that.</p> <p>All my tests li...
2
2009-09-16T09:34:08Z
1,432,100
<p>An easy answer is to do:</p> <pre><code>field = forms.ChoiceField(choices=[[0, '----------']] + [[r.id, r.name] for r in Model.objects.all()]) </code></pre> <p>Unfortunately, your approach is flawed. Even with your 'working' approach, the field choices are defined when the form is defined, not when it is instantia...
8
2009-09-16T10:08:23Z
[ "python", "django", "forms", "choicefield" ]
Casting regex arguments into a list
1,431,968
<p>Greetings,</p> <p>A script is working on one or more files. I want to pass the filenames (with regex in them) as arguments and put them in a list. What is the best way to do it?</p> <p>For example I would accept the following arguments:</p> <pre><code>script.py file[1-3].nc #would create list [file1.nc, file2.nc,...
1
2009-09-16T09:34:25Z
1,432,010
<p>Updated: Under Unix, the shell will do the example expansions you want. Under Windows it won't, and then you need to use glob.glob().</p> <p>But if you really <em>do</em> want regexp: Then you will simply have to list the directory, with listdir, and match the filenames with the regexp pattern. You'll also have to ...
1
2009-09-16T09:44:14Z
[ "python", "regex" ]
Casting regex arguments into a list
1,431,968
<p>Greetings,</p> <p>A script is working on one or more files. I want to pass the filenames (with regex in them) as arguments and put them in a list. What is the best way to do it?</p> <p>For example I would accept the following arguments:</p> <pre><code>script.py file[1-3].nc #would create list [file1.nc, file2.nc,...
1
2009-09-16T09:34:25Z
1,432,076
<p>The <a href="http://docs.python.org/library/glob.html" rel="nofollow">glob</a> module is exactly what you are looking for</p> <p>Check the examples:</p> <pre><code>&gt;&gt;&gt; import glob &gt;&gt;&gt; glob.glob('./[0-9].*') ['./1.gif', './2.txt'] &gt;&gt;&gt; glob.glob('*.gif') ['1.gif', 'card.gif'] &gt;&gt;&gt; ...
4
2009-09-16T10:02:21Z
[ "python", "regex" ]
In which module does the Timer class reside in python?
1,432,068
<p>Am reading the following online <a href="http://www.python.org/doc/2.5.2/lib/timer-objects.html" rel="nofollow">Timer</a> manual for python 2.5, but am wondering where is the actual module where the class Timer resides?</p> <p>Gath</p>
3
2009-09-16T10:01:05Z
1,432,074
<p>It's in the <code>threading</code> module.</p>
1
2009-09-16T10:02:20Z
[ "python", "timer" ]
In which module does the Timer class reside in python?
1,432,068
<p>Am reading the following online <a href="http://www.python.org/doc/2.5.2/lib/timer-objects.html" rel="nofollow">Timer</a> manual for python 2.5, but am wondering where is the actual module where the class Timer resides?</p> <p>Gath</p>
3
2009-09-16T10:01:05Z
1,432,125
<p>The way to figure this out: on the page you linked to, there's an Up link. It goes to the threading module.</p>
6
2009-09-16T10:13:26Z
[ "python", "timer" ]
deleting files with python scripts
1,432,122
<p>I want to delete some files with python scripts (while using Windows). I have tried the following code:</p> <pre><code>&gt;&gt;&gt;import os &gt;&gt;&gt; os.remove ('D:\new.docx') </code></pre> <p>but I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", ...
2
2009-09-16T10:11:59Z
1,432,128
<p><code>\</code> is the escape char for python. try replacing it with <code>\\</code> .</p> <p>ex:</p> <pre><code>os.remove ('D:\\new.docx') </code></pre>
6
2009-09-16T10:13:43Z
[ "python", "file" ]
deleting files with python scripts
1,432,122
<p>I want to delete some files with python scripts (while using Windows). I have tried the following code:</p> <pre><code>&gt;&gt;&gt;import os &gt;&gt;&gt; os.remove ('D:\new.docx') </code></pre> <p>but I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", ...
2
2009-09-16T10:11:59Z
1,432,164
<p>A few options:</p> <p>Escape the <code>backslash</code>:</p> <pre><code>&gt;&gt;&gt; os.remove('D:\\new.docx') </code></pre> <p>The runtime library in Windows accepts a <code>forward slash</code> as a separator:</p> <pre><code>&gt;&gt;&gt; os.remove('D:/new.docx') </code></pre> <p><a href="http://docs.python.or...
6
2009-09-16T10:27:02Z
[ "python", "file" ]
how to get content of a small ascii file in python?
1,432,126
<p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p> <p>What is the best practice? (elegant and reliable)</p> <p>Here are some proposition, are they correct?</p> <p>using <code>with</code> statement:<...
20
2009-09-16T10:13:28Z
1,432,151
<p><code>with</code> will make sure that the file is closed when the block is left.</p> <p>In your second example, the file handle might remain open (Python makes no guarantee that it's closed or when if you don't do it explicitly).</p>
2
2009-09-16T10:21:55Z
[ "python", "file" ]
how to get content of a small ascii file in python?
1,432,126
<p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p> <p>What is the best practice? (elegant and reliable)</p> <p>Here are some proposition, are they correct?</p> <p>using <code>with</code> statement:<...
20
2009-09-16T10:13:28Z
1,432,169
<pre><code>import os def file_get_contents(filename): if os.path.exists(filename): fp = open(filename, "r") content = fp.read() fp.close() return content </code></pre> <p>This case it will return None if the file didn't exist, and the file descriptor will be closed before we exit the function.</p>
1
2009-09-16T10:29:12Z
[ "python", "file" ]