title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Getting an input/output error from Python with pySerial
994,538
<p>I have a Python script that writes data packets to an Arduino board through <a href="http://pyserial.sourceforge.net/" rel="nofollow">pySerial</a>. Sometimes while writing the code to the board pySerial raises an input/output error with errno 5.</p> <p>Some research says that this indicates an error while writing in the file representing the connection to the Arduino board.</p> <p>The code that sends, sends only single byte packets: </p> <pre><code>try: # Check if it's already a single byte if isinstance(byte, str): if len(byte) == 1: # It is. Send it. self.serial.write(byte) else: # It's not raise PacketException # Check if it's an integer elif isinstance(byte, int): self.serial.write(chr(byte)) # It is; convert it to a byte and send it else: raise PacketException # I don't know what this is. except Exception as ex: print("Exception is: " + ex.__getitem__() + " " + ex.__str__()) </code></pre> <p>The error printed by this code is:</p> <blockquote> <p>OS Error Input/Output Error Errno 5</p> </blockquote> <p>Is there something wrong in my code while sending? Do I need to check if the serial connection is ready to send something or should there be a delay after the sending? Or could there be a problem with the hardware or the connection with the hardware?</p> <p><strong>Edit</strong>: I looked into the Linux implementation from pyserial and the implementation is only passing the error to my code. So no new real insights from there. Is there a good way to test what is happening in the program?</p>
4
2009-06-15T04:55:26Z
19,815,657
<p>Let me try to offer a few comments that might be helpful to you and other folks with similar problems. First, try to run your Arduino sketch with the Serial Monitor a few times. You can find the Serial Monitor under Tools in the IDE menu. You can also type Ctrl-Shift-M to invoke the Serial Monitor.</p> <p>The Serial Monitor displays what the Arduino sketch sends back to you. However, it also lets you type in data that gets sent to the Arduino sketch. In other words you test and debug both sides of the serial data flow, just using the Serial Monitor.</p> <p>Look at what shows up. It will frequently be quite helpful assuming your sketch tries to send data back via Serial.print(). A few notes. Make absolutely sure that the baud rate set inside the Serial Monitor exactly matches the baud rate in your sketch (9600 is a good choice in almost all cases).</p> <p>The second note is critical. Bringing up the Serial Monitor forces a reset on the Arduino board. Your sketch starts over (always). This is a good thing because it gives you a fresh run each time. Note that you can force a reset, just by setting the baud rate to 9600 (even if it is already 9600). This lets you run many tests inside the Serial Monitor without having to restart the Serial Monitor each time.</p>
0
2013-11-06T15:10:43Z
[ "python", "serial-port", "arduino", "pyserial" ]
trouble with pamie
994,627
<p>I'm having some strange trouble with pamie: <a href="http://pamie.sourceforge.net/" rel="nofollow">http://pamie.sourceforge.net/</a> .</p> <p>I have written a script to do some port (25) forwarding based on a recepie that I found on the web, Here is the code that matters:</p> <pre><code># forwardc2s(source, destination): # forwards from client to server. # Tries to post the message to ICE. def forwardc2s(source, destination): string = ' ' message = '' while string: string = source.recv(1024) if string: if string[:4] == 'DATA' or message &lt;&gt; '': # Put the entire text of the email into a variable: message message = message + string destination.sendall(string) else: posttotracker(message) # post message to tracker. source.shutdown(socket.SHUT_RD) destination.shutdown(socket.SHUT_WR) </code></pre> <p>The 'posttotracker' function is not yet complete... all that it contains is:</p> <pre><code>def posttotracker(message): ie = PAMIE('http://google.com/') </code></pre> <p>This gives me an error as follows:</p> <pre><code>Unhandled exception in thread started by &lt;function forwardc2s at 0x00E6C0B0&gt; Traceback (most recent call last): File "main.py", line 2398, in forwardc2s posttotracker(message) # post message to tracker. File "main.py", line 2420, in posttotracker ie = PAMIE('http://google.com/') File "main.py", line 58, in __init__ self._ie = win32com.client.dynamic.Dispatch('InternetExplorer.Application') File "c:\Python26\lib\site-packages\win32com\client\dynamic.py", line 112, in Dispatch IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx) File "c:\Python26\lib\site-packages\win32com\client\dynamic.py", line 104, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "c:\Python26\lib\site-packages\win32com\client\dynamic.py", line 84, in _ GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II D_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, N one) </code></pre> <p>The funny thing is that if I do the very same thing outside of this function (in the main function for example) the library works exactly as expected.</p> <p>Any ideas?</p> <p>Pardon me if this information is not sufficient, I'm just a starting python coder.</p>
1
2009-06-15T05:48:52Z
994,695
<p><strong>The PAMIE object does not work within threads!!!</strong></p> <p>I was originally starting forwardc2s as a thread. When I just call it as a function instead, everything works fine!</p> <p>Please consider this question resolved... with great thanks to the <a href="http://en.wikipedia.org/wiki/Rubber%5Fduck%5Fdebugging" rel="nofollow">rubber duck</a>.</p>
1
2009-06-15T06:18:26Z
[ "python", "debugging", "pamie" ]
How to strip the 8th bit in a KOI8-R encoded character?
994,710
<p>How to strip the 8th bit in a KOI8-R encoded character so as to have translit for a Russian letter? In particular, how to make it in Python?</p>
1
2009-06-15T06:24:31Z
994,730
<p>I'm not exactly sure what you want, but if you want to zero the 8th bit, it can be done like this:</p> <pre><code>character = character &amp; ~(1 &lt;&lt; 7) </code></pre>
1
2009-06-15T06:32:38Z
[ "python", "encoding" ]
How to strip the 8th bit in a KOI8-R encoded character?
994,710
<p>How to strip the 8th bit in a KOI8-R encoded character so as to have translit for a Russian letter? In particular, how to make it in Python?</p>
1
2009-06-15T06:24:31Z
994,794
<p>Here is one way:</p> <pre><code>import array mask = ~(1 &lt;&lt; 7) def convert(koistring): bytes = array.array('B', koistring) for i in range(len(bytes)): bytes[i] &amp;= mask return bytes.tostring() test = u'Русский Текст'.encode('koi8-r') print convert(test) # rUSSKIJ tEKST </code></pre> <p>I don't know if Python provides a cleaner way to do this kind of operations :)</p>
1
2009-06-15T06:59:51Z
[ "python", "encoding" ]
How to strip the 8th bit in a KOI8-R encoded character?
994,710
<p>How to strip the 8th bit in a KOI8-R encoded character so as to have translit for a Russian letter? In particular, how to make it in Python?</p>
1
2009-06-15T06:24:31Z
994,804
<p>Assuming s is a KOI8-R encoded string you could try this:</p> <pre><code>&gt;&gt;&gt; s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r') &gt;&gt;&gt; s &gt;&gt;&gt; '\xeb\xcf\xc4 \xef\xc2\xcd\xc5\xce\xc1 \xe9\xce\xc6\xcf\xd2\xcd\xc1\xc3\xc9\xc5\xca, 8 \xc2\xc9\xd4' &gt;&gt;&gt; print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) &gt;&gt;&gt; kOD oBMENA iNFORMACIEJ, 8 BIT </code></pre> <p>The 8th bit is stripped by the <code>(ord(c) &amp; 0x7F)</code>.</p>
2
2009-06-15T07:05:12Z
[ "python", "encoding" ]
why does this code break out of loop?
994,729
<pre><code>import math t=raw_input() k=[] a=0 for i in range(0,int(t)): s=raw_input() b=1 c=1 a=int(s) if a==0: continue else: d=math.atan(float(1)/b) + math.atan(float(1)/c) v=math.atan(float(1)/a) print v print d print float(v) print float(d) while(): if float(v)== float(d): break b=b+1 c=c+1 d=math.atan(float(1)/float(b)) + math.atan(float(1)/float(c)) print d k.append(int(b)+int(c)) for i in range(0,int(t)): print k[i] </code></pre> <p>as it's very evident <code>float(v) != float(d)</code> till <code>b</code> becomes 2 and <code>c</code> becomes 3.</p>
0
2009-06-15T06:32:27Z
994,755
<p>Your <code>while</code> loop tests on an empty tuple, which evaluates to <code>False</code>. Thus, the statements within the <code>while</code> loop will never execute:</p> <p>If you want your <code>while</code> loop to run until it encounters a <code>break</code> statement, do this:</p> <pre><code>while True: if (some_condition): break else: # Do stuff... </code></pre>
8
2009-06-15T06:41:37Z
[ "python", "syntax-error" ]
why does this code break out of loop?
994,729
<pre><code>import math t=raw_input() k=[] a=0 for i in range(0,int(t)): s=raw_input() b=1 c=1 a=int(s) if a==0: continue else: d=math.atan(float(1)/b) + math.atan(float(1)/c) v=math.atan(float(1)/a) print v print d print float(v) print float(d) while(): if float(v)== float(d): break b=b+1 c=c+1 d=math.atan(float(1)/float(b)) + math.atan(float(1)/float(c)) print d k.append(int(b)+int(c)) for i in range(0,int(t)): print k[i] </code></pre> <p>as it's very evident <code>float(v) != float(d)</code> till <code>b</code> becomes 2 and <code>c</code> becomes 3.</p>
0
2009-06-15T06:32:27Z
994,775
<p>Well, it didn't reach the break point. The problem is that <code>while()</code> does not loop at all. To do an infinite loop, do <code>while (1):</code> (since the while condition must evaluate to true. Here's a working (cleaned up) sample.</p> <pre><code>import math t = raw_input() k = [] a = 0.0 for i in range(0,int(t)): s = float(raw_input()) b = 1.0 c = 1.0 a= float(s) if a == 0: continue else: d = math.atan(1.0/b) + math.atan(1.0/c) v = math.atan(1.0/a) print v print d while True: if v == d: print 'bar' break b += 1 c += 1 d = math.atan(1.0/b) + math.atan(1.0/c) print d k.append(int(b)+int(c)) for i in range(0,int(t)): print k[i] </code></pre>
0
2009-06-15T06:49:54Z
[ "python", "syntax-error" ]
why does this code break out of loop?
994,729
<pre><code>import math t=raw_input() k=[] a=0 for i in range(0,int(t)): s=raw_input() b=1 c=1 a=int(s) if a==0: continue else: d=math.atan(float(1)/b) + math.atan(float(1)/c) v=math.atan(float(1)/a) print v print d print float(v) print float(d) while(): if float(v)== float(d): break b=b+1 c=c+1 d=math.atan(float(1)/float(b)) + math.atan(float(1)/float(c)) print d k.append(int(b)+int(c)) for i in range(0,int(t)): print k[i] </code></pre> <p>as it's very evident <code>float(v) != float(d)</code> till <code>b</code> becomes 2 and <code>c</code> becomes 3.</p>
0
2009-06-15T06:32:27Z
1,449,752
<p>If is very dangerous to make comparsisons like float(a)==float(b) since float variables have no exact representation. Due to rounding errors you may not have identic values.</p> <p>Even 2*0.5 may not be equal 1. You may use the following:</p> <pre><code>if abs(float(a)-float(b)) &lt; verySmallValue: </code></pre>
2
2009-09-19T23:04:37Z
[ "python", "syntax-error" ]
why does this code break out of loop?
994,729
<pre><code>import math t=raw_input() k=[] a=0 for i in range(0,int(t)): s=raw_input() b=1 c=1 a=int(s) if a==0: continue else: d=math.atan(float(1)/b) + math.atan(float(1)/c) v=math.atan(float(1)/a) print v print d print float(v) print float(d) while(): if float(v)== float(d): break b=b+1 c=c+1 d=math.atan(float(1)/float(b)) + math.atan(float(1)/float(c)) print d k.append(int(b)+int(c)) for i in range(0,int(t)): print k[i] </code></pre> <p>as it's very evident <code>float(v) != float(d)</code> till <code>b</code> becomes 2 and <code>c</code> becomes 3.</p>
0
2009-06-15T06:32:27Z
1,449,753
<p><a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm" rel="nofollow">http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm</a></p> <blockquote> <p>Floating point math is not exact. Simple values like 0.2 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations can change the result. Different compilers and CPU architectures store temporary results at different precisions, so results will differ depending on the details of your environment. If you do a calculation and then compare the results against some expected value it is highly unlikely that you will get exactly the result you intended. In other words, if you do a calculation and then do this comparison: if (result == expectedResult)</p> <p>then it is unlikely that the comparison will be true. If the comparison is true then it is probably unstable – tiny changes in the input values, compiler, or CPU may change the result and make the comparison be false.</p> </blockquote>
2
2009-09-19T23:04:44Z
[ "python", "syntax-error" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
994,762
<p>If all you need to do is to modify structs, you can directly use regex to split and apply changes to each value in the struct, looking for the declaration and the ending }; to know when to stop.</p> <p>If you really need a more general solution you could use a parser generator, like <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a></p>
3
2009-06-15T06:44:49Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
994,769
<p>You don't really provide much information about how what is to be modified should be determined, but to address your specific example:</p> <pre><code>$ perl -pi.bak -we'if ( /const BYTE Some_Idx/ .. /;/ ) { s/Some_Idx/Some_Idx_Mod_mul_2/g; s/(\d+)/$1 * 2/ge; }' header.h </code></pre> <p>Breaking that down, -p says loop through input files, putting each line in <code>$_</code>, running the supplied code, then printing <code>$_</code>. -i.bak enables in-place editing, renaming each original file with a .bak suffix and printing to a new file named whatever the original was. -w enables warnings. -e'....' supplies the code to be run for each input line. header.h is the only input file.</p> <p>In the perl code, <code>if ( /const BYTE Some_Idx/ .. /;/ )</code> checks that we are in a range of lines beginning with a line matching <code>/const BYTE Some_Idx/</code> and ending with a line matching <code>/;/</code>. s/.../.../g does a substitution as many times as possible. <code>/(\d+)/</code> matches a series of digits. The /e flag says the result (<code>$1 * 2</code>) is code that should be evaluated to produce a replacement string, instead of simply a replacement string. $1 is the digits that should be replaced.</p>
4
2009-06-15T06:47:14Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
994,805
<p>Keeping your data lying around in a header makes it trickier to get at using other programs like Perl. Another approach you might consider is to keep this data in a database or another file and regenerate your header file as-needed, maybe even as part of your build system. The reason for this is that generating C is much easier than parsing C, it's trivial to write a script that parses a text file and makes a header for you, and such a script could even be invoked from your build system. </p> <p>Assuming that you want to keep your data in a C header file, you will need one of two things to solve this problem:</p> <ul> <li>a quick one-off script to parse exactly (or close to exactly) the input you describe. </li> <li>a general, well-written script that can parse arbitrary C and work generally on to lots of different headers. </li> </ul> <p>The first case seems more common than the second to me, but it's hard to tell from your question if this is better solved by a script that needs to parse arbitrary C or a script that needs to parse this specific file. For code that works on your specific case, the following works for me on your input:</p> <pre><code>#!/usr/bin/perl -w use strict; open FILE, "&lt;header.h" or die $!; my @file = &lt;FILE&gt;; close FILE or die $!; my $in_block = 0; my $regex = 'Some_Idx\[\]'; my $byte_line = ''; my @byte_entries; foreach my $line (@file) { chomp $line; if ( $line =~ /$regex.*\{(.*)/ ) { $in_block = 1; my @digits = @{ match_digits($1) }; push @digits, @byte_entries; next; } if ( $in_block ) { my @digits = @{ match_digits($line) }; push @byte_entries, @digits; } if ( $line =~ /\}/ ) { $in_block = 0; } } print "const BYTE Some_Idx_Mod_mul_2[] = {\n"; print join ",", map { $_ * 2 } @byte_entries; print "};\n"; sub match_digits { my $text = shift; my @digits; while ( $text =~ /(\d+),*/g ) { push @digits, $1; } return \@digits; } </code></pre> <p>Parsing arbitrary C is a little tricky and not worth it for many applications, but maybe you need to actually do this. One trick is to let GCC do the parsing for you and read in GCC's parse tree using a CPAN module named <a href="http://search.cpan.org/~awin/GCC-TranslationUnit-1.00/TranslationUnit.pm" rel="nofollow">GCC::TranslationUnit</a>. Here's the GCC command to compile the code, assuming you have a single file named test.c:</p> <p>gcc -fdump-translation-unit -c test.c </p> <p>Here's the Perl code to read in the parse tree:</p> <pre><code> use GCC::TranslationUnit; # echo '#include &lt;stdio.h&gt;' &gt; stdio.c # gcc -fdump-translation-unit -c stdio.c $node = GCC::TranslationUnit::Parser-&gt;parsefile('stdio.c.tu')-&gt;root; # list every function/variable name while($node) { if($node-&gt;isa('GCC::Node::function_decl') or $node-&gt;isa('GCC::Node::var_decl')) { printf "%s declared in %s\n", $node-&gt;name-&gt;identifier, $node-&gt;source; } } continue { $node = $node-&gt;chain; } </code></pre>
9
2009-06-15T07:05:21Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
994,912
<p>There is a Perl module called <a href="http://search.cpan.org/dist/Parse-RecDescent" rel="nofollow">Parse::RecDescent</a> which is a very powerful recursive descent parser generator. It comes with a bunch of examples. One of them is a <a href="http://cpansearch.perl.org/src/DCONWAY/Parse-RecDescent-1.96.0/demo/demo%5FCgrammar%5Fv2.pl" rel="nofollow">grammar that can parse C</a>.</p> <p>Now, I don't think this matters in your case, but the recursive descent parsers using Parse::RecDescent are algorithmically slower (O(n^2), I think) than tools like <a href="http://search.cpan.org/dist/Parse-Yapp" rel="nofollow">Parse::Yapp</a> or <a href="http://search.cpan.org/dist/Parse-EYapp" rel="nofollow">Parse::EYapp</a>. I haven't checked whether Parse::EYapp comes with such a C-parser example, but if so, that's the tool I'd recommend learning.</p>
2
2009-06-15T07:47:45Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
994,954
<p>Python solution (not full, just a hint ;)) Sorry if any mistakes - not tested</p> <pre><code>import re text = open('your file.c').read() patt = r'(?is)(.*?{)(.*?)(}\s*;)' m = re.search(patt, text) g1, g2, g3 = m.group(1), m.group(2), m.group(3) g2 = [int(i) * 2 for i in g2.split(',') out = open('your file 2.c', 'w') out.write(g1, ','.join(g2), g3) out.close() </code></pre>
2
2009-06-15T07:59:22Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
994,981
<p>Sorry if this is a stupid question, but why worry about parsing the file at all? Why not write a C program that #includes the header, processes it as required and then spits out the source for the modified header. I'm sure this would be simpler than the Perl/Python solutions, and it would be much more reliable because the header would be being parsed by the C compilers parser.</p>
6
2009-06-15T08:08:37Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
996,289
<p>There is a really useful Perl module called <a href="http://search.cpan.org/dist/Convert-Binary-C/lib/Convert/Binary/C.pm" rel="nofollow">Convert::Binary::C</a> that parses C header files and converts structs from/to Perl data structures.</p>
2
2009-06-15T14:02:05Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
997,859
<p>You could always use <a href="http://perldoc.perl.org/functions/pack.html" rel="nofollow"><code>pack</code></a> / <a href="http://perldoc.perl.org/functions/unpack.html" rel="nofollow"><code>unpack</code></a>, to read, and write the data.</p> <pre><code>#! /usr/bin/env perl use strict; use warnings; use autodie; my @data; { open( my $file, '&lt;', 'Some_Idx.bin' ); local $/ = \1; # read one byte at a time while( my $byte = &lt;$file&gt; ){ push @data, unpack('C',$byte); } close( $file ); } print join(',', @data), "\n"; { open( my $file, '&gt;', 'Some_Idx_Mod_mul_2.bin' ); # You have two options for my $byte( @data ){ print $file pack 'C', $byte * 2; } # or print $file pack 'C*', map { $_ * 2 } @data; close( $file ); } </code></pre>
0
2009-06-15T19:15:51Z
[ "python", "c", "perl", "parsing", "header-files" ]
How can I parse a C header file with Perl?
994,732
<p>I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.</p> <p>For example I have some structure like </p> <pre><code>const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69, 70,72,76,77,81,82,83,85, 88,93,94,95,97,99,102,103, 105,106,113,115,122,124,125,126, 129,131,137,139,140,149,151,152, 153,155,158,159,160,163,165,169, 174,175,181,182,183,189,190,193, 197,201,204,206,208,210,211,212, 213,214,215,217,218,219,220,223, 225,228,230,234,236,237,240,241, 242,247,249}; </code></pre> <p>Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:</p> <pre><code>const BYTE Some_Idx_Mod_mul_2[] = { 8,14,20, ... ... 484,494,498}; </code></pre> <p>Is there any Perl library already available for this? If not Perl, something else like Python is also OK.</p> <p>Can somebody please help!!!</p>
6
2009-06-15T06:33:14Z
2,804,421
<p>For the GCC::TranslationUnit example see hparse.pl from <a href="http://gist.github.com/395160" rel="nofollow">http://gist.github.com/395160</a> which will make it into C::DynaLib, and the not yet written Ctypes also. This parses functions for FFI's, and not bare structs contrary to Convert::Binary::C. hparse will only add structs if used as func args.</p>
0
2010-05-10T16:29:44Z
[ "python", "c", "perl", "parsing", "header-files" ]
customize login in google app engine
994,965
<p>I need to add few more options for login and therefor need to customize create_login_url with some html code. Is there a way to add on your code in default login screen of google? ENvironment - python-google app engine. I want to continue having the default google ext class Users behavior to conntinue to be in place.</p>
2
2009-06-15T08:03:22Z
995,085
<p>You can't customize the login page. Allowing you to do so would introduce the possibility of XSS vulnerabilities, as well as making it harder for users to identify a legitimate login page.</p> <p>If you want to provide for federated login, you may want to simply redirect users to an interstitial page that allows them to pick standard Google login, or one of a number of other services.</p>
2
2009-06-15T08:50:51Z
[ "python", "google-app-engine", "authentication", "registration" ]
customize login in google app engine
994,965
<p>I need to add few more options for login and therefor need to customize create_login_url with some html code. Is there a way to add on your code in default login screen of google? ENvironment - python-google app engine. I want to continue having the default google ext class Users behavior to conntinue to be in place.</p>
2
2009-06-15T08:03:22Z
1,010,764
<p>You might consider OpenID, through any of the various open-source app engine projects for the purpose, such as <a href="http://code.google.com/p/google-app-engine-django-openid/" rel="nofollow">this one</a> for Django.</p> <p>You can't use the existing Users module with those (save perhaps with some serious hacking, but I have not attempted such feats and would not necessarily recommend them;-), but the various projects in question tend to offer usable replacements.</p> <p>Making your own login pages is also not too hard with these approaches, of course, since you start with all the sources to the "OpenID consumer" you choose to use.</p> <p>I don't know if all the domains you want to support are OpenID providers (though I don't see why any site supporting its own user logins <em>wouldn't</em> also be an OpenID provider -- it's easy and makes it more valuable for users to have logins on that site!-), but I hope this will take you some part of the way towards your goal!</p>
1
2009-06-18T04:20:43Z
[ "python", "google-app-engine", "authentication", "registration" ]
customize login in google app engine
994,965
<p>I need to add few more options for login and therefor need to customize create_login_url with some html code. Is there a way to add on your code in default login screen of google? ENvironment - python-google app engine. I want to continue having the default google ext class Users behavior to conntinue to be in place.</p>
2
2009-06-15T08:03:22Z
1,952,698
<p>Nick Johnson recently released an alpha version of a <a href="http://blog.notdot.net/2009/12/OpenID-on-App-Engine-made-easy-with-AEoid" rel="nofollow">WSGI middleware</a> that you could use. The API is very similar to the standard Users API in app engine. It is a way to support auth via OpenID (something Alex Martelli suggested in his <a href="http://stackoverflow.com/questions/994965/customize-login-in-google-app-engine/1010764#1010764">answer</a>). Therefore you are able to support Google as Identity Provider as well as others. If you only want to support Google accounts for some reason, you could certainly only whitelist them though.</p> <p>Nick's blog <a href="http://blog.notdot.net/2009/12/OpenID-on-App-Engine-made-easy-with-AEoid" rel="nofollow">announcement</a> also lists some things to consider (these might be deal-breakers for you):</p> <ul> <li>Users are identified uniquely by their OpenID endpoint.</li> <li>You can't construct a User object without specifying an OpenID URL.</li> <li>Nicknames and email addresses are user-supplied, so they're not guaranteed unique or validated.</li> <li>is_current_user_admin() is not yet implemented.</li> <li>login: clauses in app.yaml are not affected by AEoid - they still authenticate using the regular Users API.</li> </ul>
2
2009-12-23T13:04:31Z
[ "python", "google-app-engine", "authentication", "registration" ]
Using python regex to extract namespaces from C++ sources
995,165
<p>I am trying to extract the namespaces defined in C++ files.<br /> Basically, if my C++ file contains:</p> <pre> namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 </pre> <p>I want to be able to retrieve: n1, n1::n2, n1::n3.</p> <p>Does someone have any suggestion of how I could do that using python-regex? </p> <p>Thanks.</p>
1
2009-06-15T09:15:37Z
995,182
<p>Searching for the namespace names is pretty easy with a regular expression. However, to determine the nesting level you will have to keep track of the curly bracket nesting level in the source file. This is a parsing problem, one that cannot be solved (sanely) with regular expressions. Also, you may have to deal with any C preprocessor directives in the file which can definitely affect parsing.</p> <p>C++ is a notoriously tricky language to parse completely, but you may be able to get by with a tokeniser and a curly bracket counter.</p>
6
2009-06-15T09:22:05Z
[ "c++", "python", "regex", "namespaces" ]
Using python regex to extract namespaces from C++ sources
995,165
<p>I am trying to extract the namespaces defined in C++ files.<br /> Basically, if my C++ file contains:</p> <pre> namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 </pre> <p>I want to be able to retrieve: n1, n1::n2, n1::n3.</p> <p>Does someone have any suggestion of how I could do that using python-regex? </p> <p>Thanks.</p>
1
2009-06-15T09:15:37Z
995,277
<p>You cannot completely ignore preprocessor directives, as they may introduce additional namespaces. I have seen a lot of code like:</p> <pre><code>#define __NAMESPACE_SYSTEM__ namespace system __NAMESPACE_SYSTEM__ { // actual code here... } </code></pre> <p>Yet, I don't see any reason for using such directives, other than defeating regular expression parsing strategy...</p>
1
2009-06-15T09:54:49Z
[ "c++", "python", "regex", "namespaces" ]
Using python regex to extract namespaces from C++ sources
995,165
<p>I am trying to extract the namespaces defined in C++ files.<br /> Basically, if my C++ file contains:</p> <pre> namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 </pre> <p>I want to be able to retrieve: n1, n1::n2, n1::n3.</p> <p>Does someone have any suggestion of how I could do that using python-regex? </p> <p>Thanks.</p>
1
2009-06-15T09:15:37Z
997,065
<p>Most of the time when someone asks how to do something with regex, they're doing something very wrong. I don't think this case is different.</p> <p>If you want to parse c++, you need to use a c++ parser. There are many things that can be done that will defeat a regex but still be valid c++.</p>
0
2009-06-15T16:29:55Z
[ "c++", "python", "regex", "namespaces" ]
Using python regex to extract namespaces from C++ sources
995,165
<p>I am trying to extract the namespaces defined in C++ files.<br /> Basically, if my C++ file contains:</p> <pre> namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 </pre> <p>I want to be able to retrieve: n1, n1::n2, n1::n3.</p> <p>Does someone have any suggestion of how I could do that using python-regex? </p> <p>Thanks.</p>
1
2009-06-15T09:15:37Z
997,076
<p>You could write a basic lexer for it. It's not that hard.</p>
1
2009-06-15T16:32:19Z
[ "c++", "python", "regex", "namespaces" ]
Using python regex to extract namespaces from C++ sources
995,165
<p>I am trying to extract the namespaces defined in C++ files.<br /> Basically, if my C++ file contains:</p> <pre> namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 </pre> <p>I want to be able to retrieve: n1, n1::n2, n1::n3.</p> <p>Does someone have any suggestion of how I could do that using python-regex? </p> <p>Thanks.</p>
1
2009-06-15T09:15:37Z
997,110
<p>The need is simple enough that you may not need a complex parser. You need to:</p> <ul> <li>extract the namespace names</li> <li>count the open/close braces to keep track of where your namespace is defined.</li> </ul> <p>This simple approach works if the other conditions are met:</p> <ul> <li>you don't get spurious namespace like strings inside comments or inside strings</li> <li>you don't get unmatched open/closeing braces inside comments or strings</li> </ul> <p>I don't think this is too much asking from your source.</p>
2
2009-06-15T16:41:41Z
[ "c++", "python", "regex", "namespaces" ]
Using python regex to extract namespaces from C++ sources
995,165
<p>I am trying to extract the namespaces defined in C++ files.<br /> Basically, if my C++ file contains:</p> <pre> namespace n1 { ... namespace n2 { ... } // end namespace n2 ... namespace n3 { ...} //end namespace n3 ... } //end namespace n1 </pre> <p>I want to be able to retrieve: n1, n1::n2, n1::n3.</p> <p>Does someone have any suggestion of how I could do that using python-regex? </p> <p>Thanks.</p>
1
2009-06-15T09:15:37Z
998,230
<p>That is what I did earlier today: </p> <ul> <li>Extract the comment out of the C++ files</li> <li>Use regex to extract the namespace definition</li> <li>Use a simple string search to get the open &amp; close braces positions</li> </ul> <p>The various sanity check added show that I am successfully processing 99.925% of my files (5 failures ouf of 6678 files). The issues are due to mismatches in numbers of { and } cause by few '{' or '}' in strings, and unclean usage of the preprocessor instruction.</p> <p>However, I am only dealing with header files, and I own the code. That limits the number of scenari that could cause some issues and I can manually modify the ones I don't cover.</p> <p>Of course I know there are plenty of cases where it would fail but it is probably enough for what I want to achieve.</p> <p>Thanks for your answers.</p>
0
2009-06-15T20:34:52Z
[ "c++", "python", "regex", "namespaces" ]
How can this be written on a single line?
995,234
<p>I've seen some Python list comprehensions before, but can this be done in a single line of Python?</p> <pre><code>errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors </code></pre>
3
2009-06-15T09:38:48Z
995,238
<pre><code>errs = dict((f.auto_id, f.errors) for f in form if f.errors) </code></pre>
20
2009-06-15T09:40:24Z
[ "python", "django", "dictionary", "list-comprehension" ]
How can this be written on a single line?
995,234
<p>I've seen some Python list comprehensions before, but can this be done in a single line of Python?</p> <pre><code>errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors </code></pre>
3
2009-06-15T09:38:48Z
995,239
<p>It probably could be, but as per the “Readability counts.” rule (<a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">PEP 20</a>), I'd say it's a bad idea. :)</p> <p>On the other hand you have “Flat is better than nested.” and “Sparse is better than dense.”, so I guess it's a matter of taste :)</p>
4
2009-06-15T09:40:44Z
[ "python", "django", "dictionary", "list-comprehension" ]
How can this be written on a single line?
995,234
<p>I've seen some Python list comprehensions before, but can this be done in a single line of Python?</p> <pre><code>errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors </code></pre>
3
2009-06-15T09:38:48Z
995,685
<p>Python 3.0 has dict comprehensions as a shorter/more readable form of the anser provided by Steef:</p> <pre><code>errs = {f.auto_id: f.errors for f in form if f.errors} </code></pre>
9
2009-06-15T11:50:21Z
[ "python", "django", "dictionary", "list-comprehension" ]
How can this be written on a single line?
995,234
<p>I've seen some Python list comprehensions before, but can this be done in a single line of Python?</p> <pre><code>errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors </code></pre>
3
2009-06-15T09:38:48Z
996,238
<p>Both ways are quite readable, however you should think of future maintainers of the code. Sometimes explicit is better. List comprehensions rule though :)</p>
0
2009-06-15T13:51:05Z
[ "python", "django", "dictionary", "list-comprehension" ]
ctypes in python, problem calling a function in a DLL
995,332
<p>Hey! as you might have noticed I have an annoying issue with ctypes. I'm trying to communicate with an instrument and to do so I have to use ctypes to communicate with the DLL driver.</p> <p>so far I've managed to export the DLL by doing this:</p> <pre><code>&gt;&gt;&gt; from ctypes import * &gt;&gt;&gt;maury = WinDLL( 'MLibTuners') &gt;&gt;&gt; maury (WinDLL 'MlibTuners', handle 10000000 at 9ef9d0) &gt;&gt;&gt; maury.get_tuner_driver_version() (_FuncPtr object at 0x009F6738) &gt;&gt;&gt; version_string = create_string_buffer(80) &gt;&gt;&gt; maury.get_tuner_driver_version(version_string) 2258920 &gt;&gt;&gt; print version_string.value 'Maury Microwave MT993V04 Tuner Driver DLL, Version 1.60.00, 07/25/2007' </code></pre> <p>And it works pretty well, according to the documentation it is supposed to save the Tuner Driver DLL in the 80 byte string given as a parameter. However when I try to use the function called *add_tuner* it fails. This is what the documentation says:</p> <pre><code>short add_tuner(short tuner_number, char model[], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[], double *fmin, double *fmax, double *fcrossover, char error_string[]) </code></pre> <p>this is how I tried to call the function above: The parameters that are changed are all the pointers and max_range[], according to the manual the values below are correct too, i just don't know why I keep getting a <em>windows access violation writing 0x00000000</em></p> <pre><code>no_motors = pointer(c_short()) f_min = pointer(c_double()) f_max = pointer(c_double()) f_crossover = pointer(c_double()) maury.add_tuner(c_short(0), c_char_p('MT982EU'), c_short(serial_number), c_short(0), c_short(1),no_motors, c_long(), f_min,f_max,f_crossover, create_string_buffer(80)) </code></pre> <p>The serial number is given however censored by refering to a variable. Someone know what to do?, do you see any errors with my input?</p> <p>Thanks /Mazdak</p>
0
2009-06-15T10:10:34Z
995,384
<p>I figure it's the value you pass at the <code>long max_range[]</code> argument. The function expects a pointer to a <code>long</code> integer there (it asks for an array of <code>long</code> integers), but you're passing a long <em>value</em> of zero (result of the <code>c_long()</code> call), which is implicitly cast to a null pointer. I suspect the function then tries to write to the address passed at <code>max_range</code>, ie. the null pointer, hence the access violation at address <code>0x00000000</code>.</p> <p>To create an array of <code>long</code>s to pass in <code>max_range</code>, you first create the array type by multiplying the array data type with the size of the array (somewhat verbose for clarity):</p> <pre><code>array_size = 3 ThreeLongsArrayType = c_long * array_size </code></pre> <p>You can then instantiate an array like you would with any other Python class:</p> <pre><code>array = ThreeLongsArrayType() </code></pre>
3
2009-06-15T10:23:17Z
[ "python", "dll", "pointers", "ctypes" ]
mod_python caching of variables
995,416
<p><strong>I'm using mod_python to run Trac in Apache. I'm developing a plugin and am not sure how global variables are stored/cached.</strong></p> <p>I am new to python and have googled the subject and found that mod_python caches python modules (I think). However, I would expect that cache to be reset when the web service is restarted, but it doesn't appear to be. I'm saying this becasue I have a global variable that is a list, I test the list to see if a value exists and if it doesn't then I add it. The first time I ran this, it added three entries to the list. Subsequently, the list has three entries from the start.</p> <p>For example:</p> <pre><code>globalList = [] class globalTest: def addToTheList(itemToAdd): print(len(globalTest)) if itemToAdd not in globalList: globalList.append(itemToAdd) def doSomething(): addToTheList("I am new entry one") addToTheList("I am new entry two") addToTheList("I am new entry three") </code></pre> <p>The code above is just an example of what I'm doing, not the actual code ;-). But essentially the doSomething() method is called by Trac. The first time it ran, it added all three entries. Now - even after restarting the web server the len(globalList) command is always 3. </p> <p><strong>I suspect the answer may be that my session (and therefore the global variable) is being cached</strong> because Trac is remembering my login details when I refresh the page in Trac after the web server restart. If that's the case - how do I force the cache to be cleared. Note that I don't want to reset the globalList variable manually i.e. <code>globalList.length = 0</code></p> <p>Can anyone offer any insight as to what is happening? Thank you</p>
1
2009-06-15T10:32:44Z
995,436
<p>read the mod-python faq it says</p> <blockquote> <p>Global objects live inside mod_python for the life of the apache process, which in general is much longer than the life of a single request. This means if you expect a global variable to be initialised every time you will be surprised....</p> </blockquote> <p>go to link <a href="http://www.modpython.org/FAQ/faqw.py?req=show&amp;file=faq03.005.htp" rel="nofollow">http://www.modpython.org/FAQ/faqw.py?req=show&amp;file=faq03.005.htp</a></p> <p>so question is why you want to use global variable?</p>
2
2009-06-15T10:38:31Z
[ "python", "caching", "trac", "mod-python" ]
mod_python caching of variables
995,416
<p><strong>I'm using mod_python to run Trac in Apache. I'm developing a plugin and am not sure how global variables are stored/cached.</strong></p> <p>I am new to python and have googled the subject and found that mod_python caches python modules (I think). However, I would expect that cache to be reset when the web service is restarted, but it doesn't appear to be. I'm saying this becasue I have a global variable that is a list, I test the list to see if a value exists and if it doesn't then I add it. The first time I ran this, it added three entries to the list. Subsequently, the list has three entries from the start.</p> <p>For example:</p> <pre><code>globalList = [] class globalTest: def addToTheList(itemToAdd): print(len(globalTest)) if itemToAdd not in globalList: globalList.append(itemToAdd) def doSomething(): addToTheList("I am new entry one") addToTheList("I am new entry two") addToTheList("I am new entry three") </code></pre> <p>The code above is just an example of what I'm doing, not the actual code ;-). But essentially the doSomething() method is called by Trac. The first time it ran, it added all three entries. Now - even after restarting the web server the len(globalList) command is always 3. </p> <p><strong>I suspect the answer may be that my session (and therefore the global variable) is being cached</strong> because Trac is remembering my login details when I refresh the page in Trac after the web server restart. If that's the case - how do I force the cache to be cleared. Note that I don't want to reset the globalList variable manually i.e. <code>globalList.length = 0</code></p> <p>Can anyone offer any insight as to what is happening? Thank you</p>
1
2009-06-15T10:32:44Z
995,711
<p>Obligatory:</p> <p>Switch to <a href="http://wsgi.org" rel="nofollow">wsgi</a> using <a href="http://code.google.com/p/modwsgi/" rel="nofollow"><code>mod_wsgi</code></a>. </p> <p><a href="http://wiki.python.org/moin/PoundPythonWeb/mod%5Fpython" rel="nofollow">Don't use <code>mod_python</code></a>.</p> <p>There is <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithTrac" rel="nofollow">Help available for configuring <code>mod_wsgi</code> with trac</a>.</p>
3
2009-06-15T11:56:54Z
[ "python", "caching", "trac", "mod-python" ]
KOI8-R: Having trouble translating a string
995,531
<p>This Python script gets translit for Russian letters:</p> <pre><code>s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r') print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) # kOD oBMENA iNFORMACIEJ, 8 BIT </code></pre> <p>That works. But I want to modify it so as to get user input. Now I'm stuck at this:</p> <pre><code>s = raw_input("Enter a string you want to translit: ") s = unicode(s) s = s.encode('koi8-r') print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) </code></pre> <p>Ending up with this:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) </code></pre> <p>What's wrong? </p>
1
2009-06-15T11:06:39Z
995,564
<p><code>s = unicode(s)</code> expects ascii encoding by default. You need to supply it an encoding your input is in, e.g. <code>s = unicode(s, 'utf-8')</code>.</p>
2
2009-06-15T11:15:07Z
[ "python", "encoding" ]
KOI8-R: Having trouble translating a string
995,531
<p>This Python script gets translit for Russian letters:</p> <pre><code>s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r') print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) # kOD oBMENA iNFORMACIEJ, 8 BIT </code></pre> <p>That works. But I want to modify it so as to get user input. Now I'm stuck at this:</p> <pre><code>s = raw_input("Enter a string you want to translit: ") s = unicode(s) s = s.encode('koi8-r') print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) </code></pre> <p>Ending up with this:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) </code></pre> <p>What's wrong? </p>
1
2009-06-15T11:06:39Z
995,566
<p>try <code>unicode(s, encoding)</code> where encoding is whatever your terminal is in.</p>
1
2009-06-15T11:15:28Z
[ "python", "encoding" ]
KOI8-R: Having trouble translating a string
995,531
<p>This Python script gets translit for Russian letters:</p> <pre><code>s = u'Код Обмена Информацией, 8 бит'.encode('koi8-r') print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) # kOD oBMENA iNFORMACIEJ, 8 BIT </code></pre> <p>That works. But I want to modify it so as to get user input. Now I'm stuck at this:</p> <pre><code>s = raw_input("Enter a string you want to translit: ") s = unicode(s) s = s.encode('koi8-r') print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) </code></pre> <p>Ending up with this:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) </code></pre> <p>What's wrong? </p>
1
2009-06-15T11:06:39Z
999,351
<p>Looking at the error messages that you are seeing, it seems to me that your terminal encoding is probably set to KOI8-R, in which case you don't need to perform any decoding on the input data. If this is the case then all you need is:</p> <pre><code>&gt;&gt;&gt; s = raw_input("Enter a string you want to translit: ") &gt;&gt;&gt; print ''.join([chr(ord(c) &amp; 0x7F) for c in s]) kOD oBMENA iNFORMACIEJ, 8 BIT </code></pre> <p>You can double check this by <code>s.decode('koi8-r')</code> which should succeed and return the equivalent unicode string.</p>
0
2009-06-16T02:30:56Z
[ "python", "encoding" ]
Using data from django queries in the same view
995,970
<p>I might have missed somthing while searching through the documentation - I can't seem to find a way to use data from one query to form another query.</p> <p>My query is:</p> <pre><code>sites_list = Site.objects.filter(worker=worker) </code></pre> <p>I'm trying to do something like this:</p> <pre><code>for site in sites_list: [Insert Query Here] </code></pre> <p>Edit: I saw the awnser and im not sure how i didnt get that, maybe thats the sign im up too late coding :S</p>
1
2009-06-15T12:59:31Z
995,992
<p>You could easily do something like this:</p> <pre><code>sites_list = Site.objects.filter(worker=worker) for site in sites_list: new_sites_list = Site.objects.filter(name=site.name).filter(something else) </code></pre>
2
2009-06-15T13:03:54Z
[ "python", "django" ]
Using data from django queries in the same view
995,970
<p>I might have missed somthing while searching through the documentation - I can't seem to find a way to use data from one query to form another query.</p> <p>My query is:</p> <pre><code>sites_list = Site.objects.filter(worker=worker) </code></pre> <p>I'm trying to do something like this:</p> <pre><code>for site in sites_list: [Insert Query Here] </code></pre> <p>Edit: I saw the awnser and im not sure how i didnt get that, maybe thats the sign im up too late coding :S</p>
1
2009-06-15T12:59:31Z
1,019,848
<p>You can also use the <code>__in</code> lookup type. For example, if you had an <code>Entry</code> model with a relation to <code>Site</code>, you could write:</p> <pre><code>Entry.objects.filter(site__in=Site.objects.filter(...some conditions...)) </code></pre> <p>This will end up doing one query in the DB (the filter condition on sites would be turned into a subquery in the <code>WHERE</code> clause).</p>
0
2009-06-19T20:16:01Z
[ "python", "django" ]
IOError "no such file or folder" even though files are present
995,985
<p>I wrote a script in Python 2.6.2 that scans a directory for SVG's and resizes them if they are too large. I wrote this on my home machine (Vista, Python 2.6.2) and processed a few folders with no problems. Today, I tried this on my work computer (XP SP2, Python 2.6.2) and I get IOErrors for every file, even though files are in the directory. I think I've tried everything, and am unsure where to go from here. I am a beginner so this may be something simple. Any help would be appreciated.</p> <pre><code>import xml.etree.ElementTree as ET import os import tkFileDialog #-------------------------------------- #~~~variables #-------------------------------------- max_height = 500 max_width = 428 extList = ["svg"] proc_count = 0 resize_count = 0 #-------------------------------------- #~~~functions #-------------------------------------- def landscape_or_portrait(): resize_count +=1 if float(main_width_old)/float(main_height_old) &gt;= 1.0: print "picture is landscape" resize_width() else: print "picture is not landscape" resize_height() return def resize_height(): print "picture too tall" #calculate viewBox and height viewBox_height_new = max_height scaleFactor = (float(main_height_old) - max_height)/max_height viewBox_width_new = float(main_width_old) * scaleFactor #calculate main width and height main_height_new = str(viewBox_height_new) + "px" main_width_new = str(viewBox_width_new) + "px" viewBox = "0 0 " + str(viewBox_width_new) + " " + str(viewBox_height_new) inputFile = file(tfile, 'r') data = inputFile.read() inputFile.close() data = data.replace(str(tmain_height_old), str(main_height_new)) data = data.replace(str(tmain_width_old), str(main_width_new)) #data = data.replace(str(tviewBox), str(viewBox)) outputFile = file(tfile, 'w') outputFile.write(data) outputFile.close() return def resize_width(): print "picture too wide" #calculate viewBox width and height viewBox_width_new = max_width scaleFactor = (float(main_width_old) - max_width)/max_width viewBox_height_new = float(main_height_old) * scaleFactor #calculate main width and height main_height_new = str(viewBox_height_new) + "px" main_width_new = str(viewBox_width_new) + "px" viewBox = "0 0 " + str(viewBox_width_new) + " " + str(viewBox_height_new) inputFile = file(tfile, 'r') data = inputFile.read() inputFile.close() data = data.replace(str(tmain_height_old), str(main_height_new)) data = data.replace(str(tmain_width_old), str(main_width_new)) #data = data.replace(str(tviewBox), str(viewBox)) outputFile = file(tfile, 'w') outputFile.write(data) outputFile.close() return #-------------------------------------- #~~~operations #-------------------------------------- path = tkFileDialog.askdirectory() for tfile in os.listdir(path): #print tfile t2file = tfile if tfile.find(".") &gt;= 0: try : if t2file.split(".")[1] in extList: print "now processing " + tfile tree = ET.parse(tfile) proc_count+=1 # Get the values of the root(svg) attributes root = tree.getroot() tmain_height_old = root.get("height") tmain_width_old = root.get("width") tviewBox = root.get("viewBox") #clean up variables, remove px for float conversion main_height_old = tmain_height_old.replace("px", "", 1) main_width_old = tmain_width_old.replace("px", "", 1) #check if they are too large if float(main_height_old) &gt; max_height or float(main_width_old) &gt; max_width: landscape_or_portrait() except Exception,e: print e </code></pre>
0
2009-06-15T13:02:36Z
996,001
<p>Perhaps it's a security issue? Perhaps you don't have the rights to create files in the folder</p>
0
2009-06-15T13:05:37Z
[ "python" ]
IOError "no such file or folder" even though files are present
995,985
<p>I wrote a script in Python 2.6.2 that scans a directory for SVG's and resizes them if they are too large. I wrote this on my home machine (Vista, Python 2.6.2) and processed a few folders with no problems. Today, I tried this on my work computer (XP SP2, Python 2.6.2) and I get IOErrors for every file, even though files are in the directory. I think I've tried everything, and am unsure where to go from here. I am a beginner so this may be something simple. Any help would be appreciated.</p> <pre><code>import xml.etree.ElementTree as ET import os import tkFileDialog #-------------------------------------- #~~~variables #-------------------------------------- max_height = 500 max_width = 428 extList = ["svg"] proc_count = 0 resize_count = 0 #-------------------------------------- #~~~functions #-------------------------------------- def landscape_or_portrait(): resize_count +=1 if float(main_width_old)/float(main_height_old) &gt;= 1.0: print "picture is landscape" resize_width() else: print "picture is not landscape" resize_height() return def resize_height(): print "picture too tall" #calculate viewBox and height viewBox_height_new = max_height scaleFactor = (float(main_height_old) - max_height)/max_height viewBox_width_new = float(main_width_old) * scaleFactor #calculate main width and height main_height_new = str(viewBox_height_new) + "px" main_width_new = str(viewBox_width_new) + "px" viewBox = "0 0 " + str(viewBox_width_new) + " " + str(viewBox_height_new) inputFile = file(tfile, 'r') data = inputFile.read() inputFile.close() data = data.replace(str(tmain_height_old), str(main_height_new)) data = data.replace(str(tmain_width_old), str(main_width_new)) #data = data.replace(str(tviewBox), str(viewBox)) outputFile = file(tfile, 'w') outputFile.write(data) outputFile.close() return def resize_width(): print "picture too wide" #calculate viewBox width and height viewBox_width_new = max_width scaleFactor = (float(main_width_old) - max_width)/max_width viewBox_height_new = float(main_height_old) * scaleFactor #calculate main width and height main_height_new = str(viewBox_height_new) + "px" main_width_new = str(viewBox_width_new) + "px" viewBox = "0 0 " + str(viewBox_width_new) + " " + str(viewBox_height_new) inputFile = file(tfile, 'r') data = inputFile.read() inputFile.close() data = data.replace(str(tmain_height_old), str(main_height_new)) data = data.replace(str(tmain_width_old), str(main_width_new)) #data = data.replace(str(tviewBox), str(viewBox)) outputFile = file(tfile, 'w') outputFile.write(data) outputFile.close() return #-------------------------------------- #~~~operations #-------------------------------------- path = tkFileDialog.askdirectory() for tfile in os.listdir(path): #print tfile t2file = tfile if tfile.find(".") &gt;= 0: try : if t2file.split(".")[1] in extList: print "now processing " + tfile tree = ET.parse(tfile) proc_count+=1 # Get the values of the root(svg) attributes root = tree.getroot() tmain_height_old = root.get("height") tmain_width_old = root.get("width") tviewBox = root.get("viewBox") #clean up variables, remove px for float conversion main_height_old = tmain_height_old.replace("px", "", 1) main_width_old = tmain_width_old.replace("px", "", 1) #check if they are too large if float(main_height_old) &gt; max_height or float(main_width_old) &gt; max_width: landscape_or_portrait() except Exception,e: print e </code></pre>
0
2009-06-15T13:02:36Z
996,021
<p>It looks to me like you are missing a <code>os.path.join(path, tfile)</code> to get the full path to the file you want to open. Currently it should only work for files in the current directory.</p>
1
2009-06-15T13:11:10Z
[ "python" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
996,030
<p>Pseudocode:</p> <pre><code>Enumerate(Balls, Boxes) if Boxes&lt;=0 Error elseif Boxes=1 Box[1] = Balls PrintBoxes else forall b in 0..Balls Box[Boxes] = b Enumerate(Balls-b, Boxes-1) endfor endif end </code></pre> <p>Explanation</p> <p>Start at the first box, if there are no boxes, complain and quit. If it is the last box to be filled, drop all remaining balls and show the result. If there are more boxes, first add 0 balls and repeat the procedure with the other boxes. Then add 1, ball 2 balls until there are no balls left.</p> <p>To show, that the algorithm works, I give an example with real values, 3 balls and 2 boxes.</p> <p>We have an array of boxes called Box, and each box can hold any number of balls (the value). PrintBoxes prints the current value of the boxes.</p> <pre><code>Box = (0,0) Enumerate(3, 2) b=0 Box = (0,0) Enumerate(3,1) Box = (3,0) Print! b=1 Box = (0,1) Enumerate(2,1) Box = (2,1) Print! b=2 Box = (0,2) Enumerate(1,1) Box = (1,2) Print! b=3 Box = (0,3) Enumerate(0,1) Box = (0,3) Print! Output: (3,0) (2,1) (1,2) (0,3) Which are all the combinations. </code></pre> <p>Another example with 3 boxes and 3 balls:</p> <pre><code>Box = (0,0,0) Enumerate(3, 3) b=0 Box = (0,0,0) Enumerate(3,2) b=0 Box = (0,0,0) Enumerate(3,1) Box = (3,0,0) b=1 Box = (0,1,0) Enumerate(2,1) Box = (2,1,0) b=2 Box = (0,2,0) Enumerate(1,1) Box = (1,2,0) b=3 Box = (0,3,0) Enumerate(0,1) Box = (0,3,0) b=1 Box = (0,0,1) Enumerate(2,2) b=0 Box = (0,0,1) Enumerate(2,1) Box = (2,0,1) b=1 Box = (0,1,1) Enumerate(1,1) Box = (1,1,1) b=2 Box = (0,2,1) Enumerate(0,1) Box = (0,2,1) b=2 Box = (0,0,2) Enumerate(1,2) b=0 Box = (0,0,2) Enumerate(1,1) Box = (1,0,2) b=1 Box = (0,1,2) Enumerate(0,1) Box = (0,1,2) b=3 Box = (0,0,3) Enumerate(0,2) b=0 Box = (0,0,3) Enumerate(0,1) Box = (0,0,3) Output (3,0,0) (2,1,0) (1,2,0) (0,3,0) (2,0,1) (1,1,1) (0,2,1) (1,0,2) (0,1,2) (0,0,3) </code></pre>
3
2009-06-15T13:12:49Z
[ "python", "enumeration", "combinations" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
996,070
<p>if you want to use your own function answer by Gamecat may work else either use <a href="http://probstat.sourceforge.net/" rel="nofollow">http://probstat.sourceforge.net/</a> , it is very fast (written in c)</p> <p>or itertools in python 2.6</p>
0
2009-06-15T13:20:05Z
[ "python", "enumeration", "combinations" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
996,246
<p>This works just fine starting with python 2.6, (<a href="http://docs.python.org/library/itertools.html#itertools.permutations" rel="nofollow">2.5-friendly implementation of <code>itertools.permutations</code> is available as well</a>):</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; boxes = 3 &gt;&gt;&gt; balls = 8 &gt;&gt;&gt; rng = list(range(balls + 1)) * boxes &gt;&gt;&gt; set(i for i in itertools.permutations(rng, boxes) if sum(i) == balls) {(0, 1, 7), (3, 1, 4), (0, 4, 4), (1, 0, 7), (4, 0, 4), (3, 0, 5), (1, 2, 5), (1, 7, 0), (0, 8, 0), (1, 4, 3), (6, 0, 2), (4, 3, 1), (3, 3, 2), (0, 5, 3), (5, 3, 0), (5, 1, 2), (2, 4, 2), (4, 4, 0), (3, 2, 3), (7, 1, 0), (5, 2, 1), (0, 6, 2), (6, 1, 1), (2, 2, 4), (1, 1, 6), (0, 2, 6), (7, 0, 1), (2, 1, 5), (0, 0, 8), (2, 0, 6), (2, 6, 0), (5, 0, 3), (2, 5, 1), (1, 6, 1), (8, 0, 0), (4, 1, 3), (6, 2, 0), (3, 5, 0), (0, 3, 5), (4, 2, 2), (1, 3, 4), (0, 7, 1), (1, 5, 2), (2, 3, 3), (3, 4, 1)} </code></pre>
5
2009-06-15T13:52:43Z
[ "python", "enumeration", "combinations" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
996,351
<p>You can define a recursive <a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">generator</a> which creates a sub-generator for each 'for loop' which you wish to nest, like this:</p> <pre><code>def ballsAndBoxes(balls, boxes, boxIndex=0, sumThusFar=0): if boxIndex &lt; (boxes - 1): for counter in xrange(balls + 1 - sumThusFar): for rest in ballsAndBoxes(balls, boxes, boxIndex + 1, sumThusFar + counter): yield (counter,) + rest else: yield (balls - sumThusFar,) </code></pre> <p>When you call this at the top level, it will take only a 'balls' and 'boxes' argument, the others are there as defaults so that the recursive call can pass different things. It will yield tuples of integers (of length 'boxes') that are your values.</p> <p>To get the exact formatting you specified at the top of this post, you could call it something like this:</p> <pre><code>BALLS = 8 BOXES = 3 print '\t', for box in xrange(1, BOXES + 1): print '\tbox_%d' % (box,), print for position, value in enumerate(ballsAndBoxes(BALLS, BOXES)): print 'case-%d\t\t%s' % (position + 1, "\t".join((str(v) for v in value))) </code></pre>
1
2009-06-15T14:15:03Z
[ "python", "enumeration", "combinations" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
998,153
<p>If you simply want to know the number of possibilities, instead of listing them, then the following formula will work:</p> <blockquote> <p>Possibilities = (N+A-1) C N = (N+A-1)!/(N!x(A-1)!)</p> </blockquote> <p>Where aCb (a choose b) is the number of ways of choosing combinations of size b from a set of size a. </p> <p>! denotes the factorial ie 5!=5*4*3*2*1, n!=n*(n-1)*(n-2)*...*3*2*1. Sorry if I'm teaching you how to suck eggs.</p> <p>In python:</p> <pre><code>from math import factorial as f balls=N boxes=A def p(balls,boxes): return f(balls+boxes-1)/f(balls)/f(boxes-1) p(3,2) 4 p(3,3) 10 </code></pre> <p>which agrees with Gamecat's examples.</p> <p>To explain why the formula works, let's look at five balls and 3 boxes. Denote balls as asterisks. We want to place 3-1=2 dividing lines to split the balls into 3 compartments.</p> <p>For example, we could have</p> <pre><code>* | * | * * * (1,1,3) * * | * * * | (2,3,0) * * * * * | | (5,0,0) </code></pre> <p>7 symbols can be ordered in 7!=5040 possible ways. Since all the balls are the same, we aren't worried about the order of the balls, so we divide by 5!. Similarly, we aren't worried about the order of the dividing lines so we divide by 2!. This gives us 7C5=7!/(5!*2!)=21 possibilities.</p> <p>The Wikipedia article on <a href="http://en.wikipedia.org/wiki/Combination" rel="nofollow">Combinations</a> has a section "Number of combinations with repetition" which is the counting combinations question rephrased in a tastier way (donuts and pieces of fruit instead of balls).</p> <p>If you want to list the combinations, beware how quickly the number grows. For 20 balls and 9 boxes, there are over 3 million possibilities!</p> <p>edit: my previous answer compared this problem to integer partitions to show how quickly the number of possibilities grows. My new answer is more relevant to the original question.</p>
0
2009-06-15T20:16:54Z
[ "python", "enumeration", "combinations" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
999,234
<p>See <a href="http://docs.python.org/dev/py3k/library/itertools.html#itertools.combinations%5Fwith%5Freplacement" rel="nofollow">itertools.combinations_with_replacement</a> in 3.1 for an example written in python. Additionally, it's common in combinatorics to transform a combination-with-replacement problem into the usual combination-without-replacement problem, which is already builtin in 2.6 itertools. This has the advantage of not generating discarded tuples, like solutions based on product or permutation. Here's an example using the standard (n, r) terminology, which would be (A, N) in your example.</p> <pre><code>import itertools, operator def combinations_with_replacement_counts(n, r): size = n + r - 1 for indices in itertools.combinations(range(size), n-1): starts = [0] + [index+1 for index in indices] stops = indices + (size,) yield tuple(map(operator.sub, stops, starts)) &gt;&gt;&gt; list(combinations_with_replacement_counts(3, 8)) [(0, 0, 8), (0, 1, 7), (0, 2, 6), (0, 3, 5), (0, 4, 4), (0, 5, 3), (0, 6, 2), (0, 7, 1), (0, 8, 0), (1, 0, 7), (1, 1, 6), (1, 2, 5), (1, 3, 4), (1, 4, 3), (1, 5, 2), (1, 6, 1), (1, 7, 0), (2, 0, 6), (2, 1, 5), (2, 2, 4), (2, 3, 3), (2, 4, 2), (2, 5, 1), (2, 6, 0), (3, 0, 5), (3, 1, 4), (3, 2, 3), (3, 3, 2), (3, 4, 1), (3, 5, 0), (4, 0, 4), (4, 1, 3), (4, 2, 2), (4, 3, 1), (4, 4, 0), (5, 0, 3), (5, 1, 2), (5, 2, 1), (5, 3, 0), (6, 0, 2), (6, 1, 1), (6, 2, 0), (7, 0, 1), (7, 1, 0), (8, 0, 0)] </code></pre>
1
2009-06-16T01:24:45Z
[ "python", "enumeration", "combinations" ]
Enumeration of combinations of N balls in A boxes?
996,004
<p>I want to enumerate all possible combinations of <strong><em>N</em></strong> balls in <strong><em>A</em></strong> boxes.</p> <p>example: I have <strong><em>8</em></strong> balls to deal in <strong><em>3</em></strong> boxes :</p> <pre><code> box_1 box_2 box_3 case-1 8 0 0 case-2 0 8 0 case-3 0 0 8 case-4 7 1 0 case-5 7 0 1 case-6 6 2 0 ... </code></pre> <p>My first problem is that I need <strong><em>A</em></strong> loops to perform this but I want that <strong><em>A</em></strong> and <strong><em>N</em></strong> to be user's inputs. So how to do without writing all possible number of loops users could need?</p> <p><strong><em>a</em></strong> and <strong><em>N</em></strong> will be value between 2 and ~800, so it will be strongly demanding in computation time so. How to optimize that algorithm?</p> <p>I would be grateful if you answer me using python language. thanks for all contributions!</p>
1
2009-06-15T13:06:22Z
34,813,958
<p>It is good idea to use python generator, as it was done above but here is more straightforward (not sure about efficency) version:</p> <pre><code>def balls_in_baskets(balls=1, baskets=1): if baskets == 1: yield [balls] elif balls == 0: yield [0]*baskets else: for i in xrange(balls+1): for j in balls_in_baskets(balls-i, 1): for k in balls_in_baskets(i, baskets-1): yield j+k for i in balls_in_baskets(8,3): print i </code></pre>
1
2016-01-15T15:02:36Z
[ "python", "enumeration", "combinations" ]
py2exe windows service problem
996,129
<p>I have successfully converted my python project to a service. When using the usual options of install and start/stop, everything works correctly. However, I wish to compile the project using py2exe, which seems to work correctly until you install the EXE as a service and try and run it.</p> <p>You get the following error message:</p> <ul> <li>Starting service CherryPyService</li> <li>Error starting service: The service did not respond to the start or control request in a timely fashion.</li> </ul> <p>My compile python file (which links to the main project) is as follows:</p> <ul> <li>from distutils.core import setup</li> <li><p>import py2exe</p></li> <li><p>setup(console=['webserver.py'])</p></li> </ul> <p>Any help would be greatly appreciated.</p>
6
2009-06-15T13:31:04Z
996,645
<p>You will find an example in the py2exe package, look in site-packages\py2exe\samples\advanced.</p>
1
2009-06-15T15:07:59Z
[ "python", "windows-services", "py2exe" ]
py2exe windows service problem
996,129
<p>I have successfully converted my python project to a service. When using the usual options of install and start/stop, everything works correctly. However, I wish to compile the project using py2exe, which seems to work correctly until you install the EXE as a service and try and run it.</p> <p>You get the following error message:</p> <ul> <li>Starting service CherryPyService</li> <li>Error starting service: The service did not respond to the start or control request in a timely fashion.</li> </ul> <p>My compile python file (which links to the main project) is as follows:</p> <ul> <li>from distutils.core import setup</li> <li><p>import py2exe</p></li> <li><p>setup(console=['webserver.py'])</p></li> </ul> <p>Any help would be greatly appreciated.</p>
6
2009-06-15T13:31:04Z
996,667
<p>You setup.py file should contain</p> <pre><code>setup(service=["webserver.py"]) </code></pre> <p>as shown in the <a href="http://www.py2exe.org/old/" rel="nofollow">"old" py2exe docs</a></p>
4
2009-06-15T15:10:03Z
[ "python", "windows-services", "py2exe" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,270
<p>Maybe you could write a simple script that will convert your config into xml file and then read it just using lxml, Beatuful Soup or anything else? And your converter could use PyParsing or regular expressions for example.</p>
-1
2009-06-15T13:58:00Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,275
<p>I'll try and answer what I think is the missing question(s)...</p> <p>Configuration files come in many formats. There are well known formats such as *.ini or apache config - these tend to have many parsers available.</p> <p>Then there are custom formats. That is what yours appears to be (it could be some well-defined format you and I have never seen before - but until you know what that is it doesn't really matter).</p> <p>I would start with the software this came from and see if they have a programming API that can load/produce these files. If nothing is obvious give Quovadx a call. Chances are someone has already solved this problem.</p> <p>Otherwise you're probably on your own to create your own parser.</p> <p>Writing a parser for this format would not be terribly difficult assuming that your sample is representative of a complete example. It's a hierarchy of values where each node can contain either a value or a child hierarchy of values. Once you've defined the basic types that the values can contain the parser is a very simple structure.</p> <p>You could write this reasonably quickly using something like Lex/Flex or just a straight-forward parser in the language of your choosing.</p>
1
2009-06-15T13:58:51Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,306
<p>I searched a little on the <a href="http://pypi.python.org/pypi" rel="nofollow">Cheese Shop</a>, but I didn't find anything helpful for your example. Check the <a href="http://pyparsing.wikispaces.com/Examples" rel="nofollow">Examples</a> page, and <a href="http://pyparsing.wikispaces.com/file/view/dhcpd%5Fleases%5Fparser.py" rel="nofollow">this</a> specific parser ( it's syntax resembles yours a bit ). I think this should help you write your own.</p>
0
2009-06-15T14:04:44Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,342
<p>Look into <a href="http://dinosaur.compilertools.net/" rel="nofollow">LEX and YACC</a>. A bit of a learning curve, but they can generate parsers for any language.</p>
0
2009-06-15T14:13:24Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,366
<p>You can easily write a script in python which will convert it to python dict, format looks almost like hierarchical name value pairs, only problem seems to be Coards {0 0}, where {0 0} isn't a name value pair, but a list so who know what other such cases are in the format I think your best bet is to have spec for that format and write a simple python script to read it.</p>
1
2009-06-15T14:18:36Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,461
<p><a href="http://pyparsing.wikispaces.com/Introduction" rel="nofollow">pyparsing</a> is pretty handy for quick and simple parsing like this. A bare minimum would be something like:</p> <pre><code>import pyparsing string = pyparsing.CharsNotIn("{} \t\r\n") group = pyparsing.Forward() group &lt;&lt; pyparsing.Group(pyparsing.Literal("{").suppress() + pyparsing.ZeroOrMore(group) + pyparsing.Literal("}").suppress()) | string toplevel = pyparsing.OneOrMore(group) </code></pre> <p>The use it as:</p> <pre><code>&gt;&gt;&gt; toplevel.parseString(text) ['protocol', 'sample_thread', [['AUTOSTART', '0'], ['BITMAP', 'thread.gif'], ['COORDS', ['0', '0']], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]] </code></pre> <p>From there you can get more sophisticated as you want (parse numbers seperately from strings, look for specific field names etc). The above is pretty general, just looking for strings (defined as any non-whitespace character except "{" and "}") and {} delimited lists of strings.</p>
11
2009-06-15T14:35:14Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
996,513
<p>Your config file is very similar to <a href="http://www.json.org/" rel="nofollow">JSON</a> (pretty much, replace all your "{" and "}" with "[" and "]"). Most languages have a built in JSON parser (PHP, Ruby, Python, etc), and if not, there are libraries available to handle it for you.</p> <p>If you can not change the format of the configuration file, you can read all file contents as a string, and replace all the "{" and "}" characters via whatever means you prefer. Then you can parse the string as JSON, and you're set.</p>
1
2009-06-15T14:44:06Z
[ "python", "parsing", "config" ]
Parsing an existing config file
996,183
<p>I have a config file that is in the following form:</p> <pre><code>protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } </code></pre> <p>The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.</p> <p>I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.</p> <p>I'm looking for a module that can parse a file like this, any suggestions?</p> <p>If anyone is curious, the file in question was generated by Quovadx Cloverleaf.</p>
4
2009-06-15T13:43:23Z
1,351,502
<p>Taking Brian's pyparsing solution another step, you can create a quasi-deserializer for this format by using the Dict class:</p> <pre><code>import pyparsing string = pyparsing.CharsNotIn("{} \t\r\n") # use Word instead of CharsNotIn, to do whitespace skipping stringchars = pyparsing.printables.replace("{","").replace("}","") string = pyparsing.Word( stringchars ) # define a simple integer, plus auto-converting parse action integer = pyparsing.Word("0123456789").setParseAction(lambda t : int(t[0])) group = pyparsing.Forward() group &lt;&lt; ( pyparsing.Group(pyparsing.Literal("{").suppress() + pyparsing.ZeroOrMore(group) + pyparsing.Literal("}").suppress()) | integer | string ) toplevel = pyparsing.OneOrMore(group) sample = """ protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } """ print toplevel.parseString(sample).asList() # Now define something a little more meaningful for a protocol structure, # and use Dict to auto-assign results names LBRACE,RBRACE = map(pyparsing.Suppress,"{}") protocol = ( pyparsing.Keyword("protocol") + string("name") + LBRACE + pyparsing.Dict(pyparsing.OneOrMore( pyparsing.Group(LBRACE + string + group + RBRACE) ) )("parameters") + RBRACE ) results = protocol.parseString(sample) print results.name print results.parameters.BITMAP print results.parameters.keys() print results.dump() </code></pre> <p>Prints</p> <pre><code>['protocol', 'sample_thread', [['AUTOSTART', 0], ['BITMAP', 'thread.gif'], ['COORDS', [0, 0]], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]] sample_thread thread.gif ['DATAFORMAT', 'COORDS', 'AUTOSTART', 'BITMAP'] ['protocol', 'sample_thread', [['AUTOSTART', 0], ['BITMAP', 'thread.gif'], ['COORDS', [0, 0]], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]] - name: sample_thread - parameters: [['AUTOSTART', 0], ['BITMAP', 'thread.gif'], ['COORDS', [0, 0]], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]] - AUTOSTART: 0 - BITMAP: thread.gif - COORDS: [0, 0] - DATAFORMAT: [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]] </code></pre> <p>I think you will get further faster with pyparsing.</p> <p>-- Paul</p>
2
2009-08-29T13:57:04Z
[ "python", "parsing", "config" ]
Regex in Python
996,536
<p>Goal: Given a number (it may be very long and it is greater than 0), I'd like to get the five least meaningful digits dropping any 0 at the end of that number.</p> <p>I tried to solve this with regex, Helped by RegexBuddy I came to this one:</p> <pre><code>[\d]+([\d]{0,4}+[1-9])0* </code></pre> <p>But python can't compile that.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"[\d]+([\d]{0,4}+[1-9])0*") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/re.py", line 188, in compile return _compile(pattern, flags) File "/usr/lib/python2.5/re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat </code></pre> <p>The problem is the "+" after "{0,4}", it seems it doesn't work in python (even in 2.6)</p> <p>How can I write a working regex?</p> <p>PS: I know you can start dividing by 10 and then using the remainder n%100000... but this is a problem about regex.<br /></p>
1
2009-06-15T14:48:59Z
996,581
<p>Small tip. I recommend you test with <a href="http://cthedot.de/retest/" rel="nofollow">reTest</a> instead of RegExBuddy. There are different regular expression engines for different programming languages. ReTest is valuable in that it allows you to quickly test regular expression strings within Python itself. That way you can insure that you tested your syntax with the Python's regular expression engine.</p>
2
2009-06-15T14:56:55Z
[ "python", "regex", "regexbuddy" ]
Regex in Python
996,536
<p>Goal: Given a number (it may be very long and it is greater than 0), I'd like to get the five least meaningful digits dropping any 0 at the end of that number.</p> <p>I tried to solve this with regex, Helped by RegexBuddy I came to this one:</p> <pre><code>[\d]+([\d]{0,4}+[1-9])0* </code></pre> <p>But python can't compile that.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"[\d]+([\d]{0,4}+[1-9])0*") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/re.py", line 188, in compile return _compile(pattern, flags) File "/usr/lib/python2.5/re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat </code></pre> <p>The problem is the "+" after "{0,4}", it seems it doesn't work in python (even in 2.6)</p> <p>How can I write a working regex?</p> <p>PS: I know you can start dividing by 10 and then using the remainder n%100000... but this is a problem about regex.<br /></p>
1
2009-06-15T14:48:59Z
996,612
<p>The error seems to be that you have two quantifiers in a row, {0,4} and +. Unless + is meant to be a literal here (which I doubt, since you're talking about numbers), then I don't think you need it at all. Unless it means something different in this situation (possibly the greediness of the {} quantifier)? I would try</p> <pre><code>[\d]+([\d]{0,4}[1-9])0* </code></pre> <p>If you actually intended to have both quantifiers to be applied, then this might work</p> <pre><code>[\d]+(([\d]{0,4})+[1-9])0* </code></pre> <p>But given your specification of the problem, I doubt that's what you want.</p>
0
2009-06-15T15:02:18Z
[ "python", "regex", "regexbuddy" ]
Regex in Python
996,536
<p>Goal: Given a number (it may be very long and it is greater than 0), I'd like to get the five least meaningful digits dropping any 0 at the end of that number.</p> <p>I tried to solve this with regex, Helped by RegexBuddy I came to this one:</p> <pre><code>[\d]+([\d]{0,4}+[1-9])0* </code></pre> <p>But python can't compile that.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"[\d]+([\d]{0,4}+[1-9])0*") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/re.py", line 188, in compile return _compile(pattern, flags) File "/usr/lib/python2.5/re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat </code></pre> <p>The problem is the "+" after "{0,4}", it seems it doesn't work in python (even in 2.6)</p> <p>How can I write a working regex?</p> <p>PS: I know you can start dividing by 10 and then using the remainder n%100000... but this is a problem about regex.<br /></p>
1
2009-06-15T14:48:59Z
996,613
<p>That regular expression is very superfluous. Try this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"(\d{0,4}[1-9])0*$") </code></pre> <p>The above regular expression assumes that the number is valid (it will also match "abc<strong>012345</strong>0", for example.) If you really need the validation that there are no non-number characters, you may use this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"^\d*?(\d{0,4}[1-9])0*$") </code></pre> <p>Anyways, the <code>\d</code> does not need to be in a character class, and the quantifier <code>{0,4}</code> does not need to be forced to be greedy (as the additional <code>+</code> specifies, although apparently Python does not recognize that.)</p> <p>Also, in the second regular expression, the <code>\d</code> is non-greedy, as I believe this will improve the performance and accuracy. I also made it "zero or more" as I assume that is what you want.</p> <p>I also added anchors as this ensures that your regular expression won't match anything in the middle of a string. If this is what you desired though (maybe you're scanning a long text?), remove the anchors.</p>
10
2009-06-15T15:02:28Z
[ "python", "regex", "regexbuddy" ]
Regex in Python
996,536
<p>Goal: Given a number (it may be very long and it is greater than 0), I'd like to get the five least meaningful digits dropping any 0 at the end of that number.</p> <p>I tried to solve this with regex, Helped by RegexBuddy I came to this one:</p> <pre><code>[\d]+([\d]{0,4}+[1-9])0* </code></pre> <p>But python can't compile that.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"[\d]+([\d]{0,4}+[1-9])0*") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/re.py", line 188, in compile return _compile(pattern, flags) File "/usr/lib/python2.5/re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat </code></pre> <p>The problem is the "+" after "{0,4}", it seems it doesn't work in python (even in 2.6)</p> <p>How can I write a working regex?</p> <p>PS: I know you can start dividing by 10 and then using the remainder n%100000... but this is a problem about regex.<br /></p>
1
2009-06-15T14:48:59Z
1,001,910
<p>\d{0,4}+ is a possessive quantifier supported by certain regular expression flavors such as .NET and Java. Python does not support possessive quantifiers.</p> <p>In RegexBuddy, select Python in the toolbar at the top, and RegexBuddy will tell you that Python doesn't support possessive quantifiers. The + will be highlighted in red in the regular expression, and the Create tab will indicate the error.</p> <p>If you select Python on the Use tab in RegexBuddy, RegexBuddy will generate a Python source code snippet with a regular expression without the possessive quantifier, and a comment indicating that the removal of the possessive quantifier may yield different results. Here's the Python code that RegexBuddy generates using the regex from the question:</p> <pre><code># Your regular expression could not be converted to the flavor required by this language: # Python does not support possessive quantifiers # Because of this, the code snippet below will not work as you intended, if at all. reobj = re.compile(r"[\d]+([\d]{0,4}[1-9])0*") </code></pre> <p>What you probably did is select a flavor such as Java in the main toolbar, and then click Copy Regex as Python String. That will give you a Java regular expression formatted as a Pythong string. The items in the Copy menu do not convert your regular expression. They merely format it as a string. This allows you to do things like format a JavaScript regular expression as a Python string so your server-side Python script can feed a regex into client-side JavaScript code.</p>
5
2009-06-16T14:38:24Z
[ "python", "regex", "regexbuddy" ]
Regex in Python
996,536
<p>Goal: Given a number (it may be very long and it is greater than 0), I'd like to get the five least meaningful digits dropping any 0 at the end of that number.</p> <p>I tried to solve this with regex, Helped by RegexBuddy I came to this one:</p> <pre><code>[\d]+([\d]{0,4}+[1-9])0* </code></pre> <p>But python can't compile that.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile(r"[\d]+([\d]{0,4}+[1-9])0*") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/re.py", line 188, in compile return _compile(pattern, flags) File "/usr/lib/python2.5/re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat </code></pre> <p>The problem is the "+" after "{0,4}", it seems it doesn't work in python (even in 2.6)</p> <p>How can I write a working regex?</p> <p>PS: I know you can start dividing by 10 and then using the remainder n%100000... but this is a problem about regex.<br /></p>
1
2009-06-15T14:48:59Z
12,403,996
<p>This is my solution.</p> <pre><code>re.search(r'[1-9]\d{0,3}[1-9](?=0*(?:\b|\s|[A-Za-z]))', '02324560001230045980a').group(1) </code></pre> <p>'4598'</p> <ul> <li><code>[1-9]</code> - the number must start with 1 - 9</li> <li><code>\d{0,3}</code> - 0 or 3 digits</li> <li><code>[1-9]</code> - the number must finish with 1 or 9</li> <li><code>(?=0*(:?\b|\s\|[A-Za-z]))</code> - the final part of string must be formed from 0 and or <code>\b</code>, <code>\s</code>, <code>[A-Za-z]</code></li> </ul>
0
2012-09-13T10:13:53Z
[ "python", "regex", "regexbuddy" ]
How can i write my own aggregate functions with sqlalchemy?
996,922
<p>How can I write my own aggregate functions with SQLAlchemy? As an easy example I would like to use numpy to calculate the variance. With sqlite it would look like this:</p> <pre><code>import sqlite3 as sqlite import numpy as np class self_written_SQLvar(object): def __init__(self): import numpy as np self.values = [] def step(self, value): self.values.append(value) def finalize(self): return np.array(self.values).var() cxn = sqlite.connect(':memory:') cur = cxn.cursor() cxn.create_aggregate("self_written_SQLvar", 1, self_written_SQLvar) # Now - how to use it: cur.execute("CREATE TABLE 'mytable' ('numbers' INTEGER)") cur.execute("INSERT INTO 'mytable' VALUES (1)") cur.execute("INSERT INTO 'mytable' VALUES (2)") cur.execute("INSERT INTO 'mytable' VALUES (3)") cur.execute("INSERT INTO 'mytable' VALUES (4)") a = cur.execute("SELECT avg(numbers), self_written_SQLvar(numbers) FROM mytable") print a.fetchall() &gt;&gt;&gt; [(2.5, 1.25)] </code></pre>
4
2009-06-15T15:59:46Z
997,467
<p>The creation of new aggregate functions is backend-dependant, and must be done directly with the API of the underlining connection. SQLAlchemy offers no facility for creating those.</p> <p>However after created you can just use them in SQLAlchemy normally.</p> <p>Example:</p> <pre><code>import sqlalchemy from sqlalchemy import Column, Table, create_engine, MetaData, Integer from sqlalchemy import func, select from sqlalchemy.pool import StaticPool from random import randrange import numpy import sqlite3 class NumpyVarAggregate(object): def __init__(self): self.values = [] def step(self, value): self.values.append(value) def finalize(self): return numpy.array(self.values).var() def sqlite_memory_engine_creator(): con = sqlite3.connect(':memory:') con.create_aggregate("np_var", 1, NumpyVarAggregate) return con e = create_engine('sqlite://', echo=True, poolclass=StaticPool, creator=sqlite_memory_engine_creator) m = MetaData(bind=e) t = Table('mytable', m, Column('id', Integer, primary_key=True), Column('number', Integer) ) m.create_all() </code></pre> <p>Now for the testing:</p> <pre><code># insert 30 random-valued rows t.insert().execute([{'number': randrange(100)} for x in xrange(30)]) for row in select([func.avg(t.c.number), func.np_var(t.c.number)]).execute(): print 'RESULT ROW: ', row </code></pre> <p>That prints (with SQLAlchemy statement echo turned on):</p> <pre><code>2009-06-15 14:55:34,171 INFO sqlalchemy.engine.base.Engine.0x...d20c PRAGMA table_info("mytable") 2009-06-15 14:55:34,174 INFO sqlalchemy.engine.base.Engine.0x...d20c () 2009-06-15 14:55:34,175 INFO sqlalchemy.engine.base.Engine.0x...d20c CREATE TABLE mytable ( id INTEGER NOT NULL, number INTEGER, PRIMARY KEY (id) ) 2009-06-15 14:55:34,175 INFO sqlalchemy.engine.base.Engine.0x...d20c () 2009-06-15 14:55:34,176 INFO sqlalchemy.engine.base.Engine.0x...d20c COMMIT 2009-06-15 14:55:34,177 INFO sqlalchemy.engine.base.Engine.0x...d20c INSERT INTO mytable (number) VALUES (?) 2009-06-15 14:55:34,177 INFO sqlalchemy.engine.base.Engine.0x...d20c [[98], [94], [7], [1], [79], [77], [51], [28], [85], [26], [34], [68], [15], [43], [52], [97], [64], [82], [11], [71], [27], [75], [60], [85], [42], [40], [76], [12], [81], [69]] 2009-06-15 14:55:34,178 INFO sqlalchemy.engine.base.Engine.0x...d20c COMMIT 2009-06-15 14:55:34,180 INFO sqlalchemy.engine.base.Engine.0x...d20c SELECT avg(mytable.number) AS avg_1, np_var(mytable.number) AS np_var_1 FROM mytable 2009-06-15 14:55:34,180 INFO sqlalchemy.engine.base.Engine.0x...d20c [] RESULT ROW: (55.0, 831.0) </code></pre> <p>Note that I didn't use SQLAlchemy's ORM (just the sql expression part of SQLAlchemy was used) but you could use ORM just as well.</p>
8
2009-06-15T18:01:31Z
[ "python", "sqlite", "sqlalchemy", "aggregate-functions" ]
How can i write my own aggregate functions with sqlalchemy?
996,922
<p>How can I write my own aggregate functions with SQLAlchemy? As an easy example I would like to use numpy to calculate the variance. With sqlite it would look like this:</p> <pre><code>import sqlite3 as sqlite import numpy as np class self_written_SQLvar(object): def __init__(self): import numpy as np self.values = [] def step(self, value): self.values.append(value) def finalize(self): return np.array(self.values).var() cxn = sqlite.connect(':memory:') cur = cxn.cursor() cxn.create_aggregate("self_written_SQLvar", 1, self_written_SQLvar) # Now - how to use it: cur.execute("CREATE TABLE 'mytable' ('numbers' INTEGER)") cur.execute("INSERT INTO 'mytable' VALUES (1)") cur.execute("INSERT INTO 'mytable' VALUES (2)") cur.execute("INSERT INTO 'mytable' VALUES (3)") cur.execute("INSERT INTO 'mytable' VALUES (4)") a = cur.execute("SELECT avg(numbers), self_written_SQLvar(numbers) FROM mytable") print a.fetchall() &gt;&gt;&gt; [(2.5, 1.25)] </code></pre>
4
2009-06-15T15:59:46Z
1,052,543
<p>at first you have to import func from sqlalchemy</p> <p>you can write </p> <p>func.avg('fieldname')</p> <p>or func.avg('fieldname').label('user_deined') </p> <p>or you can go thru for mre information </p> <p><a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#using-subqueries" rel="nofollow">http://www.sqlalchemy.org/docs/05/ormtutorial.html#using-subqueries</a></p>
1
2009-06-27T10:07:39Z
[ "python", "sqlite", "sqlalchemy", "aggregate-functions" ]
Refactor this block cipher keying function
996,965
<p>I found a simple pure python blowfish implementation that meets my needs for a particular project.</p> <p>There's just one part of it that bothers me:</p> <pre><code>def initialize(key): """ Use key to setup subkeys -- requires 521 encryptions to set p and s boxes. key is a hex number corresponding to a string of 32 up to 448 1s and 0s -- keylen says how long """ # Note that parray and sboxes are globals that have been pre-initialized. hexkey = hex(key)[2:] if hexkey[-1]=='L': hexkey = hexkey[:-1] if len(hexkey)%2==1: hexkey = '0'+hexkey lenkey = len(hexkey)/8 if lenkey==0: pos=0 # XOR key segments with P-boxes for i in range(18): if lenkey&gt;0: pos = (i%lenkey)*8 # offset into key gives subkey subkey = eval('0x'+hexkey[pos:pos+8]+'L') parray[i] ^= subkey # immediate XOR -- Python 2.0+ syntax # encrypt 0-data, then keep re-encrypting and reassigning P-boxes output = 0L for i in range(0,17,2): output = bfencrypt(output) parray[i], parray[i+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # re-encrypt and reassign through all the S-boxes for i in range(4): for j in range(0,255,2): output = bfencrypt(output) sbox[i][j],sbox[i][j+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # print "Initialization complete" </code></pre> <p><strong><code>subkey = eval('0x'+hexkey[pos:pos+8]+'L')</code></strong>? Please tell me there's a better way to do this.</p> <p>Isn't there a way to refactor this to use an actual integer type rather than hex values in a string?</p>
1
2009-06-15T16:10:33Z
997,012
<p>Yes. Use int() with a base of 16.</p> <pre><code>&gt;&gt;&gt; int('ffffffff',16) 4294967295L </code></pre> <p>so:</p> <pre><code>subkey = int(hexkey[pos:pos+8], 16) </code></pre> <p>should do the same thing without needing eval.</p> <p><strong>[Edit]</strong> In fact, there's generally no reason why you'd need to convert to a string representation at all, given an integer - you can simply extract out each 32 bit value by ANDing with <code>0xffffffff</code> and shifting the key right by 32 bits in a loop. eg:</p> <pre><code>subkeys = [] while key: subkeys.append(key &amp; 0xffffffff) key &gt;&gt;= 32 if not subkeys: subkeys = [0] # Handle 0 case subkeys.reverse() # Use same order as before (BUT SEE BELOW) </code></pre> <p>However, this initialization process seems a bit odd - it's using the hex digits starting from the left, with no zero padding to round to a multiple of 8 hex digits (so the number <code>0x123456789</code> would be split into <code>0x12345678</code> and <code>0x9</code>, rather than the more customary <code>0x00000001</code> and <code>0x23456789</code>. It also repeats these numbers, rather than treating it as a single large number. You should check that this code is actually performing the correct algorithm.</p>
5
2009-06-15T16:19:31Z
[ "python", "encryption" ]
Refactor this block cipher keying function
996,965
<p>I found a simple pure python blowfish implementation that meets my needs for a particular project.</p> <p>There's just one part of it that bothers me:</p> <pre><code>def initialize(key): """ Use key to setup subkeys -- requires 521 encryptions to set p and s boxes. key is a hex number corresponding to a string of 32 up to 448 1s and 0s -- keylen says how long """ # Note that parray and sboxes are globals that have been pre-initialized. hexkey = hex(key)[2:] if hexkey[-1]=='L': hexkey = hexkey[:-1] if len(hexkey)%2==1: hexkey = '0'+hexkey lenkey = len(hexkey)/8 if lenkey==0: pos=0 # XOR key segments with P-boxes for i in range(18): if lenkey&gt;0: pos = (i%lenkey)*8 # offset into key gives subkey subkey = eval('0x'+hexkey[pos:pos+8]+'L') parray[i] ^= subkey # immediate XOR -- Python 2.0+ syntax # encrypt 0-data, then keep re-encrypting and reassigning P-boxes output = 0L for i in range(0,17,2): output = bfencrypt(output) parray[i], parray[i+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # re-encrypt and reassign through all the S-boxes for i in range(4): for j in range(0,255,2): output = bfencrypt(output) sbox[i][j],sbox[i][j+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # print "Initialization complete" </code></pre> <p><strong><code>subkey = eval('0x'+hexkey[pos:pos+8]+'L')</code></strong>? Please tell me there's a better way to do this.</p> <p>Isn't there a way to refactor this to use an actual integer type rather than hex values in a string?</p>
1
2009-06-15T16:10:33Z
997,030
<p>An alternative is "int('0x111', 0)". int's second argument is the base. "0" means "use the usual rules: no prefix is decimal, 0 prefix is octal and 0x is hexa -- just like eval".</p> <p>This is the preferred way to "emulate" the eval operation for intifying strings.</p>
1
2009-06-15T16:22:27Z
[ "python", "encryption" ]
Refactor this block cipher keying function
996,965
<p>I found a simple pure python blowfish implementation that meets my needs for a particular project.</p> <p>There's just one part of it that bothers me:</p> <pre><code>def initialize(key): """ Use key to setup subkeys -- requires 521 encryptions to set p and s boxes. key is a hex number corresponding to a string of 32 up to 448 1s and 0s -- keylen says how long """ # Note that parray and sboxes are globals that have been pre-initialized. hexkey = hex(key)[2:] if hexkey[-1]=='L': hexkey = hexkey[:-1] if len(hexkey)%2==1: hexkey = '0'+hexkey lenkey = len(hexkey)/8 if lenkey==0: pos=0 # XOR key segments with P-boxes for i in range(18): if lenkey&gt;0: pos = (i%lenkey)*8 # offset into key gives subkey subkey = eval('0x'+hexkey[pos:pos+8]+'L') parray[i] ^= subkey # immediate XOR -- Python 2.0+ syntax # encrypt 0-data, then keep re-encrypting and reassigning P-boxes output = 0L for i in range(0,17,2): output = bfencrypt(output) parray[i], parray[i+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # re-encrypt and reassign through all the S-boxes for i in range(4): for j in range(0,255,2): output = bfencrypt(output) sbox[i][j],sbox[i][j+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # print "Initialization complete" </code></pre> <p><strong><code>subkey = eval('0x'+hexkey[pos:pos+8]+'L')</code></strong>? Please tell me there's a better way to do this.</p> <p>Isn't there a way to refactor this to use an actual integer type rather than hex values in a string?</p>
1
2009-06-15T16:10:33Z
997,032
<p>You can do this with the long function:</p> <pre><code>subkey = long(hexkey[pos:pos+8], 16) </code></pre> <p>From <code>help(long)</code>:</p> <blockquote> <p>class long(object)<br /> | long(x[, base]) -> integer<br /> |<br /> | Convert a string or number to a long integer, if possible. A floating<br /> | point argument will be truncated towards zero (this does not include a<br /> | string representation of a floating point number!) When converting a<br /> | string, use the optional base. It is an error to supply a base when<br /> | converting a non-string. </p> </blockquote>
0
2009-06-15T16:22:51Z
[ "python", "encryption" ]
Refactor this block cipher keying function
996,965
<p>I found a simple pure python blowfish implementation that meets my needs for a particular project.</p> <p>There's just one part of it that bothers me:</p> <pre><code>def initialize(key): """ Use key to setup subkeys -- requires 521 encryptions to set p and s boxes. key is a hex number corresponding to a string of 32 up to 448 1s and 0s -- keylen says how long """ # Note that parray and sboxes are globals that have been pre-initialized. hexkey = hex(key)[2:] if hexkey[-1]=='L': hexkey = hexkey[:-1] if len(hexkey)%2==1: hexkey = '0'+hexkey lenkey = len(hexkey)/8 if lenkey==0: pos=0 # XOR key segments with P-boxes for i in range(18): if lenkey&gt;0: pos = (i%lenkey)*8 # offset into key gives subkey subkey = eval('0x'+hexkey[pos:pos+8]+'L') parray[i] ^= subkey # immediate XOR -- Python 2.0+ syntax # encrypt 0-data, then keep re-encrypting and reassigning P-boxes output = 0L for i in range(0,17,2): output = bfencrypt(output) parray[i], parray[i+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # re-encrypt and reassign through all the S-boxes for i in range(4): for j in range(0,255,2): output = bfencrypt(output) sbox[i][j],sbox[i][j+1] = output&gt;&gt;32, output &amp; 0xFFFFFFFFL # print "Initialization complete" </code></pre> <p><strong><code>subkey = eval('0x'+hexkey[pos:pos+8]+'L')</code></strong>? Please tell me there's a better way to do this.</p> <p>Isn't there a way to refactor this to use an actual integer type rather than hex values in a string?</p>
1
2009-06-15T16:10:33Z
997,758
<p><strong>Don't use this code, much less try to improve it.</strong></p> <p>Using crypto code found on the internet is likely to cause serious security failures in your software. See <a href="http://www.codinghorror.com/blog/archives/001275.html" rel="nofollow">Jeff Atwood's little series</a> on the topic.</p> <p>It is much better to use a proven crypto library at the highest possible level of abstraction. Ideally one that implements all the key handling in C and takes care of destroying key material after use.</p> <p>One problem of doing crypto in Python is that you have no control over proliferation of key material in memory due to the nature of Python strings and the garbage collection process.</p>
3
2009-06-15T19:00:14Z
[ "python", "encryption" ]
Unit testing for exceptions in Python constructor
997,244
<p>I'm just a beginner in Python and programming in general, and have some questions about the unittest module. </p> <p>I have a class, and in the <code>__init__</code> method I am doing some assertions to check for bad arguments. I would like to create a unittest which checks for such AssertionError when creating new instances. </p> <p>In the unittest module, one can test (with <code>assertRaises</code>) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor?</p> <p>p.s. I know that I can just try to create an instance of the class with bad arguments, and unittest will report a test failure, but that stops immeditately after the first such exception, and even if I can wrap multile tests in multiple test functions, it just doesn't seem elegant at all...</p>
7
2009-06-15T17:10:21Z
997,281
<p>Well, as a start, checking for bad arguments is not a good idea in python. Python is dynamically strong typed for a reason.</p> <p>You should just assume that the arguments are good arguments. You never know your class' users' intent so by checking for good arguments is a way to limit usage of your class in more generic instances.</p> <p>Instead define a good API and document it very well, using docstrings and text, and leave errors of bad arguments flow automatically to the user.</p> <p>Example:</p> <pre><code>def sum_two_values(value_a, value_b): return value_a + value_b </code></pre> <p>okay, this example is stupid, but if I check and assert the value as integer, the function won't work with floats, strings, list, for no reason other than my check, so why check in first place? It will automatically fail with types that it wouldn't work, so you don't have to worry.</p>
1
2009-06-15T17:18:20Z
[ "python", "unit-testing", "constructor" ]
Unit testing for exceptions in Python constructor
997,244
<p>I'm just a beginner in Python and programming in general, and have some questions about the unittest module. </p> <p>I have a class, and in the <code>__init__</code> method I am doing some assertions to check for bad arguments. I would like to create a unittest which checks for such AssertionError when creating new instances. </p> <p>In the unittest module, one can test (with <code>assertRaises</code>) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor?</p> <p>p.s. I know that I can just try to create an instance of the class with bad arguments, and unittest will report a test failure, but that stops immeditately after the first such exception, and even if I can wrap multile tests in multiple test functions, it just doesn't seem elegant at all...</p>
7
2009-06-15T17:10:21Z
997,332
<p>Don't mess with assertRaises. It's too complicated.</p> <p>Do this</p> <pre><code>class Test_Init( unittest.TestCase ): def test_something( self ): try: x= Something( "This Should Fail" ) self.fail( "Didn't raise AssertionError" ) except AssertionError, e: self.assertEquals( "Expected Message", e.message ) self.assertEquals( args, e.args ) </code></pre> <p>Any other exception will be an ordinary test error.</p> <p>Also, don't mess with too much up-front error checking in an <code>__init__</code> method. If someone provides an object of the wrong type, your code will fail in the normal course of events and raise a normal exception through normal means. You don't need to "pre-screen" objects all that much.</p>
5
2009-06-15T17:30:42Z
[ "python", "unit-testing", "constructor" ]
Unit testing for exceptions in Python constructor
997,244
<p>I'm just a beginner in Python and programming in general, and have some questions about the unittest module. </p> <p>I have a class, and in the <code>__init__</code> method I am doing some assertions to check for bad arguments. I would like to create a unittest which checks for such AssertionError when creating new instances. </p> <p>In the unittest module, one can test (with <code>assertRaises</code>) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor?</p> <p>p.s. I know that I can just try to create an instance of the class with bad arguments, and unittest will report a test failure, but that stops immeditately after the first such exception, and even if I can wrap multile tests in multiple test functions, it just doesn't seem elegant at all...</p>
7
2009-06-15T17:10:21Z
997,353
<blockquote> <p>In the unittest module, one can test (with <code>assertRaises</code>) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor?</p> </blockquote> <p>The constructor is itself a callable:</p> <pre><code>self.assertRaises(AssertionError, MyClass, arg1, arg2) </code></pre> <p>That being said, I want to echo nosklo's and S.Lott's concerns about doing type checking of arguments. Furthermore, you shouldn't be using assertions to check function arguments: assertions are most useful as sanity checks that won't get triggered unless something is internally wrong with your code. Also, assert statements are compiled out when Python is run in "optimized" <code>-O</code> mode. If a function needs to do some sort of checking of its arguments, it should raise a proper exception.</p>
13
2009-06-15T17:34:49Z
[ "python", "unit-testing", "constructor" ]
Unit testing for exceptions in Python constructor
997,244
<p>I'm just a beginner in Python and programming in general, and have some questions about the unittest module. </p> <p>I have a class, and in the <code>__init__</code> method I am doing some assertions to check for bad arguments. I would like to create a unittest which checks for such AssertionError when creating new instances. </p> <p>In the unittest module, one can test (with <code>assertRaises</code>) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor?</p> <p>p.s. I know that I can just try to create an instance of the class with bad arguments, and unittest will report a test failure, but that stops immeditately after the first such exception, and even if I can wrap multile tests in multiple test functions, it just doesn't seem elegant at all...</p>
7
2009-06-15T17:10:21Z
1,454,676
<p>S.Lott's answer is incorrect: self.fail() itself raises an exception, which will then be cause by the except in the following line:</p> <pre><code>class NetworkConfigTest1(unittest.TestCase): def runTest(self): try: NetworkConfig("192.168.256.0/24") self.fail("Exception expected but not thrown") except Exception, error: printf("Exception caught: %s" % str(error) pass </code></pre> <p>The output was "Exception expected but not thrown" but the unit test was not marked as a failure, even though the code being tested had not been written!</p> <p>A more valid way to check if a method raises an exception would be to use:</p> <p>self.failUnlessRaises([error], [callable], [arguments to callable])</p> <p>In my case the class I'm testing is called NetworkConfig, and the constructor must throw an exception if the network descriptor is invalid. And what worked is:</p> <pre><code>class NetworkConfigTest1(unittest.TestCase): def runTest(self): self.failUnlessRaises(Exception, NetworkConfig, "192.168.256.0/24") </code></pre> <p>This works as desired and performs the correct test.</p>
0
2009-09-21T14:04:04Z
[ "python", "unit-testing", "constructor" ]
Unit testing for exceptions in Python constructor
997,244
<p>I'm just a beginner in Python and programming in general, and have some questions about the unittest module. </p> <p>I have a class, and in the <code>__init__</code> method I am doing some assertions to check for bad arguments. I would like to create a unittest which checks for such AssertionError when creating new instances. </p> <p>In the unittest module, one can test (with <code>assertRaises</code>) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor?</p> <p>p.s. I know that I can just try to create an instance of the class with bad arguments, and unittest will report a test failure, but that stops immeditately after the first such exception, and even if I can wrap multile tests in multiple test functions, it just doesn't seem elegant at all...</p>
7
2009-06-15T17:10:21Z
15,909,885
<p>Don't know is this helps, but a problem I was having is as follows:</p> <pre><code>self.assertRaises(Exception, MyFunction()) </code></pre> <p>Problem is I was not just passing <code>MyFunction</code>, but calling it as well, resulting in a fail and Exception being raised. <code>Myfunction</code> expects an argument, and I want it to fail if nothing is passed in. Frustrated me for a while till I figured it out:</p> <pre><code>self.assertRaises(Exception, MyFunction) </code></pre> <p>Works as expected.</p>
0
2013-04-09T18:36:50Z
[ "python", "unit-testing", "constructor" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,329
<p>Bubble sort is a horrible algorithm to sort with. That is quite possibly the reason. If speed is necessary, I would try another algorithm like quick sort or merge sort. </p>
25
2009-06-15T17:30:01Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,334
<p>If you're interested in making your own sort, you can change a bubble sort to a comb sort with just a couple lines of code. Comb sort is nearly as good as the best sorts. Of course, making your own sort is best left as a learning exercise.</p> <blockquote> <p>Comb sort improves on bubble sort, and rivals in speed more complex algorithms like Quicksort.</p> </blockquote> <p><a href="http://en.wikipedia.org/wiki/Comb_sort" rel="nofollow">http://en.wikipedia.org/wiki/Comb_sort</a></p>
1
2009-06-15T17:30:51Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,337
<p>That doesn't look like bubble sort to me, and if it is, it's a very inefficient implementation of it.</p>
1
2009-06-15T17:32:05Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,361
<p>Like the other posts say, bubble sort is horrible. It pretty much should be avoided at all costs due to the bad proformance, like you're experiencing.<br /> Luckily for you there are lots of other sorting algorithms, <a href="http://en.wikipedia.org/wiki/Sorting%5Falgorithm" rel="nofollow">http://en.wikipedia.org/wiki/Sorting_algorithm</a>, for examples.</p> <p>In my experience in school is that quicksort and mergesort are the other two basic sorting algorithms introduced with, or shortly after, bubble sort. So I would recommend you look into those for learning more effective ways to sort.</p>
0
2009-06-15T17:36:01Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,396
<p>That's not quite a bubble sort... unless I've made a trivial error, this would be closer to a python bubble sort:</p> <pre><code>swapped = True while swapped: swapped = False for i in xrange(len(l)-1): if l[i] &gt; l[i+1]: l[i],l[i+1] = l[i+1],l[i] swapped = True </code></pre> <p>Note that the whole idea is that the "bubble" moves along the array, swapping adjacent values until it moves through the list, with nothing swapped. There are a few optimizations that can be made (such as shrinking the size of the inner loop), but they are usually only worth bothering with when you are "homework oriented".</p> <p>Edit: Fixed length() -> len()</p>
12
2009-06-15T17:43:02Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,427
<p>Bubble sort may be <em>horrible</em> and <em>slow</em> etc, but would you rather have an O(N^2) algorithm over 100 items, or O(1) one that required a dial-up connection?</p> <p>And a list of 100 items shouldnt take 2 hours. I don't know python, but are you by any chance copying entire lists when you make those assignments?</p> <p>Here's a bubble sort in Python (from Google because I am lazy):</p> <pre><code>def bubbleSort(theList, max): for n in range(0,max): #upper limit varies based on size of the list temp = 0 for i in range(1, max): #keep this for bounds purposes temp = theList[i] if theList[i] &lt; theList[i-1]: theList[i] = theList[i-1] theList[i-1] = temp </code></pre> <p>and another, from wikipedia:</p> <pre><code>def bubblesort(l): "Sorts l in place and returns it." for passesLeft in range(len(l)-1, 0, -1): for index in range(passesLeft): if l[index] &lt; l[index + 1]: l[index], l[index + 1] = l[index + 1], l[index] return l </code></pre> <p>The order of bubble sort is N(N-1). This is essentially N^2, because for every element you require to scan the list and compare every element.</p> <p>By the way, you will probably find C++ to be the fastest, then Java, then Python.</p>
6
2009-06-15T17:50:32Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,463
<p>What do you mean by numpy solution ? Numpy has some sort facilities, which are instantenous for those reasonably small arrays:</p> <pre><code>import numpy as np a = np.random.randn(100000) # Take a few ms on a decent computer np.sort(a) </code></pre> <p>There are 3 sorts of sort algorithms available, all are Nlog(N) on average.</p>
5
2009-06-15T18:01:21Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,578
<p>If you must code your own, use an insertion sort. Its about the same amount of code, but several times faster.</p>
0
2009-06-15T18:24:39Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,613
<p>For one, you're doing too many loops. Your inner loop should proceed from i + 1 to the end of the list, not from 0. Secondly, as noted by others, bubble sort has a O(N^2) complexity so for 100000 elements, you are looping 10,000,000,000 times. This is compounded by the fact that looping is one of the areas where interpreted languages have the worst performance. It all adds up to incredibly poor performance. This is why any computations that require such tight looping are usually written in C/C++ and wrapped for use by languages like Python.</p>
2
2009-06-15T18:33:27Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,707
<p>I believe you mentioned that you were trying to use that as a benchmark to compare speeds.</p> <p>I think generally Python is a bit faster than Ruby, but not really near Java/C/C++/C#. Java is within 2x of the C's, but all the interpreted languages were around 100x slower. </p> <p>You might Google "Programming Language Game" for a LOT of comparisons of apps/languages/etc. Check out a Python JIT for possibly better performance.</p> <p>You might also compare it to Ruby to see a more fair test. </p> <p>Edit: Just for fun (nothing to do with the question) check this--</p> <pre><code>public class Test { public static void main(String[]s) { int size=Integer.valueOf(s[0]).intValue(); Random r=new Random(); int[] l=new int[size]; for(int i=0;i&lt;size;i++) l[i]=r.nextInt(); long ms=(new Date()).getTime(); System.out.println("built"); if(fast) { Arrays.sort(l); else { int temp; for(int i=0;i&lt;size;i++) for(int j=0;j&lt;size;j++) if(l[i]&gt;l[j]) { temp=l[i]; l[j]=l[i]; l[j]=temp; } } ms=(new Date()).getTime()-ms; System.out.println("done in "+ms/1000); } } </code></pre> <p>The fun thing about this: The Java run times are on the order of:</p> <pre> Array size Slow Time Fast time 100k 2s 0s 1M 23s 0s 10M 39m 2s 100M NO 23s </pre> <p>Not that this addition has anything to do with the question, but holy cow the built-in impelemntation is FAST. I think it took longer to generate than sort (Guess that makes sense with calls to Random and memory allocation.)</p> <p>Had to go into the CLI and -Xmx1000M to get that last one to even run.</p>
4
2009-06-15T18:51:44Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,720
<p>Because it is going execute the comparison and possibly the swap 100,000 x 100,000 times. If the computer is fast enough to execute the innermost statement 1,000,000 times per second, that still is 167 minutes which is slightly short of 3 hours.</p> <p>On a side note, why are there so many of these inane questions on SO? <a href="http://www.codinghorror.com/blog/archives/001249.html" rel="nofollow">Isn't being able to do simple algebra a prerequisite for programming?</a> ;-)</p>
1
2009-06-15T18:53:53Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,917
<p>Here some code I put together to compare a base bubble sort against a more streamlined version (base vs modified) - the modified is about 2-3 times faster, still a slow sort, but faster</p> <pre><code>from array import * from random import * from time import * def randarray(typecode, numElements, minValue, maxValue): a = array(typecode) for i in xrange(0, numElements): a.append(randint(minValue, maxValue)) return a def basesort(l): for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&lt;l[j]: l[i], l[j] = l[j], l[i] return l def modifiedsort(l): NotComplete = True i = 0 arange = xrange(len(l)) while NotComplete: NotComplete = False for j in xrange(len(l) - i): if l[i]&lt;l[j]: l[i], l[j] = l[j], l[i] NotComplete = True i += 1 Num = 1000 b = randarray('i', Num, 1, 100000) m = b[:] print 'perform base bubble sort' t = time() basesort(b) basetime = time() - t print basetime #print a print 'complete' print 'perform modified bubble sort' t = time() modifiedsort(m) modtime = time() - t print modtime #print a print 'complete' print 'mod sort is ', basetime / modtime,' fast then base sort' </code></pre>
2
2009-06-15T19:28:22Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,984
<p>I think that you are basically wasting your time using bubble on such a large dataset. There are 3 reasons why it is slow:</p> <p>1) Python is slow 2) Bubble sort is slow 3) The bubble sort listed is coded incorrectly/inefficiently.</p> <p>Regardless of how it is coded, it will be O(N^2). Why not use a merge/tree sort ..or if you want to try quicksort (also worst case O(N^2)) it might be faster for your particular dataset. I believe quicksort is empirically faster if the data already has a lot of ordering in it.</p>
2
2009-06-15T19:43:36Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
997,994
<p>Bubblesort in general does not scale well to most possible inputs as the number of elements in the input grows. (I.e., it's O(N^2).)</p> <p>As N grows, given a random input array of size N, you are much less likely to get an array that sorts quickly with bubblesort (e.g., almost sorted arrays). You are far more likely to get an array that takes a long time to sort.</p> <p>However, the real kicker here is that the code you posted is not a bubble sort. Traditionally, bubblesort will terminate early if no swaps were made as well as not attempt to swap values that are already sorted. (After P number of passes, the P last items will be in the correct order, so you don't need to process them.) The actual code posted will always examine every pair in the array, so it will always run the inner loop N^2 times. For 100000 elements, that's 10000000000 iterations.</p>
2
2009-06-15T19:45:08Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
998,093
<p>Bubble sort makes O(N<sup>2</sup>) compare operations (or iterations). For N = 100,000, that means that there will be 10,000,000,000 iterations. If that takes 2 hours (call it 10,000 seconds), then it means you get 1,000,000 iterations per second - or 1 microsecond per iteration. That's not great speed, but it isn't too bad. And I'm waving hands and ignoring constant multiplication factors.</p> <p>If you used a quicksort, then you'd get Nlog(N) iterations, which would mean about 1,000,000 iterations, which would take 1 second in total. (log<sub>10</sub>(N) is 5; I rounded it up to 10 for simplicity.)</p> <p>So, you have just amply demonstrated why bubble sort is inappropriate for large data sets, and 100,000 items is large enough to demonstrate that.</p>
2
2009-06-15T20:02:54Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
998,116
<p>I forgot to add, if you have some idea of the size of the dataset and the distribution of keys then you can use a radix sort which would be O(N). To get the idea of radix sort, consider the case where you are sorting say numbers more or less distributed between 0, 100,000. Then you just create something similar to a hash table, say an array of 100,000 lists, and add each number to the bucket. Here's an implementation I wrote in a few minutes that generates some random data, sorts it, and prints out a random segment. The time is less than 1 sec to execute for an array of 100,000 integers.</p> <p>Option Strict On Option Explicit On</p> <p>Module Module1</p> <pre><code>Private Const MAX_SIZE As Integer = 100000 Private m_input(MAX_SIZE) As Integer Private m_table(MAX_SIZE) As List(Of Integer) Private m_randomGen As New Random() Private m_operations As Integer = 0 Private Sub generateData() ' fill with random numbers between 0 and MAX_SIZE - 1 For i = 0 To MAX_SIZE - 1 m_input(i) = m_randomGen.Next(0, MAX_SIZE - 1) Next End Sub Private Sub sortData() For i As Integer = 0 To MAX_SIZE - 1 Dim x = m_input(i) If m_table(x) Is Nothing Then m_table(x) = New List(Of Integer) End If m_table(x).Add(x) ' clearly this is simply going to be MAX_SIZE -1 m_operations = m_operations + 1 Next End Sub Private Sub printData(ByVal start As Integer, ByVal finish As Integer) If start &lt; 0 Or start &gt; MAX_SIZE - 1 Then Throw New Exception("printData - start out of range") End If If finish &lt; 0 Or finish &gt; MAX_SIZE - 1 Then Throw New Exception("printData - finish out of range") End If For i As Integer = start To finish If m_table(i) IsNot Nothing Then For Each x In m_table(i) Console.WriteLine(x) Next End If Next End Sub ' run the entire sort, but just print out the first 100 for verification purposes Private Sub test() m_operations = 0 generateData() Console.WriteLine("Time started = " &amp; Now.ToString()) sortData() Console.WriteLine("Time finished = " &amp; Now.ToString &amp; " Number of operations = " &amp; m_operations.ToString()) ' print out a random 100 segment from the sorted array Dim start As Integer = m_randomGen.Next(0, MAX_SIZE - 101) printData(start, start + 100) End Sub Sub Main() test() Console.ReadLine() End Sub </code></pre> <p>End Module Time started = 6/15/2009 4:04:08 PM Time finished = 6/15/2009 4:04:08 PM Number of operations = 100000 21429 21430 21430 21431 21431 21432 21433 21435 21435 21435 21436 21437 21437 21439 21441 ...</p>
0
2009-06-15T20:06:50Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
998,201
<p>You can do</p> <pre><code>l.reverse() </code></pre> <p>Script <em>ee.py</em>:</p> <pre><code>l = [] for i in xrange(100000): l.append(i) l.reverse() </code></pre> <p>lyrae@localhost:~/Desktop$ time python ee.py</p> <pre><code>real 0m0.047s user 0m0.044s sys 0m0.004s </code></pre>
0
2009-06-15T20:25:56Z
[ "python", "bubble-sort" ]
Why is my bubble sort in Python so slow?
997,322
<p>I have the following code thats use bubble sort to invert a list and has a worst time performance:</p> <pre><code>for i in xrange(len(l)): for j in xrange(len(l)): if l[i]&gt;l[j]: l[i], l[j] = l[j], l[i] </code></pre> <p>In some cases (when <code>len(l) = 100000</code>) the code spend more then 2h to complete execute, I think its so strange, please correct my code or give some suggestions. <code>numpy</code> and <code>numarray</code> solutions are welcome. </p>
0
2009-06-15T17:28:22Z
998,370
<p>First of all, for the purpose of this reply, I'm assuming - since you claim it yourself - that you're only doing this to benchmark different languages. So I won't go into "bubble sort is just slow" territory. The real question is why it's so much slower in Python.</p> <p>The answer is that Python is inherently much slower than C++ or even Java. You don't see it in a typical event-driven or I/O-bound application, since there most time is spent either idling while waiting for input, or waiting for I/O calls to complete. In your case, however, the algorithm is entirely CPU bound, and thus you are directly measuring the performance of Python bytecode interpreter. Which, by some estimates, is 20-30x slower than executing the corresponding native code, which is what happens with both C++ and Java.</p> <p>In general, any time you write a long-running CPU-bound loop in Python, you should expect this kind of performance. The only way to fix this is to move <em>the entire loop</em> into C. Moving just the body (e.g. using NumPy) won't help you much, since loop iteration itself will still be executed by Python intepreter.</p>
1
2009-06-15T21:01:04Z
[ "python", "bubble-sort" ]
Any yahoo messenger lib for python?
997,419
<p>Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python? </p>
2
2009-06-15T17:48:32Z
997,444
<p>Google is your friend.</p> <p>The <a href="http://pypi.python.org/pypi">Python Package Index</a> has <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=yahoo&amp;submit=search">several</a> modules to do with Yahoo, including this <a href="http://pypi.python.org/pypi/pyahoolib/0.2">one</a> which matches your requirements.</p>
5
2009-06-15T17:54:59Z
[ "python", "yahoo-messenger" ]
Any yahoo messenger lib for python?
997,419
<p>Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python? </p>
2
2009-06-15T17:48:32Z
3,828,806
<p>There is also the <a href="http://developer.yahoo.com/messenger/guide/index.html" rel="nofollow">Yahoo IM SDK</a> that might help.</p>
1
2010-09-30T07:58:28Z
[ "python", "yahoo-messenger" ]
What does %s mean in Python?
997,797
<p>What does %s mean in Python? And what does the following bit of code do?</p> <p>For instance... </p> <pre><code> if len(sys.argv) &lt; 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) </code></pre>
78
2009-06-15T19:05:10Z
997,807
<p>It is a string formatting syntax (which it borrows from C).</p> <p>Please see <a href="http://www.diveintopython.net/native_data_types/formatting_strings.html">"Formatting Strings"</a>:</p> <blockquote> <p>Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the <code>%s</code> placeholder.</p> </blockquote> <p><strong>Edit:</strong> Here is a really simple example:</p> <pre><code>name = raw_input("who are you?") print "hello %s" % (name,) </code></pre> <p>The <code>%s</code> token allows me to insert (and potentially format) a string. Notice that the <code>%s</code> token is replaced by whatever I pass to the string after the <code>%</code> symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.</p>
85
2009-06-15T19:06:11Z
[ "python" ]
What does %s mean in Python?
997,797
<p>What does %s mean in Python? And what does the following bit of code do?</p> <p>For instance... </p> <pre><code> if len(sys.argv) &lt; 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) </code></pre>
78
2009-06-15T19:05:10Z
997,819
<p>'%s' indicates a conversion type of 'string' when using python's string formatting capabilities. More specifically, '%s' converts a specified value to a string using the str() function. Compare this with the '%r' conversion type that uses the repr() function for value conversion.</p> <p>Take a look at the following: <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations">http://docs.python.org/library/stdtypes.html#string-formatting-operations</a></p>
7
2009-06-15T19:09:30Z
[ "python" ]
What does %s mean in Python?
997,797
<p>What does %s mean in Python? And what does the following bit of code do?</p> <p>For instance... </p> <pre><code> if len(sys.argv) &lt; 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) </code></pre>
78
2009-06-15T19:05:10Z
997,858
<p>In answer to your second question: What does this code do?...</p> <p>This is fairly standard error-checking code for a Python script that accepts command-line arguments.</p> <p>So the first <code>if</code> statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:</p> <pre><code>Usage: myscript.py database-name </code></pre> <p>The next <code>if</code> statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:</p> <pre><code>ERROR: Database database-name was not found! </code></pre> <p>From the <a href="http://docs.python.org/library/sys.html#sys.argv" rel="nofollow">documentation</a>:</p> <blockquote> <p>argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.</p> </blockquote>
3
2009-06-15T19:15:47Z
[ "python" ]
What does %s mean in Python?
997,797
<p>What does %s mean in Python? And what does the following bit of code do?</p> <p>For instance... </p> <pre><code> if len(sys.argv) &lt; 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) </code></pre>
78
2009-06-15T19:05:10Z
998,157
<p>Andrew's answer is good.</p> <p>And just to help you out a bit more, here's how you use multiple formatting in one string</p> <pre><code>"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike". </code></pre> <p>If you are using ints instead of string, use %d instead of %s.</p> <pre><code>"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12 </code></pre>
48
2009-06-15T20:17:14Z
[ "python" ]
What does %s mean in Python?
997,797
<p>What does %s mean in Python? And what does the following bit of code do?</p> <p>For instance... </p> <pre><code> if len(sys.argv) &lt; 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) </code></pre>
78
2009-06-15T19:05:10Z
17,706,778
<p>The <code>format</code> method was introduced in Python 2.6. It is more capable and not much more difficult to use:</p> <pre><code>&gt;&gt;&gt; "Hello {}, my name is {}".format('john', 'mike') 'Hello john, my name is mike'. &gt;&gt;&gt; "{1}, {0}".format('world', 'Hello') 'Hello, world' &gt;&gt;&gt; "{greeting}, {}".format('world', greeting='Hello') 'Hello, world' </code></pre>
5
2013-07-17T17:50:53Z
[ "python" ]
System theme icons and PyQt4
997,904
<p>I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the system's icon theme? If it matters, i'm developing this under ubuntu 9.04, so i am using the gnome desktop.</p>
7
2009-06-15T19:25:28Z
999,002
<p>Use the PyKDE4 KIcon class:</p> <p><a href="http://api.kde.org/pykde-4.2-api/kdeui/KIcon.html" rel="nofollow">http://api.kde.org/pykde-4.2-api/kdeui/KIcon.html</a></p>
0
2009-06-15T23:44:44Z
[ "python", "icons", "pyqt4" ]