title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python IDLE subprocess error?
874,757
<blockquote> <p>IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.</p> </blockquote> <p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager &amp; stop all Pythonw processes to get it to work again?</p> <p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p> <pre><code>f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() </code></pre> <p>Sometimes it works, sometimes it doesn't!</p>
9
2009-05-17T14:42:48Z
892,274
<p>If it look like truly random behavior than it could be a multi-cpu/core issue. You could try to set the interpreter affinity to a fixed cpu and see if this issue still comes up.</p> <p>Google for something like: imagecfg process affinity For more information about that.</p>
0
2009-05-21T10:34:45Z
[ "python", "python-3.x", "python-idle" ]
Python IDLE subprocess error?
874,757
<blockquote> <p>IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.</p> </blockquote> <p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager &amp; stop all Pythonw processes to get it to work again?</p> <p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p> <pre><code>f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() </code></pre> <p>Sometimes it works, sometimes it doesn't!</p>
9
2009-05-17T14:42:48Z
980,926
<p>Or..you could forget IDLE and try <a href="http://ipython.org/" rel="nofollow">IPython</a> instead. It may not exhibit the same error at all. I've never had a problem with it. You get some cool functionality with it that IDLE doesn't have. I find it very useful when working with Python.</p>
0
2009-06-11T13:00:26Z
[ "python", "python-3.x", "python-idle" ]
Python IDLE subprocess error?
874,757
<blockquote> <p>IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.</p> </blockquote> <p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager &amp; stop all Pythonw processes to get it to work again?</p> <p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p> <pre><code>f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() </code></pre> <p>Sometimes it works, sometimes it doesn't!</p>
9
2009-05-17T14:42:48Z
7,840,915
<p>Simple. Just cut all files with .py extension, paste them in a place different from the os path, one of the files is causing such error. Run the IDLE again.</p>
1
2011-10-20T19:06:07Z
[ "python", "python-3.x", "python-idle" ]
Python IDLE subprocess error?
874,757
<blockquote> <p>IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.</p> </blockquote> <p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager &amp; stop all Pythonw processes to get it to work again?</p> <p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p> <pre><code>f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() </code></pre> <p>Sometimes it works, sometimes it doesn't!</p>
9
2009-05-17T14:42:48Z
9,645,737
<p>I was getting the same error message. What was causing the problem for me was that I named one of my scripts 'string.py'. Every time I tried to run a script with 'string.py' in the same directory this happened.</p>
5
2012-03-10T10:37:44Z
[ "python", "python-3.x", "python-idle" ]
Python IDLE subprocess error?
874,757
<blockquote> <p>IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.</p> </blockquote> <p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager &amp; stop all Pythonw processes to get it to work again?</p> <p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p> <pre><code>f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() </code></pre> <p>Sometimes it works, sometimes it doesn't!</p>
9
2009-05-17T14:42:48Z
11,510,272
<p>I had this same problem in 2.7.3. I found that when I was learning how to use tkinter and I made a basic program to open a window, I named it Tkinter.py and put it in the same folder as the program I was trying to run with IDLE. It would always compile the program called Tkinter and make a second compiled file. When I tried to run my other program I would get the error message. I renamed my simple windows-opening program to something else and deleted the compiled file. I was able to run every program in that folder with IDLE no problem.</p>
2
2012-07-16T18:26:18Z
[ "python", "python-3.x", "python-idle" ]
Python IDLE subprocess error?
874,757
<blockquote> <p>IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.</p> </blockquote> <p>Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager &amp; stop all Pythonw processes to get it to work again?</p> <p>It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment-</p> <pre><code>f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() </code></pre> <p>Sometimes it works, sometimes it doesn't!</p>
9
2009-05-17T14:42:48Z
24,290,513
<p>i had the same error. I did a modem reboot and to my surprise, it worked !</p>
0
2014-06-18T16:18:04Z
[ "python", "python-3.x", "python-idle" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
874,865
<p>stdout will be buffered - so you won't get anything till that buffer is filled, or the subprocess exits.</p> <p>You can try flushing <code>stdout</code> from the sub-process, or using stderr, or changing stdout on non-buffered mode.</p>
6
2009-05-17T15:51:49Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
874,868
<p>It sounds like the issue might be the use of buffered output by the subprocess - if a relatively small amount of output is created, it could be buffered until the subprocess exits. Some background can be found <a href="http://www.pixelbeat.org/programming/stdio%5Fbuffering/" rel="nofollow">here</a>:</p>
2
2009-05-17T15:53:38Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
875,281
<p>Update with code that appears not to work (on windows anyway)</p> <pre><code>class ThreadWorker(threading.Thread): def __init__(self, callable, *args, **kwargs): super(ThreadWorker, self).__init__() self.callable = callable self.args = args self.kwargs = kwargs self.setDaemon(True) def run(self): try: self.callable(*self.args, **self.kwargs) except wx.PyDeadObjectError: pass except Exception, e: print e if __name__ == "__main__": import os from subprocess import Popen, PIPE def worker(pipe): while True: line = pipe.readline() if line == '': break else: print line proc = Popen("python subprocess_test.py", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_worker = ThreadWorker(worker, proc.stdout) stderr_worker = ThreadWorker(worker, proc.stderr) stdout_worker.start() stderr_worker.start() while True: pass </code></pre>
8
2009-05-17T19:16:53Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
1,456,182
<p>I've used the pexpect module for this, it seems to work ok. <a href="http://sourceforge.net/projects/pexpect/" rel="nofollow">http://sourceforge.net/projects/pexpect/</a></p>
0
2009-09-21T18:51:59Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
1,945,380
<p>Here's what worked for me:</p> <pre><code>cmd = ["./tester_script.bash"] p = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) while p.poll() is None: out = p.stdout.readline() do_something_with( out, err ) </code></pre> <p>In your case you could try to pass a reference to the sub-process to your Worker Thread, and do the polling inside the thread. I don't know how it will behave when two threads poll (and interact with) the same subprocess, but it may work.</p> <p>Also note thate the <code>while p.poll() is None:</code> is intended as is. Do <strong>not</strong> replace it with <code>while not p.poll()</code> as in python <code>0</code> (the returncode for successful termination) is also considered <code>False</code>.</p>
2
2009-12-22T10:06:00Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
2,328,115
<p>I've been running into this problem as well. The problem occurs because you are trying to read stderr as well. If there are no errors, then trying to read from stderr would block. </p> <p>On Windows, there is no easy way to poll() file descriptors (only Winsock sockets).</p> <p>So a solution is not to try and read from stderr.</p>
1
2010-02-24T17:37:13Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
2,858,790
<p>Using pexpect [http://www.noah.org/wiki/Pexpect] with non-blocking readlines will resolve this problem. It stems from the fact that pipes are buffered, and so your app's output is getting buffered by the pipe, therefore you can't get to that output until the buffer fills or the process dies.</p>
1
2010-05-18T15:42:43Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
15,699,282
<p>This seems to be a well-known Python limitation, see <a href="http://www.python.org/dev/peps/pep-3145/" rel="nofollow" title="PEP 3145">PEP 3145</a> and maybe others.</p>
1
2013-03-29T07:39:02Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
24,346,632
<p>Read one character at a time: <a href="http://blog.thelinuxkid.com/2013/06/get-python-subprocess-output-without.html" rel="nofollow">http://blog.thelinuxkid.com/2013/06/get-python-subprocess-output-without.html</a></p> <pre><code>import contextlib import subprocess # Unix, Windows and old Macintosh end-of-line newlines = ['\n', '\r\n', '\r'] def unbuffered(proc, stream='stdout'): stream = getattr(proc, stream) with contextlib.closing(stream): while True: out = [] last = stream.read(1) # Don't loop forever if last == '' and proc.poll() is not None: break while last not in newlines: # Don't loop forever if last == '' and proc.poll() is not None: break out.append(last) last = stream.read(1) out = ''.join(out) yield out def example(): cmd = ['ls', '-l', '/'] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # Make all end-of-lines '\n' universal_newlines=True, ) for line in unbuffered(proc): print line example() </code></pre>
1
2014-06-21T23:02:35Z
[ "python", "subprocess", "stdout", "popen" ]
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
<p>I'd like to use the subprocess module in the following way:</p> <ol> <li>create a new process that potentially takes a long time to execute. </li> <li>capture <code>stdout</code> (or <code>stderr</code>, or potentially both, either together or separately) </li> <li>Process data from the subprocess <strong>as it comes in,</strong> perhaps firing events on every line received (in wxPython say) or simply printing them out for now.</li> </ol> <p>I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. </p> <p>If I create a separate thread that does a blocking <code>readline()</code> of <code>myprocess.stdout</code> (using <code>stdout = subprocess.PIPE</code>) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize)</p> <p>Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?</p>
41
2009-05-17T15:20:29Z
38,775,458
<p>Using subprocess.Popen, I can run the .exe of one of my C# projects and redirect the output to my Python file. I am able now to <code>print()</code> all the information being output to the C# console (using <code>Console.WriteLine()</code>) to the Python console.</p> <p>Python code:</p> <pre><code>from subprocess import Popen, PIPE, STDOUT p = Popen('ConsoleDataImporter.exe', stdout = PIPE, stderr = STDOUT, shell = True) while True: line = p.stdout.readline() print(line) if not line: break </code></pre> <p>This gets the console output of my .NET project line by line as it is created and breaks out of the enclosing while loop upon the project's termination. I'd imagine this would work for two python files as well. </p>
0
2016-08-04T19:05:36Z
[ "python", "subprocess", "stdout", "popen" ]
wxPython launches my app twice when importing a sub-package
874,856
<p>I'm sorry for the verbal description.</p> <p>I have a wxPython app in a file called <code>applicationwindow.py</code> that resides in a package called <code>garlicsimwx</code>. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file <code>rundemo.py</code> in a folder which contains the <code>garlicsimwx</code> package, which runs the app as well. When I use <code>rundemo.py</code>, the app launches, however, when the main <code>wx.Frame</code> imports a sub-package of <code>garlicsimwx</code>, namely <code>simulations.life</code>, for some reason a new instance of my application is created (i.e., a new identical window pops out.)</p> <p>I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the <code>import</code> statement doesn't directly cause it. Only when control returns to <code>PyApp.MainLoop</code> the second window opens.</p> <p>How do I stop this?</p>
0
2009-05-17T15:45:07Z
874,879
<p>I think you have code in one of your modules that looks like this:</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(...): ... frame = MyFrame(...) </code></pre> <p>The frame will be created when this module is first imported. To prevent that, use the common Python idiom:</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(...): ... if __name__ == '__main__': frame = MyFrame(...) </code></pre> <p>Did I guess correctly?</p>
4
2009-05-17T16:05:06Z
[ "python", "import", "wxpython" ]
wxPython launches my app twice when importing a sub-package
874,856
<p>I'm sorry for the verbal description.</p> <p>I have a wxPython app in a file called <code>applicationwindow.py</code> that resides in a package called <code>garlicsimwx</code>. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file <code>rundemo.py</code> in a folder which contains the <code>garlicsimwx</code> package, which runs the app as well. When I use <code>rundemo.py</code>, the app launches, however, when the main <code>wx.Frame</code> imports a sub-package of <code>garlicsimwx</code>, namely <code>simulations.life</code>, for some reason a new instance of my application is created (i.e., a new identical window pops out.)</p> <p>I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the <code>import</code> statement doesn't directly cause it. Only when control returns to <code>PyApp.MainLoop</code> the second window opens.</p> <p>How do I stop this?</p>
0
2009-05-17T15:45:07Z
875,039
<p>You could create a global boolean variable like <code>g_window_was_drawn</code> and check it in the function that does the work of creating a window. The value would be false at the start of the program and would change to True when first creating a window. The function that creates the window would check if the <code>g_window_was_drawn</code> is already true, and if it is, it would throw an exception. Then You will have a nice stacktrace telling You who is responsible of executing this function.</p> <p>I hope that helps You find it. I'm sorry for the verbal solution ;)</p>
0
2009-05-17T17:26:59Z
[ "python", "import", "wxpython" ]
wxPython launches my app twice when importing a sub-package
874,856
<p>I'm sorry for the verbal description.</p> <p>I have a wxPython app in a file called <code>applicationwindow.py</code> that resides in a package called <code>garlicsimwx</code>. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file <code>rundemo.py</code> in a folder which contains the <code>garlicsimwx</code> package, which runs the app as well. When I use <code>rundemo.py</code>, the app launches, however, when the main <code>wx.Frame</code> imports a sub-package of <code>garlicsimwx</code>, namely <code>simulations.life</code>, for some reason a new instance of my application is created (i.e., a new identical window pops out.)</p> <p>I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the <code>import</code> statement doesn't directly cause it. Only when control returns to <code>PyApp.MainLoop</code> the second window opens.</p> <p>How do I stop this?</p>
0
2009-05-17T15:45:07Z
875,059
<p>Got it: There was no</p> <pre><code>if __name__=='__main__': </code></pre> <p>in my <code>rundemo</code> file. It was actually a <code>multiprocessing</code> issue: The new window was opened in a separate process.</p>
0
2009-05-17T17:36:17Z
[ "python", "import", "wxpython" ]
Project Euler Problem 245
875,027
<p>I'm onto <a href="http://projecteuler.net/index.php?section=problems&amp;id=245" rel="nofollow">problem 245</a> now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:</p> <p>We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).</p> <p>We are trying to solve:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k" alt="\frac{n-\phi(n)}{n-1}=\frac1k"></p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk" alt="\frac{n-1}{n-\phi(n)}=k"></p> <p>Hence:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29" alt="n\equiv1\ (\text{mod }n-\phi(n))"></p> <p>At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 10<sup>4</sup>:</p> <pre><code>15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 </code></pre> <p>Importantly it looks like there <a href="http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759" rel="nofollow">won't be too many</a> less than the 10<sup>11</sup> limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)</p> <p>Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.</p> <p>Returning to the original equation, note that it can be rewritten as:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk" alt="\frac{\phi(n)-1}{n-1}=\frac{k-1}k"></p> <p>Since we know k:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29" alt="k\cdot\phi(n)\equiv k\ (\text{mod }n-1)"></p> <p>And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 10<sup>8</sup> which is 5699973227 (only 237 solutions for n).</p> <p>I'm pretty much out of ideas; can anyone give away some hints?</p> <hr> <p><strong>Update</strong>: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:</p> <p>n is always odd and k is always even. k &lt;= 10<sup>5.5</sup>. n must be squarefree.</p> <p>I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k &lt; q &lt; 2k.</p> <p>For n with 2 of more prime factors, all of n's primes are greater than k.</p>
7
2009-05-17T17:20:00Z
878,313
<p>In order not to give too much away, I'd suggest two things:</p> <ol> <li><p>Analyze the sequence of numbers you've produced though brute-force: they all share a common characteristic. If you find what it is, you may then have a shot at brute forcing your way to a solution.</p></li> <li><p>Find a more sophisticated factoring algorithm. Or even better: rather than finding the factors from the numbers, build the numbers from the factors...</p></li> </ol> <p><hr /></p> <p>EDIT: The patterns you wll find will only add to your understading, and hopefully show you how you could have achieved the same amount of knowledge by an adequate manipulation of the analytical expression. Without knowing that pattern, I'm afraid that there is no path to a solution. Plus, this is probably among the hardest Project Euler problems, so you need not worry about finding the solution without a lot of sweat and toil...</p>
1
2009-05-18T15:29:11Z
[ "python", "algorithm", "math" ]
Project Euler Problem 245
875,027
<p>I'm onto <a href="http://projecteuler.net/index.php?section=problems&amp;id=245" rel="nofollow">problem 245</a> now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:</p> <p>We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).</p> <p>We are trying to solve:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k" alt="\frac{n-\phi(n)}{n-1}=\frac1k"></p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk" alt="\frac{n-1}{n-\phi(n)}=k"></p> <p>Hence:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29" alt="n\equiv1\ (\text{mod }n-\phi(n))"></p> <p>At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 10<sup>4</sup>:</p> <pre><code>15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 </code></pre> <p>Importantly it looks like there <a href="http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759" rel="nofollow">won't be too many</a> less than the 10<sup>11</sup> limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)</p> <p>Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.</p> <p>Returning to the original equation, note that it can be rewritten as:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk" alt="\frac{\phi(n)-1}{n-1}=\frac{k-1}k"></p> <p>Since we know k:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29" alt="k\cdot\phi(n)\equiv k\ (\text{mod }n-1)"></p> <p>And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 10<sup>8</sup> which is 5699973227 (only 237 solutions for n).</p> <p>I'm pretty much out of ideas; can anyone give away some hints?</p> <hr> <p><strong>Update</strong>: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:</p> <p>n is always odd and k is always even. k &lt;= 10<sup>5.5</sup>. n must be squarefree.</p> <p>I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k &lt; q &lt; 2k.</p> <p>For n with 2 of more prime factors, all of n's primes are greater than k.</p>
7
2009-05-17T17:20:00Z
881,439
<p>Multiply primes. What I did, is first check every 2-prime product; store the ones that are successes. Then using the stored products, check those with more primes (every 3-prime product shown in your brute force has a 2-prime subset that works). Use these stored products, and try again with 4 primes, 5 primes etc.</p> <p>The only downside is that you need a good sieve or list of primes.</p> <p>Here is a list of the ones for N&lt;=(10^7):</p> <p><strong>2 primes</strong> 15,85,259,391,589,1111,3193,4171,4369,12361,17473,25429,28243,47989,52537,65641, 68377,83767,91759,100777,120019,144097,186367,268321,286357,291919,316171,327937 ,346063,353029,360301,404797,406867,524851,531721,558013,563767,633727,705667,73 8607,910489,970141,1013539,1080769,1093987,1184233,1185421,1223869,1233823,12618 07,1264693,1455889,1487371,1529641,1574383,1612381,1617379,1657531,1793689,20163 79,2095087,2130871,2214031,2299459,2500681,2553709,2609689,2617963,2763697,30475 21,3146677,3397651,3514603,3539017,3820909,3961219,4078927,4186993,4197901,44997 07,4552411,4935883,4975687,5103841,5299351,5729257,5829877,5864581,6017299,62364 01,6802531,6856609,8759011,9059233,9203377,9301603,9305311,9526747,9536899,95832 79,9782347,9900217 <strong>3 primes</strong> 255,21845,335923,3817309 <strong>4 primes</strong> 65535 <strong>5 primes</strong> 83623935</p>
3
2009-05-19T07:44:41Z
[ "python", "algorithm", "math" ]
Project Euler Problem 245
875,027
<p>I'm onto <a href="http://projecteuler.net/index.php?section=problems&amp;id=245" rel="nofollow">problem 245</a> now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:</p> <p>We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).</p> <p>We are trying to solve:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k" alt="\frac{n-\phi(n)}{n-1}=\frac1k"></p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk" alt="\frac{n-1}{n-\phi(n)}=k"></p> <p>Hence:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29" alt="n\equiv1\ (\text{mod }n-\phi(n))"></p> <p>At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 10<sup>4</sup>:</p> <pre><code>15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 </code></pre> <p>Importantly it looks like there <a href="http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759" rel="nofollow">won't be too many</a> less than the 10<sup>11</sup> limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)</p> <p>Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.</p> <p>Returning to the original equation, note that it can be rewritten as:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk" alt="\frac{\phi(n)-1}{n-1}=\frac{k-1}k"></p> <p>Since we know k:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29" alt="k\cdot\phi(n)\equiv k\ (\text{mod }n-1)"></p> <p>And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 10<sup>8</sup> which is 5699973227 (only 237 solutions for n).</p> <p>I'm pretty much out of ideas; can anyone give away some hints?</p> <hr> <p><strong>Update</strong>: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:</p> <p>n is always odd and k is always even. k &lt;= 10<sup>5.5</sup>. n must be squarefree.</p> <p>I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k &lt; q &lt; 2k.</p> <p>For n with 2 of more prime factors, all of n's primes are greater than k.</p>
7
2009-05-17T17:20:00Z
911,612
<p>Project Euler isn't fond of discussing problems on public forums like StackOverflow. All tasks are made to be done solo, if you encounter problems you may ask help for a specific mathematical or programming concept, but you can't just decide to ask how to solve the problem at hand - takes away the point of project Euler.</p> <p>Point is to learn and come up with solutions yourself, and learn new concepts.</p>
9
2009-05-26T16:37:17Z
[ "python", "algorithm", "math" ]
Project Euler Problem 245
875,027
<p>I'm onto <a href="http://projecteuler.net/index.php?section=problems&amp;id=245" rel="nofollow">problem 245</a> now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:</p> <p>We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).</p> <p>We are trying to solve:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k" alt="\frac{n-\phi(n)}{n-1}=\frac1k"></p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk" alt="\frac{n-1}{n-\phi(n)}=k"></p> <p>Hence:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29" alt="n\equiv1\ (\text{mod }n-\phi(n))"></p> <p>At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 10<sup>4</sup>:</p> <pre><code>15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 </code></pre> <p>Importantly it looks like there <a href="http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759" rel="nofollow">won't be too many</a> less than the 10<sup>11</sup> limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)</p> <p>Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.</p> <p>Returning to the original equation, note that it can be rewritten as:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk" alt="\frac{\phi(n)-1}{n-1}=\frac{k-1}k"></p> <p>Since we know k:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29" alt="k\cdot\phi(n)\equiv k\ (\text{mod }n-1)"></p> <p>And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 10<sup>8</sup> which is 5699973227 (only 237 solutions for n).</p> <p>I'm pretty much out of ideas; can anyone give away some hints?</p> <hr> <p><strong>Update</strong>: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:</p> <p>n is always odd and k is always even. k &lt;= 10<sup>5.5</sup>. n must be squarefree.</p> <p>I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k &lt; q &lt; 2k.</p> <p>For n with 2 of more prime factors, all of n's primes are greater than k.</p>
7
2009-05-17T17:20:00Z
914,300
<p>Let me continue what jug started, but try a somewhat different approach. The goal again is to just find the numbers that have two distinct factors n=pq. As you already pointed out we are looking for the numbers such that n-phi(n) divides n-1. I.e., if n=pq then that means we are looking for p,q such that</p> <pre><code> p+q-1 divides pq-1 </code></pre> <p>Assume we fix p and are looking for all primes q satisfying the equation above. The equation above doesn't look very easy to solve, hence the next step is to eliminate q as much as possible. In particular, we use that if a divides b then a also divides b + ka for any integer k. Hence </p> <pre><code> p+q-1 divides pq - 1 - p(p+q-1) </code></pre> <p>and simplifying this leads to the condition </p> <pre><code> p+q-1 divides p^2 - p + 1. </code></pre> <p>We may assume that p is the smaller prime factor of n. Then p is smaller than the square root of 10<sup>11</sup>. Hence it is possible to find all numbers with two factors by iterating through all primes p below the square root of 10<sup>11</sup>, then find the divisors of p^2-p+1, solve for q and check if q is prime and pq is a solution of the problem.</p> <p>This of course, still leaves the integers with more than two prime factors. A somewhat similar approach works here too, but is more involved and needs further optimizations.</p> <p>One question I can't answer is why is this problem formulated so complicated. Couldn't the authors just have asked for the sum of composite integers where n-phi(n) divides n-1. So maybe I'm missing a big hint there.</p> <p><hr /></p> <p>Now, that the solutions with two prime factors are known, I'll try to find a potential algorithm for finding solutions with more than 2 prime factors. The goal is to find an algorithm that given a composite integer m finds all primes q such that mq is a solution. I.e., q must be such that</p> <pre><code> mq - phi(mq) divides mq - 1. </code></pre> <p>Let </p> <pre><code> F = mq - phi(mq). </code></pre> <p>Then of course </p> <pre><code> F = (m-phi(m)) q + phi(m). </code></pre> <p>As in the case of two prime factors it is possible to find a condition for F, by eliminating q from the left hand side of the equation above. Since F divides mq-1 it also divides </p> <pre><code> (m-phi(m))(mq - 1) </code></pre> <p>and hence also </p> <pre><code> m F - (m-phi(m))(mq - 1) = m phi(m) + m - phi(m). </code></pre> <p>Thus by finding all the divisors F of m phi(m) + m - phi(m) and by checking if (F - phi(m))/ (m - phi(m)) is prime it is possible to find all solutions mq for a given m. Since only the divisors F that satisfy</p> <pre><code> F == phi(m) (mod m - phi(m)) </code></pre> <p>can lead to new solutions, this fact can somtimes be used to optimze the factorization of m phi(m) + m - phi(m).</p>
5
2009-05-27T06:44:33Z
[ "python", "algorithm", "math" ]
Project Euler Problem 245
875,027
<p>I'm onto <a href="http://projecteuler.net/index.php?section=problems&amp;id=245" rel="nofollow">problem 245</a> now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:</p> <p>We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).</p> <p>We are trying to solve:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k" alt="\frac{n-\phi(n)}{n-1}=\frac1k"></p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk" alt="\frac{n-1}{n-\phi(n)}=k"></p> <p>Hence:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29" alt="n\equiv1\ (\text{mod }n-\phi(n))"></p> <p>At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 10<sup>4</sup>:</p> <pre><code>15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 </code></pre> <p>Importantly it looks like there <a href="http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759" rel="nofollow">won't be too many</a> less than the 10<sup>11</sup> limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)</p> <p>Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.</p> <p>Returning to the original equation, note that it can be rewritten as:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk" alt="\frac{\phi(n)-1}{n-1}=\frac{k-1}k"></p> <p>Since we know k:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29" alt="k\cdot\phi(n)\equiv k\ (\text{mod }n-1)"></p> <p>And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 10<sup>8</sup> which is 5699973227 (only 237 solutions for n).</p> <p>I'm pretty much out of ideas; can anyone give away some hints?</p> <hr> <p><strong>Update</strong>: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:</p> <p>n is always odd and k is always even. k &lt;= 10<sup>5.5</sup>. n must be squarefree.</p> <p>I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k &lt; q &lt; 2k.</p> <p>For n with 2 of more prime factors, all of n's primes are greater than k.</p>
7
2009-05-17T17:20:00Z
914,340
<p>I haven't found a full solution, but I would like to share my thoughts. Perhaps someone could help.</p> <p>I believe that one should try to reduce the problem to</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21O%28%5Csqrt%7Bn%7D%29.gif" alt="O(sqrt(n)" /></p> <p>complexity.The following facts can be used to make the search more effective:</p> <ul> <li>Any solution must be an odd number</li> <li>Any solution must be a multiple of distinct primes (no square number factors are allowed)</li> </ul> <p>Others have pointed out about these and it is easy to prove them using only the basic properties of the totient function.</p> <p>I'll start by analyzing all prime and composite numbers up to sqrt(10^11). This is not a big task and the time required should be well below the 1 minute requirement. All solutions above the square root are of the form:</p> <pre><code>a*b, where at least one of a,b &lt; sqrt(10^11) </code></pre> <p>While iterating the range 0..sqrt(10^11), I will search for multiples of the number in iteration that are solutions. I will only cover the case of multiplying a number below the square root with a single prime. The solution set I will get this way will be a superset of the two-prime factors solution set. It will still not be the complete solution set, as solutions of the form p1*p2*p3, where p1p2,p2p3,p1p3>sqrt(10^11) will not be found.</p> <p>Let b be the number below the square root and a the prime to multiply it.</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21b%20%3D%20k%5F%7Bb%7D%5Bb%20-%20%5Cphi%28b%29%5D%20%2B%20m%5F%7Bb%7D.gif" alt="b = kb*(b - phi(b)) + mb" /></p> <p>We have:</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21ab%20%3D%20k%5F%7Bb%7D%5Bab%20-%20a%5Cphi%28b%29%5D%20%2B%20am%5F%7Bb%7D.gif" alt="ab = kb(ab - aphi(b)) + amb" /></p> <p>Based on the facts that </p> <pre><code>phi(a) = a - 1 and phi(a)*phi(b) = phi(a*b) if a, b coprime </code></pre> <p>we have</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21ab%20%3D%20k%5F%7Bb%7D%5Bab%20-%20%5Cphi%28ab%29%5D%20-%20k%5F%7Bb%7D%5Cphi%28b%29%20%2B%20am%5F%7Bb%7D.gif" alt="ab = kb(ab - phi(ab)) - kbphi(b) + amb" /> </p> <p>The 'modulo' part on the right can be written as:</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21m%20%3D%20am%5F%7Bb%7D%20-%20k%5F%7Bb%7D%5Cphi%28b%29%20%3D%20%28a-1%29m%5F%7Bb%7D%20-%20%28k%5F%7Bb%7D-1%29b.gif" alt="m = amb - kbphi(b) = (a-1)mb - (kb-1)b" /></p> <p>Let me temporarily accept that </p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%210%20%5Cleq%20m%20%5Cleq%20ab%20-%20%5Cphi%28ab%29.gif" alt="0 &lt;= m &lt;= ab - phi(ab)" /></p> <p>Then I could solve the above equation for a (m=1), verify that the result is prime and then I will have the only solution that is a multiple of b. If the m is not within the limits to be the actual modulo, then I need to either solve the equation for different values of k:</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21%28k-1%29%28ab%20-%20%5Cphi%28ab%29%29%20%5Cleq%20m%20%5Cleq%20k%28ab%20-%20%5Cphi%28ab%29%29.gif" alt="(k-1)(ab - phi(ab)) &lt;= m &lt;= k(ab - phi(ab))" /></p> <p>(k values must be somehow limited) or prove that in that case the will be a higher b &lt; sqrt(10^11) to cover for this.</p> <p>There is a special case for b prime or b composite and mb = 0. In that case:</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21m%20%3D%20-%28k%5F%7Bb%7D%20-%201%29b.gif" alt="m = -(kb - 1)b" /></p> <p>This can be calculated. For b a prime number:</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21m%20%3D%20-%28b%20-%201%29b.gif" alt="m = -(b-1)b" /> </p> <p>I need to find a prime a that satisfies the equation:</p> <p><img src="http://www.texify.com/img/%5CLARGE%5C%21k%5Bab%20-%20%28a-1%29%5Cphi%28b%29%5D%20%2B%20m%20%20%3D%201%2C%20k%20%3D%201%2C2%2C....gif" alt="k(ab - (a-1)phi(b)) + m = 1, k = 1,2,..." /></p> <p>For example, let b=3, phi(b)=2.</p> <p>I need to solve:</p> <p>k[3a-2(a-1)] - 6 = 1 => k(a + 2) = 5</p> <p>For k=1, a=7, a prime (solution) For all other values of k, the above equation can't be satisfied.</p>
0
2009-05-27T07:01:08Z
[ "python", "algorithm", "math" ]
Project Euler Problem 245
875,027
<p>I'm onto <a href="http://projecteuler.net/index.php?section=problems&amp;id=245" rel="nofollow">problem 245</a> now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:</p> <p>We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).</p> <p>We are trying to solve:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k" alt="\frac{n-\phi(n)}{n-1}=\frac1k"></p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk" alt="\frac{n-1}{n-\phi(n)}=k"></p> <p>Hence:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29" alt="n\equiv1\ (\text{mod }n-\phi(n))"></p> <p>At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 10<sup>4</sup>:</p> <pre><code>15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 </code></pre> <p>Importantly it looks like there <a href="http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759" rel="nofollow">won't be too many</a> less than the 10<sup>11</sup> limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)</p> <p>Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.</p> <p>Returning to the original equation, note that it can be rewritten as:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk" alt="\frac{\phi(n)-1}{n-1}=\frac{k-1}k"></p> <p>Since we know k:</p> <p><img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29" alt="k\cdot\phi(n)\equiv k\ (\text{mod }n-1)"></p> <p>And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 10<sup>8</sup> which is 5699973227 (only 237 solutions for n).</p> <p>I'm pretty much out of ideas; can anyone give away some hints?</p> <hr> <p><strong>Update</strong>: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:</p> <p>n is always odd and k is always even. k &lt;= 10<sup>5.5</sup>. n must be squarefree.</p> <p>I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k &lt; q &lt; 2k.</p> <p>For n with 2 of more prime factors, all of n's primes are greater than k.</p>
7
2009-05-17T17:20:00Z
916,466
<p>no direct help for this problem, but maybe interesting for future math projects: instead of using WolframAlpha to analyze the sequence, I'd recommend <a href="http://www.research.att.com/~njas/sequences/" rel="nofollow">"The On-Line Encyclopedia of Integer Sequences"</a> on research.att.com.</p> <p>Have fun solving all Euler problems!</p>
1
2009-05-27T15:38:37Z
[ "python", "algorithm", "math" ]
Receiving 16-bit integers in Python
875,046
<p>I'm reading 16-bit integers from a piece of hardware over the serial port.</p> <p>Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data?</p>
8
2009-05-17T17:31:50Z
875,062
<p>Try using the <a href="http://docs.python.org/library/struct.html">struct</a> module:</p> <pre><code>import struct # read 2 bytes from hardware as a string s = hardware.readbytes(2) # h means signed short # &lt; means "little-endian, standard size (16 bit)" # &gt; means "big-endian, standard size (16 bit)" value = struct.unpack("&lt;h", s) # hardware returns little-endian value = struct.unpack("&gt;h", s) # hardware returns big-endian </code></pre>
19
2009-05-17T17:36:48Z
[ "python", "integer" ]
How to print a list, dict or collection of objects, in Python
875,074
<p>I have written a class in python that implements <code>__str__(self)</code> but when I use print on a list containing instances of this class, I just get the default output <code>&lt;__main__.DSequence instance at 0x4b8c10&gt;</code>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function?</p> <p>Here's the class:</p> <pre><code>class DSequence: def __init__(self, sid, seq): """Sequence object for a dummy dna string""" self.sid = sid self.seq = seq def __iter__(self): return self def __str__(self): return '[' + str(self.sid) + '] -&gt; [' + str(self.seq) + ']' def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.seq[self.index] </code></pre>
17
2009-05-17T17:41:03Z
875,077
<p>Yes, you need to use <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Frepr%5F%5F"><code>__repr__</code></a>. A quick example of its behavior:</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __str__(self): ... return '__str__' ... def __repr__(self): ... return '__repr__' ... &gt;&gt;&gt; bar = Foo() &gt;&gt;&gt; bar __repr__ &gt;&gt;&gt; print bar __str__ &gt;&gt;&gt; repr(bar) '__repr__' &gt;&gt;&gt; str(bar) '__str__' </code></pre> <p>However, if you don't define a <code>__str__</code>, it falls back to <code>__repr__</code>, although this isn't recommended:</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __repr__(self): ... return '__repr__' ... &gt;&gt;&gt; bar = Foo() &gt;&gt;&gt; bar __repr__ &gt;&gt;&gt; print bar __repr__ </code></pre> <p>All things considered, as the manual recommends, <code>__repr__</code> is used for debugging and should return something <code>repr</code>esentative of the object.</p>
21
2009-05-17T17:42:22Z
[ "python", "list" ]
How to print a list, dict or collection of objects, in Python
875,074
<p>I have written a class in python that implements <code>__str__(self)</code> but when I use print on a list containing instances of this class, I just get the default output <code>&lt;__main__.DSequence instance at 0x4b8c10&gt;</code>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function?</p> <p>Here's the class:</p> <pre><code>class DSequence: def __init__(self, sid, seq): """Sequence object for a dummy dna string""" self.sid = sid self.seq = seq def __iter__(self): return self def __str__(self): return '[' + str(self.sid) + '] -&gt; [' + str(self.seq) + ']' def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.seq[self.index] </code></pre>
17
2009-05-17T17:41:03Z
875,197
<p>Just a little enhancement avoiding the + for concatenating:</p> <pre><code>def __str__(self): return '[%s] -&gt; [%s]' % (self.sid, self.seq) </code></pre>
1
2009-05-17T18:48:02Z
[ "python", "list" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
875,128
<p>Navigating through a binary search tree requires state (in which node I am?) and comparisons (is that value less or greater than that?), things that cannot be done by a finite state automaton.</p> <p>Sure, you can search for the node with a given value, but how then you could, for example, remove a node that isn't a leaf if you don't know its parent?</p> <p>And even if you know the parent via the information supplied by the node, how do you determine the minimum of the left subtree, remove it and place it in the node?</p> <p>I think you're asking too much to FSA.</p>
1
2009-05-17T18:13:22Z
[ "java", "python", "c", "regex", "tree-structure" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
875,131
<p>I don't know a general purpose langugae that can do that, but it seems to me that you are looking for something like <a href="http://en.wikipedia.org/wiki/XPath">XPath</a>.</p>
5
2009-05-17T18:17:02Z
[ "java", "python", "c", "regex", "tree-structure" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
875,133
<p>There is <a href="http://www.txl.ca/" rel="nofollow">TXL</a> for pattern based tree rewriting.</p> <p>Tree rewriting with patterns is also done with parser toolkits such as <a href="http://www.antlr.org/wiki/display/~admin/2008/11/30/Example%2Btree%2Brewriting%2Bwith%2Bpatterns" rel="nofollow">ANTLR</a></p> <p>Code generation with bottom up tree rewriting, google BURS or BURG.</p>
4
2009-05-17T18:17:31Z
[ "java", "python", "c", "regex", "tree-structure" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
875,137
<p><a href="http://www.perl.com/pub/a/2003/06/06/regexps.html" rel="nofollow">This</a> article gives some tasty hints about recursive Perl regular expressions, but honestly it's rare to see a tree structure approached this way.</p> <p>More typically, one would write a state machine style parser, that might use regexes to parse each particular node in the tree.</p> <p><a href="http://expat.sourceforge.net/" rel="nofollow">Expat</a> is probably a good example to look at.</p>
1
2009-05-17T18:17:55Z
[ "java", "python", "c", "regex", "tree-structure" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
875,168
<p>Pattern Matching, provided by languages such as Scala, F#, Erlang and Haskell (I'm sure there's more) is designed to succinctly manipulate data structures like trees, esp when used with recursion. </p> <p><a href="http://www.scala-lang.org/node/120" rel="nofollow">here</a> is a very high level view of what pattren matching can do in Scala. The examples shown really don't do pattern matching justice. </p> <p>Wikipedia has a couple of references to pattern matching, too. <a href="http://en.wikibooks.org/wiki/Haskell/Pattern%5Fmatching" rel="nofollow">Here</a> and <a href="http://en.wikipedia.org/wiki/Pattern%5FMatching#Tree%5Fpatterns%5Ffor%5Fstrings" rel="nofollow">here</a>.</p>
1
2009-05-17T18:33:12Z
[ "java", "python", "c", "regex", "tree-structure" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
875,462
<p>I'm somewhat surprised that <a href="http://www.w3schools.com/xsl/" rel="nofollow">XSLT</a> hasn't come up as an answer. Granted, I don't think it's a particularly elegant language, and most existent solutions tend to favour procedural approaches rather than pattern matching, and it's gotten a mighty bad rep from being blindly applied just because it's XML being applied to XML -- but otherwise it fits the bill. Pity its canonical representation is so verbose, though... </p>
1
2009-05-17T20:51:00Z
[ "java", "python", "c", "regex", "tree-structure" ]
Regex for tree structures?
875,100
<p>Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for.</p> <p>Here is an example that might clarify what I am looking for.</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;/node&gt; &lt;node name="2"&gt; &lt;node name="2.1"&gt; data &lt;/node&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>An operation that would be possible on the above tree is "move subtree at node 2.1 into the subtree at node 1." The result of the operation might look something like..</p> <pre><code>&lt;root&gt; &lt;node name="1"&gt; subtrees .... &lt;node name="2.1"&gt; data &lt;/node&gt; &lt;/node&gt; &lt;node name="2"&gt; other subtrees... &lt;/node&gt; &lt;/root&gt; </code></pre> <p>Search and replace operations like find all nodes with atleast 2 children, find all nodes whose data starts with "a" and replace it with "b" if the subtrees have atleast 2 other siblings, etc. should be supported. </p> <p>For strings, where the only dimension is across the length of the string, we can do many of above operations (or their 1D equivalents) using regular expressions. I wonder if there are equivalents for trees. (instead of a single regex, you might need to write a set of transformation rules, but that is ok).</p> <p>I would like to know if there is some simple mini language (not regex per.se, but something that is as accessible as regex via libraries, etc..). to perform these operations? Preferably, as a python library.</p>
6
2009-05-17T17:57:26Z
6,082,100
<p>TSurgeon and Tregex from Stanford is capable of doing that. You can download the library from <a href="http://nlp.stanford.edu/software/tregex.shtml">http://nlp.stanford.edu/software/tregex.shtml</a></p>
6
2011-05-21T13:40:55Z
[ "java", "python", "c", "regex", "tree-structure" ]
Zlib in database - Django
875,122
<p>When I try to put a zlibbed string in models.TextField</p> <pre><code>&gt;&gt;&gt; f = VCFile(head = 'blahblah'.encode('zlib')) &gt;&gt;&gt; f.save() </code></pre> <p>it fails:</p> <pre><code> ... raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte. You passed in 'x\x9cK\xcaI\xccH\x02b\x00\x0eP\x03/' (&lt;type 'str'&gt;) </code></pre> <p>Is there any way to fix this (apart from escaping the string - it has to be space-efficent)?</p>
1
2009-05-17T18:10:58Z
875,153
<p>If you don't want to encode it, you have to store it as a binary object (BLOB), not a string. Django doesn't seem to support BlobFields out of the box, so go find it on the net or hack something together.</p>
0
2009-05-17T18:24:58Z
[ "python", "database", "django", "django-models", "zlib" ]
Zlib in database - Django
875,122
<p>When I try to put a zlibbed string in models.TextField</p> <pre><code>&gt;&gt;&gt; f = VCFile(head = 'blahblah'.encode('zlib')) &gt;&gt;&gt; f.save() </code></pre> <p>it fails:</p> <pre><code> ... raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte. You passed in 'x\x9cK\xcaI\xccH\x02b\x00\x0eP\x03/' (&lt;type 'str'&gt;) </code></pre> <p>Is there any way to fix this (apart from escaping the string - it has to be space-efficent)?</p>
1
2009-05-17T18:10:58Z
878,719
<p>Like Marcus says, you'll have to use BLOB if you want to keep it in binary format. If you're OK with encoding it, you can use base64 encoding:</p> <pre><code>from base64 import binascii f = VCFile(head = binascii.b2a_base64('blahblah'.encode('zlib'))) </code></pre> <p>In my very basic tests with 33k characters, the zlib string was 28% the size of the original string, the base64 encoded zlib string was 37% the size of the original string. Not quite as good on compression, but still a big improvement.</p>
1
2009-05-18T16:59:28Z
[ "python", "database", "django", "django-models", "zlib" ]
Daemon python wrapper "subprocess I/O timed out", need some directions
875,190
<p>I am not very familiar with the way of creating a daemon in Python, therefore wheb trying to install and run a third party open source TeX Python Wrapper i got bite by an error i do nor really understand.</p> <p>I added some print to help debugging.</p> <p>The faulty one is called texdp.py</p> <p>When i run mathrand which calls texdp server start, i get the following error</p> <pre><code>output_fds {8: 'dvi', 5: 'log', 6: 'logfile', 7: 'err'} input_fds 3 readable, writable [] [3] outflds, inputflds: [8, 5, 6, 7] [3] pointer len_str: 0 63 folder fd: 7 readable, writable [5] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 7 readable, writable [5] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 5 readable, writable [] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 5 SUB IO ERROR: readable [] pointer == len_str: 63 , 63 Traceback (most recent call last): File "/usr/local/bin/mathtrand", line 18, in &lt;module&gt; server.start() File "/usr/local/lib/python2.6/dist-packages/mathtran/server.py", line 71, in start self.secplain.start() File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 159, in start self.process(self._params.start) File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 175, in process value = self._process(str + self._params.done, self._params.done_str) File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 210, in _process raise SubprocessError, 'subprocess I/O timed out' </code></pre> <p>The part of the code responsible is attached and located around line 200 in the method <strong>def _process</strong>.</p> <p>I have no idea of where to start looking, and what does this error really means. Any help is more than welcome.</p> <p>https://texd.svn.sourceforge.net/svnroot/texd/trunk/py/tex/texdp.py</p> <pre><code># Copyright: (c) 2007 The Open University, Milton Keynes, UK # License: GPL version 2 or (at your option) any later version. # Author: Jonathan Fine &lt;jfine@pytex.org&gt;, &lt;J.Fine@open.ac.uk&gt; """Wrapper around TeX process, to handle input and output. Further comments to go here. """ __version__ = '$Revision: 116 $'[11:-2] # $Source$ # TODO: Move interface instances to elsewhere. # TODO: error recovery, e.g. undefined control sequence. # TODO: Abnormal exit is leaving orphaned processes. # TODO: Refactor _process into tex.util, share with metapostdp. import os # Create directories and fifos from select import select # Helps handle i/o to TeX process from tex.util import make_nonblocking # For non-blocking file descriptor from tex.util import DaemonSubprocess from tex.dviopcode import FNT_DEF1, FNT_DEF4 import signal class SubprocessError(EnvironmentError): pass # TODO: This belongs elsewhere. class Interface(object): """Stores useful, but format specific, constants.""" def __init__(self, **kwargs): # TODO: Be more specific about the parameters. self.__dict__ = kwargs # TeX knows about these fonts, but Python does not yet know. # This list created by command: $tex --ini '&amp;plain' \\dump preloaded_fonts = ( 'cmr10', 'cmr9', 'cmr8', 'cmr7', 'cmr6', 'cmr5', 'cmmi10', 'cmmi9', 'cmmi8', 'cmmi7', 'cmmi6', 'cmmi5', 'cmsy10', 'cmsy9', 'cmsy8', 'cmsy7', 'cmsy6', 'cmsy5', 'cmex10', 'cmss10', 'cmssq8', 'cmssi10', 'cmssqi8', 'cmbx10', 'cmbx9', 'cmbx8', 'cmbx7', 'cmbx6', 'cmbx5', 'cmtt10', 'cmtt9', 'cmtt8', 'cmsltt10', 'cmsl10', 'cmsl9', 'cmsl8', 'cmti10', 'cmti9', 'cmti8', 'cmti7', 'cmu10', 'cmmib10', 'cmbsy10', 'cmcsc10', 'cmssbx10', 'cmdunh10', 'cmr7 scaled 2074', 'cmtt10 scaled 1440', 'cmssbx10 scaled 1440', 'manfnt', ) # Ship out a page that starts with a font def. load_font_template = \ r'''%% \begingroup \hoffset 0sp \voffset 0sp \setbox0\hbox{\font\tmp %s\relax\tmp M}%% \ht0 0sp \shipout\box 0 \endgroup ''' secplain_load_font_template = \ r'''%% \_begingroup \_hoffset 0sp \_voffset 0sp \_setbox0\_hbox{\_font\_tmp %s\_relax\_tmp M}%% \_ht0 0sp \_shipout\_box 0 \_endgroup ''' plain = Interface(format='plain', start = r'\shipout\hbox{}' '\n', done = '\n' r'\immediate\write16{DONE}\read-1to\temp ' '\n', done_str = 'DONE\n', stop = '\end' '\n', preloaded_fonts = preloaded_fonts, load_font_template = load_font_template, ) secplain = Interface(format='secplain', start = r'\_shipout\_hbox{}' '\n', done = '\n' r'\_immediate\_write16{DONE}\_read-1to\_temp ' '\n', done_str = 'DONE\n', stop = '\_end' '\n', preloaded_fonts = preloaded_fonts, load_font_template = secplain_load_font_template, ) class Texdp(DaemonSubprocess): """Wrapper around TeX process that handles input and output. More comments go here. """ _fifos = ('texput.tex', 'texput.log', 'texput.dvi') def _make_args(self): # Don Knuth created plain.fmt, renamed by some to tex.fmt. fmt = self._params.format if fmt == 'plain' or fmt == 'tex': fmt = '' else: fmt = '--fmt=' + fmt # Build up the arguments list. args = ('tex', '--ipc',) args += ('--output-comment=""',) # Don't record time of run. if fmt: args += (fmt,) args += ('texput.tex',) return args def start(self): super(Texdp, self).start() # Start the TeX process. # We will now initialise TeX, and conprocessnect to file descriptors. # We need to do some low-level input/output, in order to # manage long input strings. Therefore, we use file # descriptors rather than file objects. # We map output fds to what will be a dictionary key. ofd = self._output_fd_dict = {} cwd = self._cwd # Shorthand. child = self._child # For us, stdin and stdout are special. self._stdin = child.stdin.fileno() self._stdout = child.stdout.fileno() # Read stdout and stderr to 'log' and 'err' respectively. ofd[self._stdout] = 'log' ofd[child.stderr.fileno()] = 'err' # Open 'texput.tex', and block until it is available, which is # when TeX has started. Then make 'texput.tex' non-blocking, # in case of a long write. self._texin = os.open(os.path.join(cwd, 'texput.tex'), os.O_WRONLY) make_nonblocking(self._texin) # Read 'texput.log' and 'texput.dvi' to 'logfile' and 'dvi'. for src, tgt in (('texput.log', 'logfile'), ('texput.dvi', 'dvi')): fd = os.open(os.path.join(cwd, src), os.O_RDONLY|os.O_NONBLOCK) ofd[fd] = tgt # Ship out blank page, and initialise preloaded fonts. self.process(self._params.start) self._fontdefs = [] for font_spec in self._params.preloaded_fonts: self.load_new_font(font_spec) def process(self, str): "Return dictionary with log, dvi, logfile and err entries." # TeX will read the data, following by the 'done' command. # The 'done' command will cause TeX to write the 'done_str', # which signals the end of the process. It will also pause # TeX for input. # TODO: I do not know why the pause is required, but it is. # Remove it here and in the _params, and the program hangs. value = self._process(str + self._params.done, self._params.done_str) self._child.stdin.write('\n') # TeX is paused for input. return value def _process(self, str, done_str): # Write str, and read output, until we are done. Then gather # up the accumulated output, and return as a dictionary. The # input string might be long. Later, we might allow writing to # stdin, in response to errors. # Initialisation. print "output_fds ", self._output_fd_dict output_fds = self._output_fd_dict.keys() print "input_fds ", self._texin input_fds = [self._texin] accumulator = {} for fd in output_fds: accumulator[fd] = [] pointer, len_str = 0, len(str) # The main input/ouput loop. # TOD0: magic number, timeout. done = False while not done: readable, writable = select(output_fds, input_fds, [], 0.1)[0:2] print "readable, writable", readable, writable, " outflds, inputflds: ", output_fds, input_fds print "pointer len_str: ", pointer, len_str print "folder fd: ", fd if not readable and pointer == len_str: print "SUB IO ERROR: readable", readable, " pointer == len_str:", pointer, ",", len_str os.kill(self._child.pid, signal.SIGKILL) self._child.wait() raise SubprocessError, 'subprocess I/O timed out' if pointer != len_str and writable: written = os.write(self._texin, str[pointer:pointer+4096]) pointer += written if pointer == len_str: input_fds = [] for fd in readable: if self._child.poll() is not None: raise SubprocessError, 'read from terminated subprocess' tmp = os.read(fd, 4096) if fd == self._stdout: if tmp.endswith(done_str): tmp = tmp[:-len(done_str)] done = True accumulator[fd].append(tmp) if pointer != len_str: raise SystemError, "TeX said 'done' before end of input." # Join accumulated output, create and return ouput dictionary. value = {} for fd, name in self._output_fd_dict.items(): value[name] = ''.join(accumulator[fd]) return value def load_new_font(self, font_spec): """Tell both TeX and Python about a new font. Raises an exception if the font is not new. """ # Ask TeX to load font, and ship out page that uses it. command mathtran= self._params.load_font_template % font_spec dvi = self.process(command)['dvi'] bytes = dvi[45:-1] # Page body. opcode = ord(bytes[0]) # First opcode. # The first opcode should be a fontdef, which we extract. if FNT_DEF1 &lt;= opcode &lt;= FNT_DEF4: body_len = (2 + (opcode - FNT_DEF1) + 12 # Checksum, scale, design size. + 2) # Length of 'area' and font name. name_len = ord(bytes[body_len - 2]) \ + ord(bytes[body_len - 1]) fontdef = bytes[:body_len + name_len] self._fontdefs.append(fontdef) return else: raise ValueError, "font '%s' not new or not found" % font_spec </code></pre>
1
2009-05-17T18:43:17Z
875,827
<p>The timeout is based on the <code>select</code> call </p> <pre><code>readable, writable = select(output_fds, input_fds, [], 0.1)[0:2] </code></pre> <p>The timeout is 0.1 seconds. Is this appropriate? </p> <p>The variable names are murky ("pointer" makes little sense in Python). However, it appears that if nothing happens on 0.1 seconds, a "timeout" is raised.</p> <p><hr /></p> <p>Weirdly, this program opens files to communicate with a subprocess. That's very odd to be "sharing" a file with a subprocess.</p> <p>Usually we do one of two things -- use pipes to communicate actively with a subprocess or use files to leave the subprocess run on its own.</p> <p>Here's a simpler design. </p> <ol> <li><p>Put the input into the input file.</p></li> <li><p>Run the Tex daemon subprocess until it finishes or you're tired of waiting for it.</p></li> <li><p>If you're tired of waiting for it, kill it.</p> <p>Else</p> <ul> <li><p>Look at the status from the wait function</p></li> <li><p>Read the output file.</p></li> </ul></li> </ol> <p>That's pretty much all you need. And there will be no mysterious "pause", no low-level I/O, no non-blocking I/O.</p> <p>If, for some reason you need to communicate with the subprocess, then you should look at replacing the files with pipes (which aren't shared and are probably a better for for whatever you're doing.)</p>
2
2009-05-18T00:27:11Z
[ "python", "daemon", "tex" ]
Simple data storing in Python
875,228
<p>I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.</p> <p>I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: </p> <ul> <li>the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data.</li> <li>Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. </li> <li>CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data.</li> </ul> <p>I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.</p>
3
2009-05-17T19:00:20Z
875,272
<p><a href="http://docs.python.org/library/pickle.html" rel="nofollow">http://docs.python.org/library/pickle.html</a></p>
6
2009-05-17T19:13:10Z
[ "python", "file-io", "csv", "multidimensional-array", "fileparsing" ]
Simple data storing in Python
875,228
<p>I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.</p> <p>I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: </p> <ul> <li>the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data.</li> <li>Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. </li> <li>CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data.</li> </ul> <p>I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.</p>
3
2009-05-17T19:00:20Z
875,280
<p>Must the file be human readable? If not, <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> is really easy to use.</p>
4
2009-05-17T19:15:45Z
[ "python", "file-io", "csv", "multidimensional-array", "fileparsing" ]
Simple data storing in Python
875,228
<p>I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.</p> <p>I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: </p> <ul> <li>the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data.</li> <li>Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. </li> <li>CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data.</li> </ul> <p>I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.</p>
3
2009-05-17T19:00:20Z
875,347
<p>In addition to <code>pickle</code> (<a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python/875272#875272">mentioned above</a>), there's <a href="http://docs.python.org/library/json.html" rel="nofollow"><code>json</code></a> (built in to 2.6, available via <a href="http://pypi.python.org/pypi/simplejson/" rel="nofollow">simplejson</a> before that), and <a href="http://docs.python.org/library/marshal.html#module-marshal" rel="nofollow"><code>marshal</code></a>. Also, there's a <a href="http://docs.python.org/library/csv.html#csv.reader" rel="nofollow"><code>reader</code></a> in the same <a href="http://docs.python.org/library/csv.html" rel="nofollow"><code>csv</code> module</a> the writer is in.</p> <p>UPDATE: As S. Lott pointed out in a comment, there's also YAML, available via <a href="http://pyyaml.org/" rel="nofollow">PyYAML</a>, among others.</p>
10
2009-05-17T19:51:09Z
[ "python", "file-io", "csv", "multidimensional-array", "fileparsing" ]
Simple data storing in Python
875,228
<p>I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.</p> <p>I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: </p> <ul> <li>the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data.</li> <li>Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. </li> <li>CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data.</li> </ul> <p>I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.</p>
3
2009-05-17T19:00:20Z
875,525
<blockquote> <p>I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.</p> </blockquote> <p>Is the data only ever going to be parsed by Python programs? If not, then I'd avoid pickle et al (shelve and marshal) since they're very Python specific. JSON and YAML have the important advantage that parsers are easily available for most any language.</p>
2
2009-05-17T21:16:12Z
[ "python", "file-io", "csv", "multidimensional-array", "fileparsing" ]
Simple data storing in Python
875,228
<p>I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.</p> <p>I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: </p> <ul> <li>the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data.</li> <li>Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. </li> <li>CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data.</li> </ul> <p>I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.</p>
3
2009-05-17T19:00:20Z
1,416,925
<p>This solution at SourceForge uses only standard Python modules:</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p> <p>SQLite is not "overkill" at all -- you will be amazed how simple it is; plus it solves more general data persistance issues.</p>
1
2009-09-13T05:29:56Z
[ "python", "file-io", "csv", "multidimensional-array", "fileparsing" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
875,342
<pre><code>map(lambda item: item.my_func(), items) </code></pre>
-3
2009-05-17T19:48:14Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
875,344
<p>You could use <a href="http://docs.python.org/3.0/library/functions.html#map"><code>map</code></a> instead of the <code>for</code> loop you've shown, but since you do not appear to use the result of <code>item.my_func()</code>, this is <strong>not recommended</strong>. <code>map</code> should be used if you want to apply a function without side-effects to all elements of a list. In all other situations, use an explicit for-loop.</p> <p>Also, as of Python 3.0 <code>map</code> returns a generator, so in that case <code>map</code> will not behave the same (unless you explicitly evaluate all elements returned by the generator, e.g. by calling <a href="http://docs.python.org/3.0/library/functions.html#list"><code>list</code></a> on it).</p> <hr> <p><strong>Edit</strong>: <a href="http://stackoverflow.com/users/81804/kibibu">kibibu</a> asks in the comments for a clarification on why <code>map</code>'s first argument should not be a function with side effects. I'll give answering that question a shot:</p> <p><code>map</code> is meant to be passed a function <code>f</code> <a href="http://en.wikipedia.org/wiki/Function_%28mathematics%29">in the mathematical sense</a>. Under such circumstances it does not matter in which order <code>f</code> is applied to the elements of the second argument (as long as they are <em>returned</em> in their original order, of course). More importantly, under those circumstances <code>map(g, map(f, l))</code> is semantically equivalent to <code>map(lambda x: g(f(x)), l)</code>, <em>regardless of the order in which <code>f</code> and <code>g</code> are applied to their respective inputs</em>.</p> <p>E.g., it doesn't matter whether <code>map</code> returns and iterator or a full list at once. However, if <code>f</code> and/or <code>g</code> cause side effects, then this equivalence is only guaranteed if the semantics of <code>map(g, map(f, l))</code> are such that at any stage <code>g</code> is applied to the first <em>n</em> elements returned by <code>map(f, l)</code> before <code>map(f, l)</code> applies <code>f</code> to the <em>(n + 1)</em>&#8203;st element of <code>l</code>. (Meaning that <code>map</code> must perform the laziest possible iteration---which it does in Python 3, but not in Python 2!)</p> <p>Going one step further: even if we assume the Python 3 implementation of <code>map</code>, the semantic equivalence may easily break down if the output of <code>map(f, l)</code> is e.g. passed through <a href="http://docs.python.org/3.1/library/itertools.html#itertools.tee"><code>itertools.tee</code></a> before being supplied to the outer <code>map</code> call. </p> <p>The above discussion may seem of a theoretic nature, but as programs become more complex, they become more difficult to reason about and therefore harder to debug. Ensuring that some things are invariant alleviates that problem somewhat, and may in fact prevent a whole class of bugs.</p> <p>Lastly, <code>map</code> reminds many people of its truly functional counterpart in various (purely) functional languages. Passing it a "function" with side effects will confuse those people. Therefore, seeing as the alternative (i.e., using an explicit loop) is not harder to implement than a call to <code>map</code>, it is highly recommended that one restricts use of <code>map</code> to those cases in which the function to be applied does not cause side effects.</p>
23
2009-05-17T19:49:16Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
875,353
<p>The main advantage of <code>map</code> is when you want to get the result of some calculation on every element in a list. For example, this snippet doubles every value in a list:</p> <pre><code>map(lambda x: x * 2, [1,2,3,4]) #=&gt; [2, 4, 6, 8] </code></pre> <p>It is important to note that <code>map</code> returns a new list with the results. It does not modify the original list in place.</p> <p>To do the same thing with <code>for</code>, you would have to create an empty list and add an extra line to the <code>for</code> body to add the result of each calculation to the new list. The <code>map</code> version is more concise and functional.</p>
1
2009-05-17T19:53:35Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
875,369
<p>You can write this using map like this:</p> <pre><code>map(cls.my_func, items) </code></pre> <p>replacing cls with the class of the items you are iterating over.</p> <p>As mentioned by Stephan202, this is <strong>not recommended</strong> in this case.</p> <p>As a rule, if you want to create a new list by applying some function to each item in the list, use map. This has the implied meaning that the function has no side effect, and thus you could (potentially) run the map in parallel.</p> <p>If you don't want to create a new list, or if the function has side effects, use a for loop. This is the case in your example.</p>
5
2009-05-17T20:00:38Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
875,406
<p>There is a slight semantic difference, which is probably closed in python language spec. The <em>map</em> is explicitly parallelizable, while <em>for</em> only in special situations. Code can <em>break</em> out from <em>for</em>, but only escape with exception from <em>map</em>.</p> <p>In my opinion <em>map</em> shouldn't also guarantee order of function application while <em>for</em> must. AFAIK no python implementation is currently able to do this auto-parallelization.</p>
2
2009-05-17T20:18:55Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
875,581
<p>You can switch Your <code>map</code> to some cool threaded OR multiprocessing OR distributed computing framework if You need to. <a href="http://discoproject.org/" rel="nofollow">Disco</a> is an example of distributed, resistant to failures erlang-and-python based framework. I configured it on 2 boxes of 8 cores and now my program runs 16 times faster, thanks to the Disco cluster, however I had to rewrite my program from list comprehensions and for loops to map/reduce.</p> <p>It's the same deal to write a program using for loops and list comprehensions and map/reduce, but when You need it to run on a cluster, You can do it almost for free if You used map/reduce. If You didn't, well, You will have to rewrite.</p> <p>Beware: as far as I know, python 2.x returns a list instead of an iterator from map. I've heard this can be bypassed by using <code>iter.imap()</code> (never used it though).</p>
2
2009-05-17T21:53:43Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
877,606
<p>Use an explicit for-loop when you don't need a list of results back (eg. functions with side-effects).</p> <p>Use a list comprehension when you do need a list of results back (eg. functions that return a value based directly on the input).</p> <p>Use map() when you're trying to convince Lisp users that Python is worth using. ;)</p>
2
2009-05-18T12:57:04Z
[ "python", "for-loop", "map-function" ]
Is there a value in using map() vs for?
875,337
<p>Does map() iterate through the list like "for" would? Is there a value in using map vs for?</p> <p>If so, right now my code looks like this:</p> <pre><code>for item in items: item.my_func() </code></pre> <p>If it makes sense, I would like to make it map(). Is that possible? What is an example like?</p>
10
2009-05-17T19:45:43Z
880,046
<p>Map can sometimes be faster for built-in functions than manually coding a for loop. Try timing map(str, range(1000000)) vs. a similar for loop.</p>
0
2009-05-18T22:02:03Z
[ "python", "for-loop", "map-function" ]
Printing Daemonic Thread Exceptions in Python
875,453
<p>Python does not print traceback messages from exceptions raised in daemon threads.</p> <p>For example, this code creates a daemonic thread and raises an exception in the new thread:</p> <pre><code>def error_raiser(): raise Exception import threading thread = threading.Thread(target=error_raiser) thread.daemon = True thread.start() </code></pre> <p>but does not print a traceback. (It gives no output).</p> <p>However, if the thread is not set as a daemon thread, Python will print the traceback. Here is the same code with one line commented out:</p> <pre><code>def error_raiser(): raise Exception import threading thread = threading.Thread(target=error_raiser) # thread.daemon = True thread.start() </code></pre> <p>and the output:</p> <pre><code>Exception in Thread-1: Traceback (most recent call last): File "C:\Python26\lib\threading.py", line 525, in __bootstrap_inner self.run() File "C:\Python26\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File "test.py", line 2, in error_raiser raise Exception Exception </code></pre> <p>Executing this code in both Python 2.6.2 and Python 3.0.1 and gives the same results. Interestingly, however, if I execute the code by importing it in the IPython shell, the exception is displayed whether the thread is daemonic or not.</p> <p>According to the documentation, the only significance of the 'daemon' flag is that "the entire Python program exits when only daemon threads are left." This would make me believe that not printing a traceback after an exception is a bug in Python, unless I missed something in the documentation.</p> <p>Is this a bug, or did I miss something in the documentation and this behavior is intentional? If it is intentional, how can I force Python to print the traceback in daemon threads without using IPython?</p>
7
2009-05-17T20:45:28Z
875,485
<p>According to Wikipedia, by definition a daemon should detach itself from the controlling tty, so I think it's correct that no exception is shown (and after all, a daemon should keep working even if you close the shell that launched it)..<br /> See <a href="http://en.wikipedia.org/wiki/Daemon%5F%28computer%5Fsoftware%29#Types%5Fof%5Fdaemons">here</a>.</p> <p>As for how to print the traceback, I think that a simple try/except_then_log_to_file would do the trick :)</p>
6
2009-05-17T20:56:46Z
[ "python", "multithreading" ]
editing a wav files using python
875,476
<p>and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's)</p> <p>how can I cut the non-silence sound ?</p> <p>I'm programming using python</p> <p>thanks</p>
3
2009-05-17T20:54:38Z
875,502
<p>I have no experience with this, but have a look at the <a href="http://docs.python.org/library/wave.html" rel="nofollow">wave</a> module present in the standard library. That may do what you want. Otherwise you'll have to read the file as a byte stream an cut out sequences of 0-bytes (but you cannot just cut out all 0-bytes, as that would invalidate the file...)</p>
1
2009-05-17T21:00:43Z
[ "python", "audio" ]
editing a wav files using python
875,476
<p>and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's)</p> <p>how can I cut the non-silence sound ?</p> <p>I'm programming using python</p> <p>thanks</p>
3
2009-05-17T20:54:38Z
875,571
<p>You might want to try using <a href="http://linux.die.net/man/1/sox" rel="nofollow">sox</a>, a command-line sound processing tool. It has many modes, one of them is <code>silence</code>:</p> <blockquote> <p>silence: Removes silence from the beginning, middle, or end of a sound file. Silence is anything below a specified threshold.</p> </blockquote> <p>It supports multiple sound formats and it's quite fast, so parsing large files shouldn't be a problem.</p> <blockquote> <p>To remove silence from the middle of a file, specify a <code>below_periods</code> that is negative. This value is then treated as a positive value and is also used to indicate the effect should restart processing as specified by the <code>above_periods</code>, making it suitable for removing periods of silence in the middle of the sound file.</p> </blockquote> <p>I haven't found any python building for libsox, though, but You can use it as You use all command line programs in python (or You can rewrite it - use sox sources for guidance then).</p>
1
2009-05-17T21:46:24Z
[ "python", "audio" ]
editing a wav files using python
875,476
<p>and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's)</p> <p>how can I cut the non-silence sound ?</p> <p>I'm programming using python</p> <p>thanks</p>
3
2009-05-17T20:54:38Z
875,775
<p>Python has a <a href="http://docs.python.org/library/wave.html">wav module</a>. You can use it to open a wav file for reading and use the `getframes(1)' command to walk through the file frame by frame.</p> <pre><code>import wave w = wave.open('beeps.wav', 'r') for i in range(): frame = w.readframes(1) </code></pre> <p>The frame returned will be a byte string with hex values in it. If the file is stereo the result will look something like this (4 bytes):</p> <pre><code>'\xe2\xff\xe2\xff' </code></pre> <p>If its mono, it will have half the data (2 bytes):</p> <pre><code>'\xe2\xff' </code></pre> <p>Each channel is 2 bytes long because the audio is 16 bit. If is 8 bit, each channel will only be one byte. You can use the <code>getsampwidth()</code> method to determine this. Also, <code>getchannels()</code> will determine if its mono or stereo.</p> <p>You can loop over these bytes to see if they all equal zero, meaning both channels are silent. In the following example I use the <code>ord()</code> function to convert the <code>'\xe2'</code> hex values to integers.</p> <pre><code>import wave w = wave.open('beeps.wav', 'r') for i in range(w.getnframes()): ### read 1 frame and the position will updated ### frame = w.readframes(1) all_zero = True for j in range(len(frame)): # check if amplitude is greater than 0 if ord(frame[j]) &gt; 0: all_zero = False break if all_zero: # perform your cut here print 'silence found at frame %s' % w.tell() print 'silence found at second %s' % (w.tell()/w..getframerate()) </code></pre> <p>It is worth noting that a single frame of silence doesn't necessarily denote empty space since the amplitude may cross the 0 mark normal frequencies. Therefore, it is recommended that a certain number of frames at 0 be observed before deciding if the region is, in fact, silent.</p>
14
2009-05-17T23:50:00Z
[ "python", "audio" ]
editing a wav files using python
875,476
<p>and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's)</p> <p>how can I cut the non-silence sound ?</p> <p>I'm programming using python</p> <p>thanks</p>
3
2009-05-17T20:54:38Z
877,551
<p>You will need to come up with some threshold value of a minimum number of consecutive zeros before you cut them. Otherwise you'll be removing perfectly valid zeros from the middle of normal audio data. You can iterate through the wave file, copying any non-zero values, and buffering up zero values. When you're buffering zeroes and eventually come across the next non-zero, if the buffer has fewer samples that the threshold, copy them over, otherwise discard it.</p> <p>Python is not a great tool for this sort of task though. :(</p>
1
2009-05-18T12:44:19Z
[ "python", "audio" ]
editing a wav files using python
875,476
<p>and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's)</p> <p>how can I cut the non-silence sound ?</p> <p>I'm programming using python</p> <p>thanks</p>
3
2009-05-17T20:54:38Z
878,275
<p>See also <a href="http://stackoverflow.com/questions/841049/how-to-edit-raw-pcm-audio-data-without-an-audio-library">How to edit raw PCM audio data without an audio library?</a></p>
2
2009-05-18T15:19:45Z
[ "python", "audio" ]
editing a wav files using python
875,476
<p>and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's)</p> <p>how can I cut the non-silence sound ?</p> <p>I'm programming using python</p> <p>thanks</p>
3
2009-05-17T20:54:38Z
25,130,170
<p>I have been doing some research on this topic for a project I'm working on and I came across a few problems with the solution provided, namely the method for determining silence is incorrect. A "more correct" implementation would be:</p> <pre><code>import struct import wave wave_file = wave.open("sound_file.wav", "r") for i in range(wave_file.getnframes()): # read a single frame and advance to next frame current_frame = wave_file.readframes(1) # check for silence silent = True # wave frame samples are stored in little endian** # this example works for a single channel 16-bit per sample encoding unpacked_signed_value = struct.unpack("&lt;h", current_frame) # * if abs(unpacked_signed_value[0]) &gt; 500: silent = False if silent: print "Frame %s is silent." % wave_file.tell() else print "Frame %s is not silent." % wave_file.tell() </code></pre> <h1><strong>References and Useful Links</strong></h1> <p>*<code>Struct Unpacking</code> will be useful here: <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">https://docs.python.org/2/library/struct.html</a></p> <p>**A good reference I found explaining the format of wave files for dealing with different size bit-encodings and multiple channels is: <a href="http://www.piclist.com/techref/io/serial/midi/wave.html" rel="nofollow">http://www.piclist.com/techref/io/serial/midi/wave.html</a></p> <p>Using the built-in ord() function in Python on the first element of the string object returned by the readframes(x) method will not work correctly.</p> <p>Another key point is that multiple channel audio is interleaved and thus a little extra logic is needed for dealing with channels. Again, the link above goes into detail about this.</p> <p>Hopefully this helps someone in the future.</p> <p>Here are some of the more important points from the link, and what I found helpful.</p> <p><strong>Data Organization</strong></p> <hr> <p>All data is stored in 8-bit bytes, arranged in Intel 80x86 (ie, little endian) format. The bytes of multiple-byte values are stored with the low-order (ie, least significant) bytes first. Data bits are as follows (ie, shown with bit numbers on top):</p> <pre><code> 7 6 5 4 3 2 1 0 +-----------------------+ char: | lsb msb | +-----------------------+ 7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 +-----------------------+-----------------------+ short: | lsb byte 0 | byte 1 msb | +-----------------------+-----------------------+ 7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24 +-----------------------+-----------------------+-----------------------+-----------------------+ long: | lsb byte 0 | byte 1 | byte 2 | byte 3 msb | +-----------------------+-----------------------+-----------------------+-----------------------+ </code></pre> <p><strong>Interleaving</strong></p> <hr> <p>For multichannel sounds (for example, a stereo waveform), single sample points from each channel are interleaved. For example, assume a stereo (ie, 2 channel) waveform. Instead of storing all of the sample points for the left channel first, and then storing all of the sample points for the right channel next, you "mix" the two channels' sample points together. You would store the first sample point of the left channel. Next, you would store the first sample point of the right channel. Next, you would store the second sample point of the left channel. Next, you would store the second sample point of the right channel, and so on, alternating between storing the next sample point of each channel. This is what is meant by interleaved data; you store the next sample point of each of the channels in turn, so that the sample points that are meant to be "played" (ie, sent to a DAC) simultaneously are stored contiguously.</p>
2
2014-08-05T02:05:33Z
[ "python", "audio" ]
How can I color certain things in Emacs?
875,543
<p>I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange.</p> <p>How can I set up some colors for important Django template tags?</p>
4
2009-05-17T21:26:58Z
875,549
<p><a href="http://code.djangoproject.com/wiki/Emacs" rel="nofollow">Here</a> <a href="http://www.chickenwingsoftware.com/scratches/python/how-i-edit-django-templates" rel="nofollow">are</a> <a href="http://www.chickenwingsoftware.com/scratches/python/more-on-editing-django-templates-in-xemacs" rel="nofollow">some</a> <a href="http://importskynet.blogspot.com/2009/01/some-thoughts-about-django-template.html" rel="nofollow">links</a>. I found them on the Google. It seems there is no one fully-complete and "official" solution to this problem, but a number of possibly quite usable substitutes avaliable.</p>
1
2009-05-17T21:32:18Z
[ "python", "django", "emacs", "syntax-highlighting" ]
How can I color certain things in Emacs?
875,543
<p>I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange.</p> <p>How can I set up some colors for important Django template tags?</p>
4
2009-05-17T21:26:58Z
875,628
<p>You could use dedicated modes like <a href="http://code.djangoproject.com/wiki/Emacs">django-mode</a> or <a href="http://www.emacswiki.org/emacs/MuMaMo">MuMaMo</a>.</p> <p>If you want something very basic, and assuming you're editing in <code>html-mode</code>, you could try the following:</p> <pre><code>(defun django-highlight-comments () (interactive "p") (highlight-regexp "{%.*?%}" 'hi-orange)) (add-hook 'html-mode-hook 'django-highlight-comments) </code></pre> <p>(Just add the above lines to your <code>.emacs</code> or <code>init.el</code>, and eval it or restart emacs).</p>
6
2009-05-17T22:17:10Z
[ "python", "django", "emacs", "syntax-highlighting" ]
How can I color certain things in Emacs?
875,543
<p>I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange.</p> <p>How can I set up some colors for important Django template tags?</p>
4
2009-05-17T21:26:58Z
880,114
<p>Here's what I do. It's a little more general than the code above, and it uses the built-in font-lock mechanisms.</p> <pre><code>(defvar django-tag-face (make-face 'django-tag-face)) (defvar django-variable-face (make-face 'django-variable-face)) (set-face-background 'django-tag-face "Aquamarine") (set-face-foreground 'django-tag-face "Black") (set-face-background 'django-variable-face "Plum") (set-face-foreground 'django-variable-face "Black") (font-lock-add-keywords 'html-mode '(("\\({%[^%]*%}\\)" 1 django-tag-face prepend) ("\\({{[^}]*}}\\)" 1 django-variable-face prepend))) </code></pre>
3
2009-05-18T22:23:11Z
[ "python", "django", "emacs", "syntax-highlighting" ]
PersistentSet in ZODB 3
875,607
<p>ZODB provides a <code>PersistentList</code> and a <code>PersistentMapping</code>, but I'd like a <code>PersistentSet</code>. I wrote a quick class that mirrors the ancient <a href="http://sysinf0.klabs.be/usr/share/zope2.7/lib/python/ZODB/PersistentList.py?f=view" rel="nofollow"><code>PersistentList</code></a> from ZODB 2. Because there's no <code>UserSet</code> in Python, I had to extend from the C-based built-in <code>set</code>.</p> <pre><code>class PersistentSet(UserSet, Persistent): def __iand__(self, other): set.__iand__(other) self._p_changed = 1 ... ... ... def symmetric_difference_update(self, other): set.symmetric_difference_update(other) self._p_changed = 1 </code></pre> <p>The code produced a "multiple bases have instance lay-out conflict" <a href="http://stackoverflow.com/questions/309129/why-cant-i-inherit-from-dict-and-exception-in-python">error</a>. I tried creating a <code>UserSet</code> wrapper around <code>set</code>, but that didn't solve the problem either.</p> <pre><code>class UserSet(set): def __init__(self): self.value = set def __getattribute__(self, name): return self.value.__getattribute__(name </code></pre> <p>Finally, I imported <code>sets.Set</code> (superseded by the built-in <code>set</code>), but that seems to be implemented in C, too. I didn't find any set implementations on PyPI so I'm at a dead end now.</p> <p><strong>What are my options?</strong> I may have to implement a set from scratch or use <code>UserDict</code> and throw away all the <code>value</code>s.</p>
3
2009-05-17T22:07:09Z
876,415
<p>Forward all attribute requests to the internal set:</p> <pre><code>class PersistentSet(Persistent): def __init__(self): self.inner_set = set() def __getattribute__(self, name): try: inner_set = Persistent.__getattribute__(self, "inner_set") output = getattr(inner_set, name) except AttributeError: output = Persistent.__getattribute__(self, name) return output </code></pre>
1
2009-05-18T05:51:30Z
[ "python", "set", "zodb" ]
PersistentSet in ZODB 3
875,607
<p>ZODB provides a <code>PersistentList</code> and a <code>PersistentMapping</code>, but I'd like a <code>PersistentSet</code>. I wrote a quick class that mirrors the ancient <a href="http://sysinf0.klabs.be/usr/share/zope2.7/lib/python/ZODB/PersistentList.py?f=view" rel="nofollow"><code>PersistentList</code></a> from ZODB 2. Because there's no <code>UserSet</code> in Python, I had to extend from the C-based built-in <code>set</code>.</p> <pre><code>class PersistentSet(UserSet, Persistent): def __iand__(self, other): set.__iand__(other) self._p_changed = 1 ... ... ... def symmetric_difference_update(self, other): set.symmetric_difference_update(other) self._p_changed = 1 </code></pre> <p>The code produced a "multiple bases have instance lay-out conflict" <a href="http://stackoverflow.com/questions/309129/why-cant-i-inherit-from-dict-and-exception-in-python">error</a>. I tried creating a <code>UserSet</code> wrapper around <code>set</code>, but that didn't solve the problem either.</p> <pre><code>class UserSet(set): def __init__(self): self.value = set def __getattribute__(self, name): return self.value.__getattribute__(name </code></pre> <p>Finally, I imported <code>sets.Set</code> (superseded by the built-in <code>set</code>), but that seems to be implemented in C, too. I didn't find any set implementations on PyPI so I'm at a dead end now.</p> <p><strong>What are my options?</strong> I may have to implement a set from scratch or use <code>UserDict</code> and throw away all the <code>value</code>s.</p>
3
2009-05-17T22:07:09Z
1,717,187
<p>Why don't you use the persistent set class provided with the <a href="http://www.zodb.org/documentation/guide/modules.html#btrees-package" rel="nofollow">BTree</a> libraries in ZODB. There are 4 such classes available. IITreeSet and IOTreeSet manage sets of integers and OITreeSet and OOTreeSet manage set of arbitrary objects. They correspond to the four BTree classes IIBTree, IOBTree, OIBTree and OOBTree respectively. Their advantages over the set implementation built into Python are their fast lookup mechanism (thanx to the underlying BTree) and their persistence support. </p> <p>Here is some sample code:</p> <pre><code>&gt;&gt;&gt; from BTrees.IIBTree import IITreeSet, union, intersection &gt;&gt;&gt; a = IITreeSet([1,2,3]) &gt;&gt;&gt; a &lt;BTrees._IIBTree.IITreeSet object at 0x00B3FF18&gt; &gt;&gt;&gt; b = IITreeSet([4,3,2]) &gt;&gt;&gt; list(a) [1, 2, 3] &gt;&gt;&gt; list(b) [2, 3, 4] &gt;&gt;&gt; union(a,b) IISet([1, 2, 3, 4]) &gt;&gt;&gt; intersection(a,b) IISet([2, 3]) </code></pre>
3
2009-11-11T18:30:34Z
[ "python", "set", "zodb" ]
PersistentSet in ZODB 3
875,607
<p>ZODB provides a <code>PersistentList</code> and a <code>PersistentMapping</code>, but I'd like a <code>PersistentSet</code>. I wrote a quick class that mirrors the ancient <a href="http://sysinf0.klabs.be/usr/share/zope2.7/lib/python/ZODB/PersistentList.py?f=view" rel="nofollow"><code>PersistentList</code></a> from ZODB 2. Because there's no <code>UserSet</code> in Python, I had to extend from the C-based built-in <code>set</code>.</p> <pre><code>class PersistentSet(UserSet, Persistent): def __iand__(self, other): set.__iand__(other) self._p_changed = 1 ... ... ... def symmetric_difference_update(self, other): set.symmetric_difference_update(other) self._p_changed = 1 </code></pre> <p>The code produced a "multiple bases have instance lay-out conflict" <a href="http://stackoverflow.com/questions/309129/why-cant-i-inherit-from-dict-and-exception-in-python">error</a>. I tried creating a <code>UserSet</code> wrapper around <code>set</code>, but that didn't solve the problem either.</p> <pre><code>class UserSet(set): def __init__(self): self.value = set def __getattribute__(self, name): return self.value.__getattribute__(name </code></pre> <p>Finally, I imported <code>sets.Set</code> (superseded by the built-in <code>set</code>), but that seems to be implemented in C, too. I didn't find any set implementations on PyPI so I'm at a dead end now.</p> <p><strong>What are my options?</strong> I may have to implement a set from scratch or use <code>UserDict</code> and throw away all the <code>value</code>s.</p>
3
2009-05-17T22:07:09Z
27,656,955
<p>For future readings, I just wanted to offer a slight improvement over the already proposed answers...</p> <p><strong>Custom persistent set class</strong></p> <pre><code>class PersistentSet(Persistent): def __init__(self, *args, **kwargs): self._set = set(*args, **kwargs) def __getattr__(self, name): return getattr(self._set, name) </code></pre> <p><strong>Persistent set class from the library</strong></p> <pre><code>from BTrees.OOBTree import OOSet </code></pre> <hr> <p><em>See also</em></p> <ul> <li><a href="http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters">What does ** (double star) and * (star) do for Python parameters?</a></li> <li><a href="http://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute">Difference between __getattr__ vs __getattribute__</a> </li> <li><a href="http://docs.zope.org/zope3/Code/BTrees/OOBTree/OOSet.1" rel="nofollow">http://docs.zope.org/zope3/Code/BTrees/OOBTree/OOSet.1</a></li> </ul>
0
2014-12-26T12:12:25Z
[ "python", "set", "zodb" ]
python-fastcgi extension
875,713
<p>There's not much documentation surrounding the <a href="http://pypi.python.org/pypi/python-fastcgi" rel="nofollow">python-fastcgi</a> C library, so I'm wondering if someone could provide a simple example on how to make a simple FastCGI server with it. A "Hello World" example would be great.</p>
3
2009-05-17T23:13:29Z
876,116
<p><strong>Edit:</strong> I misread the question. Ooops.</p> <p><a href="http://jonpy.sourceforge.net/" rel="nofollow">Jon's Python modules</a> is a collection of useful modules and includes a great FastCGI module: <a href="http://jonpy.sourceforge.net/fcgi.html" rel="nofollow">http://jonpy.sourceforge.net/fcgi.html</a></p> <p>Here's the example from the page:</p> <pre><code>import jon.cgi as cgi import jon.fcgi as fcgi class Handler(cgi.Handler): def process(self, req): req.set_header("Content-Type", "text/plain") req.write("Hello, world!\n") fcgi.Server({fcgi.FCGI_RESPONDER: Handler}).run() </code></pre>
4
2009-05-18T03:20:07Z
[ "python", "fastcgi" ]
python-fastcgi extension
875,713
<p>There's not much documentation surrounding the <a href="http://pypi.python.org/pypi/python-fastcgi" rel="nofollow">python-fastcgi</a> C library, so I'm wondering if someone could provide a simple example on how to make a simple FastCGI server with it. A "Hello World" example would be great.</p>
3
2009-05-17T23:13:29Z
878,118
<p>I would recommend using a fastcgi WSGI wrapper such as <a href="http://svn.saddi.com/py-lib/trunk/fcgi.py" rel="nofollow">this one</a>, so you aren't tied in to the fastcgi approach from the start.</p> <p>And then a simple test.fgi file like such:</p> <pre><code>#!/usr/bin/env python from fcgi import WSGIServer def app(env, start): start('200 OK', [('Content-Type', 'text/plain')]) yield 'Hello, World!\n' yield '\n' yield 'Your environment is:\n' for k, v in sorted(env.items()): yield '\t%s: %r\n' % (k, v) WSGIServer(app).run() </code></pre>
3
2009-05-18T14:45:40Z
[ "python", "fastcgi" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
875,777
<p>One way of doing the encode/decode is to use the package base64, for an example:</p> <pre><code>import base64 import sys encoded = base64.b64encode(sys.stdin.read()) print encoded decoded = base64.b64decode(encoded) print decoded </code></pre> <p>Is it what you were looking for? With your particular case you get:</p> <p>input: 12234_1_Hello'World_34433_22acb_4554344_accCC44</p> <p>encoded: MTIyMzRfMV9IZWxsbydXb3JsZF8zNDQzM18yMmFjYl80NTU0MzQ0X2FjY0NDNDQ=</p> <p>decoded: 12234_1_Hello'World_34433_22acb_4554344_accCC44</p>
9
2009-05-17T23:51:22Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
875,782
<p>The base64 module provides encoding and decoding for a string to and from different bases, since python 2.4.</p> <p>In you example, you would do the following:</p> <pre><code>import base64 string_b = base64.b64encode(string_a) string_a = base64.b64decode(string_b) </code></pre> <p>For full API: <a href="http://docs.python.org/library/base64.html" rel="nofollow">http://docs.python.org/library/base64.html</a></p>
2
2009-05-17T23:54:06Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
875,783
<p>Are you looking to encrypt the string or encode it to remove illegal characters for urls? If the latter, you can use <a href="http://docs.python.org/library/urllib.html#quote" rel="nofollow"><code>urllib.quote</code></a>:</p> <pre><code>&gt;&gt;&gt; quoted = urllib.quote("12234_1_Hello'World_34433_22acb_4554344_accCC44") &gt;&gt;&gt; quoted '12234_1_Hello%27World_34433_22acb_4554344_accCC44' &gt;&gt;&gt; urllib.unquote(quoted) "12234_1_Hello'World_34433_22acb_4554344_accCC44" </code></pre>
4
2009-05-17T23:54:47Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
875,785
<p>Are you after encryption, compression, or just urlencoding? The string can be passed after urlencoding, but that will not make it smaller as in your example. Compression might shrink it, but you would still need to urlencode the result.</p> <p>Do you actually need to hide the string data from the viewer (e.g. sensitive data, should not be viewable by someone reading the URL over your shoulder)?</p>
5
2009-05-17T23:56:46Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
875,844
<p>To make it really short -> just insert a row into the database. Store something like a list of <code>(id auto_increment, url)</code> tuples. Then you can <code>base64</code> encode the id to get a "proxy url". Decode it by decoding the id and looking up the proper url in the database. Or if you don't mind the identifiers looking sequential, just use the numbers.</p>
5
2009-05-18T00:41:19Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
875,847
<p>It's hard to reduce the size of a string and preserve arbitrary content.</p> <p>You have to restrict the data to something you can usefully compress.</p> <p>Your alternative is to do the following.</p> <ol> <li><p>Save "all the arguments in the URL" in a database row.</p></li> <li><p>Assign a GUID key to this collection of arguments.</p></li> <li><p>Then provide that shortened GUID key.</p></li> </ol>
2
2009-05-18T00:43:06Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
876,161
<p>Another method that would also shorten the string would be to calculate the md5/sha1 hash of the string (concatenated with a seed if you wished):</p> <pre><code>import hashlib &gt;&gt;&gt; hashlib.sha1("12234_1_Hello'World_34433_22acb_4554344_accCC44").hexdigest() 'e1153227558aadc00a2e90b5013fdd6b0804fdfb' </code></pre> <p>In theory you should get a set of strings with very few collisions and with a fixed length. The <a href="http://docs.python.org/library/hashlib.html" rel="nofollow"><code>hashlib</code></a> library has an array of different hash functions you can use in this manner, with different output sizes.</p> <p>Edit: You also said that you needed a reversible string, so this wouldn't work for that. Afaik, however, many web platforms that use clean URLs like you seem to want to implement use hash functions to calculate a shortened URL and then store that URL along with the page's other data to provide the reverse lookup capability.</p>
1
2009-05-18T03:36:04Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
How does one encode and decode a string with Python for use in a URL?
875,771
<p>I have a string like this: </p> <pre><code>String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] </code></pre> <p>I would like to encrypt String A to be used in a clean URL. something like this:</p> <pre><code>String B: [ cYdfkeYss4543423sdfHsaaZ ] </code></pre> <p>Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?</p>
4
2009-05-17T23:45:12Z
1,184,226
<p>note that theres a huge difference between encoding and encryption.</p> <p>if you want to send sensitive data, then dont use the encoding mentioned above ;)</p>
9
2009-07-26T10:27:29Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
PyQt: splash screen while loading "heavy" libraries
876,107
<p>My PyQt application that uses <code>matplotlib</code> takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows).</p> <p>I'm wondering whether it's feasible to show a splash screen while the <code>matplotlib</code> library is being loaded. Where does the actual loading take place - is it when the <code>from</code> line is executed? If so, how can I make this line execute during the splash screen and still be able to use the module throughout the code?</p> <p>A related dilemma is how to test this - can I ask Windows to load the DLLs for every execution and not cache them?</p>
2
2009-05-18T03:15:35Z
876,151
<p>Yes, loading the module takes place at the line where the import statement is. If you create your <code>QApplication</code> and show your splash screen before that, you should be able to do what you want -- also you need to call <code>QApplication.processEvents()</code> whenever you need the splash screen to update with a new message.</p>
2
2009-05-18T03:33:49Z
[ "python", "performance", "matplotlib", "pyqt" ]
is there any AES encryption python library that will work well with python 3.0?
876,258
<p>I want to know is there any python 3.0 supported library for encryption. To encrypt files of 128 bits of data??</p>
0
2009-05-18T04:34:12Z
876,284
<p>I suggest my open-source project <code>slowaes</code>, <a href="http://code.google.com/p/slowaes/" rel="nofollow">http://code.google.com/p/slowaes/</a> -- should be trivial to adapt if it doesn't work out of the box, as it's pure-Python (and for 128 bits of data, the "slow" part shouldn't matter).</p>
3
2009-05-18T04:49:10Z
[ "python", "encryption", "aes" ]
is there any AES encryption python library that will work well with python 3.0?
876,258
<p>I want to know is there any python 3.0 supported library for encryption. To encrypt files of 128 bits of data??</p>
0
2009-05-18T04:34:12Z
876,304
<p>To properly encrypt data, you need more than just an encryption algorithm. It's probably best you find a complete library with documentation showing how to do things properly, if you absolutely must do it yourself. </p> <p>Encryption alone is not sufficient. How are you generating keys? What mode of operation are you using? Are you using a MAC on the data? </p> <p>Straight AES in ECB mode leaks information. Without a MAC, even though the data is encrypted, an attacker can still tamper with your data. </p>
0
2009-05-18T05:01:14Z
[ "python", "encryption", "aes" ]
Generating color ranges in Python
876,853
<p>I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like:</p> <ul> <li>(0, 0, 1)</li> <li>(0, 1, 0)</li> <li>(1, 0, 0)</li> <li>(1, 0.5, 1)</li> <li>(0, 0, 0.5)</li> </ul> <p>Of course, if there are more entries than combination of 0 and 1 it should turn to use fractions, etc. What would be the best way to do this?</p>
9
2009-05-18T09:24:32Z
876,872
<p>Use the HSV/HSB/HSL color space (three names for more or less the same thing). Generate N tuples equally spread in hue space, then just convert them to RGB.</p> <p>Sample code:</p> <pre><code>import colorsys N = 5 HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)] RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples) </code></pre>
27
2009-05-18T09:29:59Z
[ "python", "colors" ]
Generating color ranges in Python
876,853
<p>I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like:</p> <ul> <li>(0, 0, 1)</li> <li>(0, 1, 0)</li> <li>(1, 0, 0)</li> <li>(1, 0.5, 1)</li> <li>(0, 0, 0.5)</li> </ul> <p>Of course, if there are more entries than combination of 0 and 1 it should turn to use fractions, etc. What would be the best way to do this?</p>
9
2009-05-18T09:24:32Z
876,885
<p>This has already been answered in <a href="http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors">http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors</a> so you can use that in python too</p> <p>also look at this thread <a href="http://mail.python.org/pipermail/python-list/2004-June/266748.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2004-June/266748.html</a></p>
1
2009-05-18T09:33:48Z
[ "python", "colors" ]
Generating color ranges in Python
876,853
<p>I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like:</p> <ul> <li>(0, 0, 1)</li> <li>(0, 1, 0)</li> <li>(1, 0, 0)</li> <li>(1, 0.5, 1)</li> <li>(0, 0, 0.5)</li> </ul> <p>Of course, if there are more entries than combination of 0 and 1 it should turn to use fractions, etc. What would be the best way to do this?</p>
9
2009-05-18T09:24:32Z
17,684,501
<p>I created the following function based on <a href="http://stackoverflow.com/users/54486/kquinn">kquinn's</a> answer. </p> <pre><code>import colorsys def get_N_HexCol(N=5): HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in xrange(N)] hex_out = [] for rgb in HSV_tuples: rgb = map(lambda x: int(x*255),colorsys.hsv_to_rgb(*rgb)) hex_out.append("".join(map(lambda x: chr(x).encode('hex'),rgb))) return hex_out </code></pre>
2
2013-07-16T18:41:30Z
[ "python", "colors" ]
Django reusable app for like functionality as in friendfeed
876,898
<p>I am looking to implement "like" functionallity a bit similar as they do in <a href="http://friendfeed.com" rel="nofollow">friendfeed</a>. Is there a django reusable app that already does this?</p> <p>Thanks! Nick.</p>
2
2009-05-18T09:36:15Z
876,982
<p>You could put your own together using parts of <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a>.</p> <p>There isn't one app that would do this for you as it's too specific and reusable Django apps are supposed to be very focussed.</p>
1
2009-05-18T09:58:35Z
[ "python", "django" ]
Django reusable app for like functionality as in friendfeed
876,898
<p>I am looking to implement "like" functionallity a bit similar as they do in <a href="http://friendfeed.com" rel="nofollow">friendfeed</a>. Is there a django reusable app that already does this?</p> <p>Thanks! Nick.</p>
2
2009-05-18T09:36:15Z
877,014
<p>Search <a href="http://djangoplugables.com/" rel="nofollow">http://djangoplugables.com/</a> </p>
0
2009-05-18T10:07:37Z
[ "python", "django" ]
Django reusable app for like functionality as in friendfeed
876,898
<p>I am looking to implement "like" functionallity a bit similar as they do in <a href="http://friendfeed.com" rel="nofollow">friendfeed</a>. Is there a django reusable app that already does this?</p> <p>Thanks! Nick.</p>
2
2009-05-18T09:36:15Z
877,045
<p>This sort of thing you should just write yourself from scratch. A 'like' in its most basic form is going to be an object with relations to a user and some other object. Look at the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/" rel="nofollow">contenttypes framework</a> docs to see how to use generic foreign keys for this. The only other thing you need to worry about is to make the create view idempotent. </p> <p>If you're new to django this is probably a fun little exercise to familiarise yourself with contenttypes. If you're not new, the whole app should take you less than an hour. I wouldn't go searching for a pluggable app either way.</p>
4
2009-05-18T10:17:08Z
[ "python", "django" ]
How can I create an local webserver for my python scripts?
877,033
<p>I'm looking to use a local webserver to run a series of python scripts for the user. For various unavoidable reasons, the python script must run locally, not on a server. As a result, I'll be using HTML+browser as the UI, which I'm comfortable with, for the front end.</p> <p>I've been looking, therefore, for a lightweight web server that can execute python scripts, sitting in the background on a machine, ideally as a Windows service. Security and extensibility are not high priorities as it's all running internally on a small network. </p> <p>Should I run a native python webserver as a Windows service (in which case, how)? Or is it just as easy to install Apache onto the user's machine and run as CGI? Since this is all local, performance is not an issue either.</p> <p>Or am I missing something obvious?</p>
14
2009-05-18T10:13:26Z
877,053
<p>Don't waste a lot of time creating Windows service.</p> <p>Don't waste a lot of time on Windows Apache.</p> <p>Just make a Python service that responds to HTTP requests. </p> <p>Look at <a href="http://docs.python.org/library/basehttpserver.html">http://docs.python.org/library/basehttpserver.html</a> Python offers an HTTP server that you can extend with your server-side methods.</p> <p>Look at <a href="http://docs.python.org/library/wsgiref.html">http://docs.python.org/library/wsgiref.html</a> Python offers a WSGI reference implementation that makes your server easy and standards-compliant.</p> <p>Also <a href="http://fragments.turtlemeat.com/pythonwebserver.php">http://fragments.turtlemeat.com/pythonwebserver.php</a></p> <p><hr /></p> <p>"I'm trying to <em>avoid</em> making the user run python stuff from the command prompt."</p> <p>I don't see how clicking a web page is any different from clicking desktop icons.</p> <p>Starting a web server based on Python is relatively easy, once you have the web server. First, build the server. Later, you can make sure the server starts. Let's look at some ways.</p> <ol> <li><p>Your user can't use a random browser to open your local page. They need a bookmark to launch "localhost:8000/myspecialserverinsteadofthedestop/" That bookmark can be a .BAT file that (1) runs the server, (2) runs firefox with the proper initial URL.</p></li> <li><p>You can put the server in the user's start-this menu.</p></li> <li><p>You can make your Python program a windows "service".</p></li> </ol>
15
2009-05-18T10:19:46Z
[ "python", "webserver", "simplehttpserver" ]
How can I create an local webserver for my python scripts?
877,033
<p>I'm looking to use a local webserver to run a series of python scripts for the user. For various unavoidable reasons, the python script must run locally, not on a server. As a result, I'll be using HTML+browser as the UI, which I'm comfortable with, for the front end.</p> <p>I've been looking, therefore, for a lightweight web server that can execute python scripts, sitting in the background on a machine, ideally as a Windows service. Security and extensibility are not high priorities as it's all running internally on a small network. </p> <p>Should I run a native python webserver as a Windows service (in which case, how)? Or is it just as easy to install Apache onto the user's machine and run as CGI? Since this is all local, performance is not an issue either.</p> <p>Or am I missing something obvious?</p>
14
2009-05-18T10:13:26Z
877,056
<p>Running a native python webserver as a windows service should be a no brainer. Check out the documentation for writing windows services (win32api, ActiveState python) in python and also the documentation for subclassing BaseHttpServer and SimpleHttpServer.</p> <p>BTW: I had a similar question on stackoverflow: <a href="http://stackoverflow.com/questions/268629/how-to-stop-basehttpserver-serveforever-in-a-basehttprequesthandler-subclass">How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?</a></p> <p>Basically, you subclass BaseHTTPServer (you have to anyway...) and then... but just read the accepted answer - it set me on the right track!</p>
0
2009-05-18T10:20:45Z
[ "python", "webserver", "simplehttpserver" ]
How can I create an local webserver for my python scripts?
877,033
<p>I'm looking to use a local webserver to run a series of python scripts for the user. For various unavoidable reasons, the python script must run locally, not on a server. As a result, I'll be using HTML+browser as the UI, which I'm comfortable with, for the front end.</p> <p>I've been looking, therefore, for a lightweight web server that can execute python scripts, sitting in the background on a machine, ideally as a Windows service. Security and extensibility are not high priorities as it's all running internally on a small network. </p> <p>Should I run a native python webserver as a Windows service (in which case, how)? Or is it just as easy to install Apache onto the user's machine and run as CGI? Since this is all local, performance is not an issue either.</p> <p>Or am I missing something obvious?</p>
14
2009-05-18T10:13:26Z
22,310,248
<p>Best way is to make your own local server by using command prompt.</p> <ol> <li>Make a new folder say Project</li> <li>Make a new folder inside project &amp; name it as "cgi-bin"(without quotes)</li> <li>Paste your .py file inside the cgi-bin folder</li> <li>Open cmd and change to the directory from which you want to run the server and type "python -m CGIHTTPServer"(without quotes)</li> <li>Minimize the cmd window &amp; open your browser and type "localhost:8000/cgi-bin/yourpythonfilename.py"(without quotes).</li> </ol>
1
2014-03-10T20:09:19Z
[ "python", "webserver", "simplehttpserver" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,081
<p>I'm not an expert of Python, but what is wrong with a simple loop from start to end of first array? </p> <p>In C# I would do something like:</p> <pre><code>int match=0; for (int cnt=0; cnt&lt; A.Count;cnt++) { if ((A[cnt]==B[cnt]==1)) match++; } </code></pre> <p>Would that be possible in your language?</p>
1
2009-05-18T10:29:06Z
[ "python", "list" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,082
<p>A little shorter and hopefully more pythonic way:</p> <pre><code>&gt;&gt;&gt; A=[0,0,0,1,0,1] &gt;&gt;&gt; B=[0,0,1,1,1,1] x = sum(1 for a,b in zip(A,B) if (a==b==1)) &gt;&gt;&gt; x 2 </code></pre>
19
2009-05-18T10:29:26Z
[ "python", "list" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,102
<p>Motivated by brief need to be perverse, I offer the following solution:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] print len(set(i for i, n in enumerate(A) if n == 1) &amp; set(i for i, n in enumerate(B) if n == 1)) </code></pre> <p>(Drakosha's suggestion is a far more reasonable way to solve this problem. This just demonstrates that one can often look at the same problem in different ways.)</p>
1
2009-05-18T10:40:34Z
[ "python", "list" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,243
<p>With <a href="http://www.scipy.org" rel="nofollow">SciPy</a>:</p> <pre><code>&gt;&gt;&gt; from scipy import array &gt;&gt;&gt; A=array([0,0,0,1,0,1]) &gt;&gt;&gt; B=array([0,0,1,1,1,1]) &gt;&gt;&gt; A==B array([ True, True, False, True, False, True], dtype=bool) &gt;&gt;&gt; sum(A==B) 4 &gt;&gt;&gt; A!=B array([False, False, True, False, True, False], dtype=bool) &gt;&gt;&gt; sum(A!=B) 2 </code></pre>
0
2009-05-18T11:23:16Z
[ "python", "list" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,443
<p>Slightly shorter variation of Drakosha's:</p> <pre><code>&gt;&gt;&gt; A = [0,0,0,1,0,1] &gt;&gt;&gt; B = [0,0,1,1,1,1] &gt;&gt;&gt; sum(a*b for a, b in zip(A, B) ) 2 </code></pre>
3
2009-05-18T12:15:33Z
[ "python", "list" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,450
<p>Here comes another method which exploits the fact that the array just contains zeros and ones.</p> <p>The scalar product of two vectors x and y is sum( x(i)*y(i) ) the only situation yielding a non zero result is if x(i)==y(i)==1 thus using numpy for instance</p> <pre><code>from numpy import * x = array([0,0,0,1,0,1]) y = array([0,0,1,1,1,1]) print dot(x,y) </code></pre> <p>simple and nice. This method does n multiplications and adds n-1 times, however there are fast implementations using SSE, GPGPU, vectorisation, (add your fancy word here) for dot products (scalar products)</p> <p>I timed the numpy-method against this method:</p> <pre><code>sum(1 for a,b in zip(x,y) if (a==b==1)) </code></pre> <p>and found that for 1000000 loops the numpy-version did it in 2121ms and the zip-method did it in 9502ms thus the numpy-version is a lot faster</p> <p>I did a better analysis of the efectivness and found that for n element(s) in the array the zip method took t1 ms and the dot product took t2 ms for one itteration</p> <pre> elements zip dot 1 0.0030 0.0207 10 0.0063 0.0230 100 0.0393 0.0476 1000 0.3696 0.2932 10000 7.6144 2.7781 100000 115.8824 30.1305 </pre> <p>From this data one could draw the conclusion that if the number of elements in the array is expected to (in mean) be more than 350 (or say 1000) one should consider to use the dot-product method instead.</p>
0
2009-05-18T12:17:45Z
[ "python", "list" ]
Find the number of 1s in the same position in two arrays
877,059
<p>I have two lists:</p> <pre><code>A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] </code></pre> <p>I want to find the number of 1s in the same position in both lists.</p> <p>The answer for these arrays would be 2.</p>
7
2009-05-18T10:21:45Z
877,915
<pre><code>[A[i]+B[i] for i in range(min([len(A), len(B)]))].count(2) </code></pre> <p>Basically this just creates a new list which has all the elements of the other two added together. You know there were two 1's if the sum is 2 (assuming only 0's and 1's in the list). Therefore just perform the count operation on 2.</p>
0
2009-05-18T14:05:20Z
[ "python", "list" ]
Learning threading concepts
877,068
<p>I have started threading in C and also Python recently and would like to know any good tutorials available for it.</p>
4
2009-05-18T10:23:17Z
877,078
<p>I could think of couple of MSDN links (for windows):</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms810438.aspx" rel="nofollow">Multithreading for Rookies</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/y6h8hye8%28VS.80%29.aspx" rel="nofollow">Multithreading with C and Win32</a> </p>
0
2009-05-18T10:27:40Z
[ "python", "c", "multithreading" ]
Learning threading concepts
877,068
<p>I have started threading in C and also Python recently and would like to know any good tutorials available for it.</p>
4
2009-05-18T10:23:17Z
877,094
<p><strong>C - Recommended Books</strong></p> <p>Unix: <a href="http://rads.stackoverflow.com/amzn/click/0201633922" rel="nofollow">Butenhof, David R. - Programming with POSIX(R) Threads (Addison-Wesley Professional Computing Series)</a></p> <p>Windows: <a href="http://rads.stackoverflow.com/amzn/click/0321256190" rel="nofollow">Hart, Johnson M. - Windows System Programming (3rd Edition)</a></p> <p><strong>Python - Online</strong></p> <p><a href="http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf" rel="nofollow">Tutorial on Threads Programming with Python</a> (PDF)</p>
2
2009-05-18T10:35:53Z
[ "python", "c", "multithreading" ]
Learning threading concepts
877,068
<p>I have started threading in C and also Python recently and would like to know any good tutorials available for it.</p>
4
2009-05-18T10:23:17Z
877,135
<p>You could write the threading yourself, it could be hard but doing that, you will learn more about threading.</p> <p>Or you could use a preexisting threading library. It will let you implement threading faster in your application, but you may not learn as much as to what goes on "under the hood".</p> <p>From your question, I cant see which path you want to take. For the latter, I suggest <a href="http://www.boost.org/doc/libs/1%5F39%5F0/doc/html/thread.html" rel="nofollow">boosts threading library</a>. The other answers hold great links if you prefer the former path. </p> <p>Good luck. :)</p>
1
2009-05-18T10:47:48Z
[ "python", "c", "multithreading" ]
Learning threading concepts
877,068
<p>I have started threading in C and also Python recently and would like to know any good tutorials available for it.</p>
4
2009-05-18T10:23:17Z
878,644
<p>I have found Interprocess <a href="http://rads.stackoverflow.com/amzn/click/0130460427" rel="nofollow">Communications in Linux: The Nooks and Crannies</a> to be extremely useful for IPC (and threading) in C.</p>
0
2009-05-18T16:47:18Z
[ "python", "c", "multithreading" ]
HTTPSConnection module missing in Python 2.6 on CentOS 5.2
877,072
<p>I'm playing around with a Python application on CentOS 5.2. It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection.</p> <p>When I try running my application I get an error regarding HTTPSConnection being missing: "AttributeError: 'module' object has no attribute 'HTTPSConnection'"</p> <p>Google doesn't really return anything relevant, I've tried most of the solutions but none of them solve the problem.</p> <p>Has anyone come across anything like it?</p> <p>Here's the traceback:</p> <pre><code>Traceback (most recent call last): File "./chatter.py", line 114, in &lt;module&gt; sys.exit(main()) File "./chatter.py", line 92, in main chatter.status( ) File "/mnt/application/chatter/__init__.py", line 161, in status cQueue.connect() File "/mnt/application/chatter/tools.py", line 42, in connect self.connection = SQSConnection(cConfig.get("AWS", "KeyId"), cConfig.get("AWS", "AccessKey")); File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/sqs/connection.py", line 54, in __init__ self.region.endpoint, debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 418, in __init__ debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 189, in __init__ self.refresh_http_connection(self.server, self.is_secure) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 247, in refresh_http_connection connection = httplib.HTTPSConnection(host) AttributeError: 'module' object has no attribute 'HTTPSConnection' </code></pre>
7
2009-05-18T10:24:57Z
877,292
<p>citing from the python documentation (<a href="http://docs.python.org/library/httplib.html">http://docs.python.org/library/httplib.html</a>):</p> <p><strong>Note</strong> HTTPS support is only available if the socket module was compiled with SSL support.</p> <p>You should find out how python on the CentOS you are using was built.</p>
7
2009-05-18T11:38:46Z
[ "python", "centos" ]
HTTPSConnection module missing in Python 2.6 on CentOS 5.2
877,072
<p>I'm playing around with a Python application on CentOS 5.2. It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection.</p> <p>When I try running my application I get an error regarding HTTPSConnection being missing: "AttributeError: 'module' object has no attribute 'HTTPSConnection'"</p> <p>Google doesn't really return anything relevant, I've tried most of the solutions but none of them solve the problem.</p> <p>Has anyone come across anything like it?</p> <p>Here's the traceback:</p> <pre><code>Traceback (most recent call last): File "./chatter.py", line 114, in &lt;module&gt; sys.exit(main()) File "./chatter.py", line 92, in main chatter.status( ) File "/mnt/application/chatter/__init__.py", line 161, in status cQueue.connect() File "/mnt/application/chatter/tools.py", line 42, in connect self.connection = SQSConnection(cConfig.get("AWS", "KeyId"), cConfig.get("AWS", "AccessKey")); File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/sqs/connection.py", line 54, in __init__ self.region.endpoint, debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 418, in __init__ debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 189, in __init__ self.refresh_http_connection(self.server, self.is_secure) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 247, in refresh_http_connection connection = httplib.HTTPSConnection(host) AttributeError: 'module' object has no attribute 'HTTPSConnection' </code></pre>
7
2009-05-18T10:24:57Z
877,549
<p>How come you have python 2.6? In CentOS 2.4 is standard, this might be the cause of your problem. Might be worth installing boto again as the library paths might not be correct</p>
0
2009-05-18T12:44:01Z
[ "python", "centos" ]
HTTPSConnection module missing in Python 2.6 on CentOS 5.2
877,072
<p>I'm playing around with a Python application on CentOS 5.2. It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection.</p> <p>When I try running my application I get an error regarding HTTPSConnection being missing: "AttributeError: 'module' object has no attribute 'HTTPSConnection'"</p> <p>Google doesn't really return anything relevant, I've tried most of the solutions but none of them solve the problem.</p> <p>Has anyone come across anything like it?</p> <p>Here's the traceback:</p> <pre><code>Traceback (most recent call last): File "./chatter.py", line 114, in &lt;module&gt; sys.exit(main()) File "./chatter.py", line 92, in main chatter.status( ) File "/mnt/application/chatter/__init__.py", line 161, in status cQueue.connect() File "/mnt/application/chatter/tools.py", line 42, in connect self.connection = SQSConnection(cConfig.get("AWS", "KeyId"), cConfig.get("AWS", "AccessKey")); File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/sqs/connection.py", line 54, in __init__ self.region.endpoint, debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 418, in __init__ debug, https_connection_factory) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 189, in __init__ self.refresh_http_connection(self.server, self.is_secure) File "/usr/local/lib/python2.6/site-packages/boto-1.7a-py2.6.egg/boto/connection.py", line 247, in refresh_http_connection connection = httplib.HTTPSConnection(host) AttributeError: 'module' object has no attribute 'HTTPSConnection' </code></pre>
7
2009-05-18T10:24:57Z
2,598,936
<p>Please install openssl and openssl-devel before you install python2.6.</p> <p>You can simply install those packages using yum, and do a re-install of python2.6 (no need to remove already installed python2.6)</p> <pre><code>]# yum install openssl openssl-devel Python-2.6.x]# ./configure Python-2.6.x]# make &amp;&amp; make altinstall </code></pre>
6
2010-04-08T10:01:32Z
[ "python", "centos" ]