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
Is there a more pythonic way to build this dictionary?
753,986
<p>What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: <code>values</code> is a list that is not related to any dictionary.</p> <pre><code>for value in values: new_dict[key_from_value(value)] = value </code></pre>
6
2009-04-15T22:26:44Z
754,154
<p>This method avoids the list comprehension syntax:</p> <pre><code>dict(zip(map(key_from_value, values), values)) </code></pre> <p>I will never claim to be an authority on "Pythonic", but this way feels like a good way.</p>
0
2009-04-15T23:26:40Z
[ "python" ]
Is there a more pythonic way to build this dictionary?
753,986
<p>What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: <code>values</code> is a list that is not related to any dictionary.</p> <pre><code>for value in values: new_dict[key_from_value(value)] = value </code></pre>
6
2009-04-15T22:26:44Z
755,252
<p>Py3K:</p> <pre><code>{ key_for_value(value) : value for value in values } </code></pre>
5
2009-04-16T08:42:09Z
[ "python" ]
Python: Read a file (from an external server)
754,170
<p>Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function.</p> <p>It would be great if someone could post the entire code for such a script.</p> <p>Thanks in advance!</p>
0
2009-04-15T23:33:46Z
754,175
<p>The entire script is:</p> <pre><code>import urllib content = urllib.urlopen('http://www.google.com/').read() </code></pre>
12
2009-04-15T23:35:55Z
[ "python", "file" ]
Python: Read a file (from an external server)
754,170
<p>Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function.</p> <p>It would be great if someone could post the entire code for such a script.</p> <p>Thanks in advance!</p>
0
2009-04-15T23:33:46Z
754,501
<p>better would be the same as Jarret's code, but using urllib2:</p> <pre><code>import urllib2 content = urllib2.urlopen('http://google.com').read() </code></pre> <p>urllib2 is a bit newer and more modern. Doesn't matter too much in your case, but it's good practice to use it.</p>
5
2009-04-16T02:10:18Z
[ "python", "file" ]
How to know when to manage resources in Python
754,187
<p>I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this:</p> <pre><code>for file in os.listdir(dir): y=open(dir+'\\'+file,'r').readlines() for line in y: pass y.close() </code></pre> <p>It should be no surprise that I get an AttributeError since y is a list. I didn't think about that when I wrote the snippet. </p> <p>I am thinking about this and am afraid that I have five open files (there are five files in the directory specified by dir.</p> <p>I can fix the code so it runs and I explicitly close the files after opening them. I am curious if I need to or if Python handles closing the file in the next iteration of the loop. If so then I only need to write:</p> <pre><code>for file in os.listdir(dir): y=open(dir+'\\'+file,'r').readlines() for line in y: pass </code></pre> <p>I am guessing that it(python) does handle this effortlessly. The reason I think that this might be handled is that I have changed the object/thing that y is referencing. When I start the second iteration there are no more memory references to the file that was opened and read using the readlines method. </p>
4
2009-04-15T23:39:48Z
754,215
<p>Python will close open files when they get garbage-collected, so generally you can forget about it -- particularly when reading.</p> <p>That said, if you want to close explicitely, you could do this:</p> <pre><code>for file in os.listdir(dir): f = open(dir+'\\'+file,'r') y = f.readlines() for line in y: pass f.close() </code></pre> <p>However, we can immediately improve this, because in python you can iterate over file-like objects directly:</p> <pre><code>for file in os.listdir(dir): y = open(dir+'\\'+file,'r') for line in y: pass y.close() </code></pre> <p>Finally, in recent python, there is the '<a href="http://docs.python.org/whatsnew/2.6.html#pep-343-the-with-statement">with</a>' statement:</p> <pre><code>for file in os.listdir(dir): with open(dir+'\\'+file,'r') as y: for line in y: pass </code></pre> <p>When the <code>with</code> block ends, python will close the file for you and clean it up.</p> <p>(you also might want to look into <code>os.path</code> for more pythonic tools for manipulating file names and directories)</p>
11
2009-04-15T23:47:26Z
[ "python", "garbage-collection" ]
How to know when to manage resources in Python
754,187
<p>I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this:</p> <pre><code>for file in os.listdir(dir): y=open(dir+'\\'+file,'r').readlines() for line in y: pass y.close() </code></pre> <p>It should be no surprise that I get an AttributeError since y is a list. I didn't think about that when I wrote the snippet. </p> <p>I am thinking about this and am afraid that I have five open files (there are five files in the directory specified by dir.</p> <p>I can fix the code so it runs and I explicitly close the files after opening them. I am curious if I need to or if Python handles closing the file in the next iteration of the loop. If so then I only need to write:</p> <pre><code>for file in os.listdir(dir): y=open(dir+'\\'+file,'r').readlines() for line in y: pass </code></pre> <p>I am guessing that it(python) does handle this effortlessly. The reason I think that this might be handled is that I have changed the object/thing that y is referencing. When I start the second iteration there are no more memory references to the file that was opened and read using the readlines method. </p>
4
2009-04-15T23:39:48Z
754,275
<p>Don't worry about it. Python's garbage collector is good, and I've never had a problem with not closing file-pointers (for read operations at least)</p> <p>If you did want to explicitly close the file, just store the <code>open()</code> in one variable, then call <code>readlines()</code> on that, for example..</p> <pre><code>f = open("thefile.txt") all_lines = f.readlines() f.close() </code></pre> <p>Or, you can use the <code>with</code> statement, which was added in Python 2.5 as a <code>from __future__</code> import, and "properly" added in Python 2.6:</p> <pre><code>from __future__ import with_statement # for python 2.5, not required for &gt;2.6 with open("thefile.txt") as f: print f.readlines() # or the_file = open("thefile.txt") with the_file as f: print f.readlines() </code></pre> <p>The file will automatically be closed at the end of the block.</p> <p>..but, there are other more important things to worry about in the snippets you posted, mostly stylistic things.</p> <p>Firstly, try to avoid manually constructing paths using string-concatenation. The <a href="http://docs.python.org/library/os.path.html" rel="nofollow"><code>os.path</code></a> module contains lots of methods to do this, in a more reliable, cross-platform manner.</p> <pre><code>import os y = open(os.path.join(dir, file), 'r') </code></pre> <p>Also, you are using two variable names, <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir</code></a> and <a href="http://docs.python.org/library/functions.html#file" rel="nofollow"><code>file</code></a> - both of which are built-in functions. <a href="http://www.logilab.org/857" rel="nofollow">Pylint</a> is a good tool to spot things like this, in this case it would give the warning:</p> <pre><code>[W0622] Redefining built-in 'file' </code></pre>
3
2009-04-16T00:13:07Z
[ "python", "garbage-collection" ]
How is this "referenced before assignment"?
754,421
<p>I have a bit of Python to connect to a database with a switch throw in for local versus live. </p> <pre><code> LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"} LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y", "database": "nottesting"} if debug_mode: connection_info = LOCAL_CONNECTION else: connnection_info = LIVE_CONNECTION self.connection = MySQLdb.connect(host = connection_info["server"], user = connection_info["user"], passwd = connection_info["password"], db = connection_info["database"]) </code></pre> <p>Works fine locally (Windows, Python 2.5) but live (Linux, Python 2.4) I'm getting:</p> <pre><code>UnboundLocalError: local variable 'connection_info' referenced before assignment </code></pre> <p>I see the same error even if I remove the if/ else and just assign connection info directly to the LIVE_CONNECTION value. If I hard-code the live connection values into the last line, it all works. Clearly I'm sleepy. What am I not seeing? </p>
1
2009-04-16T01:17:43Z
754,428
<p>The second assignement is misspelled.</p> <p>You wrote <code>connnection_info = LIVE_CONNECTION</code> with 3 n's.</p>
16
2009-04-16T01:19:32Z
[ "python" ]
How is this "referenced before assignment"?
754,421
<p>I have a bit of Python to connect to a database with a switch throw in for local versus live. </p> <pre><code> LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"} LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y", "database": "nottesting"} if debug_mode: connection_info = LOCAL_CONNECTION else: connnection_info = LIVE_CONNECTION self.connection = MySQLdb.connect(host = connection_info["server"], user = connection_info["user"], passwd = connection_info["password"], db = connection_info["database"]) </code></pre> <p>Works fine locally (Windows, Python 2.5) but live (Linux, Python 2.4) I'm getting:</p> <pre><code>UnboundLocalError: local variable 'connection_info' referenced before assignment </code></pre> <p>I see the same error even if I remove the if/ else and just assign connection info directly to the LIVE_CONNECTION value. If I hard-code the live connection values into the last line, it all works. Clearly I'm sleepy. What am I not seeing? </p>
1
2009-04-16T01:17:43Z
754,429
<p>Typo: connnection_info = LIVE_CONNECTION</p>
4
2009-04-16T01:19:58Z
[ "python" ]
Some Basic Python Questions
754,468
<p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p> <p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Python waters so I figure something simple like this is a good place to start. It seems that I would need to:</p> <ol> <li>load text pasted from MS Word into a variable</li> <li>run some sort of replace function on the contents</li> <li>output it</li> </ol> <p>In PHP I would do it like this:</p> <pre><code>$test = $_POST['pasted_from_Word']; //for example “Going Mobile” function defangWord($string) { $search = array( (chr(0xe2) . chr(0x80) . chr(0x98)), (chr(0xe2) . chr(0x80) . chr(0x99)), (chr(0xe2) . chr(0x80) . chr(0x9c)), (chr(0xe2) . chr(0x80) . chr(0x9d)), (chr(0xe2) . chr(0x80) . chr(0x93)), (chr(0xe2) . chr(0x80) . chr(0x94)), (chr(0x2d)) ); $replace = array( "&amp;lsquo;", "&amp;rsquo;", "&amp;ldquo;", "&amp;rdquo;", "&amp;ndash;", "&amp;mdash;", "&amp;ndash;" ); return str_replace($search, $replace, $string); } echo defangWord($test); </code></pre> <p>How would you do it in Python?</p> <p>EDIT: Hmmm, ok ignore my confusion about UTF-8 and entities for the moment. The input contains text pasted from MS Word. Things like curly quotes are showing up as odd symbols. Various PHP functions I used to try and fix it were not giving me the results I wanted. By viewing those odd symbols in a hex editor I saw that they corresponded to the symbols I used above (0xe2, 0x80 etc.). So I simply swapped out the oddball characters with HTML entities. So if the bit I have above already IS UTF-8, what is being pasted in from MS Word that is causing the odd symbols? </p> <p>EDIT2: So I set out to learn a bit about Python and found I don't really understand encoding. The problem I was trying to solve can be handled simply by having sonsistent encoding from end to end. If the input form is UTF-8, the database that stores the input is UTF-8 and the page that outputs it is UTF-8... pasting from Word works fine. No special functions needed. Now, about learning a little Python...</p>
5
2009-04-16T01:41:41Z
754,473
<p>The Python code has the same outline.</p> <p>Just replace all of the PHP-isms with Python-isms.</p> <p>Start by creating a <a href="http://docs.python.org/library/stdtypes.html#file-objects" rel="nofollow">File</a> object. The result of a file.read() is a <a href="http://docs.python.org/library/stdtypes.html#string-methods" rel="nofollow">string</a> object. Strings have a "replace" operation. </p>
3
2009-04-16T01:47:24Z
[ "php", "python", "unicode", "replace", "html-entities" ]
Some Basic Python Questions
754,468
<p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p> <p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Python waters so I figure something simple like this is a good place to start. It seems that I would need to:</p> <ol> <li>load text pasted from MS Word into a variable</li> <li>run some sort of replace function on the contents</li> <li>output it</li> </ol> <p>In PHP I would do it like this:</p> <pre><code>$test = $_POST['pasted_from_Word']; //for example “Going Mobile” function defangWord($string) { $search = array( (chr(0xe2) . chr(0x80) . chr(0x98)), (chr(0xe2) . chr(0x80) . chr(0x99)), (chr(0xe2) . chr(0x80) . chr(0x9c)), (chr(0xe2) . chr(0x80) . chr(0x9d)), (chr(0xe2) . chr(0x80) . chr(0x93)), (chr(0xe2) . chr(0x80) . chr(0x94)), (chr(0x2d)) ); $replace = array( "&amp;lsquo;", "&amp;rsquo;", "&amp;ldquo;", "&amp;rdquo;", "&amp;ndash;", "&amp;mdash;", "&amp;ndash;" ); return str_replace($search, $replace, $string); } echo defangWord($test); </code></pre> <p>How would you do it in Python?</p> <p>EDIT: Hmmm, ok ignore my confusion about UTF-8 and entities for the moment. The input contains text pasted from MS Word. Things like curly quotes are showing up as odd symbols. Various PHP functions I used to try and fix it were not giving me the results I wanted. By viewing those odd symbols in a hex editor I saw that they corresponded to the symbols I used above (0xe2, 0x80 etc.). So I simply swapped out the oddball characters with HTML entities. So if the bit I have above already IS UTF-8, what is being pasted in from MS Word that is causing the odd symbols? </p> <p>EDIT2: So I set out to learn a bit about Python and found I don't really understand encoding. The problem I was trying to solve can be handled simply by having sonsistent encoding from end to end. If the input form is UTF-8, the database that stores the input is UTF-8 and the page that outputs it is UTF-8... pasting from Word works fine. No special functions needed. Now, about learning a little Python...</p>
5
2009-04-16T01:41:41Z
754,480
<p>Your best bet for cleaning Word HTML is using <a href="http://tidy.sourceforge.net/" rel="nofollow">HTML Tidy</a> which has a mode just for that. There are <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=tidy&amp;submit=search" rel="nofollow">a few Python wrappers</a> you can use if you need to do it programmatically.</p>
2
2009-04-16T01:53:12Z
[ "php", "python", "unicode", "replace", "html-entities" ]
Some Basic Python Questions
754,468
<p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p> <p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Python waters so I figure something simple like this is a good place to start. It seems that I would need to:</p> <ol> <li>load text pasted from MS Word into a variable</li> <li>run some sort of replace function on the contents</li> <li>output it</li> </ol> <p>In PHP I would do it like this:</p> <pre><code>$test = $_POST['pasted_from_Word']; //for example “Going Mobile” function defangWord($string) { $search = array( (chr(0xe2) . chr(0x80) . chr(0x98)), (chr(0xe2) . chr(0x80) . chr(0x99)), (chr(0xe2) . chr(0x80) . chr(0x9c)), (chr(0xe2) . chr(0x80) . chr(0x9d)), (chr(0xe2) . chr(0x80) . chr(0x93)), (chr(0xe2) . chr(0x80) . chr(0x94)), (chr(0x2d)) ); $replace = array( "&amp;lsquo;", "&amp;rsquo;", "&amp;ldquo;", "&amp;rdquo;", "&amp;ndash;", "&amp;mdash;", "&amp;ndash;" ); return str_replace($search, $replace, $string); } echo defangWord($test); </code></pre> <p>How would you do it in Python?</p> <p>EDIT: Hmmm, ok ignore my confusion about UTF-8 and entities for the moment. The input contains text pasted from MS Word. Things like curly quotes are showing up as odd symbols. Various PHP functions I used to try and fix it were not giving me the results I wanted. By viewing those odd symbols in a hex editor I saw that they corresponded to the symbols I used above (0xe2, 0x80 etc.). So I simply swapped out the oddball characters with HTML entities. So if the bit I have above already IS UTF-8, what is being pasted in from MS Word that is causing the odd symbols? </p> <p>EDIT2: So I set out to learn a bit about Python and found I don't really understand encoding. The problem I was trying to solve can be handled simply by having sonsistent encoding from end to end. If the input form is UTF-8, the database that stores the input is UTF-8 and the page that outputs it is UTF-8... pasting from Word works fine. No special functions needed. Now, about learning a little Python...</p>
5
2009-04-16T01:41:41Z
754,484
<p>As S.Lott said, the Python code would be very, very similar—the only differences would essentially be the function calls/statements.</p> <p>I don't think Python has a direct equivalent to <code>file_get_contents()</code>, but since you can obtain an array of the lines in the file, you can then join them by newlines, like this:</p> <pre><code>sample = '\n'.join(open(test, 'r').readlines()) </code></pre> <p>EDIT: Never mind, there's a much easier way: <code>sample = file(test).read()</code></p> <p>String replacing is almost exactly the same as <code>str_replace()</code>:</p> <pre><code>sample = sample.replace(search, replace) </code></pre> <p>And outputting is as simple as a <code>print</code> statement:</p> <pre><code>print defang_word(sample) </code></pre> <p>So as you can see, the two versions look almost exactly the same.</p>
1
2009-04-16T01:54:55Z
[ "php", "python", "unicode", "replace", "html-entities" ]
Some Basic Python Questions
754,468
<p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p> <p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Python waters so I figure something simple like this is a good place to start. It seems that I would need to:</p> <ol> <li>load text pasted from MS Word into a variable</li> <li>run some sort of replace function on the contents</li> <li>output it</li> </ol> <p>In PHP I would do it like this:</p> <pre><code>$test = $_POST['pasted_from_Word']; //for example “Going Mobile” function defangWord($string) { $search = array( (chr(0xe2) . chr(0x80) . chr(0x98)), (chr(0xe2) . chr(0x80) . chr(0x99)), (chr(0xe2) . chr(0x80) . chr(0x9c)), (chr(0xe2) . chr(0x80) . chr(0x9d)), (chr(0xe2) . chr(0x80) . chr(0x93)), (chr(0xe2) . chr(0x80) . chr(0x94)), (chr(0x2d)) ); $replace = array( "&amp;lsquo;", "&amp;rsquo;", "&amp;ldquo;", "&amp;rdquo;", "&amp;ndash;", "&amp;mdash;", "&amp;ndash;" ); return str_replace($search, $replace, $string); } echo defangWord($test); </code></pre> <p>How would you do it in Python?</p> <p>EDIT: Hmmm, ok ignore my confusion about UTF-8 and entities for the moment. The input contains text pasted from MS Word. Things like curly quotes are showing up as odd symbols. Various PHP functions I used to try and fix it were not giving me the results I wanted. By viewing those odd symbols in a hex editor I saw that they corresponded to the symbols I used above (0xe2, 0x80 etc.). So I simply swapped out the oddball characters with HTML entities. So if the bit I have above already IS UTF-8, what is being pasted in from MS Word that is causing the odd symbols? </p> <p>EDIT2: So I set out to learn a bit about Python and found I don't really understand encoding. The problem I was trying to solve can be handled simply by having sonsistent encoding from end to end. If the input form is UTF-8, the database that stores the input is UTF-8 and the page that outputs it is UTF-8... pasting from Word works fine. No special functions needed. Now, about learning a little Python...</p>
5
2009-04-16T01:41:41Z
754,503
<p>First of all, those aren't Microsoft Word entities—they <strong>are</strong> UTF-8. You're converting them to HTML entities.</p> <p>The Pythonic way to write something like:</p> <pre><code>chr(0xe2) . chr(0x80) . chr(0x98) </code></pre> <p>would be:</p> <pre><code>'\xe2\x80\x98' </code></pre> <p>But Python already has built-in functionality for the type of conversion you want to do:</p> <pre><code>def defang(string): return string.decode('utf-8').encode('ascii', 'xmlcharrefreplace') </code></pre> <p>This will replace the UTF-8 codes in a string for characters like <code>‘</code> with numeric entities like <code>&amp;#8220;</code>.</p> <p>If you want to replace those numeric entities with named ones where possible:</p> <pre><code>import re from htmlentitydefs import codepoint2name def convert_match_to_named(match): num = int(match.group(1)) if num in codepoint2name: return "&amp;%s;" % codepoint2name[num] else: return match.group(0) def defang_named(string): return re.sub('&amp;#(\d+);', convert_match_to_named, defang(string)) </code></pre> <p>And use it like so:</p> <pre><code>&gt;&gt;&gt; defang_named('\xe2\x80\x9cHello, world!\xe2\x80\x9d') '&amp;ldquo;Hello, world!&amp;rdquo;' </code></pre> <p><hr /></p> <p>To complete the answer, the equivalent code to your example to process a file would look something like this:</p> <pre><code># in Python, it's common to operate a line at a time on a file instead of # reading the entire thing into memory my_file = open("test100.html") for line in my_file: print defang_named(line) my_file.close() </code></pre> <p>Note that this answer is targeted at Python 2.5; the Unicode situation is dramatically different for Python 3+.</p> <p>I also agree with bobince's comment below: if you can just keep the text in UTF-8 format and send it with the correct content-type and charset, do that; if you need it to be in ASCII, then stick with the numeric entities—there's really no need to use the named ones.</p>
20
2009-04-16T02:10:31Z
[ "php", "python", "unicode", "replace", "html-entities" ]
How do you Debug/Take Apart/Learn from someone else's Python code (web-based)?
754,481
<p>A good example of this is: <a href="http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py" rel="nofollow">http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py</a></p> <p>In Visual Studio (ASP.net C#) where I come from, the classes are usually split into separate files + I can set break points to understand the code level.</p> <p>If I run a program like this, do I just do "system.out" to print out where in the code I am in?</p> <p>I read through this <a href="http://stackoverflow.com/questions/246546/good-techniques-for-understanding-someone-elses-code">http://stackoverflow.com/questions/246546/good-techniques-for-understanding-someone-elses-code</a> which was quite helpful.</p>
1
2009-04-16T01:53:33Z
754,500
<p>You've run into a pretty specific case of code that will be hard to understand. They probably did that for the convenience of having all the code in one file.</p> <p>I would recommend letting epydoc have a pass at it. It will create HTML documentation of the program. This will show you the class structure and you can even build charts of which functions call which other functions.</p> <p><a href="http://epydoc.sourceforge.net/manual-usage.html" rel="nofollow">http://epydoc.sourceforge.net/manual-usage.html</a></p> <p>Your other options are to break it into multiple files yourself (which I think will be tedious and not of much benefit)</p>
3
2009-04-16T02:10:01Z
[ "python", "google-app-engine" ]
How do you Debug/Take Apart/Learn from someone else's Python code (web-based)?
754,481
<p>A good example of this is: <a href="http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py" rel="nofollow">http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py</a></p> <p>In Visual Studio (ASP.net C#) where I come from, the classes are usually split into separate files + I can set break points to understand the code level.</p> <p>If I run a program like this, do I just do "system.out" to print out where in the code I am in?</p> <p>I read through this <a href="http://stackoverflow.com/questions/246546/good-techniques-for-understanding-someone-elses-code">http://stackoverflow.com/questions/246546/good-techniques-for-understanding-someone-elses-code</a> which was quite helpful.</p>
1
2009-04-16T01:53:33Z
755,218
<p>If you install <a href="http://www.eclipse.org" rel="nofollow">Eclipse</a> and <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a> you can set breakpoints in the same way you can in visual studio.</p> <p>Failing that, printing out information at cucial points is often a good way to see what's going on. I quite often add in debug information that way and leave it in the code but disabled until I change a variable. I find this often helps if you break the code and need to go back and take another look at what's going on. Better still, send your debug information to a logging class and you can start to use the output in unit tests... you do test your code right? ;)</p>
0
2009-04-16T08:28:09Z
[ "python", "google-app-engine" ]
What is the purpose of the sub-interpreter API in CPython?
755,070
<p>I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other purposes?</p>
14
2009-04-16T07:20:45Z
755,125
<p>I imagine the purpose is to create separate python execution environments. For instance, <a href="https://code.google.com/p/modwsgi/">mod_wsgi</a> (Apache Python module) hosts a single python interpreter and then hosts multiple applications within sub-interpreters (in the default configuration).</p> <p>Some key points from the <a href="http://docs.python.org/c-api/init.html#Py_NewInterpreter">documentation</a>:</p> <ul> <li>This is an (almost) totally separate environment for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules, including the fundamental modules <code>__builtin__</code>, <code>__main__</code> and <code>sys</code>.</li> <li>The table of loaded modules (sys.modules) and the module search path (sys.path) are also separate.</li> <li>Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn’t perfect — for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect each other’s open files. </li> <li>Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when the extension makes use of (static) global variables, or when the extension manipulates its module’s dictionary after its initialization.</li> </ul>
14
2009-04-16T07:45:18Z
[ "mod-wsgi", "python" ]
What is the purpose of the sub-interpreter API in CPython?
755,070
<p>I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other purposes?</p>
14
2009-04-16T07:20:45Z
19,104,744
<p>As I understood it last, the idea was to be able to execute multiple applications as well as <em>multiple copies of the same application</em> within the same process. </p> <p>This is a feature found in other scripting languages (e.g. TCL), and is of particular use to gui builders, web servers, etc.</p> <p>It breaks in python because many extensions are not multiple-interpreter safe, so one interpreter's actions could affect the variables in another interpreter.</p>
0
2013-09-30T22:08:59Z
[ "mod-wsgi", "python" ]
finditer hangs when matching against long string
755,332
<p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be? Here's the code snippet:</p> <pre><code>pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)" matches = re.finditer(pattern, string) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre> <p>It prints out the first four occurrences, but then it hangs. When I kill it using Ctrl-C, it tells me it was killed in the iterator:</p> <pre><code>Traceback (most recent call last): File "code.py", line 133, in &lt;module&gt; main(sys.argv[1:]) File "code.py", line 106, in main for match in matches: KeyboardInterrupt </code></pre> <p>If I try it with a simpler re, it works fine.</p> <p>I'm running this on python 2.5.4 running on Cygwin on Windows XP.</p> <p>I managed to get it to hang with a very much shorter string. With this 50 character string, it never returned after about 5 minutes:</p> <pre><code>ddddddeddbedddbddddddddddddddddddddddddddddddddddd </code></pre> <p>With this 39 character string it took about 15 seconds to return (and display no matches):</p> <pre><code>ddddddeddbedddbdddddddddddddddddddddddd </code></pre> <p>And with this string it returns instantly:</p> <pre><code>ddddddeddbedddbdddddddddddddd </code></pre>
2
2009-04-16T09:14:26Z
755,351
<p>Could it be that your expression triggers exponential behavior in the Python RE engine?</p> <p><a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow">This article</a> deals with the problem. If you have the time, you might want to try running your expression in an RE engine developed using those ideas.</p>
5
2009-04-16T09:22:12Z
[ "python", "regex", "performance" ]
finditer hangs when matching against long string
755,332
<p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be? Here's the code snippet:</p> <pre><code>pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)" matches = re.finditer(pattern, string) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre> <p>It prints out the first four occurrences, but then it hangs. When I kill it using Ctrl-C, it tells me it was killed in the iterator:</p> <pre><code>Traceback (most recent call last): File "code.py", line 133, in &lt;module&gt; main(sys.argv[1:]) File "code.py", line 106, in main for match in matches: KeyboardInterrupt </code></pre> <p>If I try it with a simpler re, it works fine.</p> <p>I'm running this on python 2.5.4 running on Cygwin on Windows XP.</p> <p>I managed to get it to hang with a very much shorter string. With this 50 character string, it never returned after about 5 minutes:</p> <pre><code>ddddddeddbedddbddddddddddddddddddddddddddddddddddd </code></pre> <p>With this 39 character string it took about 15 seconds to return (and display no matches):</p> <pre><code>ddddddeddbedddbdddddddddddddddddddddddd </code></pre> <p>And with this string it returns instantly:</p> <pre><code>ddddddeddbedddbdddddddddddddd </code></pre>
2
2009-04-16T09:14:26Z
755,358
<p>You already gave yourself the answer: The regular expression is to complex and ambiguous.</p> <p>You should try to find a less complex and more distinct expression that is easier to process. Or tell us what you want to accomplish and we could try to help you to find one.</p> <p><hr /></p> <p><strong>Edit</strong>   If you just want to allow <code>d</code>s in every position as you said in a comment to <a href="http://stackoverflow.com/questions/755332/can-anyone-help-with-this-problem-i-am-having-with-finditer-in-python/755378#755378">John Montgomery’s answer</a>, you should remove them before testing the pattern:</p> <pre><code>import re string = "ddddddeddbedddbddddddddddddddddddddddddddddddddddd" pattern = "(([ef]|([gh](a[gh])*b))b([ef]b)*c)" matches = re.finditer(pattern, re.sub("d+", "", string)) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre>
1
2009-04-16T09:24:38Z
[ "python", "regex", "performance" ]
finditer hangs when matching against long string
755,332
<p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be? Here's the code snippet:</p> <pre><code>pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)" matches = re.finditer(pattern, string) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre> <p>It prints out the first four occurrences, but then it hangs. When I kill it using Ctrl-C, it tells me it was killed in the iterator:</p> <pre><code>Traceback (most recent call last): File "code.py", line 133, in &lt;module&gt; main(sys.argv[1:]) File "code.py", line 106, in main for match in matches: KeyboardInterrupt </code></pre> <p>If I try it with a simpler re, it works fine.</p> <p>I'm running this on python 2.5.4 running on Cygwin on Windows XP.</p> <p>I managed to get it to hang with a very much shorter string. With this 50 character string, it never returned after about 5 minutes:</p> <pre><code>ddddddeddbedddbddddddddddddddddddddddddddddddddddd </code></pre> <p>With this 39 character string it took about 15 seconds to return (and display no matches):</p> <pre><code>ddddddeddbedddbdddddddddddddddddddddddd </code></pre> <p>And with this string it returns instantly:</p> <pre><code>ddddddeddbedddbdddddddddddddd </code></pre>
2
2009-04-16T09:14:26Z
755,362
<p>I think you experience what is known as "catastrophic backtracking".</p> <p>Your regex has many optional/alternative parts, all of which still try to match, so previous sub-expressions give back characters to the following expression on local failure. This leads to a back-and-fourth behavior within the regex and exponentially rising execution times.</p> <p>Python (2.7+?, I'm not sure) supports atomic grouping and possessive quantifiers, you could examine your regex to identify the parts that should match or fail as a whole. Unnecessary backtracking can be brought under control with that.</p>
2
2009-04-16T09:28:34Z
[ "python", "regex", "performance" ]
finditer hangs when matching against long string
755,332
<p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be? Here's the code snippet:</p> <pre><code>pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)" matches = re.finditer(pattern, string) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre> <p>It prints out the first four occurrences, but then it hangs. When I kill it using Ctrl-C, it tells me it was killed in the iterator:</p> <pre><code>Traceback (most recent call last): File "code.py", line 133, in &lt;module&gt; main(sys.argv[1:]) File "code.py", line 106, in main for match in matches: KeyboardInterrupt </code></pre> <p>If I try it with a simpler re, it works fine.</p> <p>I'm running this on python 2.5.4 running on Cygwin on Windows XP.</p> <p>I managed to get it to hang with a very much shorter string. With this 50 character string, it never returned after about 5 minutes:</p> <pre><code>ddddddeddbedddbddddddddddddddddddddddddddddddddddd </code></pre> <p>With this 39 character string it took about 15 seconds to return (and display no matches):</p> <pre><code>ddddddeddbedddbdddddddddddddddddddddddd </code></pre> <p>And with this string it returns instantly:</p> <pre><code>ddddddeddbedddbdddddddddddddd </code></pre>
2
2009-04-16T09:14:26Z
755,369
<p>catastrophic backtracking!</p> <blockquote> <p>Regular Expressions can be very expensive. Certain (unintended and intended) strings may cause RegExes to exhibit exponential behavior. We've taken several hotfixes for this. RegExes are so handy, but devs really need to understand how they work; we've gotten bitten by them. </p> </blockquote> <p>example and debugger:</p> <p><a href="http://www.codinghorror.com/blog/archives/000488.html" rel="nofollow">http://www.codinghorror.com/blog/archives/000488.html</a></p>
2
2009-04-16T09:31:19Z
[ "python", "regex", "performance" ]
finditer hangs when matching against long string
755,332
<p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be? Here's the code snippet:</p> <pre><code>pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)" matches = re.finditer(pattern, string) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre> <p>It prints out the first four occurrences, but then it hangs. When I kill it using Ctrl-C, it tells me it was killed in the iterator:</p> <pre><code>Traceback (most recent call last): File "code.py", line 133, in &lt;module&gt; main(sys.argv[1:]) File "code.py", line 106, in main for match in matches: KeyboardInterrupt </code></pre> <p>If I try it with a simpler re, it works fine.</p> <p>I'm running this on python 2.5.4 running on Cygwin on Windows XP.</p> <p>I managed to get it to hang with a very much shorter string. With this 50 character string, it never returned after about 5 minutes:</p> <pre><code>ddddddeddbedddbddddddddddddddddddddddddddddddddddd </code></pre> <p>With this 39 character string it took about 15 seconds to return (and display no matches):</p> <pre><code>ddddddeddbedddbdddddddddddddddddddddddd </code></pre> <p>And with this string it returns instantly:</p> <pre><code>ddddddeddbedddbdddddddddddddd </code></pre>
2
2009-04-16T09:14:26Z
755,378
<p>Definitely exponential behaviour. You've got so many <code>d*</code> parts to your regexp that it'll be backtracking like crazy when it gets to the long string of d's, but fails to match something earlier. You need to rethink the regexp, so it has less possible paths to try.</p> <p>In particular I think:</p> <pre><code>([ef]d\*b|d\*)*&lt;/pre&gt;&lt;/code&gt; and &lt;code&gt;&lt;pre&gt;([ef]|([gh]d\*(ad\*[gh]d)\*b))d\*b </code></pre> <p>Might need rethinking, as they'll force a retry of the alternate match. Plus they also overlap in terms of what they match. They'd both match edb for example, but if one fails and tries to backtrack the other part will probably have the same behaviour.</p> <p>So in short try not to use the <code>|</code> if you can and try to make sure the patterns don't overlap where possible.</p>
4
2009-04-16T09:35:45Z
[ "python", "regex", "performance" ]
finditer hangs when matching against long string
755,332
<p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be? Here's the code snippet:</p> <pre><code>pattern = "(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)" matches = re.finditer(pattern, string) for match in matches: print "(%d-%d): %s" % (match.start(), match.end(), match.group()) </code></pre> <p>It prints out the first four occurrences, but then it hangs. When I kill it using Ctrl-C, it tells me it was killed in the iterator:</p> <pre><code>Traceback (most recent call last): File "code.py", line 133, in &lt;module&gt; main(sys.argv[1:]) File "code.py", line 106, in main for match in matches: KeyboardInterrupt </code></pre> <p>If I try it with a simpler re, it works fine.</p> <p>I'm running this on python 2.5.4 running on Cygwin on Windows XP.</p> <p>I managed to get it to hang with a very much shorter string. With this 50 character string, it never returned after about 5 minutes:</p> <pre><code>ddddddeddbedddbddddddddddddddddddddddddddddddddddd </code></pre> <p>With this 39 character string it took about 15 seconds to return (and display no matches):</p> <pre><code>ddddddeddbedddbdddddddddddddddddddddddd </code></pre> <p>And with this string it returns instantly:</p> <pre><code>ddddddeddbedddbdddddddddddddd </code></pre>
2
2009-04-16T09:14:26Z
755,436
<p>Thanks to all the responses, which were very helpful. In the end, surprisingly, it was easy to speed it up. Here's the original regex:</p> <pre><code>(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c) </code></pre> <p>I noticed that the |d* near the end was not really what I needed, so I modified it as follows:</p> <pre><code>(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*bd*)*c) </code></pre> <p>Now it works almost instantaneously on the 65,536 character string. I guess now I just have to make sure that the regex is really matching the strings I need it to match...</p>
2
2009-04-16T09:56:54Z
[ "python", "regex", "performance" ]
delete *.pyc
755,694
<p>I have three modules as:</p> <p><strong><code>one.py</code>:</strong></p> <pre><code>def abc(): print "Heeeeeeeeeeeiiiiiioooooooooo" </code></pre> <p><strong><code>two.py</code>:</strong></p> <pre><code>import one def defg(): one.abc() </code></pre> <p><strong><code>three.py</code>:</strong></p> <pre><code>import os from time import sleep import two two.defg() sleep(20) directory = os.listdir('.') for filename in directory: if filename[-3:] == 'pyc': print '- ' + filename os.remove(filename) </code></pre> <p>I have three doubts.<strong>Kindly help me</strong>.</p> <p>When i run <code>three.py</code> for the first time <code>one.pyc</code> and <code>two.pyc</code> will be created. I can see it since i gave 20 sec delay. After executing the statement <code>os.remove(filename)</code>, they gets removed. Until here its fine.</p> <p>Again without closing the IDLE as well as script i ran <code>three.py</code>. This time no <code>.pyc</code> file was created. <strong>Why is this so</strong> ?</p> <p>If I close IDLE as well as the script, <code>.pyc</code> will be created as before.</p> <p><strong>Why the compiled code is not getting created again and agin ?</strong></p> <p>Also,if I make a change in <code>one.py</code> it will not be shown if I run without closing the shells. <strong>I need a solution for this also.</strong></p> <p>Third doubt is <strong>if the compiled code is getting deleted first time itself then how the second run gives the same result without <code>.pyc</code>?</strong></p> <p>Hoping for a solution...</p>
1
2009-04-16T11:24:38Z
755,739
<p>I think that IDLE is caching the bytecode within its own Python process, so it doesn't need to regenerate the it each time the file is run.</p>
1
2009-04-16T11:37:55Z
[ "python", "caching" ]
delete *.pyc
755,694
<p>I have three modules as:</p> <p><strong><code>one.py</code>:</strong></p> <pre><code>def abc(): print "Heeeeeeeeeeeiiiiiioooooooooo" </code></pre> <p><strong><code>two.py</code>:</strong></p> <pre><code>import one def defg(): one.abc() </code></pre> <p><strong><code>three.py</code>:</strong></p> <pre><code>import os from time import sleep import two two.defg() sleep(20) directory = os.listdir('.') for filename in directory: if filename[-3:] == 'pyc': print '- ' + filename os.remove(filename) </code></pre> <p>I have three doubts.<strong>Kindly help me</strong>.</p> <p>When i run <code>three.py</code> for the first time <code>one.pyc</code> and <code>two.pyc</code> will be created. I can see it since i gave 20 sec delay. After executing the statement <code>os.remove(filename)</code>, they gets removed. Until here its fine.</p> <p>Again without closing the IDLE as well as script i ran <code>three.py</code>. This time no <code>.pyc</code> file was created. <strong>Why is this so</strong> ?</p> <p>If I close IDLE as well as the script, <code>.pyc</code> will be created as before.</p> <p><strong>Why the compiled code is not getting created again and agin ?</strong></p> <p>Also,if I make a change in <code>one.py</code> it will not be shown if I run without closing the shells. <strong>I need a solution for this also.</strong></p> <p>Third doubt is <strong>if the compiled code is getting deleted first time itself then how the second run gives the same result without <code>.pyc</code>?</strong></p> <p>Hoping for a solution...</p>
1
2009-04-16T11:24:38Z
755,740
<p>The .pyc isnt getting created again because there is a refernce to your imported module in code. When it is re-run, this reference is used.</p> <p>This is why the .pyc isnt generated again, and also why the extra changes you make arent getting run.</p> <p>You can either remove all references and call a garbage collect, or use the built in reload() function on the modules. e.g.:</p> <pre><code>reload(three) </code></pre>
8
2009-04-16T11:37:58Z
[ "python", "caching" ]
delete *.pyc
755,694
<p>I have three modules as:</p> <p><strong><code>one.py</code>:</strong></p> <pre><code>def abc(): print "Heeeeeeeeeeeiiiiiioooooooooo" </code></pre> <p><strong><code>two.py</code>:</strong></p> <pre><code>import one def defg(): one.abc() </code></pre> <p><strong><code>three.py</code>:</strong></p> <pre><code>import os from time import sleep import two two.defg() sleep(20) directory = os.listdir('.') for filename in directory: if filename[-3:] == 'pyc': print '- ' + filename os.remove(filename) </code></pre> <p>I have three doubts.<strong>Kindly help me</strong>.</p> <p>When i run <code>three.py</code> for the first time <code>one.pyc</code> and <code>two.pyc</code> will be created. I can see it since i gave 20 sec delay. After executing the statement <code>os.remove(filename)</code>, they gets removed. Until here its fine.</p> <p>Again without closing the IDLE as well as script i ran <code>three.py</code>. This time no <code>.pyc</code> file was created. <strong>Why is this so</strong> ?</p> <p>If I close IDLE as well as the script, <code>.pyc</code> will be created as before.</p> <p><strong>Why the compiled code is not getting created again and agin ?</strong></p> <p>Also,if I make a change in <code>one.py</code> it will not be shown if I run without closing the shells. <strong>I need a solution for this also.</strong></p> <p>Third doubt is <strong>if the compiled code is getting deleted first time itself then how the second run gives the same result without <code>.pyc</code>?</strong></p> <p>Hoping for a solution...</p>
1
2009-04-16T11:24:38Z
27,978,761
<blockquote> <p>Edit ~/.bashrc and add this shell function to it</p> <blockquote> <p>$ cd ; pyclean</p> </blockquote> </blockquote> <pre><code>pyclean () { find . -type f -name "*.py[co]" -delete find . -type d -name "__pycache__" -delete } </code></pre>
0
2015-01-16T06:56:36Z
[ "python", "caching" ]
Google App Engine for pseudo-cronjobs?
755,777
<p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p> <p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p> <p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p> <p>The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute.</p> <p>So my script would be:</p> <pre><code>import time import urllib while time.clock() &lt; 86400: # execute pseudo-cronjob file and then wait 60 seconds content = urllib.urlopen('http://www.example.org/cronjob_file.php').read() time.sleep(60) </code></pre> <p>Unfortunately, I have no possibility to test the script, so my questions are: 1) Do you think this would work? 2) Is it allowed (Google TOS) to use the service for such an activity? 3) Is my calculation for the URL accesses per minute right?</p> <p>Thanks in advance!</p>
3
2009-04-16T11:48:33Z
755,792
<p>Duplicate, see <a href="http://stackoverflow.com/questions/145651/cron-jobs-on-google-appengine">http://stackoverflow.com/questions/145651/cron-jobs-on-google-appengine</a></p> <p>Cron jobs are now officaly supported on GAE: <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">http://code.google.com/appengine/docs/python/config/cron.html</a></p>
1
2009-04-16T11:52:31Z
[ "python", "google-app-engine", "cron" ]
Google App Engine for pseudo-cronjobs?
755,777
<p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p> <p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p> <p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p> <p>The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute.</p> <p>So my script would be:</p> <pre><code>import time import urllib while time.clock() &lt; 86400: # execute pseudo-cronjob file and then wait 60 seconds content = urllib.urlopen('http://www.example.org/cronjob_file.php').read() time.sleep(60) </code></pre> <p>Unfortunately, I have no possibility to test the script, so my questions are: 1) Do you think this would work? 2) Is it allowed (Google TOS) to use the service for such an activity? 3) Is my calculation for the URL accesses per minute right?</p> <p>Thanks in advance!</p>
3
2009-04-16T11:48:33Z
755,976
<p>Maybe I'm misunderstanding you, but the cron config files will let you do this (without Python). You can add something like this to you cron.yaml file:</p> <pre><code>cron: - description: job that runs every minute url: /cronjobs/job1 schedule: every minute </code></pre> <p>See <a href="http://code.google.com/appengine/docs/python/config/cron.html#About%5Fcron%5Fyaml" rel="nofollow">Google's documentation</a> for more info on scheduling.</p>
6
2009-04-16T12:48:53Z
[ "python", "google-app-engine", "cron" ]
Google App Engine for pseudo-cronjobs?
755,777
<p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p> <p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p> <p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p> <p>The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute.</p> <p>So my script would be:</p> <pre><code>import time import urllib while time.clock() &lt; 86400: # execute pseudo-cronjob file and then wait 60 seconds content = urllib.urlopen('http://www.example.org/cronjob_file.php').read() time.sleep(60) </code></pre> <p>Unfortunately, I have no possibility to test the script, so my questions are: 1) Do you think this would work? 2) Is it allowed (Google TOS) to use the service for such an activity? 3) Is my calculation for the URL accesses per minute right?</p> <p>Thanks in advance!</p>
3
2009-04-16T11:48:33Z
757,914
<p>Google has some limits on how long a task can run. </p> <p>URLFetch calls made in the SDK now have a 5 second timeout, <a href="http://googleappengine.blogspot.com/2008/11/sdk-116-released.html" rel="nofollow">here</a></p> <p>They allow you to schedule up to 20 cron tasks in any given day. <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">Here</a></p>
2
2009-04-16T20:28:05Z
[ "python", "google-app-engine", "cron" ]
Google App Engine for pseudo-cronjobs?
755,777
<p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p> <p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p> <p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p> <p>The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute.</p> <p>So my script would be:</p> <pre><code>import time import urllib while time.clock() &lt; 86400: # execute pseudo-cronjob file and then wait 60 seconds content = urllib.urlopen('http://www.example.org/cronjob_file.php').read() time.sleep(60) </code></pre> <p>Unfortunately, I have no possibility to test the script, so my questions are: 1) Do you think this would work? 2) Is it allowed (Google TOS) to use the service for such an activity? 3) Is my calculation for the URL accesses per minute right?</p> <p>Thanks in advance!</p>
3
2009-04-16T11:48:33Z
757,986
<p>You may want to clarify which way around you want to do it</p> <p>Do you want to use appengine to RUN the job? Ie, the job runs on google's server?</p> <p>or</p> <p>Do you want to use your OWN code on your server, and trigger it by using google app engine?</p> <p>If it's the former: google does cron now. Use that :)</p> <p>If it's the latter: you could use google's cron to trigger your own, even if it's indirectly (ie, google-cron calls google-app-engine which calls your-app). </p> <p>If you can, spin up a thread to do the job, so your page returns immediatly. Dont forgot: if you call <a href="http://whatever/mypage.php" rel="nofollow">http://whatever/mypage.php</a>, and your browser dies (or in this case, google kills your process for running too long), the php script usually still runs to the end - the output just goes no where.</p> <p>Failing that, try to spin up a thread (not sure if you can do that in PHP tho - I'm a C# guy new to PHP)</p> <p>And if all else fails: get a better webhost! I pay $6/month or so for dreamhost.com, and I can run cron jobs on their servers - it's included. They do PHP, Rails et al. You could even ping me for a discount code :) (view profile for website etc)</p>
1
2009-04-16T20:47:24Z
[ "python", "google-app-engine", "cron" ]
Google App Engine for pseudo-cronjobs?
755,777
<p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p> <p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p> <p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p> <p>The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute.</p> <p>So my script would be:</p> <pre><code>import time import urllib while time.clock() &lt; 86400: # execute pseudo-cronjob file and then wait 60 seconds content = urllib.urlopen('http://www.example.org/cronjob_file.php').read() time.sleep(60) </code></pre> <p>Unfortunately, I have no possibility to test the script, so my questions are: 1) Do you think this would work? 2) Is it allowed (Google TOS) to use the service for such an activity? 3) Is my calculation for the URL accesses per minute right?</p> <p>Thanks in advance!</p>
3
2009-04-16T11:48:33Z
30,807,464
<p>Do what Nic Wise said or also outsource the cronjob using a service like www.guardiano.pm so you can actually call www.yoursite.com/myjob.php and every time you call that url something you want will be executed. </p> <p>Ps is free Pss is my pet project and is in beta</p>
0
2015-06-12T16:00:21Z
[ "python", "google-app-engine", "cron" ]
Default value for field in Django model
755,857
<p>Suppose I have a model:</p> <pre><code>class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.CharField(max_length=10) b = models.CharField(max_length=7) </code></pre> <p>Currently I am using the default admin to create/edit objects of this type. How do I remove the field <strong><code>b</code></strong> from the admin so that each object <em>cannot</em> be created with a value, and rather will receive a default value of <code>0000000</code>?</p>
57
2009-04-16T12:13:34Z
755,863
<p>Set <code>editable</code> to <code>False</code> and <code>default</code> to your default value.</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#editable">http://docs.djangoproject.com/en/dev/ref/models/fields/#editable</a></p> <pre><code>b = models.CharField(max_length=7, default='0000000', editable=False) </code></pre> <p>Also, your <code>id</code> field is unnecessary. Django will add it automatically.</p>
84
2009-04-16T12:16:41Z
[ "python", "django", "django-models", "django-admin" ]
Default value for field in Django model
755,857
<p>Suppose I have a model:</p> <pre><code>class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.CharField(max_length=10) b = models.CharField(max_length=7) </code></pre> <p>Currently I am using the default admin to create/edit objects of this type. How do I remove the field <strong><code>b</code></strong> from the admin so that each object <em>cannot</em> be created with a value, and rather will receive a default value of <code>0000000</code>?</p>
57
2009-04-16T12:13:34Z
755,872
<p>You can set the default like this:</p> <pre><code>b = models.CharField(max_length=7,default="foobar") </code></pre> <p>and then you can hide the field with your model's Admin class like this:</p> <pre><code>class SomeModelAdmin(admin.ModelAdmin): exclude = ("b") </code></pre>
17
2009-04-16T12:20:38Z
[ "python", "django", "django-models", "django-admin" ]
Default value for field in Django model
755,857
<p>Suppose I have a model:</p> <pre><code>class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.CharField(max_length=10) b = models.CharField(max_length=7) </code></pre> <p>Currently I am using the default admin to create/edit objects of this type. How do I remove the field <strong><code>b</code></strong> from the admin so that each object <em>cannot</em> be created with a value, and rather will receive a default value of <code>0000000</code>?</p>
57
2009-04-16T12:13:34Z
7,969,092
<p>You can also use a callable in the default field, such as:</p> <pre><code>b = models.CharField(max_length=7, default=foo) </code></pre> <p>And then define the callable:</p> <pre><code>def foo(): return 'bar' </code></pre>
12
2011-11-01T15:53:42Z
[ "python", "django", "django-models", "django-admin" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
756,083
<p>First of all: it smells like <em>recursion</em> of course!</p> <p>Since you also wanted to know the principle, I did my best to explain it human language. I think recursion is very easy most of the times. You only have to grasp two steps:</p> <ol> <li>The first step</li> <li>All the other steps (all with the same logic)</li> </ol> <p>In <strong>human language</strong>:</p> <blockquote> <p>In short:<br/> 1. The permutation of 1 element is one element.<br/> 2. The permutation of a set of elements is a list each of the elements, concatenated with every permutation of the other elements.<br/></p> <p><strong><em>Example:</em></strong></p> <p>If the set just has one element --><br/> return it.<br/> <strong>perm(a) -> a</strong></p> <p>If the set has two characters: for each element in it: return the element, with the permutation of the rest of the elements added, like so:<br/></p> <p><em>perm(ab) -></em> <br/></p> <p>a + perm(b) -> <strong>ab</strong> <br/></p> <p>b + perm(a) -> <strong>ba</strong> <br/></p> <p>Further: for each character in the set: return a character, concatenated with a perumation of > the rest of the set</p> <p>perm(abc) -><br/></p> <p>a + perm(bc) --> <strong>abc</strong>, <strong>acb</strong><br/></p> <p>b + perm(ac) --> <strong>bac</strong>, <strong>bca</strong><br/></p> <p>c + perm(ab) --> <strong>cab</strong>, <strong>cba</strong><br/></p> <p>perm(abc...z) --><br/></p> <p>a + perm(...), b + perm(....) <br/> ....</p> </blockquote> <p>I found the <strong>pseudocode</strong> on <a href="http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/">http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/</a>:</p> <pre><code>makePermutations(permutation) { if (length permutation &lt; required length) { for (i = min digit to max digit) { if (i not in permutation) { makePermutations(permutation+i) } } } else { add permutation to list } } </code></pre> <p><strong>C#</strong></p> <p>OK, and something more elaborate (and since it is tagged c #), from <a href="http://radio.weblogs.com/0111551/stories/2002/10/14/permutations.html">http://radio.weblogs.com/0111551/stories/2002/10/14/permutations.html</a> : Rather lengthy, but I decided to copy it anyway, so the post is not dependent on the original.</p> <blockquote> <p>The function takes a string of characters, and writes down every possible permutation of that exact string, so for example, if "ABC" has been supplied, should spill out:</p> </blockquote> <p>ABC, ACB, BAC, BCA, CAB, CBA.</p> <p>Code:</p> <pre><code>class Program { private static void Swap(ref char a, ref char b) { if (a == b) return; a ^= b; b ^= a; a ^= b; } public static void GetPer(char[] list) { int x = list.Length - 1; GetPer(list, 0, x); } private static void GetPer(char[] list, int k, int m) { if (k == m) { Console.Write(list); } else for (int i = k; i &lt;= m; i++) { Swap(ref list[k], ref list[i]); GetPer(list, k + 1, m); Swap(ref list[k], ref list[i]); } } static void Main() { string str = "sagiv"; char[] arr = str.ToCharArray(); GetPer(arr); } } </code></pre>
106
2009-04-16T13:22:28Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
756,102
<p>First of all, sets have permutations, not strings or integers, so I'll just assume you mean "the set of characters in a string."</p> <p>Note that a set of size n has n! n-permutations.</p> <p>The following pseudocode (from Wikipedia), called with k = 1...n! will give all the permutations:</p> <pre><code>function permutation(k, s) { for j = 2 to length(s) { swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1 k := k / j; // integer division cuts off the remainder } return s; } </code></pre> <p>Here's the equivalent Python code (for 0-based array indexes):</p> <pre><code>def permutation(k, s): r = s[:] for j in range(2, len(s)+1): r[j-1], r[k%j] = r[k%j], r[j-1] k = k/j+1 return r </code></pre>
9
2009-04-16T13:25:08Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
756,145
<p>Here's a good article covering three algorithms for finding all permutations, including one to find the next permutation.</p> <p><a href="http://www.cut-the-knot.org/do_you_know/AllPerm.shtml">http://www.cut-the-knot.org/do_you_know/AllPerm.shtml</a></p> <p>C++ and Python have built-in <a href="http://www.cplusplus.com/reference/algorithm/next_permutation/">next_permutation</a> and <a href="http://docs.python.org/library/itertools.html#itertools.permutations">itertools.permutations</a> functions respectively.</p>
5
2009-04-16T13:34:49Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
756,467
<p>Here's a purely functional F# implementation:</p> <pre> <code> let factorial i = let rec fact n x = match n with | 0 -> 1 | 1 -> x | _ -> fact (n-1) (x*n) fact i 1 let swap (arr:'a array) i j = [| for k in 0..(arr.Length-1) -> if k = i then arr.[j] elif k = j then arr.[i] else arr.[k] |] let rec permutation (k:int,j:int) (r:'a array) = if j = (r.Length + 1) then r else permutation (k/j+1, j+1) (swap r (j-1) (k%j)) let permutations (source:'a array) = seq { for k = 0 to (source |> Array.length |> factorial) - 1 do yield permutation (k,2) source } </code></pre> <p>Performance can be greatly improved by changing swap to take advantage of the mutable nature of CLR arrays, but this implementation is thread safe with regards to the source array and that may be desirable in some contexts. Also, for arrays with more than 16 elements int must be replaced with types with greater/arbitrary precision as factorial 17 results in an int32 overflow.</p>
5
2009-04-16T14:46:52Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
1,447,183
<pre><code>void permute (char *str, int ptr) { int i, len; len = strlen(str); if (ptr == len) { printf ("%s\n", str); return; } for (i = ptr ; i &lt; len ; i++) { swap (&amp;str[ptr], &amp;str[i]); permute (str, ptr + 1); swap (&amp;str[ptr], &amp;str[i]); } } </code></pre> <p>You can write your swap function to swap characters.<br /> This is to be called as permute(string, 0);</p>
11
2009-09-18T23:08:27Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
8,566,913
<p>Here is the function which will print all permutaion. This function implements logic Explained by peter.</p> <pre><code>public class Permutation { //http://www.java2s.com/Tutorial/Java/0100__Class-Definition/RecursivemethodtofindallpermutationsofaString.htm public static void permuteString(String beginningString, String endingString) { if (endingString.Length &lt;= 1) Console.WriteLine(beginningString + endingString); else for (int i = 0; i &lt; endingString.Length; i++) { String newString = endingString.Substring(0, i) + endingString.Substring(i + 1); permuteString(beginningString + endingString.ElementAt(i), newString); } } } static void Main(string[] args) { Permutation.permuteString(String.Empty, "abc"); Console.ReadLine(); } </code></pre>
2
2011-12-19T20:09:19Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
10,630,026
<p>It's just two lines of code if LINQ is allowed to use. Please see my answer <a href="http://stackoverflow.com/a/10629938/1251423">here</a>.</p> <p><strong>EDIT</strong></p> <p>Here is my generic function which can return all the permutations (not combinations) from a list of T:</p> <pre><code>static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; GetPermutations&lt;T&gt;(IEnumerable&lt;T&gt; list, int length) { if (length == 1) return list.Select(t =&gt; new T[] { t }); return GetPermutations(list, length - 1) .SelectMany(t =&gt; list.Where(e =&gt; !t.Contains(e)), (t1, t2) =&gt; t1.Concat(new T[] { t2 })); } </code></pre> <p>Example:</p> <pre><code>IEnumerable&lt;IEnumerable&lt;int&gt;&gt; result = GetPermutations(Enumerable.Range(1, 3), 3); </code></pre> <p>Output - a list of integer-lists:</p> <pre><code>{1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1} </code></pre> <p>As this function uses LINQ so it requires .net 3.5 or higher.</p>
40
2012-05-17T04:54:32Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
12,542,156
<p>The below is my implementation of permutation . Don't mind the variable names, as i was doing it for fun :) </p> <pre><code>class combinations { static void Main() { string choice = "y"; do { try { Console.WriteLine("Enter word :"); string abc = Console.ReadLine().ToString(); Console.WriteLine("Combinatins for word :"); List&lt;string&gt; final = comb(abc); int count = 1; foreach (string s in final) { Console.WriteLine("{0} --&gt; {1}", count++, s); } Console.WriteLine("Do you wish to continue(y/n)?"); choice = Console.ReadLine().ToString(); } catch (Exception exc) { Console.WriteLine(exc); } } while (choice == "y" || choice == "Y"); } static string swap(string test) { return swap(0, 1, test); } static List&lt;string&gt; comb(string test) { List&lt;string&gt; sec = new List&lt;string&gt;(); List&lt;string&gt; first = new List&lt;string&gt;(); if (test.Length == 1) first.Add(test); else if (test.Length == 2) { first.Add(test); first.Add(swap(test)); } else if (test.Length &gt; 2) { sec = generateWords(test); foreach (string s in sec) { string init = s.Substring(0, 1); string restOfbody = s.Substring(1, s.Length - 1); List&lt;string&gt; third = comb(restOfbody); foreach (string s1 in third) { if (!first.Contains(init + s1)) first.Add(init + s1); } } } return first; } static string ShiftBack(string abc) { char[] arr = abc.ToCharArray(); char temp = arr[0]; string wrd = string.Empty; for (int i = 1; i &lt; arr.Length; i++) { wrd += arr[i]; } wrd += temp; return wrd; } static List&lt;string&gt; generateWords(string test) { List&lt;string&gt; final = new List&lt;string&gt;(); if (test.Length == 1) final.Add(test); else { final.Add(test); string holdString = test; while (final.Count &lt; test.Length) { holdString = ShiftBack(holdString); final.Add(holdString); } } return final; } static string swap(int currentPosition, int targetPosition, string temp) { char[] arr = temp.ToCharArray(); char t = arr[currentPosition]; arr[currentPosition] = arr[targetPosition]; arr[targetPosition] = t; string word = string.Empty; for (int i = 0; i &lt; arr.Length; i++) { word += arr[i]; } return word; } } </code></pre>
2
2012-09-22T08:29:58Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
13,022,090
<p>Slightly modified version in C# that yields needed permutations in an array of ANY type.</p> <pre><code> // USAGE: create an array of any type, and call Permutations() var vals = new[] {"a", "bb", "ccc"}; foreach (var v in Permutations(vals)) Console.WriteLine(string.Join(",", v)); // Print values separated by comma public static IEnumerable&lt;T[]&gt; Permutations&lt;T&gt;(T[] values, int fromInd = 0) { if (fromInd + 1 == values.Length) yield return values; else { foreach (var v in Permutations(values, fromInd + 1)) yield return v; for (var i = fromInd + 1; i &lt; values.Length; i++) { SwapValues(values, fromInd, i); foreach (var v in Permutations(values, fromInd + 1)) yield return v; SwapValues(values, fromInd, i); } } } private static void SwapValues&lt;T&gt;(T[] values, int pos1, int pos2) { if (pos1 != pos2) { T tmp = values[pos1]; values[pos1] = values[pos2]; values[pos2] = tmp; } } </code></pre>
5
2012-10-23T00:44:50Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
18,181,573
<p>Here is the function which will print all permutations recursively. </p> <pre><code>public void Permutations(string input, StringBuilder sb) { if (sb.Length == input.Length) { Console.WriteLine(sb.ToString()); return; } char[] inChar = input.ToCharArray(); for (int i = 0; i &lt; input.Length; i++) { if (!sb.ToString().Contains(inChar[i])) { sb.Append(inChar[i]); Permutations(input, sb); RemoveChar(sb, inChar[i]); } } } private bool RemoveChar(StringBuilder input, char toRemove) { int index = input.ToString().IndexOf(toRemove); if (index &gt;= 0) { input.Remove(index, 1); return true; } return false; } </code></pre>
0
2013-08-12T07:28:53Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
21,843,611
<p>Here I have found the solution. It was written in Java, but I have converted it to C#. I hope it will help you.</p> <p><img src="http://i.stack.imgur.com/F0lDq.jpg" alt="Enter image description here"></p> <p>Here's the code in C#:</p> <pre><code>static void Main(string[] args) { string str = "ABC"; char[] charArry = str.ToCharArray(); permute(charArry, 0, 2); Console.ReadKey(); } static void permute(char[] arry, int i, int n) { int j; if (i==n) Console.WriteLine(arry); else { for(j = i; j &lt;=n; j++) { swap(ref arry[i],ref arry[j]); permute(arry,i+1,n); swap(ref arry[i], ref arry[j]); //backtrack } } } static void swap(ref char a, ref char b) { char tmp; tmp = a; a=b; b = tmp; } </code></pre>
17
2014-02-18T03:11:27Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
21,963,875
<pre><code>class Permutation { public static List&lt;string&gt; Permutate(string seed, List&lt;string&gt; lstsList) { loopCounter = 0; // string s="\w{0,2}"; var lstStrs = PermuateRecursive(seed); Trace.WriteLine("Loop counter :" + loopCounter); return lstStrs; } // Recursive function to find permutation private static List&lt;string&gt; PermuateRecursive(string seed) { List&lt;string&gt; lstStrs = new List&lt;string&gt;(); if (seed.Length &gt; 2) { for (int i = 0; i &lt; seed.Length; i++) { str = Swap(seed, 0, i); PermuateRecursive(str.Substring(1, str.Length - 1)).ForEach( s =&gt; { lstStrs.Add(str[0] + s); loopCounter++; }); ; } } else { lstStrs.Add(seed); lstStrs.Add(Swap(seed, 0, 1)); } return lstStrs; } //Loop counter variable to count total number of loop execution in various functions private static int loopCounter = 0; //Non recursive version of permuation function public static List&lt;string&gt; Permutate(string seed) { loopCounter = 0; List&lt;string&gt; strList = new List&lt;string&gt;(); strList.Add(seed); for (int i = 0; i &lt; seed.Length; i++) { int count = strList.Count; for (int j = i + 1; j &lt; seed.Length; j++) { for (int k = 0; k &lt; count; k++) { strList.Add(Swap(strList[k], i, j)); loopCounter++; } } } Trace.WriteLine("Loop counter :" + loopCounter); return strList; } private static string Swap(string seed, int p, int p2) { Char[] chars = seed.ToCharArray(); char temp = chars[p2]; chars[p2] = chars[p]; chars[p] = temp; return new string(chars); } } </code></pre>
-1
2014-02-23T03:35:51Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
23,147,324
<p>Here is a C# answer which is a little simplified.</p> <pre><code>public static void StringPermutationsDemo() { strBldr = new StringBuilder(); string result = Permute("ABCD".ToCharArray(), 0); MessageBox.Show(result); } static string Permute(char[] elementsList, int startIndex) { if (startIndex == elementsList.Length) { foreach (char element in elementsList) { strBldr.Append(" " + element); } strBldr.AppendLine(""); } else { for (int tempIndex = startIndex; tempIndex &lt;= elementsList.Length - 1; tempIndex++) { Swap(ref elementsList[startIndex], ref elementsList[tempIndex]); Permute(elementsList, (startIndex + 1)); Swap(ref elementsList[startIndex], ref elementsList[tempIndex]); } } return strBldr.ToString(); } static void Swap(ref char Char1, ref char Char2) { char tempElement = Char1; Char1 = Char2; Char2 = tempElement; } </code></pre> <p>Output:</p> <pre><code>1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2 </code></pre>
0
2014-04-18T04:22:42Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
25,048,284
<pre><code> /// &lt;summary&gt; /// Print All the Permutations. /// &lt;/summary&gt; /// &lt;param name="inputStr"&gt;input string&lt;/param&gt; /// &lt;param name="strLength"&gt;length of the string&lt;/param&gt; /// &lt;param name="outputStr"&gt;output string&lt;/param&gt; private void PrintAllPermutations(string inputStr, int strLength,string outputStr, int NumberOfChars) { //Means you have completed a permutation. if (outputStr.Length == NumberOfChars) { Console.WriteLine(outputStr); return; } //For loop is used to print permutations starting with every character. first print all the permutations starting with a,then b, etc. for(int i=0 ; i&lt; strLength; i++) { // Recursive call : for a string abc = a + perm(bc). b+ perm(ac) etc. PrintAllPermutations(inputStr.Remove(i, 1), strLength - 1, outputStr + inputStr.Substring(i, 1), 4); } } </code></pre>
-1
2014-07-30T22:53:11Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
25,386,936
<p>Here's a high level example I wrote which illustrates the <strong>human language</strong> explanation Peter gave:</p> <pre><code> public List&lt;string&gt; FindPermutations(string input) { if (input.Length == 1) return new List&lt;string&gt; { input }; var perms = new List&lt;string&gt;(); foreach (var c in input) { var others = input.Remove(input.IndexOf(c), 1); perms.AddRange(FindPermutations(others).Select(perm =&gt; c + perm)); } return perms; } </code></pre>
2
2014-08-19T15:08:37Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
30,312,182
<p>I liked <em>FBryant87</em> approach since it's simple. Unfortunately, it does like many other "solutions" not offer all permutations or of e.g. an integer if it contains the same digit more than once. Take 656123 as an example. The line:</p> <pre><code>var tail = chars.Except(new List&lt;char&gt;(){c}); </code></pre> <p>using Except will cause all occurrences to be removed, i.e. when c = 6, two digits are removed and we are left with e.g. 5123. Since none of the solutions I tried solved this, I decided to try and solve it myself by <em>FBryant87</em>'s code as base. This is what I came up with:</p> <pre><code>private static List&lt;string&gt; FindPermutations(string set) { var output = new List&lt;string&gt;(); if (set.Length == 1) { output.Add(set); } else { foreach (var c in set) { // Remove one occurrence of the char (not all) var tail = set.Remove(set.IndexOf(c), 1); foreach (var tailPerms in FindPermutations(tail)) { output.Add(c + tailPerms); } } } return output; } </code></pre> <p>I simply just remove the first found occurrence using .Remove and .IndexOf. Seems to work as intended for my usage at least. I'm sure it could be made cleverer.</p> <p>One thing to note though: The resulting list may contain duplicates, so make sure you either make the method return e.g. a HashSet instead or remove the duplicates after the return using any method you like.</p>
4
2015-05-18T20:23:29Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
32,037,976
<p>This is my solution which it is easy for me to understand</p> <pre><code>class ClassicPermutationProblem { ClassicPermutationProblem() { } private static void PopulatePosition&lt;T&gt;(List&lt;List&lt;T&gt;&gt; finalList, List&lt;T&gt; list, List&lt;T&gt; temp, int position) { foreach (T element in list) { List&lt;T&gt; currentTemp = temp.ToList(); if (!currentTemp.Contains(element)) currentTemp.Add(element); else continue; if (position == list.Count) finalList.Add(currentTemp); else PopulatePosition(finalList, list, currentTemp, position + 1); } } public static List&lt;List&lt;int&gt;&gt; GetPermutations(List&lt;int&gt; list) { List&lt;List&lt;int&gt;&gt; results = new List&lt;List&lt;int&gt;&gt;(); PopulatePosition(results, list, new List&lt;int&gt;(), 1); return results; } } static void Main(string[] args) { List&lt;List&lt;int&gt;&gt; results = ClassicPermutationProblem.GetPermutations(new List&lt;int&gt;() { 1, 2, 3 }); } </code></pre>
0
2015-08-16T17:28:09Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
32,544,916
<p><strong>Recursion</strong> is not necessary, <a href="http://stackoverflow.com/a/1506337/1486443">here</a> is good information about this solution.</p> <pre><code>var values1 = new[] { 1, 2, 3, 4, 5 }; foreach (var permutation in values1.GetPermutations()) { Console.WriteLine(string.Join(", ", permutation)); } var values2 = new[] { 'a', 'b', 'c', 'd', 'e' }; foreach (var permutation in values2.GetPermutations()) { Console.WriteLine(string.Join(", ", permutation)); } Console.ReadLine(); </code></pre> <p>I have been used this algorithm for years, it has <strong>O(N)</strong> <em>time</em> and <em>space</em> complexity to calculate each <strong>permutation</strong>. </p> <pre><code>public static class SomeExtensions { public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; GetPermutations&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable) { var array = enumerable as T[] ?? enumerable.ToArray(); var factorials = Enumerable.Range(0, array.Length + 1) .Select(Factorial) .ToArray(); for (var i = 0L; i &lt; factorials[array.Length]; i++) { var sequence = GenerateSequence(i, array.Length - 1, factorials); yield return GeneratePermutation(array, sequence); } } private static IEnumerable&lt;T&gt; GeneratePermutation&lt;T&gt;(T[] array, IReadOnlyList&lt;int&gt; sequence) { var clone = (T[]) array.Clone(); for (int i = 0; i &lt; clone.Length - 1; i++) { Swap(ref clone[i], ref clone[i + sequence[i]]); } return clone; } private static int[] GenerateSequence(long number, int size, IReadOnlyList&lt;long&gt; factorials) { var sequence = new int[size]; for (var j = 0; j &lt; sequence.Length; j++) { var facto = factorials[sequence.Length - j]; sequence[j] = (int)(number / facto); number = (int)(number % facto); } return sequence; } static void Swap&lt;T&gt;(ref T a, ref T b) { T temp = a; a = b; b = temp; } private static long Factorial(int n) { long result = n; for (int i = 1; i &lt; n; i++) { result = result * i; } return result; } } </code></pre>
8
2015-09-12T23:47:19Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
36,634,228
<p>If performance and memory is an issue, I suggest this very efficient implementation. According to <a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow">Heap's algorithm in Wikipedia</a>, it should be the fastest. Hope it will fits your need :-) !</p> <p>Just as comparison of this with a Linq implementation for 10! (code included):</p> <ul> <li>This: 36288000 items in 235 millisecs</li> <li><p>Linq: 36288000 items in 50051 millisecs</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; namespace WpfPermutations { /// &lt;summary&gt; /// EO: 2016-04-14 /// Generator of all permutations of an array of anything. /// Base on Heap's Algorithm. See: https://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3 /// &lt;/summary&gt; public static class Permutations { /// &lt;summary&gt; /// Heap's algorithm to find all pmermutations. Non recursive, more efficient. /// &lt;/summary&gt; /// &lt;param name="items"&gt;Items to permute in each possible ways&lt;/param&gt; /// &lt;param name="funcExecuteAndTellIfShouldStop"&gt;&lt;/param&gt; /// &lt;returns&gt;Return true if cancelled&lt;/returns&gt; public static bool ForAllPermutation&lt;T&gt;(T[] items, Func&lt;T[], bool&gt; funcExecuteAndTellIfShouldStop) { int countOfItem = items.Length; if (countOfItem &lt;= 1) { return funcExecuteAndTellIfShouldStop(items); } var indexes = new int[countOfItem]; for (int i = 0; i &lt; countOfItem; i++) { indexes[i] = 0; } if (funcExecuteAndTellIfShouldStop(items)) { return true; } for (int i = 1; i &lt; countOfItem;) { if (indexes[i] &lt; i) { // On the web there is an implementation with a multiplication which should be less efficient. if ((i &amp; 1) == 1) // if (i % 2 == 1) ... more efficient ??? At least the same. { Swap(ref items[i], ref items[indexes[i]]); } else { Swap(ref items[i], ref items[0]); } if (funcExecuteAndTellIfShouldStop(items)) { return true; } indexes[i]++; i = 1; } else { indexes[i++] = 0; } } return false; } /// &lt;summary&gt; /// This function is to show a linq way but is far less efficient /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="list"&gt;&lt;/param&gt; /// &lt;param name="length"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; GetPermutations&lt;T&gt;(IEnumerable&lt;T&gt; list, int length) { if (length == 1) return list.Select(t =&gt; new T[] { t }); return GetPermutations(list, length - 1) .SelectMany(t =&gt; list.Where(e =&gt; !t.Contains(e)), (t1, t2) =&gt; t1.Concat(new T[] { t2 })); } /// &lt;summary&gt; /// Swap 2 elements of same type /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="a"&gt;&lt;/param&gt; /// &lt;param name="b"&gt;&lt;/param&gt; [MethodImpl(MethodImplOptions.AggressiveInlining)] static void Swap&lt;T&gt;(ref T a, ref T b) { T temp = a; a = b; b = temp; } /// &lt;summary&gt; /// Func to show how to call. It does a little test for an array of 4 items. /// &lt;/summary&gt; public static void Test() { ForAllPermutation("123".ToCharArray(), (vals) =&gt; { Debug.Print(String.Join("", vals)); return false; }); int[] values = new int[] { 0, 1, 2, 4 }; Debug.Print("Non Linq"); ForAllPermutation(values, (vals) =&gt; { Debug.Print(String.Join("", vals)); return false; }); Debug.Print("Linq"); foreach(var v in GetPermutations(values, values.Length)) { Debug.Print(String.Join("", v)); } // Performance int count = 0; values = new int[10]; for(int n = 0; n &lt; values.Length; n++) { values[n] = n; } Stopwatch stopWatch = new Stopwatch(); stopWatch.Reset(); stopWatch.Start(); ForAllPermutation(values, (vals) =&gt; { foreach(var v in vals) { count++; } return false; }); stopWatch.Stop(); Debug.Print($"Non Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs"); count = 0; stopWatch.Reset(); stopWatch.Start(); foreach (var vals in GetPermutations(values, values.Length)) { foreach (var v in vals) { count++; } } stopWatch.Stop(); Debug.Print($"Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs"); } } } </code></pre></li> </ul>
0
2016-04-14T21:20:51Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
38,175,625
<p>Here is an easy to understand permutaion function for both string and integer as input. With this <strong>you can even set your output length</strong>(which in normal case it is equal to input length)</p> <p><strong><em>String</em></strong></p> <pre><code> static ICollection&lt;string&gt; result; public static ICollection&lt;string&gt; GetAllPermutations(string str, int outputLength) { result = new List&lt;string&gt;(); MakePermutations(str.ToCharArray(), string.Empty, outputLength); return result; } private static void MakePermutations( char[] possibleArray,//all chars extracted from input string permutation, int outputLength//the length of output) { if (permutation.Length &lt; outputLength) { for (int i = 0; i &lt; possibleArray.Length; i++) { var tempList = possibleArray.ToList&lt;char&gt;(); tempList.RemoveAt(i); MakePermutations(tempList.ToArray(), string.Concat(permutation, possibleArray[i]), outputLength); } } else if (!result.Contains(permutation)) result.Add(permutation); } </code></pre> <p>and for <strong><em>Integer</em></strong> just change the caller method and <em>MakePermutations()</em> remains untouched:</p> <pre><code> public static ICollection&lt;int&gt; GetAllPermutations(int input, int outputLength) { result = new List&lt;string&gt;(); MakePermutations(input.ToString().ToCharArray(), string.Empty, outputLength); return result.Select(m =&gt; int.Parse(m)).ToList&lt;int&gt;(); } </code></pre> <p>example 1: GetAllPermutations("abc",3); "abc" "acb" "bac" "bca" "cab" "cba" </p> <p>example 2: GetAllPermutations("abcd",2); "ab" "ac" "ad" "ba" "bc" "bd" "ca" "cb" "cd" "da" "db" "dc"</p> <p>example 3: GetAllPermutations(486,2); 48 46 84 86 64 68</p>
1
2016-07-04T00:50:33Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
Listing all permutations of a string/integer
756,055
<p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p> <p>Is there an example of how this is done and the logic behind solving such a problem?</p> <p>I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.</p>
96
2009-04-16T13:13:39Z
38,213,245
<p>Here is one more implementation of the algo mentioned. </p> <pre><code>public class Program { public static void Main(string[] args) { string str = "abcefgh"; var astr = new Permutation().GenerateFor(str); Console.WriteLine(astr.Length); foreach(var a in astr) { Console.WriteLine(a); } //a.ForEach(Console.WriteLine); } } class Permutation { public string[] GenerateFor(string s) { if(s.Length == 1) { return new []{s}; } else if(s.Length == 2) { return new []{s[1].ToString()+s[0].ToString(),s[0].ToString()+s[1].ToString()}; } var comb = new List&lt;string&gt;(); foreach(var c in s) { string cStr = c.ToString(); var sToProcess = s.Replace(cStr,""); if (!string.IsNullOrEmpty(sToProcess) &amp;&amp; sToProcess.Length&gt;0) { var conCatStr = GenerateFor(sToProcess); foreach(var a in conCatStr) { comb.Add(c.ToString()+a); } } } return comb.ToArray(); } } </code></pre>
0
2016-07-05T21:40:47Z
[ "c#", "python", "algorithm", "f#", "permutation" ]
pylint warning on 'except Exception:'
756,180
<p>For a block like this:</p> <pre><code>try: #some stuff except Exception: pass </code></pre> <p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
10
2009-04-16T13:42:24Z
756,183
<p>It's considered good practice to not normally catch the root Exception object, but instead to catch more specific ones - for example IOException.</p> <p>Consider if an out of memory exception occurred - simply using "pass" isn't going to leave your programme in a good state.</p> <p>Pretty much the only time you should catch Exception is at the top level of your programme, where you can (try to) log it, display an error, and exit as gracefully as you can.</p>
18
2009-04-16T13:44:45Z
[ "python", "pylint" ]
pylint warning on 'except Exception:'
756,180
<p>For a block like this:</p> <pre><code>try: #some stuff except Exception: pass </code></pre> <p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
10
2009-04-16T13:42:24Z
756,187
<p>because it thinks that you're catching too much. and it's right.</p>
3
2009-04-16T13:45:33Z
[ "python", "pylint" ]
pylint warning on 'except Exception:'
756,180
<p>For a block like this:</p> <pre><code>try: #some stuff except Exception: pass </code></pre> <p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
10
2009-04-16T13:42:24Z
756,190
<p>Exception are raised when something... exceptional occurs. It's generally a good thing that the program terminates.</p> <p>You may want to ignore some exceptions, but IMO there's no good reason for catching a base-class like that.</p>
2
2009-04-16T13:46:09Z
[ "python", "pylint" ]
pylint warning on 'except Exception:'
756,180
<p>For a block like this:</p> <pre><code>try: #some stuff except Exception: pass </code></pre> <p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
10
2009-04-16T13:42:24Z
816,524
<p>Catching Exception (without re-raising) has 2 really bad side effects: errors get eaten, so you lose the stack trace, but also that ctrl-c (or whatever the break key is on your operating system) also gets handled here.</p> <p>The typical behavior of programs like this is that either they can't be stopped, or that ctrl-c causes the control flow to skip forward (to the exception handler), and then continue. Then either the code can't be interrupted, or you need to hammer on ctrl-c to get it to stop.</p>
-1
2009-05-03T07:37:11Z
[ "python", "pylint" ]
pylint warning on 'except Exception:'
756,180
<p>For a block like this:</p> <pre><code>try: #some stuff except Exception: pass </code></pre> <p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
10
2009-04-16T13:42:24Z
1,114,833
<p>It's good practice to catch only a very narrow range of types. 'Exception' is too general - you will end up catching not just the errors you planned for, but other errors too, which may mask bugs in your code that would be quicker to diagnose if they weren't caught at all, or possibly would be better dealt with by a single very high level exception handler.</p> <p>Having said that, since Python2.6, catching Exception has become a lot more reasonable, because all the exceptions that you wouldn't want to catch (SystemExit, KeyboardInterrupt) no longer inherit from Exception. They instead inherit from a common BaseException instead. This has been done deliberately in order to make catching Exception relatively harmless, since it is such a common idiom.</p> <p>See <a href="http://www.python.org/dev/peps/pep-3110/" rel="nofollow">PEP 3110</a> for details &amp; future plans.</p>
14
2009-07-11T22:37:07Z
[ "python", "pylint" ]
pylint warning on 'except Exception:'
756,180
<p>For a block like this:</p> <pre><code>try: #some stuff except Exception: pass </code></pre> <p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
10
2009-04-16T13:42:24Z
6,714,306
<p>like Greg's answer, 'Exception' is a base class and exceptions should be derived from this class, see also <a href="http://docs.python.org/library/exceptions.html#exceptions.Exception" rel="nofollow">exceptions.Exception</a>.</p> <p>Here a very usefull <b> list of Errors in <a href="http://docs.python.org/c-api/exceptions.html#standard-exceptions" rel="nofollow">pydocs</a></b></p> <p>Note also the very handy traceback module which allows you to find out where the exception occured. Using only 'except: ...' will show you what Error you should best use in your case. For example, try this code (toggle the comment), perhaps you'll accept it:</p> <pre><code>import traceback #absent = 'nothing' try: something = absent except NameError: traceback.print_exc() else: print("you get here only when you uncomment 'absent'") </code></pre>
0
2011-07-15T23:51:56Z
[ "python", "pylint" ]
Can you write a permutation function just as elegantly in C#?
756,223
<p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p> <pre><code>def permute(xs, pre=[]): if len(xs) == 0: yield pre for i, x in enumerate(xs): for y in permute(xs[:i] + xs[i+1:], pre + [x]): yield y </code></pre>
5
2009-04-16T13:53:49Z
756,262
<p>Not entirely to the point I must admit after some comments, but the code below can be used to generate a random permutation of a finite sequence. It's a variation of the <a href="http://en.wikipedia.org/wiki/Fisher-Yates%5Fshuffle" rel="nofollow">Fisher-Yates shuffle algorithm</a>. The example uses a sequence of <code>int</code>'s but you can use any <code>Enumerable&lt;T&gt;</code> of course.</p> <pre><code>var ints = Enumerable.Range(0, 51); var shuffledInts = ints.OrderBy(a =&gt; Guid.NewGuid()); </code></pre> <p>You order by a random value (in this case a <code>Guid</code>) which essentially permutates your list. Whether <a href="http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx" rel="nofollow">NewGuid</a> is a good source of randomness is debatable, but it's an elegant and compact solution (albeit for another problem then the question was actually about).</p> <p>Taken from <a href="http://www.codinghorror.com/blog/archives/001008.html" rel="nofollow">Jeff Atwood (Coding Horror)</a>.</p>
-6
2009-04-16T14:04:50Z
[ "c#", "python", "algorithm" ]
Can you write a permutation function just as elegantly in C#?
756,223
<p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p> <pre><code>def permute(xs, pre=[]): if len(xs) == 0: yield pre for i, x in enumerate(xs): for y in permute(xs[:i] + xs[i+1:], pre + [x]): yield y </code></pre>
5
2009-04-16T13:53:49Z
756,274
<p>C# has a yield keyword that I imagine works pretty much the same as what your python code is doing, so it shouldn't be too hard to get a mostly direct translation.</p> <p>However this is a recursive solution, so for all it's brevity it's sub-optimal. I don't personally understand all the math involved, but for good efficient mathematical permutations you want to use <a href="http://en.wikipedia.org/wiki/Factoradic" rel="nofollow">factoradics</a>. This article should help:<br /> <a href="http://msdn.microsoft.com/en-us/library/aa302371.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa302371.aspx</a></p> <p>[Update]: The other answer brings up a good point: if you're just using permutations to do a shuffle there are still better options available. Specifically, the <a href="http://en.wikipedia.org/wiki/Fisher-Yates%5Fshuffle" rel="nofollow">Knuth/Fisher-Yates</a> <a href="http://www.codinghorror.com/blog/archives/001015.html" rel="nofollow">shuffle</a>.</p>
1
2009-04-16T14:06:45Z
[ "c#", "python", "algorithm" ]
Can you write a permutation function just as elegantly in C#?
756,223
<p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p> <pre><code>def permute(xs, pre=[]): if len(xs) == 0: yield pre for i, x in enumerate(xs): for y in permute(xs[:i] + xs[i+1:], pre + [x]): yield y </code></pre>
5
2009-04-16T13:53:49Z
756,308
<p>Well, it probably isn't how I'd write it, but:</p> <pre><code>static IEnumerable&lt;T[]&gt; Permute&lt;T&gt;(this T[] xs, params T[] pre) { if (xs.Length == 0) yield return pre; for (int i = 0; i &lt; xs.Length; i++) { foreach (T[] y in Permute(xs.Take(i).Union(xs.Skip(i+1)).ToArray(), pre.Union(new[] { xs[i] }).ToArray())) { yield return y; } } } </code></pre> <p><hr /></p> <p>Re your comment; I'm not <em>entirely</em> clear on the question; if you mean "why is this useful?" - among other things, there are a range of brute-force scenarios where you would want to try different permutations - for example, for small ordering problems like travelling sales person (that aren't big enough to warrant a more sophisticated solution), you might want to check whether it is best to go {base,A,B,C,base}, {base,A,C,B,base},{base,B,A,C,base}, etc.</p> <p>If you mean "how would I use this method?" - untested, but something like:</p> <pre><code>int[] values = {1,2,3}; foreach(int[] perm in values.Permute()) { WriteArray(perm); } void WriteArray&lt;T&gt;(T[] values) { StringBuilder sb = new StringBuilder(); foreach(T value in values) { sb.Append(value).Append(", "); } Console.WriteLine(sb); } </code></pre> <p>If you mean "how does it work?" - iterator blocks (<code>yield return</code>) are a complex subject in themselves - Jon has a free chapter (6) <a href="http://www.manning.com/skeet/" rel="nofollow">in his book</a>, though. The rest of the code is very much like your original question - just using LINQ to provide the moral equivalent of <code>+</code> (for arrays).</p>
12
2009-04-16T14:13:01Z
[ "c#", "python", "algorithm" ]
Can you write a permutation function just as elegantly in C#?
756,223
<p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p> <pre><code>def permute(xs, pre=[]): if len(xs) == 0: yield pre for i, x in enumerate(xs): for y in permute(xs[:i] + xs[i+1:], pre + [x]): yield y </code></pre>
5
2009-04-16T13:53:49Z
756,328
<p>While you cannot port it while maintaining the brevity, you can get pretty close.</p> <pre><code>public static class IEnumerableExtensions { public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Permutations&lt;T&gt;(this IEnumerable&lt;T&gt; source) { if (source == null) throw new ArgumentNullException("source"); return PermutationsImpl(source, new T[0]); } private static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; PermutationsImpl&lt;T&gt;(IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; prefix) { if (source.Count() == 0) yield return prefix; foreach (var x in source) foreach (var permutation in PermutationsImpl(source.Except(new T[] { x }), prefix.Union(new T[] { x })))) yield return permutation; } } </code></pre>
0
2009-04-16T14:18:06Z
[ "c#", "python", "algorithm" ]
Elixir Event Handler
756,529
<p>I want to use the @after_insert decorator of Elixir, but i can't access the Session within the model. Since i have autocommit set to False, i can't commit any changes in the event handler. Is there any best practice how to deal with that?</p> <p>The Code I used to build model, database connection etc. are mostly taken off the documentations.</p> <p>The desired method:</p> <pre><code>class Artefact(Entity): [...] @after_insert def make_signature(self): self.signature = '%s-%s' % (self.artefact_type.title.upper()[:3], self.id) </code></pre> <p>All the Session initialization is done in the <strong>init</strong>.py in the same directory.</p> <p>When I then call:</p> <pre><code>Session.update(self) Session.commit() </code></pre> <p>I get an error that Session is undefined. Any idea?</p>
0
2009-04-16T14:57:49Z
759,908
<p>Have you imported Session?</p> <p><code>from packagename import Session</code></p> <p>at the top of your model file should do the trick. Packagename is the directory name.</p>
0
2009-04-17T10:28:56Z
[ "python", "pylons", "python-elixir" ]
Multiple Tuple to Two-Pair Tuple in Python?
756,550
<p>What is the nicest way of splitting this:</p> <pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') </code></pre> <p>into this:</p> <pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] </code></pre> <p>Assuming that the input always has an even number of values.</p>
11
2009-04-16T15:02:38Z
756,580
<pre><code>[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)] </code></pre>
15
2009-04-16T15:07:24Z
[ "python", "data-structures", "tuples" ]
Multiple Tuple to Two-Pair Tuple in Python?
756,550
<p>What is the nicest way of splitting this:</p> <pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') </code></pre> <p>into this:</p> <pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] </code></pre> <p>Assuming that the input always has an even number of values.</p>
11
2009-04-16T15:02:38Z
756,602
<p><code>zip()</code> is your friend:</p> <pre><code>t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') zip(t[::2], t[1::2]) </code></pre>
36
2009-04-16T15:10:52Z
[ "python", "data-structures", "tuples" ]
Multiple Tuple to Two-Pair Tuple in Python?
756,550
<p>What is the nicest way of splitting this:</p> <pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') </code></pre> <p>into this:</p> <pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] </code></pre> <p>Assuming that the input always has an even number of values.</p>
11
2009-04-16T15:02:38Z
756,701
<p>Here's a general recipe for any-size chunk, if it might not always be 2:</p> <pre><code>def chunk(seq, n): return [seq[i:i+n] for i in range(0, len(seq), n)] chunks= chunk(tuples, 2) </code></pre> <p>Or, if you enjoy iterators:</p> <pre><code>def iterchunk(iterable, n): it= iter(iterable) while True: chunk= [] try: for i in range(n): chunk.append(it.next()) except StopIteration: break finally: if len(chunk)!=0: yield tuple(chunk) </code></pre>
-1
2009-04-16T15:35:14Z
[ "python", "data-structures", "tuples" ]
Multiple Tuple to Two-Pair Tuple in Python?
756,550
<p>What is the nicest way of splitting this:</p> <pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') </code></pre> <p>into this:</p> <pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] </code></pre> <p>Assuming that the input always has an even number of values.</p>
11
2009-04-16T15:02:38Z
756,704
<p>Or, using <code>itertools</code> (see the <a href="http://docs.python.org/library/itertools.html#recipes">recipe</a> for <code>grouper</code>):</p> <pre><code>from itertools import izip def group2(iterable): args = [iter(iterable)] * 2 return izip(*args) tuples = [ab for ab in group2(tuple)] </code></pre>
7
2009-04-16T15:36:04Z
[ "python", "data-structures", "tuples" ]
Multiple Tuple to Two-Pair Tuple in Python?
756,550
<p>What is the nicest way of splitting this:</p> <pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') </code></pre> <p>into this:</p> <pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] </code></pre> <p>Assuming that the input always has an even number of values.</p>
11
2009-04-16T15:02:38Z
17,899,786
<p>I present this code based on <a href="http://stackoverflow.com/a/756580/117870">Peter Hoffmann's answer</a> as a response to <a href="http://stackoverflow.com/questions/756550/17899786#comment568676_756602">dfa's comment</a>. </p> <p>It is guaranteed to work whether or not your tuple has an even number of elements.</p> <pre><code>[(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)] </code></pre> <p>The <code>(len(tup)/2)*2</code> range parameter calculates the highest even number less or equal to the length of the tuple so it is guaranteed to work whether or not the tuple has an even number of elements.</p> <p>The result of the method is going to be a list. This can be converted to tuples using the <code>tuple()</code> function.</p> <p><strong>Sample:</strong></p> <pre><code>def inPairs(tup): return [(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)] # odd number of elements print("Odd Set") odd = range(5) print(odd) po = inPairs(odd) print(po) # even number of elements print("Even Set") even = range(4) print(even) pe = inPairs(even) print(pe) </code></pre> <p>Output</p> <pre> Odd Set [0, 1, 2, 3, 4] [(0, 1), (2, 3)] Even Set [0, 1, 2, 3] [(0, 1), (2, 3)] </pre>
0
2013-07-27T16:05:25Z
[ "python", "data-structures", "tuples" ]
How do you use Binary conversion in Python/Bash/AWK?
756,630
<p>I am new in binary conversion. I use Python, Bash and AWK daily.</p> <p>I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work.</p> <p><strong>Where do you use binary conversion in Python/Bash/AWK?</strong></p> <p>I would like to see examples of codes.</p>
1
2009-04-16T15:14:46Z
756,705
<p>Conversion of strings of binary digits to a number using Python on the commandline:</p> <pre><code>binary=00001111 DECIMAL=$(python -c "print int('$BINARY', 2)") echo $decimal </code></pre> <p>See the docs for the <a href="http://docs.python.org/library/functions.html#int" rel="nofollow">int function</a>.</p> <p>Oh, wait, I misread the question, you want to know what converting to binary gets you. Well, that depends on what you mean by "convert to binary". Say I want to store a file with a million integers. The integers will be between 0 and 32,000. If I were to store them as text it would take at best two bytes for each number (single digit number and a separator), at worst six bytes (five digit number and a separator), with an average size of 4.6 bytes per number (see comment for the math). I also would have no easy way of choosing the 15th number. If I were store them as 16bit integers (in binary), every number would take up exactly two bytes and I could find the 15th number by <code>seek</code>'ing to offset <code>2*(15-1)</code> and reading two bytes. Also, when I go to do math on the text based version I (or my language) must first convert the string to a number, whereas the binary version is already a 16bit number. </p> <p>So, in short, you use binary types to</p> <ol> <li>save space</li> <li>have consistent record sizes</li> <li>speed up programs </li> </ol>
2
2009-04-16T15:36:17Z
[ "python", "bash", "binary", "awk" ]
How do you use Binary conversion in Python/Bash/AWK?
756,630
<p>I am new in binary conversion. I use Python, Bash and AWK daily.</p> <p>I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work.</p> <p><strong>Where do you use binary conversion in Python/Bash/AWK?</strong></p> <p>I would like to see examples of codes.</p>
1
2009-04-16T15:14:46Z
756,745
<p>In shell, a nice use of <a href="http://stackoverflow.com/questions/750606/what-technologies-are-you-using-even-though-they-are-embarassingly-out-of-date/750620#750620"><code>dc</code></a>:</p> <pre><code>echo 2i 00001111 pq | dc </code></pre> <p>2i means: <em>base for input numbers is 2</em>.</p> <p>pq means: <em>print and quit</em>.</p> <p>The other way is:</p> <pre><code>echo 2o 15 pq | dc </code></pre> <p>I don't remember having used this feature in real-world situations.</p>
2
2009-04-16T15:45:12Z
[ "python", "bash", "binary", "awk" ]
How do you use Binary conversion in Python/Bash/AWK?
756,630
<p>I am new in binary conversion. I use Python, Bash and AWK daily.</p> <p>I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work.</p> <p><strong>Where do you use binary conversion in Python/Bash/AWK?</strong></p> <p>I would like to see examples of codes.</p>
1
2009-04-16T15:14:46Z
6,600,616
<p>In newer versions of Python there exists the <code>bin()</code> function which I believe takes an int and returns a binary literal, of form <code>0b011010</code> or whatever.</p>
0
2011-07-06T17:35:53Z
[ "python", "bash", "binary", "awk" ]
Using multiple listboxes in python tkinter
756,662
<pre><code>from Tkinter import * master = Tk() listbox = Listbox(master) listbox.pack() listbox.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox.insert(END, item) listbox2 = Listbox(master) listbox2.pack() listbox2.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox2.insert(END, item) mainloop() </code></pre> <p>The code above creates a tkinter window with two listboxes. But there's a problem if you want to retrieve the values from both, because as soon as you select a value in one, it deselects whatever you selected in the other. Is this just a limitation developers have to live with?</p>
12
2009-04-16T15:24:17Z
756,831
<p><code>exportselection=0</code> when defining a listbox seems to take care of this issue.</p>
2
2009-04-16T16:01:56Z
[ "python", "listbox", "tkinter" ]
Using multiple listboxes in python tkinter
756,662
<pre><code>from Tkinter import * master = Tk() listbox = Listbox(master) listbox.pack() listbox.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox.insert(END, item) listbox2 = Listbox(master) listbox2.pack() listbox2.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox2.insert(END, item) mainloop() </code></pre> <p>The code above creates a tkinter window with two listboxes. But there's a problem if you want to retrieve the values from both, because as soon as you select a value in one, it deselects whatever you selected in the other. Is this just a limitation developers have to live with?</p>
12
2009-04-16T15:24:17Z
756,875
<p>Short answer: set the value of the <code>exportselection</code> attribute of all listbox widgets to False or zero.</p> <p>From <a href="http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/TkIntro/introduction/listbox.htm">a pythonware overview</a> of the listbox widget:</p> <blockquote> <p>By default, the selection is exported to the X selection mechanism. If you have more than one listbox on the screen, this really messes things up for the poor user. If he selects something in one listbox, and then selects something in another, the original selection is cleared. It is usually a good idea to disable this mechanism in such cases. In the following example, three listboxes are used in the same dialog:</p> <pre><code>b1 = Listbox(exportselection=0) for item in families: b1.insert(END, item) b2 = Listbox(exportselection=0) for item in fonts: b2.insert(END, item) b3 = Listbox(exportselection=0) for item in styles: b3.insert(END, item) </code></pre> </blockquote> <p>The definitive documentation for tk widgets is based on the Tcl language rather than python, but it is easy to translate to python. The <code>exportselection</code> attribute can be found on the <a href="http://tcl.tk/man/tcl8.5/TkCmd/options.htm#M-exportselection">standard options manual page</a>. </p>
19
2009-04-16T16:11:42Z
[ "python", "listbox", "tkinter" ]
Matching a pair of comments in HTML using regular expressions
756,898
<p>I have a mako template that looks something like this:</p> <pre><code>% if staff: &lt;!-- begin staff --&gt; ... &lt;!-- end staff --&gt; % endif </code></pre> <p>That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a regular expression that looks like this:</p> <pre><code>re.search('&lt;!-- begin staff --&gt;.*&lt;!-- end staff --&gt;', text) </code></pre> <p>I've verified that the comments appear in the HTML output, but the regular expression doesn't match. I've even tried putting the comments (<code>&lt;!-- begin staff --&gt;</code> and <code>&lt;!-- end staff --&gt;</code>) through re.escape, but still no luck. What am I doing wrong?</p> <p>Or is there a better way to run this test?</p>
1
2009-04-16T16:17:03Z
756,914
<p>By default <code>.</code> doesn't match newlines - you need to add the <code>re.DOTALL</code> option.</p> <pre><code>re.search('&lt;!-- begin staff --&gt;.*&lt;!-- end staff --&gt;', text, re.DOTALL) </code></pre> <p>If you have more than one staff section, you might also want to make the match ungreedy:</p> <pre><code>re.search('&lt;!-- begin staff --&gt;.*?&lt;!-- end staff --&gt;', text, re.DOTALL) </code></pre>
9
2009-04-16T16:21:01Z
[ "python", "regex", "unit-testing", "mako" ]
Matching a pair of comments in HTML using regular expressions
756,898
<p>I have a mako template that looks something like this:</p> <pre><code>% if staff: &lt;!-- begin staff --&gt; ... &lt;!-- end staff --&gt; % endif </code></pre> <p>That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a regular expression that looks like this:</p> <pre><code>re.search('&lt;!-- begin staff --&gt;.*&lt;!-- end staff --&gt;', text) </code></pre> <p>I've verified that the comments appear in the HTML output, but the regular expression doesn't match. I've even tried putting the comments (<code>&lt;!-- begin staff --&gt;</code> and <code>&lt;!-- end staff --&gt;</code>) through re.escape, but still no luck. What am I doing wrong?</p> <p>Or is there a better way to run this test?</p>
1
2009-04-16T16:17:03Z
756,919
<p>Use an HTML Parser like <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser</a> instead. See <a href="http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege">Can you provide some examples of why it is hard to parse XML and HTML with a regex?</a> for why.</p>
2
2009-04-16T16:22:47Z
[ "python", "regex", "unit-testing", "mako" ]
How do I send large amounts of data from a forked process?
757,020
<p>I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.</p> <p>The best way to do this seems to be forking a process and sending the results back from the child. I'd like to do something along these lines:</p> <pre><code>r, w = os.pipe() pid = os.fork() if pid == 0: # child result = ctypes_fn() os.write(w, pickle.dumps(result)) os.close(w) else: # parent os.waitpid(pid, 0) result = os.read(r, 524288) # can be this big os.close(r) return pickle.loads(result) </code></pre> <p>This doesn't quite work, though. The forked process hangs on the write. Am I trying to send too much at once? Is there a simpler solution to this problem?</p>
3
2009-04-16T16:47:21Z
757,269
<p>Probably you are trying to write more data than can fit into the pipe, so it is blocking until someone comes along and reads some of that info out of there. That will never happen, because the only reader is the parent process, which you appear to have written to wait until the child terminates before it reads anything. This is what we call a <em>deadlock</em>.</p> <p>You might consider taking out that os.waitpid call and see what happens. Another option would be to see if os.pipe has any methods that give it a bigger buffer (I don't know your environment enough to say).</p>
4
2009-04-16T17:45:01Z
[ "python", "fork", "pipe" ]
How do I send large amounts of data from a forked process?
757,020
<p>I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.</p> <p>The best way to do this seems to be forking a process and sending the results back from the child. I'd like to do something along these lines:</p> <pre><code>r, w = os.pipe() pid = os.fork() if pid == 0: # child result = ctypes_fn() os.write(w, pickle.dumps(result)) os.close(w) else: # parent os.waitpid(pid, 0) result = os.read(r, 524288) # can be this big os.close(r) return pickle.loads(result) </code></pre> <p>This doesn't quite work, though. The forked process hangs on the write. Am I trying to send too much at once? Is there a simpler solution to this problem?</p>
3
2009-04-16T16:47:21Z
757,622
<p>One solution to the deadlock that ted.dennison mentioned is the following pseudocode:</p> <pre><code>#parent while waitpid(pid, WNOHANG) == (0, 0): result = os.read(r, 1024) #sleep for a short time #at this point the child process has ended #and you need the last bit of data from the pipe result = os.read(r, 1024) os.close(r) </code></pre> <p>Waitpid with the WNOHANG option causes waitpid to return immediately when the child process hasn't exited yet. In this case it returns (0,0). You'll need to make sure not to overwrite the result variable each time through the loop like the above code does.</p>
0
2009-04-16T19:15:38Z
[ "python", "fork", "pipe" ]
How do I send large amounts of data from a forked process?
757,020
<p>I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.</p> <p>The best way to do this seems to be forking a process and sending the results back from the child. I'd like to do something along these lines:</p> <pre><code>r, w = os.pipe() pid = os.fork() if pid == 0: # child result = ctypes_fn() os.write(w, pickle.dumps(result)) os.close(w) else: # parent os.waitpid(pid, 0) result = os.read(r, 524288) # can be this big os.close(r) return pickle.loads(result) </code></pre> <p>This doesn't quite work, though. The forked process hangs on the write. Am I trying to send too much at once? Is there a simpler solution to this problem?</p>
3
2009-04-16T16:47:21Z
757,624
<p>The basic problem is that there's a 64kB limit on the pipe. A few possible solutions, from the simple to the complex:</p> <ol> <li>Send less data. zlib.compress could help in getting under the limit.</li> <li>Store the actual data somewhere else (file, mmap, memcache), only using the pipe to send control information.</li> <li>Continue using the pipe, but chunk the output. Use two sets of pipes so the processes can talk to each other and synchronize their communication. The code is more complex, but is otherwise very effective.</li> </ol>
2
2009-04-16T19:15:57Z
[ "python", "fork", "pipe" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
757,042
<p>It doesn't seem you can serialize an instance, you'd have to serialize a QuerySet of one object.</p> <pre><code>from django.core import serializers from models import * def getUser(request): return HttpResponse(json(Users.objects.filter(id=88))) </code></pre> <p>I run out of the <code>svn</code> release of django, so this may not be in earlier versions.</p>
1
2009-04-16T16:51:02Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
757,233
<p>It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object. If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.</p> <p>Here's what I do:</p> <p>First, I use <a href="http://deron.meranda.us/python/demjson/"><code>demjson</code></a> for the conversion. It happened to be what I found first, but it might not be the best. My implementation depends on one of its features, but there should be similar ways with other converters.</p> <p>Second, implement a <code>json_equivalent</code> method on all models that you might need serialized. This is a magic method for <code>demjson</code>, but it's probably something you're going to want to think about no matter what implementation you choose. The idea is that you return an object that is directly convertible to <code>json</code> (i.e. an array or dictionary). If you really want to do this automatically:</p> <pre><code>def json_equivalent(self): dictionary = {} for field in self._meta.get_all_field_names() dictionary[field] = self.__getattribute__(field) return dictionary </code></pre> <p>This will not be helpful to you unless you have a completely flat data structure (no <code>ForeignKeys</code>, only numbers and strings in the database, etc.). Otherwise, you should seriously think about the right way to implement this method.</p> <p>Third, call <code>demjson.JSON.encode(instance)</code> and you have what you want.</p>
9
2009-04-16T17:36:47Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
903,369
<pre><code>ville = UneVille.objects.get(nom='lihlihlihlih') .... blablablab ....... return HttpResponse(simplejson.dumps(ville.__dict__)) </code></pre> <p>I return the dict of my instance</p> <p>so it return something like {'field1':value,"field2":value,....}</p>
2
2009-05-24T08:54:13Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
2,617,501
<p>I solved this problem by adding a serialization method to my model:</p> <pre><code>def toJSON(self): import simplejson return simplejson.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]])) </code></pre> <p>Here's the verbose equivalent for those averse to one-liners:</p> <pre><code>def toJSON(self): fields = [] for field in self._meta.fields: fields.append(field.name) d = {} for attr in fields: d[attr] = getattr(self, attr) import simplejson return simplejson.dumps(d) </code></pre> <p><code>_meta.fields</code> is an ordered list of model fields which can be accessed from instances and from the model itself.</p>
3
2010-04-11T15:18:57Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
3,289,057
<p>You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:</p> <pre><code>from django.core import serializers # assuming obj is a model instance serialized_obj = serializers.serialize('json', [ obj, ]) </code></pre>
150
2010-07-20T10:31:13Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
6,435,163
<p>how about this way:</p> <pre><code>def ins2dic(obj): SubDic = obj.__dict__ del SubDic['id'] del SubDic['_state'] return SubDic </code></pre> <p>or exclude anything you don't want.</p>
2
2011-06-22T05:11:07Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
13,884,771
<p>To avoid the array wrapper, remove it before you return the response:</p> <pre><code>import json from django.core import serializers def getObject(request, id): obj = MyModel.objects.get(pk=id) data = serializers.serialize('json', [obj,]) struct = json.loads(data) data = json.dumps(struct[0]) return HttpResponse(data, mimetype='application/json') </code></pre> <p>I found this interesting post on the subject too:</p> <p><a href="http://timsaylor.com/convert-django-model-instances-to-dictionaries">http://timsaylor.com/convert-django-model-instances-to-dictionaries</a></p> <p>It uses django.forms.models.model_to_dict, which looks like the perfect tool for the job.</p>
31
2012-12-14T19:05:17Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
15,740,398
<p>Here's my solution for this, which allows you to easily customize the JSON as well as organize related records</p> <p>Firstly implement a method on the model. I call is <code>json</code> but you can call it whatever you like, e.g.:</p> <pre><code>class Car(Model): ... def json(self): return { 'manufacturer': self.manufacturer.name, 'model': self.model, 'colors': [color.json for color in self.colors.all()], } </code></pre> <p>Then in the view I do:</p> <pre><code>data = [car.json for car in Car.objects.all()] return HttpResponse(json.dumps(data), content_type='application/json; charset=UTF-8', status=status) </code></pre>
2
2013-04-01T08:53:55Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
17,402,219
<p>If you're asking how to serialize a single object from a model and you <strong>know</strong> you're only going to get one object in the queryset (for instance, using objects.get), then use something like:</p> <pre><code>import django.core.serializers import django.http import models def jsonExample(request,poll_id): s = django.core.serializers.serialize('json',[models.Poll.objects.get(id=poll_id)]) # s is a string with [] around it, so strip them off o=s.strip("[]") return django.http.HttpResponse(o, mimetype="application/json") </code></pre> <p>which would get you something of the form:</p> <pre><code>{"pk": 1, "model": "polls.poll", "fields": {"pub_date": "2013-06-27T02:29:38.284Z", "question": "What's up?"}} </code></pre>
6
2013-07-01T10:24:46Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
29,550,004
<p>To serialize and deserialze, use the following:</p> <pre><code>from django.core import serializers serial = serializers.serialize("json", [obj]) ... # .next() pulls the first object out of the generator # .object retrieves django object the object from the DeserializedObject obj = serializers.deserialize("json", serial).next().object </code></pre>
0
2015-04-09T22:15:29Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
35,612,936
<p>If you're dealing with a list of model instances the best you can do is using <code>serializers.serialize()</code>, it gonna fit your need perfectly. </p> <p>However, you are to face an issue with trying to serialize a <em>single</em> object, not a <code>list</code> of objects. That way, in order to get rid of different hacks, just use Django's <code>model_to_dict</code> (if I'm not mistaken, <code>serializers.serialize()</code> relies on it, too): </p> <pre><code>from django.forms.models import model_to_dict # assuming obj is your model instance dict_obj = model_to_dict( obj ) </code></pre> <p>You now just need one straight <code>json.dumps</code> call to serialize it to json:</p> <pre><code>import json serialized = json.dumps(dict_obj) </code></pre> <p>That's it! :)</p>
9
2016-02-24T20:57:09Z
[ "python", "django", "json", "django-models", "serialization" ]
How do you serialize a model instance in Django?
757,022
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
93
2009-04-16T16:47:31Z
39,943,877
<p>Use list, it will solve problem</p> <p>Step1:</p> <pre><code> result=YOUR_MODELE_NAME.objects.values('PROP1','PROP2').all(); </code></pre> <p>Step2:</p> <pre><code> result=list(result) #after getting data from model convert result to list </code></pre> <p>Step3:</p> <pre><code> return HttpResponse(json.dumps(result), content_type = "application/json") </code></pre>
1
2016-10-09T12:56:54Z
[ "python", "django", "json", "django-models", "serialization" ]
Converting tree list to hierarchy dict
757,244
<p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p> <p>I want to convert this list to hierarchy dict. Example of output dict:</p> <pre><code>{ 'Technology': { 'Gadgets':{}, 'Gaming':{}, 'Programming': { 'Python':{}, 'PHP':{}, 'Ruby':{}, 'C++':{} }, 'Enterprise':{}, 'Mac':{}, 'Mobile':{}, 'Seo':{}, 'Ui':{}, 'Virtual Worlds':{}, 'Windows':{}, }, 'News':{ 'Blogging':{}, 'Economics':{}, 'Journalism':{}, 'Politics':{}, 'News':{} },} </code></pre> <p>I don't know algorithm. How to do it? </p>
6
2009-04-16T17:40:18Z
757,387
<p>Everything without a parent is your top level, so make those dicts first. Then do a second pass through your array to find everything with a parent at that top level, etc... It could be written as a loop or a recursive function. You really don't need any of the provided info besides "parent".</p>
1
2009-04-16T18:13:53Z
[ "python", "tree", "hierarchical-trees" ]
Converting tree list to hierarchy dict
757,244
<p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p> <p>I want to convert this list to hierarchy dict. Example of output dict:</p> <pre><code>{ 'Technology': { 'Gadgets':{}, 'Gaming':{}, 'Programming': { 'Python':{}, 'PHP':{}, 'Ruby':{}, 'C++':{} }, 'Enterprise':{}, 'Mac':{}, 'Mobile':{}, 'Seo':{}, 'Ui':{}, 'Virtual Worlds':{}, 'Windows':{}, }, 'News':{ 'Blogging':{}, 'Economics':{}, 'Journalism':{}, 'Politics':{}, 'News':{} },} </code></pre> <p>I don't know algorithm. How to do it? </p>
6
2009-04-16T17:40:18Z
757,507
<p>It sounds like what you're basically wanting to do is a variant of <a href="http://en.wikipedia.org/wiki/Topological%5Fsorting" rel="nofollow">topological sorting</a>. The most common algorithm for this is the source removal algorithm. The pseudocode would look something like this:</p> <pre><code>import copy def TopSort(elems): #elems is an unsorted list of elements. unsorted = set(elems) output_dict = {} for item in elems: if item.is_root(): output_dict[item.name] = {} unsorted.remove(item) FindChildren(unsorted, item.name, output_dict[item.name]) return output_dict def FindChildren(unsorted, name, curr_dict): for item in unsorted: if item.parent == name: curr_dict[item.name] = {} #NOTE: the next line won't work in Python. You #can't modify a set while iterating over it. unsorted.remove(item) FindChildren(unsorted, item.name, curr_dict[item.name]) </code></pre> <p>This obviously is broken in a couple of places (at least as actual Python code). However, <em>hopefully</em> that will give you an idea of how the algorithm will work. Note that this will fail horribly if there's a cycle in the items you have (say item a has item b as a parent while item b has item a as a parent). But then that would probably be impossible to represent in the format you're wanting to do anyway.</p>
2
2009-04-16T18:42:00Z
[ "python", "tree", "hierarchical-trees" ]
Converting tree list to hierarchy dict
757,244
<p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p> <p>I want to convert this list to hierarchy dict. Example of output dict:</p> <pre><code>{ 'Technology': { 'Gadgets':{}, 'Gaming':{}, 'Programming': { 'Python':{}, 'PHP':{}, 'Ruby':{}, 'C++':{} }, 'Enterprise':{}, 'Mac':{}, 'Mobile':{}, 'Seo':{}, 'Ui':{}, 'Virtual Worlds':{}, 'Windows':{}, }, 'News':{ 'Blogging':{}, 'Economics':{}, 'Journalism':{}, 'Politics':{}, 'News':{} },} </code></pre> <p>I don't know algorithm. How to do it? </p>
6
2009-04-16T17:40:18Z
757,582
<p>Here's a less sophisticated, recursive version like chmod700 described. Completely untested of course:</p> <pre><code>def build_tree(nodes): # create empty tree to fill tree = {} # fill in tree starting with roots (those with no parent) build_tree_recursive(tree, None, nodes) return tree def build_tree_recursive(tree, parent, nodes): # find children children = [n for n in nodes if n.parent == parent] # build a subtree for each child for child in children: # start new subtree tree[child.name] = {} # call recursively to build a subtree for current node build_tree_recursive(tree[child.name], child, nodes) </code></pre>
9
2009-04-16T19:02:37Z
[ "python", "tree", "hierarchical-trees" ]
Converting tree list to hierarchy dict
757,244
<p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p> <p>I want to convert this list to hierarchy dict. Example of output dict:</p> <pre><code>{ 'Technology': { 'Gadgets':{}, 'Gaming':{}, 'Programming': { 'Python':{}, 'PHP':{}, 'Ruby':{}, 'C++':{} }, 'Enterprise':{}, 'Mac':{}, 'Mobile':{}, 'Seo':{}, 'Ui':{}, 'Virtual Worlds':{}, 'Windows':{}, }, 'News':{ 'Blogging':{}, 'Economics':{}, 'Journalism':{}, 'Politics':{}, 'News':{} },} </code></pre> <p>I don't know algorithm. How to do it? </p>
6
2009-04-16T17:40:18Z
758,649
<p>Something simple like this might work:</p> <pre><code>def build_tree(category_data): top_level_map = {} cat_map = {} for cat_name, parent, depth in cat_data: cat_map.setdefault(parent, {}) cat_map.setdefault(cat_name, {}) cat_map[parent][cat_name] = cat_map[cat_name] if depth == 0: top_level_map[cat_name] = cat_map[cat_name] return top_level_map </code></pre>
0
2009-04-17T01:05:37Z
[ "python", "tree", "hierarchical-trees" ]
Difference in regex behavior between Perl and Python?
757,476
<p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p> <p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p> <pre><code>/\w+@(tickets\.)?company\.com/i </code></pre> <p>In python, I simply wrote the above regex as<code> '\w+@(tickets\.)?company\.com'</code> expecting the same result. However, <code>support@company.com</code> isn't found at all and a findall on the second returns a list containing only <code>'tickets.'</code>. So clearly the <code>'(tickets\.)?'</code> is the problem area, but what exactly is the difference in regular expression rules between Perl and Python that I'm missing?</p>
3
2009-04-16T18:35:40Z
757,509
<p>Two problems jump out at me:</p> <ol> <li>You need to use a raw string to avoid having to escape "<code>\</code>"</li> <li>You need to escape "<code>.</code>"</li> </ol> <p>So try:</p> <pre><code>r'\w+@(tickets\.)?company\.com' </code></pre> <p>EDIT</p> <p>Sample output:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; exp = re.compile(r'\w+@(tickets\.)?company\.com') &gt;&gt;&gt; bool(exp.match("s@company.com")) True &gt;&gt;&gt; bool(exp.match("1234567@tickets.company.com")) True </code></pre>
2
2009-04-16T18:42:40Z
[ "python", "regex", "perl" ]
Difference in regex behavior between Perl and Python?
757,476
<p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p> <p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p> <pre><code>/\w+@(tickets\.)?company\.com/i </code></pre> <p>In python, I simply wrote the above regex as<code> '\w+@(tickets\.)?company\.com'</code> expecting the same result. However, <code>support@company.com</code> isn't found at all and a findall on the second returns a list containing only <code>'tickets.'</code>. So clearly the <code>'(tickets\.)?'</code> is the problem area, but what exactly is the difference in regular expression rules between Perl and Python that I'm missing?</p>
3
2009-04-16T18:35:40Z
757,518
<p>I think the problem is in your expectations of extracted values. Try using this in your current Python code:</p> <pre><code>'(\w+@(?:tickets\.)?company\.com)' </code></pre>
4
2009-04-16T18:45:10Z
[ "python", "regex", "perl" ]
Difference in regex behavior between Perl and Python?
757,476
<p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p> <p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p> <pre><code>/\w+@(tickets\.)?company\.com/i </code></pre> <p>In python, I simply wrote the above regex as<code> '\w+@(tickets\.)?company\.com'</code> expecting the same result. However, <code>support@company.com</code> isn't found at all and a findall on the second returns a list containing only <code>'tickets.'</code>. So clearly the <code>'(tickets\.)?'</code> is the problem area, but what exactly is the difference in regular expression rules between Perl and Python that I'm missing?</p>
3
2009-04-16T18:35:40Z
757,521
<p>The documentation for <code>re.findall</code>:</p> <blockquote> <pre><code>findall(pattern, string, flags=0) Return a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. </code></pre> </blockquote> <p>Since <code>(tickets\.)</code> is a group, <code>findall</code> returns that instead of the whole match. If you want the whole match, put a group around the whole pattern and/or use non-grouping matches, i.e.</p> <pre><code>r'(\w+@(tickets\.)?company\.com)' r'\w+@(?:tickets\.)?company\.com' </code></pre> <p>Note that you'll have to pick out the first element of each tuple returned by <code>findall</code> in the first case.</p>
7
2009-04-16T18:46:12Z
[ "python", "regex", "perl" ]
Difference in regex behavior between Perl and Python?
757,476
<p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p> <p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p> <pre><code>/\w+@(tickets\.)?company\.com/i </code></pre> <p>In python, I simply wrote the above regex as<code> '\w+@(tickets\.)?company\.com'</code> expecting the same result. However, <code>support@company.com</code> isn't found at all and a findall on the second returns a list containing only <code>'tickets.'</code>. So clearly the <code>'(tickets\.)?'</code> is the problem area, but what exactly is the difference in regular expression rules between Perl and Python that I'm missing?</p>
3
2009-04-16T18:35:40Z
757,539
<p>There isn't a difference in the regexes, but there is a difference in what you are looking for. Your regex is capturing only <code>"tickets."</code> if it exists in both regexes. You probably want something like this</p> <pre><code>#!/usr/bin/python import re regex = re.compile("(\w+@(?:tickets\.)?company\.com)"); a = [ "foo@company.com", "foo@tickets.company.com", "foo@ticketsacompany.com", "foo@compant.org" ]; for string in a: print regex.findall(string) </code></pre>
1
2009-04-16T18:52:00Z
[ "python", "regex", "perl" ]