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
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
16,958,086
<p>Try to set your time zone (TIME_ZONE variable) in settings.py</p> <p>That worked for me.</p>
0
2013-06-06T09:11:41Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
What is an exotic function signature in Python?
884,068
<p>I recently saw a <a href="http://pypi.python.org/pypi/decorator/" rel="nofollow">reference to "exotic signatures"</a> and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is</p> <pre><code>def exotic_signature((x, y)=(1,2)): return x+y </code></pre> <p>What makes this an "exotic" signature?</p>
3
2009-05-19T17:28:52Z
884,073
<p>What's exotic is that x and y represent a single function argument that is unpacked into two values... x and y. It's equivalent to:</p> <pre><code>def func(n): x, y = n ... </code></pre> <p>Both functions require a single argument (list or tuple) that contains two elements.</p>
6
2009-05-19T17:31:20Z
[ "python" ]
What is an exotic function signature in Python?
884,068
<p>I recently saw a <a href="http://pypi.python.org/pypi/decorator/" rel="nofollow">reference to "exotic signatures"</a> and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is</p> <pre><code>def exotic_signature((x, y)=(1,2)): return x+y </code></pre> <p>What makes this an "exotic" signature?</p>
3
2009-05-19T17:28:52Z
884,114
<p>More information about tuple parameter unpacking (and why it is removed) here: <a href="http://www.python.org/dev/peps/pep-3113/">http://www.python.org/dev/peps/pep-3113/</a></p>
6
2009-05-19T17:41:57Z
[ "python" ]
What is an exotic function signature in Python?
884,068
<p>I recently saw a <a href="http://pypi.python.org/pypi/decorator/" rel="nofollow">reference to "exotic signatures"</a> and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is</p> <pre><code>def exotic_signature((x, y)=(1,2)): return x+y </code></pre> <p>What makes this an "exotic" signature?</p>
3
2009-05-19T17:28:52Z
885,290
<p>Here's a slightly more complex example. Let's say you're doing some kind of graphics programming and you've got a list of points.</p> <pre><code>points = [(1,2), (-3,1), (4,-2), (-1,5), (3,3)] </code></pre> <p>and you want to know how far away they are from the origin. You might define a function like this:</p> <pre><code>def magnitude((x,y)): return (x**2 + y**2)**0.5 </code></pre> <p>and then you can find the distances of your points from (0,0) as:</p> <pre><code>map(magnitude, points) </code></pre> <p>...well, at least, you could in python 2.x :-)</p>
1
2009-05-19T22:11:11Z
[ "python" ]
How can I create a RSA public key in PEM format from an RSA modulus?
884,207
<p>I have the modulus of an RSA public key. I want to use this public key with the <a href="http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto" rel="nofollow">Python library "M2Crypto",</a> but it requires a public key in PEM format. </p> <p>Thus, I have to convert the RSA modulus to a PEM file.</p> <p>The modulus can be found <a href="http://paste.pocoo.org/show/118040/" rel="nofollow">here.</a> </p> <p>Any ideas?</p>
2
2009-05-19T17:58:14Z
884,562
<p>The M2Crypto library has <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.RSA-module.html#new%5Fpub%5Fkey" rel="nofollow">a way to reconstruct a public key.</a> You need to know the public exponent, <code>e</code> (often 65337 for RSA keys, but other numbers such as 3 or 17 have been used), and the modulus, <code>n</code> (which is the 512-bit number provided in the question). Note that the docs describe the length-encoded format used for <code>e</code> and <code>n</code>.</p> <p>Once the public key has been reconstructed, it can be <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.RSA.RSA%5Fpub-class.html#save%5Fkey" rel="nofollow">saved into a file</a> and used again later without the hassle of conversion.</p>
4
2009-05-19T19:21:54Z
[ "python", "cryptography", "rsa", "m2crypto" ]
How to return a function value with decorator and thread
884,410
<p>have this code</p> <pre><code>import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): return a+b print(add_item(2,2)) </code></pre> <p>but the function never return the value, exits a way to get the return ? </p>
2
2009-05-19T18:46:54Z
884,415
<p>That's because you never return a value in your "decorator"-function.</p> <p>You have to include a shared variable in your thread and move the return value of your threaded function back into the "decorator"-function.</p>
2
2009-05-19T18:49:31Z
[ "python", "multithreading", "decorator" ]
How to return a function value with decorator and thread
884,410
<p>have this code</p> <pre><code>import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): return a+b print(add_item(2,2)) </code></pre> <p>but the function never return the value, exits a way to get the return ? </p>
2
2009-05-19T18:46:54Z
884,425
<p>The reason <code>None</code> is returned, is because there is nothing to return (besides the fact that <code>decorator</code> doesn't have a return statement). <code>join()</code> always returns <code>None</code>, as per the <a href="http://docs.python.org/3.0/library/threading.html#threading.Thread.join" rel="nofollow">documentation</a>.</p> <p>For an example of how to communicate with a thread, see <a href="http://mail.python.org/pipermail/python-list/2005-September/339892.html" rel="nofollow">this email</a>.</p> <p>If I may ask though: since <code>join()</code> blocks the calling thread, what is there to gain here?</p> <p><hr /></p> <p><strong>Edit:</strong> I played around a bit, and the following is a solution that doesn't require a queue (not saying it's a better solution. Just different):</p> <pre><code>import threading # Callable that stores the result of calling the given callable f. class ResultCatcher: def __init__(self, f): self.f = f self.val = None def __call__(self, *args, **kwargs): self.val = self.f(*args, **kwargs) def threaded(f): def decorator(*args,**kargs): # Encapsulate f so that the return value can be extracted. retVal = ResultCatcher(f) th = threading.Thread(target=retVal, args=args) th.start() th.join() # Extract and return the result of executing f. return retVal.val decorator.__name__ = f.__name__ return decorator @threaded def add_item(a, b): return a + b print(add_item(2, 2)) </code></pre>
4
2009-05-19T18:53:41Z
[ "python", "multithreading", "decorator" ]
Wrapping a Python Object
884,594
<p>I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:</p> <pre><code>def __init__(self, anObject): self.theObject = anObject </code></pre> <p>and provides a "write" method: </p> <pre><code>def write(self, pathOrFile): plistlib.writeToPlist(self.theObject.__dict__, pathOrFile) </code></pre> <p>Now it would be nice if the PlistObject behaved just like wrapped object itself, meaning that all attributes and methods are somehow "forwarded" to the wrapped object. I realize that the methods <code>__getattr__</code> and <code>__setattr__</code> can be used for complex attribute operations:</p> <pre><code> def __getattr__(self, name): return self.theObject.__getattr__(name) </code></pre> <p>But then of course I run into the problem that the constructor now produces an infinite recursion, since also <code>self.theObject = anObject</code> tries to access the wrapped object.</p> <p>How can I avoid this? If the whole idea seems like a bad one, tell me too.</p>
1
2009-05-19T19:27:00Z
884,634
<blockquote> <p>But then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object.</p> </blockquote> <p>That's why the manual suggests that you do this for all "real" attribute accesses.</p> <pre><code>theobj = object.__getattribute__(self, "theObject") </code></pre>
2
2009-05-19T19:36:15Z
[ "python" ]
Wrapping a Python Object
884,594
<p>I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:</p> <pre><code>def __init__(self, anObject): self.theObject = anObject </code></pre> <p>and provides a "write" method: </p> <pre><code>def write(self, pathOrFile): plistlib.writeToPlist(self.theObject.__dict__, pathOrFile) </code></pre> <p>Now it would be nice if the PlistObject behaved just like wrapped object itself, meaning that all attributes and methods are somehow "forwarded" to the wrapped object. I realize that the methods <code>__getattr__</code> and <code>__setattr__</code> can be used for complex attribute operations:</p> <pre><code> def __getattr__(self, name): return self.theObject.__getattr__(name) </code></pre> <p>But then of course I run into the problem that the constructor now produces an infinite recursion, since also <code>self.theObject = anObject</code> tries to access the wrapped object.</p> <p>How can I avoid this? If the whole idea seems like a bad one, tell me too.</p>
1
2009-05-19T19:27:00Z
884,655
<p>Unless I'm missing something, this will work just fine:</p> <pre><code>def __getattr__(self, name): return getattr(self.theObject, name) </code></pre> <p><hr /></p> <p><strong>Edit:</strong> for those thinking that the lookup of <code>self.theObject</code> will result in an infinite recursive call to <code>__getattr__</code>, let me show you:</p> <pre><code>&gt;&gt;&gt; class Test: ... a = "a" ... def __init__(self): ... self.b = "b" ... def __getattr__(self, name): ... return 'Custom: %s' % name ... &gt;&gt;&gt; Test.a 'a' &gt;&gt;&gt; Test().a 'a' &gt;&gt;&gt; Test().b 'b' &gt;&gt;&gt; Test().c 'Custom: c' </code></pre> <p><code>__getattr__</code> is only called as a <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetattr%5F%5F" rel="nofollow">last</a> <a href="http://docs.python.org/3.0/reference/datamodel.html?highlight=%5F%5Fgetattr%5F%5F#object.%5F%5Fgetattr%5F%5F" rel="nofollow">resort</a>. Since <code>theObject</code> can be found in <code>__dict__</code>, no issues arise.</p>
3
2009-05-19T19:41:07Z
[ "python" ]
Wrapping a Python Object
884,594
<p>I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:</p> <pre><code>def __init__(self, anObject): self.theObject = anObject </code></pre> <p>and provides a "write" method: </p> <pre><code>def write(self, pathOrFile): plistlib.writeToPlist(self.theObject.__dict__, pathOrFile) </code></pre> <p>Now it would be nice if the PlistObject behaved just like wrapped object itself, meaning that all attributes and methods are somehow "forwarded" to the wrapped object. I realize that the methods <code>__getattr__</code> and <code>__setattr__</code> can be used for complex attribute operations:</p> <pre><code> def __getattr__(self, name): return self.theObject.__getattr__(name) </code></pre> <p>But then of course I run into the problem that the constructor now produces an infinite recursion, since also <code>self.theObject = anObject</code> tries to access the wrapped object.</p> <p>How can I avoid this? If the whole idea seems like a bad one, tell me too.</p>
1
2009-05-19T19:27:00Z
885,340
<p>I'm glad to see others have been able to help you with the recursive call to <code>__getattr__</code>. Since you've asked for comments on the general approach of serializing to plist, I just wanted to chime in with a few thoughts.</p> <p>Python's plist implementation handles basic types only, and provides no extension mechanism for you to instruct it on serializing/deserializing complex types. If you define a custom class, for example, writePlist won't be able to help, as you've discovered since you're passing the instance's <code>__dict__</code> for serialization.</p> <p>This has a couple implications:</p> <ol> <li><p>You won't be able to use this to serialize any objects that contain other objects of non-basic type without converting them to a <code>__dict__</code>, and so-on recursively for the entire network graph.</p></li> <li><p>If you roll your own network graph walker to serialize all non-basic objects that can be reached, you'll have to worry about circles in the graph where one object has another in a property, which in turn holds a reference back to the first, etc etc.</p></li> </ol> <p>Given then, you may wish to look at pickle instead as it can handle all of these and more. If you need the plist format for other reasons, and you're sure you can stick to "simple" object dicts, then you may wish to just use a simple function... trying to have the PlistObject mock every possible function in the contained object is an onion with potentially many layers as you need to handle all the possibilities of the wrapped instance.</p> <p>Something as simple as this may be more pythonic, and keep the usability of the wrapped object simpler by not wrapping it in the first place:</p> <pre><code>def to_plist(obj, f_handle): writePlist(obj.__dict__, f_handle) </code></pre> <p>I know that doesn't seem very sexy, but it is a lot more maintainable in my opinion than a wrapper given the severe limits of the plist format, and certainly better than artificially forcing all objects in your application to inherit from a common base class when there's nothing in your business domain that actually indicates those disparate objects are related.</p>
1
2009-05-19T22:30:14Z
[ "python" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something like XYZ, ABC, NYU etc.</p> <p>In my parent controller script I retrieve the name variable from a list:</p> <pre><code>my_list = [ 'XYZ', 'ABC', 'NYU' ] </code></pre> <p>So my question is, what is the best way to spawn off these processes as children? I want to limit the number of children to 64 at a time, so need to track the status (if the child process has finished or not) so I can efficiently keep the whole generation running.</p> <p>I looked into using the subprocess package, but rejected it because it only spawns one child at a time. I finally found the multiprocessor package, but I admit to being overwhelmed by the whole threads vs. subprocesses documentation.</p> <p>Right now, my script uses <code>subprocess.call</code> to only spawn one child at a time and looks like this:</p> <pre><code>#!/path/to/python import subprocess, multiprocessing, Queue from multiprocessing import Process my_list = [ 'XYZ', 'ABC', 'NYU' ] if __name__ == '__main__': processors = multiprocessing.cpu_count() for i in range(len(my_list)): if( i &lt; processors ): cmd = ["python", "/path/to/create_graphs.py", "--name="+ my_list[i]] child = subprocess.call( cmd, shell=False ) </code></pre> <p>I really want it to spawn up 64 children at a time. In other stackoverflow questions I saw people using Queue, but it seems like that creates a performance hit?</p>
33
2009-05-19T19:39:42Z
884,751
<p>I would definitely use <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> rather than rolling my own solution using subprocess.</p>
1
2009-05-19T20:04:01Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something like XYZ, ABC, NYU etc.</p> <p>In my parent controller script I retrieve the name variable from a list:</p> <pre><code>my_list = [ 'XYZ', 'ABC', 'NYU' ] </code></pre> <p>So my question is, what is the best way to spawn off these processes as children? I want to limit the number of children to 64 at a time, so need to track the status (if the child process has finished or not) so I can efficiently keep the whole generation running.</p> <p>I looked into using the subprocess package, but rejected it because it only spawns one child at a time. I finally found the multiprocessor package, but I admit to being overwhelmed by the whole threads vs. subprocesses documentation.</p> <p>Right now, my script uses <code>subprocess.call</code> to only spawn one child at a time and looks like this:</p> <pre><code>#!/path/to/python import subprocess, multiprocessing, Queue from multiprocessing import Process my_list = [ 'XYZ', 'ABC', 'NYU' ] if __name__ == '__main__': processors = multiprocessing.cpu_count() for i in range(len(my_list)): if( i &lt; processors ): cmd = ["python", "/path/to/create_graphs.py", "--name="+ my_list[i]] child = subprocess.call( cmd, shell=False ) </code></pre> <p>I really want it to spawn up 64 children at a time. In other stackoverflow questions I saw people using Queue, but it seems like that creates a performance hit?</p>
33
2009-05-19T19:39:42Z
884,753
<p>I don't think you need queue unless you intend to get data out of the applications (Which if you do want data, I think it may be easier to add it to a database anyway)</p> <p>but try this on for size:</p> <p>put the contents of your create_graphs.py script all into a function called "create_graphs"</p> <pre><code>import threading from create_graphs import create_graphs num_processes = 64 my_list = [ 'XYZ', 'ABC', 'NYU' ] threads = [] # run until all the threads are done, and there is no data left while threads or my_list: # if we aren't using all the processors AND there is still data left to # compute, then spawn another thread if (len(threads) &lt; num_processes) and my_list: t = threading.Thread(target=create_graphs, args=[ my_list.pop() ]) t.setDaemon(True) t.start() threads.append(t) # in the case that we have the maximum number of threads check if any of them # are done. (also do this when we run out of data, until all the threads are done) else: for thread in threads: if not thread.isAlive(): threads.remove(thread) </code></pre> <p>I know that this will result in 1 less threads than processors, which is probably good, it leaves a processor to manage the threads, disk i/o, and other things happening on the computer. If you decide you want to use the last core just add one to it</p> <p><strong>edit</strong>: I think I may have misinterpreted the purpose of my_list. You do not need <code>my_list</code> to keep track of the threads at all (as they're all referenced by the items in the <code>threads</code> list). But this is a fine way of feeding the processes input - or even better: use a generator function ;)</p> <h2>The purpose of <code>my_list</code> and <code>threads</code></h2> <p><code>my_list</code> holds the data that you need to process in your function<br> <code>threads</code> is just a list of the currently running threads</p> <p>the while loop does two things, start new threads to process the data, and check if any threads are done running.</p> <p>So as long as you have either (a) more data to process, or (b) threads that aren't finished running.... you want to program to continue running. <strong>Once both lists are empty they will evaluate to <code>False</code> and the while loop will exit</strong></p>
2
2009-05-19T20:04:26Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something like XYZ, ABC, NYU etc.</p> <p>In my parent controller script I retrieve the name variable from a list:</p> <pre><code>my_list = [ 'XYZ', 'ABC', 'NYU' ] </code></pre> <p>So my question is, what is the best way to spawn off these processes as children? I want to limit the number of children to 64 at a time, so need to track the status (if the child process has finished or not) so I can efficiently keep the whole generation running.</p> <p>I looked into using the subprocess package, but rejected it because it only spawns one child at a time. I finally found the multiprocessor package, but I admit to being overwhelmed by the whole threads vs. subprocesses documentation.</p> <p>Right now, my script uses <code>subprocess.call</code> to only spawn one child at a time and looks like this:</p> <pre><code>#!/path/to/python import subprocess, multiprocessing, Queue from multiprocessing import Process my_list = [ 'XYZ', 'ABC', 'NYU' ] if __name__ == '__main__': processors = multiprocessing.cpu_count() for i in range(len(my_list)): if( i &lt; processors ): cmd = ["python", "/path/to/create_graphs.py", "--name="+ my_list[i]] child = subprocess.call( cmd, shell=False ) </code></pre> <p>I really want it to spawn up 64 children at a time. In other stackoverflow questions I saw people using Queue, but it seems like that creates a performance hit?</p>
33
2009-05-19T19:39:42Z
884,846
<p>What you are looking for is the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool">process pool</a> class in multiprocessing.</p> <pre><code>import multiprocessing import subprocess def work(cmd): return subprocess.call(cmd, shell=False) if __name__ == '__main__': count = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes=count) print pool.map(work, ['ls'] * count) </code></pre> <p>And here is a calculation example to make it easier to understand. The following will divide 10000 tasks on N processes where N is the cpu count. Note that I'm passing None as the number of processes. This will cause the Pool class to use cpu_count for the number of processes (<a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool">reference</a>)</p> <pre><code>import multiprocessing import subprocess def calculate(value): return value * 10 if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10000) results = [] r = pool.map_async(calculate, tasks, callback=results.append) r.wait() # Wait on the results print results </code></pre>
44
2009-05-19T20:26:13Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something like XYZ, ABC, NYU etc.</p> <p>In my parent controller script I retrieve the name variable from a list:</p> <pre><code>my_list = [ 'XYZ', 'ABC', 'NYU' ] </code></pre> <p>So my question is, what is the best way to spawn off these processes as children? I want to limit the number of children to 64 at a time, so need to track the status (if the child process has finished or not) so I can efficiently keep the whole generation running.</p> <p>I looked into using the subprocess package, but rejected it because it only spawns one child at a time. I finally found the multiprocessor package, but I admit to being overwhelmed by the whole threads vs. subprocesses documentation.</p> <p>Right now, my script uses <code>subprocess.call</code> to only spawn one child at a time and looks like this:</p> <pre><code>#!/path/to/python import subprocess, multiprocessing, Queue from multiprocessing import Process my_list = [ 'XYZ', 'ABC', 'NYU' ] if __name__ == '__main__': processors = multiprocessing.cpu_count() for i in range(len(my_list)): if( i &lt; processors ): cmd = ["python", "/path/to/create_graphs.py", "--name="+ my_list[i]] child = subprocess.call( cmd, shell=False ) </code></pre> <p>I really want it to spawn up 64 children at a time. In other stackoverflow questions I saw people using Queue, but it seems like that creates a performance hit?</p>
33
2009-05-19T19:39:42Z
1,008,113
<p>Here is the solution I came up, based on Nadia and Jim's comments. I am not sure if it is the best way, but it works. The original child script being called needs to be a shell script because I need to use some 3rd party apps including Matlab. So I had to take it out of Python and code it in bash.</p> <pre><code>import sys import os import multiprocessing import subprocess def work(staname): print 'Processing station:',staname print 'Parent process:', os.getppid() print 'Process id:', os.getpid() cmd = [ "/bin/bash" "/path/to/executable/create_graphs.sh","--name=%s" % (staname) ] return subprocess.call(cmd, shell=False) if __name__ == '__main__': my_list = [ 'XYZ', 'ABC', 'NYU' ] my_list.sort() print my_list # Get the number of processors available num_processes = multiprocessing.cpu_count() threads = [] len_stas = len(my_list) print "+++ Number of stations to process: %s" % (len_stas) # run until all the threads are done, and there is no data left for list_item in my_list: # if we aren't using all the processors AND there is still data left to # compute, then spawn another thread if( len(threads) &lt; num_processes ): p = multiprocessing.Process(target=work,args=[list_item]) p.start() print p, p.is_alive() threads.append(p) else: for thread in threads: if not thread.is_alive(): threads.remove(thread) </code></pre> <p>Does this seem like a reasonable solution? I tried to use Jim's while loop format, but my script just returned nothing. I am not sure why that would be. Here is the output when I run the script with Jim's 'while' loop replacing the 'for' loop:</p> <pre><code>hostname{me}2% controller.py ['ABC', 'NYU', 'XYZ'] Number of processes: 64 +++ Number of stations to process: 3 hostname{me}3% </code></pre> <p>When I run it with the 'for' loop, I get something more meaningful:</p> <pre><code>hostname{me}6% controller.py ['ABC', 'NYU', 'XYZ'] Number of processes: 64 +++ Number of stations to process: 3 Processing station: ABC Parent process: 1056 Process id: 1068 Processing station: NYU Parent process: 1056 Process id: 1069 Processing station: XYZ Parent process: 1056 Process id: 1071 hostname{me}7% </code></pre> <p>So this works, and I am happy. However, I still don't get why I can't use Jim's 'while' style loop instead of the 'for' loop I am using. Thanks for all the help - I am impressed with the breadth of knowledge @ stackoverflow.</p>
2
2009-06-17T16:16:38Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
885,048
<p>There is a parsedate function in <a href="http://docs.python.org/library/email.util.html" rel="nofollow">email.util</a>. It parses all valid RFC 2822 dates and some special cases.</p>
8
2009-05-19T21:10:19Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
885,049
<pre><code>from email.utils import parsedate print parsedate('Fri, 15 May 2009 17:58:28 +0000') </code></pre> <p><a href="http://docs.python.org/library/email.util.html#email.utils.parsedate">Documentation</a>.</p>
12
2009-05-19T21:11:14Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
1,258,623
<p>The problem is that parsedate will ignore the offset.</p> <p>Do this instead:</p> <pre><code>from email.utils import parsedate_tz print parsedate_tz('Fri, 15 May 2009 17:58:28 +0700') </code></pre>
26
2009-08-11T05:50:00Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
17,155,727
<p>I'd like to elaborate on previous answers. <code>email.utils.parsedate</code> and <code>email.utils.parsedate_tz</code> both return tuples, since the OP needs a <code>datetime.datetime</code> object, I'm adding these examples for completeness:</p> <pre><code>from email.utils import parsedate from datetime import datetime import time t = parsedate('Sun, 14 Jul 2013 20:14:30 -0000') d1 = datetime.fromtimestamp(time.mktime(t)) </code></pre> <p>Or:</p> <pre><code>d2 = datetime.datetime(*t[:6]) </code></pre> <p>Note that <code>d1</code> and <code>d2</code> are both naive datetime objects, there's no timezone information stored. If you need aware datetime objects, check the <code>tzinfo</code> <code>datetime()</code> arg.</p> <p>Alternatively you could use the <a href="https://pypi.python.org/pypi/python-dateutil">dateutil</a> module</p>
7
2013-06-17T19:58:42Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
22,486,403
<p>It looks like Python 3.3 going forward has a new method <code>parsedate_to_datetime</code> in email.utils that takes care of the intermediate steps:</p> <blockquote> <p><strong>email.utils.parsedate_to_datetime(date)</strong> </p> <p>The inverse of format_datetime(). Performs the same function as parsedate(), but on success returns a datetime. If the input date has a timezone of -0000, the datetime will be a naive datetime, and if the date is conforming to the RFCs it will represent a time in UTC but with no indication of the actual source timezone of the message the date comes from. If the input date has any other valid timezone offset, the datetime will be an aware datetime with the corresponding a timezone tzinfo.</p> <p>New in version 3.3.</p> </blockquote> <p><a href="http://python.readthedocs.org/en/latest/library/email.util.html#email.utils.parsedate_to_datetime" rel="nofollow">http://python.readthedocs.org/en/latest/library/email.util.html#email.utils.parsedate_to_datetime</a></p>
4
2014-03-18T17:14:44Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
Django Admin & Model Deletion
885,103
<p>I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its <code>delete</code> method.</p> <pre><code>class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, self).delete() </code></pre> <p>When I call delete on the Child from the shell I get:</p> <pre><code>bar foo </code></pre> <p>as expected</p> <p>When I use the admin, the custom delete functions don't seem to get called. Am I missing something obvious?</p> <p>Thanks,</p> <p>Dom</p> <p>p.s. This is obviously a simplified version of the code I'm using, apologies if it contains typos. Feel free to leave a comment and I'll fix it.</p>
2
2009-05-19T21:26:03Z
885,222
<p>According to <a href="http://code.djangoproject.com/ticket/11022" rel="nofollow">this</a> documentation bug report (<a href="http://code.djangoproject.com/ticket/11022" rel="nofollow">Document that the admin bulk delete doesn't call Model.delete()</a>), the admin's <em>bulk</em> delete does NOT call the model's delete function. If you're using bulk delete from the admin, this would explain your problem.</p> <p>From the added documentation on this ticket, the advice is to write a custom bulk delete function that does call the model's delete function.</p> <p>Further information on this behavior is <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/" rel="nofollow">here</a>. The bulk delete action doesn't call the model's <code>delete()</code> method for the sake of efficiency.</p>
9
2009-05-19T21:54:56Z
[ "python", "django", "django-admin" ]
python orm
885,172
<p>This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)?</p> <p>So, I start with a basic Phone app Object person: name, address, city, state, zip, phone and I change to Object person: title, name, address, city, state, zip, phone object Object phone: type, phone #</p> <p>Do I manually convert via the db and change the code OR does the ORM middleware make the change? and if so - how?</p>
2
2009-05-19T21:41:11Z
885,203
<p>The Django book covers this issue in <a href="http://www.djangobook.com/en/1.0/chapter05/" rel="nofollow">Chapter 5</a>, near the end of the chapter (or bottom of the page, in the web edition). Basically, the rules are:</p> <ul> <li>When <em>adding</em> a field, first add it to the database manually (using, e.g., <code>ALTER TABLE</code>) and then add the field to the model. (You can use <code>manage.py sqlall</code> to see what SQL statement to execute.)</li> <li>When removing a field, remove it from your model and then execute the appropriate SQL statement to remove the column (e.g., an <code>ALTER TABLE</code> command), and any join tables that were created.</li> <li>Renaming a field is basically a combination of adding/removing fields, as well as copying data.</li> </ul> <p>So to answer your question, in Django's case, no, the ORM will <em>not</em> handle modifications for you -- but they're not that hard to do. See that chapter of the book (linked above) for more info.</p>
4
2009-05-19T21:50:00Z
[ "python", "database", "django", "django-models" ]
python orm
885,172
<p>This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)?</p> <p>So, I start with a basic Phone app Object person: name, address, city, state, zip, phone and I change to Object person: title, name, address, city, state, zip, phone object Object phone: type, phone #</p> <p>Do I manually convert via the db and change the code OR does the ORM middleware make the change? and if so - how?</p>
2
2009-05-19T21:41:11Z
885,513
<p>As of Django 1.02 (and as of the latest run-up to 1.1 in subversion), there is no automatic "schema migration". Your choices are to drop the schema and have Django recreate it (via manage.py syncdb), or alter the schema by hand yourself.</p> <p>There are some tools on the horizon for Django schema migration. (I'm watching <a href="http://south.aeracode.org/" rel="nofollow">South</a>.)</p>
5
2009-05-19T23:19:06Z
[ "python", "database", "django", "django-models" ]
python orm
885,172
<p>This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)?</p> <p>So, I start with a basic Phone app Object person: name, address, city, state, zip, phone and I change to Object person: title, name, address, city, state, zip, phone object Object phone: type, phone #</p> <p>Do I manually convert via the db and change the code OR does the ORM middleware make the change? and if so - how?</p>
2
2009-05-19T21:41:11Z
885,738
<p>We include a 'version' number in the application name.</p> <p>Our directories look like this</p> <pre><code>project settings.py appA_1 __init__.py models.py tests.py appB_1 __init__.py models.py tests.py appB_2 __init__.py models.py tests.py </code></pre> <p>This shows two versions of appB. appB_1 was the original version. When we changed the model, we started by copying the app to create appB_2, and then modified that one.</p> <p>A <code>manage.py syncdb</code> will create the fresh new appB_2. </p> <p>We have to unload and reload the tables by copying from appB_1 to appB_2. Once.</p> <p>Then we can remove appB_1 from the settings.py. Later we can delete the tables from the database.</p>
0
2009-05-20T01:05:59Z
[ "python", "database", "django", "django-models" ]
Problems eagerloading a set of object using SQLAlchemy
885,235
<p>I'm using Turbogears2 and SQLAlchemy to develop a webapp. I have two mapped tables O1 and O2. O2 has a sorted list of O1s in 'ones'. At some point I want to query all O2's and the referenced O1's.</p> <p>Unfortunately the query below fails because table O2 is aliased in the query and the column referenced by the order_by phrase is no longer known.</p> <p>I'd like to know how I can fix this problem while, if possible, staying in the declarative syntax.</p> <pre><code>base = declarative_base() class O1(base): __tablename__ = 'O1' value = Column(Integer) o2_id = Column(Integer, ForeignKey('O1.id')) # The culprit class O2(base): __tablename__ = 'O2' id = Column(Integer, primary_key=True) ones = relation('O1', order_by = ['O1.value']) Session.query(O2).options(eagerload('ones')).all() # Throws an error </code></pre>
2
2009-05-19T21:57:26Z
885,282
<p>Use a lambda of clause elements to achieve late binding of the order by, like this:</p> <pre><code>ones = relation('O1', order_by=lambda:[O1.value]) </code></pre> <p>Or as an another option, make the whole order_by a string, like this:</p> <pre><code>ones = relation('O1', order_by='O1.value, O1.something_else') </code></pre>
3
2009-05-19T22:08:02Z
[ "python", "orm", "sqlalchemy" ]
wxPython dialogs: "Enter" keyboard button would not "ok" the dialog
885,294
<p>I am creating a custom wxPython dialog by subclassing <code>wx.Dialog</code>. When I press Enter while using it, (and while being focused on one of the form elements,) it just takes the focus to the next form element, while I want it to press the ok button.</p> <p>How do I solve this?</p>
2
2009-05-19T22:13:28Z
885,307
<p>That should happen automatically if the button has the <em>wx.ID&#95;OK</em> id. If that's impossible then the <em>wx.StdDialogButtonSizer.SetAffirmativeButton()</em> method could be a solution (using the <em>StdDialogButtonSizer</em> class will help with correct button placement and positioning on the different platforms), and there is also <em>wx.Button.SetDefault()</em>.</p>
5
2009-05-19T22:18:02Z
[ "python", "keyboard", "wxpython" ]
Closing and Opening Frames in wxPython
885,453
<p>I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. </p> <p>The login frame is a subclass of wx.Frame, and basically I just want to close it and open the main frame when it receives confirmation from the server:</p> <pre><code>def handleServerSignon(self, msg): if msg.getCode() == net.message.HANDLE_IN_USE: self.status.SetStatusText('Handle already in use') elif msg.getCode() == net.message.SIGNON_SUCCESSFUL: self.Close() mainWindow = wx.Frame(None, wx.ID_ANY, 'main window', wx.DefaultPosition, \ (640, 480)) mainWindow.Show(True) </code></pre> <p>I can't even get this to give a consistent error message though... sometimes it works, sometimes it crashes with the following:</p> <blockquote> <p>python: ../../src/xcb_io.c:242: process_responses: Assertion `(((long) (dpy->last_request_read) - (long) (dpy->request)) &lt;= 0)' failed.</p> </blockquote> <p>Any help is very much appreciated!</p> <p>Walker</p>
0
2009-05-19T23:02:13Z
885,654
<p>I would make your main frame appear, then show a modal login dialog over top instead.</p> <p>If you don't want to do that, I suggest you create two separate Frames and have your application listen for a close event on the login frame. Handle the login in that event handler, then have it show the main window. Basically, you don't want to be instantiating the main window in your event handler since once you leave the function, scope is lost the the garbage collector will try to remove your frame.</p> <p>Lastly, you should consider calling <code>getCode()</code> once and caching the result for your comparisons. Since your if statement <em>and</em> elif statement both call <code>getCode()</code> it very well may be yielding different results.</p>
1
2009-05-20T00:18:19Z
[ "python", "user-interface", "network-programming", "wxpython" ]
Closing and Opening Frames in wxPython
885,453
<p>I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. </p> <p>The login frame is a subclass of wx.Frame, and basically I just want to close it and open the main frame when it receives confirmation from the server:</p> <pre><code>def handleServerSignon(self, msg): if msg.getCode() == net.message.HANDLE_IN_USE: self.status.SetStatusText('Handle already in use') elif msg.getCode() == net.message.SIGNON_SUCCESSFUL: self.Close() mainWindow = wx.Frame(None, wx.ID_ANY, 'main window', wx.DefaultPosition, \ (640, 480)) mainWindow.Show(True) </code></pre> <p>I can't even get this to give a consistent error message though... sometimes it works, sometimes it crashes with the following:</p> <blockquote> <p>python: ../../src/xcb_io.c:242: process_responses: Assertion `(((long) (dpy->last_request_read) - (long) (dpy->request)) &lt;= 0)' failed.</p> </blockquote> <p>Any help is very much appreciated!</p> <p>Walker</p>
0
2009-05-19T23:02:13Z
889,899
<p><code>mainWindow</code> is a local variable of <code>handleServerSignon</code>. This is a guess, but I think it may be garbage collected as soon as the <code>handleServerSignon</code> method returns.</p>
0
2009-05-20T19:52:13Z
[ "python", "user-interface", "network-programming", "wxpython" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
885,551
<p>This code seems to work:</p> <pre><code>l = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] previous = None # value/repetition pair greatest = (-1, -1) reps = 1 for e in l: if e == previous: reps += 1 else: if reps &gt; greatest[1]: greatest = (previous, reps) previous = e reps = 1 if reps &gt; greatest[1]: greatest = (previous, reps) print greatest </code></pre>
0
2009-05-19T23:30:22Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
885,554
<p>I'd use a hashmap of item to counter.</p> <p>Every time you see a 'key' succession, increment its counter value. If you hit a new element, set the counter to 1 and keep going. At the end of this linear search, you should have the maximum succession count for each number. </p>
0
2009-05-19T23:31:23Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
885,566
<p>Loop through the list, keep track of the current number, how many times it has been repeated, and compare that to the most times youve seen that number repeated.</p> <pre><code>Counts={} Current=0 Current_Count=0 LIST = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] for i in LIST: if Current == i: Current_Count++ else: Current_Count=1 Current=i if Current_Count&gt;Counts[i]: Counts[i]=Current_Count print Counts </code></pre>
3
2009-05-19T23:37:19Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
885,584
<p>Use <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">groupby</a>, it group elements by value:</p> <pre><code>from itertools import groupby group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]) print max(group, key=lambda k: len(list(k[1]))) </code></pre> <p>And here is the code in action:</p> <pre><code>&gt;&gt;&gt; group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]) &gt;&gt;&gt; print max(group, key=lambda k: len(list(k[1]))) (2, &lt;itertools._grouper object at 0xb779f1cc&gt;) &gt;&gt;&gt; group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3]) &gt;&gt;&gt; print max(group, key=lambda k: len(list(k[1]))) (3, &lt;itertools._grouper object at 0xb7df95ec&gt;) </code></pre> <p>From python documentation:</p> <blockquote> <p>The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes</p> </blockquote> <pre><code># [k for k, g in groupby('AAAABBBCCDAABBB')] --&gt; A B C D A B # [list(g) for k, g in groupby('AAAABBBCCD')] --&gt; AAAA BBB CC D </code></pre> <p>If you also want the index of the longest run you can do the following:</p> <pre><code>group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3]) result = [] index = 0 for k, g in group: length = len(list(g)) result.append((k, length, index)) index += length print max(result, key=lambda a:a[1]) </code></pre>
42
2009-05-19T23:43:39Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
885,595
<p>If you want it for just <em>any</em> element (i.e. the element with the most repetitions), you could use:</p> <pre><code>def f((v, l, m), x): nl = l+1 if x==v else 1 return (x, nl, max(m,nl)) maxrep = reduce(f, l, (0,0,0))[2]; </code></pre> <p>This only counts continuous repetitions (Result for <code>[1,2,2,2,1,2]</code> would be <code>3</code>) and only records the element with the the maximum number.</p> <p><strong>Edit</strong>: Made definition of f a bit shorter ...</p>
1
2009-05-19T23:48:49Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
12,696,788
<p>This is my solution:</p> <pre class="lang-py prettyprint-override"><code>def longest_repetition(l): if l == []: return None element = l[0] new = [] lar = [] for e in l: if e == element: new.append(e) else: if len(new) &gt; len(lar): lar = new new = [] new.append(e) element = e if len(new) &gt; len(lar): lar = new return lar[0] </code></pre>
1
2012-10-02T19:17:42Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this but also record the index at which the longest run began?</p>
10
2009-05-19T23:27:17Z
15,770,461
<p>-You can make new copy of the list but with unique values and a corresponding hits list.</p> <p>-Then get the Max of hits list and get from it's index your most repeated item.</p> <pre><code>oldlist = ["A", "B", "E", "C","A", "C","D","A", "E"] newlist=[] hits=[] for i in range(len(oldlist)): if oldlist[i] in newlist: hits[newlist.index(oldlist[i])]+= 1 else: newlist.append(oldlist[i]) hits.append(1); #find the most repeated item temp_max_hits=max(hits) temp_max_hits_index=hits.index(temp_max_hits) print(newlist[temp_max_hits_index]) print(temp_max_hits) </code></pre> <p>But I don't know is this the fastest way to do that or there are faster solution. If you think there are faster or more efficient solution, kindly inform us. </p>
1
2013-04-02T17:31:02Z
[ "python", "list" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle file when the application called for it. The parameters supplied by the user will be used to lookup the needed output.</p> <p>I selected this structure because I have gotten pretty comfortable with dictionaries and pickle files and I see this going out the door with the smallest learning curve on my part. There might be as many as two million keys in the dictionary. I have been satisfied with the performance on my machine with a reasonable subset. I have already thought through about how to break the dictionary apart if I have any performance concerns when the whole thing is put together. I am not really that worried about the amount of disk space on their machine as we are working with terabyte storage values.</p> <p>Having said all of that I have been poking around in the docs and am wondering if I need to invest some time to learn and implement an alternative data storage file. The only reason I can think of is if there is an alternative that could increase the lookup speed by a factor of three to five or more.</p>
0
2009-05-20T00:03:05Z
885,643
<p>Here are three things you can try:</p> <ol> <li>Compress the pickled dictionary with zlib. pickle.dumps(dict).encode("zlib")</li> <li>Make your own serializing format (shouldn't be too hard).</li> <li>Load the data in a sqlite database.</li> </ol>
0
2009-05-20T00:11:09Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle file when the application called for it. The parameters supplied by the user will be used to lookup the needed output.</p> <p>I selected this structure because I have gotten pretty comfortable with dictionaries and pickle files and I see this going out the door with the smallest learning curve on my part. There might be as many as two million keys in the dictionary. I have been satisfied with the performance on my machine with a reasonable subset. I have already thought through about how to break the dictionary apart if I have any performance concerns when the whole thing is put together. I am not really that worried about the amount of disk space on their machine as we are working with terabyte storage values.</p> <p>Having said all of that I have been poking around in the docs and am wondering if I need to invest some time to learn and implement an alternative data storage file. The only reason I can think of is if there is an alternative that could increase the lookup speed by a factor of three to five or more.</p>
0
2009-05-20T00:03:05Z
885,657
<p>To get fast lookups, use the standard Python <code>dbm</code> module (see <a href="http://docs.python.org/library/dbm.html" rel="nofollow">http://docs.python.org/library/dbm.html</a>) to build your database file, and do lookups in it. The dbm file format may not be cross-platform, so you may want to to distrubute your data in Pickle or repr or JSON or YAML or XML format, and build the <code>dbm</code> database the user runs your program.</p>
2
2009-05-20T00:19:02Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle file when the application called for it. The parameters supplied by the user will be used to lookup the needed output.</p> <p>I selected this structure because I have gotten pretty comfortable with dictionaries and pickle files and I see this going out the door with the smallest learning curve on my part. There might be as many as two million keys in the dictionary. I have been satisfied with the performance on my machine with a reasonable subset. I have already thought through about how to break the dictionary apart if I have any performance concerns when the whole thing is put together. I am not really that worried about the amount of disk space on their machine as we are working with terabyte storage values.</p> <p>Having said all of that I have been poking around in the docs and am wondering if I need to invest some time to learn and implement an alternative data storage file. The only reason I can think of is if there is an alternative that could increase the lookup speed by a factor of three to five or more.</p>
0
2009-05-20T00:03:05Z
885,684
<p>The standard <code>shelve</code> module will give you a persistent dictionary that is stored in a dbm style database. Providing that your keys are strings and your values are picklable (since you're using pickle already, this must be true), this could be a better solution that simply storing the entire dictionary in a single pickle.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import shelve &gt;&gt;&gt; d = shelve.open('mydb') &gt;&gt;&gt; d['key1'] = 12345 &gt;&gt;&gt; d['key2'] = value2 &gt;&gt;&gt; print d['key1'] 12345 &gt;&gt;&gt; d.close() </code></pre> <p>I'd also recommend <a href="http://www.mems-exchange.org/software/durus/" rel="nofollow">Durus</a>, but that requires some extra learning on your part. It'll let you create a PersistentDictionary. From memory, keys can be any pickleable object.</p>
6
2009-05-20T00:33:29Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle file when the application called for it. The parameters supplied by the user will be used to lookup the needed output.</p> <p>I selected this structure because I have gotten pretty comfortable with dictionaries and pickle files and I see this going out the door with the smallest learning curve on my part. There might be as many as two million keys in the dictionary. I have been satisfied with the performance on my machine with a reasonable subset. I have already thought through about how to break the dictionary apart if I have any performance concerns when the whole thing is put together. I am not really that worried about the amount of disk space on their machine as we are working with terabyte storage values.</p> <p>Having said all of that I have been poking around in the docs and am wondering if I need to invest some time to learn and implement an alternative data storage file. The only reason I can think of is if there is an alternative that could increase the lookup speed by a factor of three to five or more.</p>
0
2009-05-20T00:03:05Z
885,813
<p>How much memory can your application reasonably use? Is this going to be running on each user's desktop, or will there just be one deployment somewhere?</p> <p>A python dictionary in memory can certainly cope with two million keys. You say that you've got a subset of the data; do you have the whole lot? Maybe you should throw the full dataset at it and see whether it copes.</p> <p>I just tested creating a two million record dictionary; the total memory usage for the process came in at about 200MB. If speed is your primary concern and you've got the RAM to spare, you're probably not going to do better than an in-memory python dictionary.</p>
2
2009-05-20T01:46:25Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle file when the application called for it. The parameters supplied by the user will be used to lookup the needed output.</p> <p>I selected this structure because I have gotten pretty comfortable with dictionaries and pickle files and I see this going out the door with the smallest learning curve on my part. There might be as many as two million keys in the dictionary. I have been satisfied with the performance on my machine with a reasonable subset. I have already thought through about how to break the dictionary apart if I have any performance concerns when the whole thing is put together. I am not really that worried about the amount of disk space on their machine as we are working with terabyte storage values.</p> <p>Having said all of that I have been poking around in the docs and am wondering if I need to invest some time to learn and implement an alternative data storage file. The only reason I can think of is if there is an alternative that could increase the lookup speed by a factor of three to five or more.</p>
0
2009-05-20T00:03:05Z
1,416,881
<p>See this solution at SourceForge, esp. the "endnotes" documentation:</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>
1
2009-09-13T04:52:36Z
[ "python", "database", "dictionary" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference </code></pre> <p>In the python CLI, a dir(answers) gives me:</p> <pre>['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset']</pre> <p>Two things are confusing to me (which are related): <li> Iteration over the answers object. What is rdata in the example?</li> <li> None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from.</li></p>
2
2009-05-20T00:07:31Z
885,640
<p>In the example code, <code>answers</code> is an iterable object containing zero or more items, which are each assigned to <code>rdata</code> in turn. To see the properties of the individual responses, try:</p> <pre><code>dir(answers[0]) </code></pre>
1
2009-05-20T00:10:38Z
[ "python", "dns", "dnspython" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference </code></pre> <p>In the python CLI, a dir(answers) gives me:</p> <pre>['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset']</pre> <p>Two things are confusing to me (which are related): <li> Iteration over the answers object. What is rdata in the example?</li> <li> None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from.</li></p>
2
2009-05-20T00:07:31Z
885,648
<p>answers is an iterable as indicated by its "__iter__" method. Think of answers as a list of rdatas.</p> <p>You can try doing this to get 1 rdata from answers:</p> <pre><code>answers.__iter__().next() </code></pre>
1
2009-05-20T00:14:56Z
[ "python", "dns", "dnspython" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference </code></pre> <p>In the python CLI, a dir(answers) gives me:</p> <pre>['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset']</pre> <p>Two things are confusing to me (which are related): <li> Iteration over the answers object. What is rdata in the example?</li> <li> None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from.</li></p>
2
2009-05-20T00:07:31Z
885,796
<p>If you're on Python 2.6, the "proper" way to get the first item of any iterable (such as <code>answers</code> here) is <code>next(iter(answers))</code>; if you want to avoid an exception when <code>answers</code> is an empty iterable, then <code>next(iter(answers), somevalue)</code> will return <code>somevalue</code> instead of raising <code>StopIteration</code>. If you're on 2.5, then <code>iter(answers).next()</code>, but you'll have to use it inside a <code>try/except StopIteration:</code> statement if you need to deal with a possible empty iterable.</p>
0
2009-05-20T01:38:01Z
[ "python", "dns", "dnspython" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference </code></pre> <p>In the python CLI, a dir(answers) gives me:</p> <pre>['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset']</pre> <p>Two things are confusing to me (which are related): <li> Iteration over the answers object. What is rdata in the example?</li> <li> None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from.</li></p>
2
2009-05-20T00:07:31Z
886,171
<p>I haven't looked at <code>dns.resolver</code> as of yet - I just added it to the ever-growing list of things to check out. I would guess that <code>rdata</code> refers to the resource record type specific data as described in <a href="http://tools.ietf.org/html/rfc1035#section-4.1.3" rel="nofollow">Section 4.1.3 of RFC1035</a>. The response of a DNS request contains three data sections in addition to the query and headers:</p> <ol> <li>Answers</li> <li>Authoritative Name Server records</li> <li>Additional Resource records</li> </ol> <p>From the looks of it <code>dns.resolver.query()</code> is returning the first section. In this case, each resource record in the answer section is going to have different attributes based on the record type. In this case, you asked for <code>MX</code> records so the records should have exactly the attributes that you have - <code>exchange</code> and <code>preference</code>. These are described in <a href="http://tools.ietf.org/html/rfc1035#section-3.3.9" rel="nofollow">Section 3.3.9 of RFC1035</a>.</p> <p>I suspect that <code>dns.resolver</code> is overriding <code>__getattr__</code> or something similar to perform the magic that you are seeing so you won't see the fields directly in a <code>dir()</code>. Chances are that you are safe using the attributes as defined in RFC1035. I will definitely have to check this out tomorrow since I have need of a decent DNS subsystem for Python.</p> <p>Thanks for mentioning this module and have fun with DNS. It is really pretty interesting stuff if you really dig into how it works. I still think that it is one of the earlier expressions of that ReSTful thing that is all the rage these days ;)</p>
1
2009-05-20T04:45:08Z
[ "python", "dns", "dnspython" ]
How does MySQL's RENAME TABLE statment work/perform?
885,771
<p>MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. </p> <p>The manual mentions </p> <blockquote> <p>The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running</p> </blockquote> <p>The manual does not (to my knowedge) state how this renaming is accomplished. Is an entire copy of the table created, given a new name, and then the old table deleted? Or does MySQL do some magic behind the scenes to quickly rename the table?</p> <p>In other words, does the size of the table have an effect on how long the RENAME table statement will take to run. Are there other things that might cause the renaming of a block to significantly block? </p>
3
2009-05-20T01:22:36Z
885,783
<p>I believe MySQL only needs to alter metadata and references to the table's old name in stored procedures -- the number of records in the table should be irrelevant.</p>
5
2009-05-20T01:29:27Z
[ "php", "python", "mysql", "ruby", "migration" ]
How does MySQL's RENAME TABLE statment work/perform?
885,771
<p>MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. </p> <p>The manual mentions </p> <blockquote> <p>The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running</p> </blockquote> <p>The manual does not (to my knowedge) state how this renaming is accomplished. Is an entire copy of the table created, given a new name, and then the old table deleted? Or does MySQL do some magic behind the scenes to quickly rename the table?</p> <p>In other words, does the size of the table have an effect on how long the RENAME table statement will take to run. Are there other things that might cause the renaming of a block to significantly block? </p>
3
2009-05-20T01:22:36Z
885,848
<p>In addition to altering the metadata, it also renames the associated .FRM file. While they can claim it being an "atomic" operation, this is an actual comment in the code for the mysql_rename_tables function...</p> <pre><code>/* Lets hope this doesn't fail as the result will be messy */ </code></pre> <p>=)</p>
1
2009-05-20T02:03:22Z
[ "php", "python", "mysql", "ruby", "migration" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;/links&gt; </code></pre> <p>My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1:</p> <pre><code>link_id = r'id="1"' parameter = 'mode' link_regex = '&lt;link [\w\W]+ %s&gt;[\w\W]*[\w\W]*&lt;%s&gt;([\w\W]*)&lt;/%s&gt;[\w\W]*&lt;/link&gt;' \ % (link_id, parameter, parameter) </code></pre> <p>Thus,</p> <pre><code>print re.search(final_regex, f_read).group(1) </code></pre> <p>prints ipsec</p> <p>The examples in the <a href="http://docs.python.org/howto/regex.html" rel="nofollow">regex howto</a> all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).</p>
0
2009-05-20T04:20:04Z
886,129
<p>not sure i'd do it that way, but the quickest way would be to shift the captures:</p> <p>([\w\W]<em>[\w\W]</em>&lt;%s>)[\w\W]<em>([\w\W]</em>)' and replace with group1 +mode+group2</p>
0
2009-05-20T04:30:00Z
[ "python", "regex", "groups" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;/links&gt; </code></pre> <p>My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1:</p> <pre><code>link_id = r'id="1"' parameter = 'mode' link_regex = '&lt;link [\w\W]+ %s&gt;[\w\W]*[\w\W]*&lt;%s&gt;([\w\W]*)&lt;/%s&gt;[\w\W]*&lt;/link&gt;' \ % (link_id, parameter, parameter) </code></pre> <p>Thus,</p> <pre><code>print re.search(final_regex, f_read).group(1) </code></pre> <p>prints ipsec</p> <p>The examples in the <a href="http://docs.python.org/howto/regex.html" rel="nofollow">regex howto</a> all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).</p>
0
2009-05-20T04:20:04Z
886,175
<p>Supposing that your link_regex is correct, you can add parenthesis like this:</p> <pre><code>(&lt;link [\w\W]+ %s&gt;[\w\W]*[\w\W]*&lt;%s&gt;)([\w\W]*)(&lt;/%s&gt;[\w\W]*&lt;/link&gt;) </code></pre> <p>and then you could do:</p> <pre><code>p = re.compile(link_regex) replacement = 'foo' print p.sub(r'\g&lt;1&gt;' + replacement + r'\g&lt;3&gt;' , f_read) </code></pre>
1
2009-05-20T04:47:16Z
[ "python", "regex", "groups" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;/links&gt; </code></pre> <p>My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1:</p> <pre><code>link_id = r'id="1"' parameter = 'mode' link_regex = '&lt;link [\w\W]+ %s&gt;[\w\W]*[\w\W]*&lt;%s&gt;([\w\W]*)&lt;/%s&gt;[\w\W]*&lt;/link&gt;' \ % (link_id, parameter, parameter) </code></pre> <p>Thus,</p> <pre><code>print re.search(final_regex, f_read).group(1) </code></pre> <p>prints ipsec</p> <p>The examples in the <a href="http://docs.python.org/howto/regex.html" rel="nofollow">regex howto</a> all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).</p>
0
2009-05-20T04:20:04Z
886,195
<p>I have to give you the obligatory: "don't use regular expressions to do this."</p> <p>Check out how very easily awesome it is to do this with <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML" rel="nofollow">BeautifulSoup</a>, for example:</p> <pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulStoneSoup &gt;&gt;&gt; html = """ ... &lt;config&gt; ... &lt;links&gt; ... &lt;link name="Link1" id="1"&gt; ... &lt;encapsulation&gt; ... &lt;mode&gt;ipsec&lt;/mode&gt; ... &lt;/encapsulation&gt; ... &lt;/link&gt; ... &lt;link name="Link2" id="2"&gt; ... &lt;encapsulation&gt; ... &lt;mode&gt;udp&lt;/mode&gt; ... &lt;/encapsulation&gt; ... &lt;/link&gt; ... &lt;/links&gt; ... &lt;/config&gt; ... """ &gt;&gt;&gt; soup = BeautifulStoneSoup(html) &gt;&gt;&gt; soup.find('link', id=1) &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &gt;&gt;&gt; soup.find('link', id=1).mode.contents[0].replaceWith('whatever') &gt;&gt;&gt; soup.find('link', id=1) &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;whatever&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; </code></pre> <p>Looking at your regular expression I can't really tell if this is exactly what you wanted to do, but whatever it is you want to do, using a library like BeautifulSoup is much, much, better than trying to patch a regular expression together. I highly recommend going this route if possible.</p>
6
2009-05-20T04:58:12Z
[ "python", "regex", "groups" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;/links&gt; </code></pre> <p>My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1:</p> <pre><code>link_id = r'id="1"' parameter = 'mode' link_regex = '&lt;link [\w\W]+ %s&gt;[\w\W]*[\w\W]*&lt;%s&gt;([\w\W]*)&lt;/%s&gt;[\w\W]*&lt;/link&gt;' \ % (link_id, parameter, parameter) </code></pre> <p>Thus,</p> <pre><code>print re.search(final_regex, f_read).group(1) </code></pre> <p>prints ipsec</p> <p>The examples in the <a href="http://docs.python.org/howto/regex.html" rel="nofollow">regex howto</a> all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).</p>
0
2009-05-20T04:20:04Z
886,273
<p>This looks like valid XML, in that case you don't need BeautifulSoup, definitely not the regex, just load XML using any good XML library, edit it and print it out, here is a approach using ElementTree:</p> <pre><code>import xml.etree.cElementTree as ET s = """&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;/links&gt; &lt;/config&gt; """ configElement = ET.fromstring(s) for modeElement in configElement.findall("*/*/*/mode"): modeElement.text = "udp" print ET.tostring(configElement) </code></pre> <p>It will change all mode elements to <code>udp</code>, this is the output:</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link id="1" name="Link1"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link id="2" name="Link2"&gt; &lt;encapsulation&gt; &lt;mode&gt;udp&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;/links&gt; &lt;/config&gt; </code></pre>
2
2009-05-20T05:23:36Z
[ "python", "regex", "groups" ]
What is "wua" mode when opening a file in python?
886,238
<p>I have recently been going through some of our windows python 2.4 code and come across this:</p> <pre><code>self.logfile = open(self.logfile_name, "wua") </code></pre> <p>I know what <code>w</code>, <code>u</code> and <code>a</code> do on their own, but what happens when you combine them?</p>
4
2009-05-20T05:13:13Z
886,274
<p>The <code>a</code> is superfluous. <code>wua</code> is the same as <code>wu</code> since <code>w</code> comes first and will thus truncate the file. If you would reverse the order, that is, <code>auw</code>, that would be the same as <code>au</code>. Visualized:</p> <pre><code>&gt;&gt;&gt; f = open('test.txt', 'r') &gt;&gt;&gt; f.read() 'Initial contents\n' &gt;&gt;&gt; f.close() &gt;&gt;&gt; f = open('test.txt', 'wua') &gt;&gt;&gt; print &gt;&gt; f, 'writing' &gt;&gt;&gt; f.close() &gt;&gt;&gt; f = open('test.txt', 'r') &gt;&gt;&gt; f.read() 'writing\n' &gt;&gt;&gt; f.close() &gt;&gt;&gt; f = open('test.txt', 'auw') &gt;&gt;&gt; print &gt;&gt; f, 'appending' &gt;&gt;&gt; f.close() &gt;&gt;&gt; f = open('test.txt', 'r') &gt;&gt;&gt; f.read() 'writing\nappending\n' &gt;&gt;&gt; f.close() </code></pre> <p>(Reminder: both <code>a</code> and <code>w</code> <a href="http://docs.python.org/3.0/library/functions.html#open" rel="nofollow">open the file for writing</a>, but the former appends while the other truncates.)</p>
5
2009-05-20T05:24:07Z
[ "python", "file" ]
What is "wua" mode when opening a file in python?
886,238
<p>I have recently been going through some of our windows python 2.4 code and come across this:</p> <pre><code>self.logfile = open(self.logfile_name, "wua") </code></pre> <p>I know what <code>w</code>, <code>u</code> and <code>a</code> do on their own, but what happens when you combine them?</p>
4
2009-05-20T05:13:13Z
886,280
<p>I did not notice that you knew what the modifiers did. Combined they will do the following:</p> <p>A and W together is superfluous since both will open for writing. When using W, the file will be overwritten. When using A, all new text is appended after the existing content.</p> <p>U means "open file XXX for input as a text file with universal newline interpretation".</p> <ul> <li>W is for Write</li> <li>A is for Append</li> <li>U will convert the file to use the defined newline character.</li> </ul> <p>More here: <a href="http://codesnippets.joyent.com/posts/show/1969" rel="nofollow">http://codesnippets.joyent.com/posts/show/1969</a></p>
3
2009-05-20T05:24:55Z
[ "python", "file" ]
What is "wua" mode when opening a file in python?
886,238
<p>I have recently been going through some of our windows python 2.4 code and come across this:</p> <pre><code>self.logfile = open(self.logfile_name, "wua") </code></pre> <p>I know what <code>w</code>, <code>u</code> and <code>a</code> do on their own, but what happens when you combine them?</p>
4
2009-05-20T05:13:13Z
890,542
<p>Underneath the hood Python 2.4 passes the the builtin <code>open</code>'s arguments on to the operating system's <code>fopen</code> function. Python does do some mangling of the mode string under certain conditions.</p> <pre><code>if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0) mode = "rb"; </code></pre> <p>So if you pass an upper case <code>U</code> or <code>rU</code> it will open the file for binary reading. Looking at the GNU libc source and according to the MSDN page describing the windows implementation of <code>fopen</code> the '<code>u</code>' option is ignored.</p> <p>Having more than one mode designator ('<code>r</code>', '<code>w</code>' and '<code>a</code>') in the mode string has no effect. This can be seen by looking at the GNU libc implementation of mode string parsing:</p> <pre><code>switch (*mode) { case 'r': omode = O_RDONLY; break; case 'w': omode = O_WRONLY; oflags = O_CREAT|O_TRUNC; break; case 'a': omode = O_WRONLY; oflags = O_CREAT|O_APPEND; break; default: __set_errno (EINVAL); return NULL; } </code></pre> <p>The first character of the mode string is searched for one of '<code>r</code>', '<code>w</code>' or '<code>a</code>', if it's not one of these characters an error is raised.</p> <p>Therefore when a file is opened as "<code>wua</code>" it will be opened for writing only, created if it doesn't exist and truncated. '<code>u</code>' and '<code>a</code>' will be ignored.</p>
1
2009-05-20T22:17:53Z
[ "python", "file" ]
Beautiful Soup and uTidy
886,381
<p>I want to pass the results of <a href="http://utidylib.berlios.de/" rel="nofollow">utidy</a> to Beautiful Soup, ala:</p> <pre><code>page = urllib2.urlopen(url) options = dict(output_xhtml=1,add_xml_decl=0,indent=1,tidy_mark=0) cleaned_html = tidy.parseString(page.read(), **options) soup = BeautifulSoup(cleaned_html) </code></pre> <p>When run, the following error results:</p> <pre><code>Traceback (most recent call last): File "soup.py", line 34, in &lt;module&gt; soup = BeautifulSoup(cleaned_html) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1499, in __init__ BeautifulStoneSoup.__init__(self, *args, **kwargs) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1230, in __init__ self._feed(isHTML=isHTML) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1245, in _feed smartQuotesTo=self.smartQuotesTo, isHTML=isHTML) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1751, in __init__ self._detectEncoding(markup, isHTML) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1899, in _detectEncoding xml_encoding_match = re.compile(xml_encoding_re).match(xml_data) TypeError: expected string or buffer </code></pre> <p>I gather utidy returns an XML document while BeautifulSoup wants a string. Is there a way to cast cleaned_html? Or am I doing it wrong and should take a different approach?</p>
3
2009-05-20T06:05:38Z
886,400
<p>Just wrap <a href="http://docs.python.org/library/functions.html#str"><code>str()</code></a> around <code>cleaned_html</code> when passing it to BeautifulSoup. </p>
9
2009-05-20T06:11:05Z
[ "python", "screen-scraping", "beautifulsoup", "tidy" ]
Beautiful Soup and uTidy
886,381
<p>I want to pass the results of <a href="http://utidylib.berlios.de/" rel="nofollow">utidy</a> to Beautiful Soup, ala:</p> <pre><code>page = urllib2.urlopen(url) options = dict(output_xhtml=1,add_xml_decl=0,indent=1,tidy_mark=0) cleaned_html = tidy.parseString(page.read(), **options) soup = BeautifulSoup(cleaned_html) </code></pre> <p>When run, the following error results:</p> <pre><code>Traceback (most recent call last): File "soup.py", line 34, in &lt;module&gt; soup = BeautifulSoup(cleaned_html) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1499, in __init__ BeautifulStoneSoup.__init__(self, *args, **kwargs) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1230, in __init__ self._feed(isHTML=isHTML) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1245, in _feed smartQuotesTo=self.smartQuotesTo, isHTML=isHTML) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1751, in __init__ self._detectEncoding(markup, isHTML) File "/var/lib/python-support/python2.6/BeautifulSoup.py", line 1899, in _detectEncoding xml_encoding_match = re.compile(xml_encoding_re).match(xml_data) TypeError: expected string or buffer </code></pre> <p>I gather utidy returns an XML document while BeautifulSoup wants a string. Is there a way to cast cleaned_html? Or am I doing it wrong and should take a different approach?</p>
3
2009-05-20T06:05:38Z
32,613,070
<p>Convert the value passed to BeautifulSoup into a string. In your case, do the following edit to the last line:</p> <pre><code>soup = BeautifulSoup(str(cleaned_html)) </code></pre>
2
2015-09-16T15:39:29Z
[ "python", "screen-scraping", "beautifulsoup", "tidy" ]
Django without shell access
886,526
<p>Is it possible to run django without shell access? My hoster supports the following for 5€/month:</p> <ul> <li>python (I assume via mod_python)</li> <li>mysql </li> </ul> <p>There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it.</p> <p>I know that Google Apps also work without shell access, but I assume that is possible because of their special configuration.</p>
0
2009-05-20T07:07:41Z
886,561
<p>It is possible.</p> <p>Usually you will develop your application locally (where shell access is nice to have) and publish your work to your server. All you need for this is FTP access and some way to import a database dump from your development database (often hosters provide an installation of phpMyAdmin for this).</p> <blockquote> <p>python (I assume via mod_python)</p> </blockquote> <p>From my experience, you are most certainly wrong with that assumption. Many low-cost providers claim to support python but in fact provide only an outdated version that can be used with CGI scripts. This setup will have a pretty low performance for Django apps.</p>
1
2009-05-20T07:17:38Z
[ "python", "django", "shell" ]
Django without shell access
886,526
<p>Is it possible to run django without shell access? My hoster supports the following for 5€/month:</p> <ul> <li>python (I assume via mod_python)</li> <li>mysql </li> </ul> <p>There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it.</p> <p>I know that Google Apps also work without shell access, but I assume that is possible because of their special configuration.</p>
0
2009-05-20T07:07:41Z
886,581
<p>It's possible but not desirable. Having shell access makes it possible to centralise things properly using symlinks. </p> <p>Get a better host would be my first suggestion. <a href="http://www.webfaction.com/" rel="nofollow">WebFaction</a> is the most recommended shared host for using with Django.</p> <p>If that's out of your price range, there are plenty of hosts that give you a proper system account (vs just a ftp account) and have <code>mod_python</code> or <code>mod_wsgi</code> (preferred now).</p> <p>Google Apps works without shell because their system looks for a dispatcher script that you have to write to an exact specification.</p>
4
2009-05-20T07:22:44Z
[ "python", "django", "shell" ]
How to perform a query in django that selects all projects where I am a team member of?
886,624
<p>I have the concept of a team in my django app.</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=200) #snip team_members = models.ManyToManyField(User) </code></pre> <p>I would like to fetch all teams the currently logged in user is member of. Something along the lines of </p> <pre><code>Team.objects.all().filter(request.user.id__in = team_members.all()) </code></pre> <p>This obvious doesn't work. Does anyone have some suggestions on how to do such query without going directly to sql? I did look at <a href="http://docs.djangoproject.com/en/1.0/ref/models/querysets/" rel="nofollow">the django documentation</a> of "in" queries, but I couldn't find my use case there.</p> <p>Many thanks! Nick.</p>
0
2009-05-20T07:33:36Z
886,891
<p>You don't need <code>in</code> here, Django handles that automatically in a ManyToMany lookup.</p> <p>Also, you need to understand that the database fields must always be on the <em>left</em> of the lookup, as they are actually handled as parameters to a function.</p> <p>What you actually want is very simple:</p> <pre><code>Team.objects.filter(team_members=request.user) </code></pre> <p>or</p> <pre><code>request.user.team_set.all() </code></pre>
4
2009-05-20T08:48:11Z
[ "python", "django", "pinax" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,643
<p>counter += 1</p> <p>but that isn't the problem. What's the error? Indentation error maybe?</p>
1
2009-05-20T07:40:27Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,644
<p>The error you're seeing is because you're indexing out of range on the <code>str_date_list</code> list, not because you're incrementing the variable.</p> <p>Compare the largest value of <code>counter</code> that the loop prints (<code>30</code>) to the length of the list (<code>len(str_date_list)</code>). Since indexing starts at <code>0</code>, the largest index into a list of length n is <code>n - 1</code>.</p>
2
2009-05-20T07:40:51Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,670
<p>You don't need to duplicate the loop iteration variable and the counter:</p> <pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') for i in xrange(len(my_date_list)-1): daily_user_status_list=[] print i val_time1 = str_date_list[i] val_time2 = str_date_list[i + 1] </code></pre>
2
2009-05-20T07:52:14Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,694
<ol> <li><p>you do not need to create a iterator for going thru 0-31 you can use enumerate e.g.</p> <p>for i, sdate in enumerate(str_date_list): print i, sdate</p></li> <li><p>if you are using iter isn't item and counter same?</p></li> </ol>
2
2009-05-20T07:58:42Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,787
<p>Better written:</p> <pre><code>str_date_list=[] for n in xrange(1,32): str_date_list.append(str(n).zfill(2)+'-'+'05' + '-' +'09') for i in xrange(len(str_date_list)): daily_user_status_list=[] print i val_time1 = str_date_list[i] val_time2 = str_date_list[i + 1] </code></pre> <ul> <li>xrange gives us a (quite performing) iterator over natural numbers given bounds.</li> <li>we use zfill to make sure there is a leading zero instead of writing them all explicitly</li> <li>it's important to avoid iterating out of the array bounds!</li> </ul>
0
2009-05-20T08:20:00Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,879
<p>The counter is getting out of step with the sequences you're iterating over. But more than that, the counter is totally unnecessary.</p> <p>You've got several manual iterations of things that could be automated, and they're causing you to trip over. Especially, you hardly ever need to manually track a counter while iterating; Python's sequence types know how to iterate themselves.</p> <p>Here's my re-write of the intent of the above code (in the interactive interpreter to show it working):</p> <pre><code>&gt;&gt;&gt; dates = ["%(day)02d-05-09" % vars() for day in range(1, 31+1)] &gt;&gt;&gt; date_ranges = zip(dates[:-1], dates[1:]) &gt;&gt;&gt; for (date_begin, date_end) in date_ranges: ... print (date_begin, date_end) ... ('01-05-09', '02-05-09') ('02-05-09', '03-05-09') ('03-05-09', '04-05-09') … ('28-05-09', '29-05-09') ('29-05-09', '30-05-09') ('30-05-09', '31-05-09') </code></pre>
8
2009-05-20T08:44:37Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 </code></pre> <p>I am getting code error while doing counter = counter + 1 Basically I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it.</p> <p>Thanks</p>
1
2009-05-20T07:36:04Z
886,882
<p>Just for kicks, here's the super-compact Pythonic way to write this:</p> <pre><code>from itertools import izip, islice str_date_list = ['%02d-05-09' % i for i in xrange(1, 32)] for val_time1, val_time2 in izip(islice(str_date_list, 0, None), islice(str_date_list, 1, None)): daily_user_status_list = [ &lt;whatever goes here&gt; ] # more code... </code></pre>
4
2009-05-20T08:45:17Z
[ "python", "iterator" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,672
<p>You appear to be asking for the sum of the differences between the paired components of the two arrays:</p> <pre><code>&gt;&gt;&gt; A=[1,2,3,4] &gt;&gt;&gt; B=[2,3,4,5] &gt;&gt;&gt; sum(abs(a - b) for a, b in zip(A, B)) 4 </code></pre>
6
2009-05-20T07:52:53Z
[ "python", "vector", "norm" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,675
<p>It is not clear what exactly is required here, but here is my guess</p> <pre><code>a=[1,2,3,4] b=[2,3,4,5] def a_b(a,b): return sum(map(lambda a:abs(a[0]-a[1]), zip(a,b))) print a_b(a,b) </code></pre>
2
2009-05-20T07:54:17Z
[ "python", "vector", "norm" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,762
<p>Python has powerful built-in types, but <strong>Python lists are not mathematical vectors or matrices</strong>. You <em>could</em> do this with lists, but it will likely be cumbersome for anything more than trivial operations.</p> <p>If you find yourself needing vector or matrix arithmetic often, the <strong>standard in the field is <a href="http://scipy.org/NumPy/">NumPy</a></strong>, which probably already comes packaged for your operating system the way Python also was.</p> <p>I share the confusion of others about exactly what it is you're trying to do, but perhaps the <strong>numpy.linalg.norm</strong> function will help:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array([1, 2, 3, 4]) &gt;&gt;&gt; b = numpy.array([2, 3, 4, 5]) &gt;&gt;&gt; numpy.linalg.norm((a - b), ord=1) 4 </code></pre> <p>To show how that's working under the covers:</p> <pre><code>&gt;&gt;&gt; a array([1, 2, 3, 4]) &gt;&gt;&gt; b array([2, 3, 4, 5]) &gt;&gt;&gt; (a - b) array([-1, -1, -1, -1]) &gt;&gt;&gt; numpy.linalg.norm((a - b)) 2.0 &gt;&gt;&gt; numpy.linalg.norm((a - b), ord=1) 4 </code></pre>
15
2009-05-20T08:15:52Z
[ "python", "vector", "norm" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,791
<p>In NumPy, for two vectors <code>a</code> and <code>b</code>, this is just</p> <pre><code>numpy.linalg.norm(a - b, ord=1) </code></pre>
8
2009-05-20T08:20:33Z
[ "python", "vector", "norm" ]
Making a python cgi script to finish gracefully
886,653
<p>I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and as a result no cleanup code gets executed. How can i force the script to always finish.</p>
2
2009-05-20T07:44:14Z
886,671
<p>You can trap the exit signal with the <strong>signal</strong> module. Haven't tried this with mod_python though.</p> <p><a href="http://docs.python.org/library/signal.html" rel="nofollow">http://docs.python.org/library/signal.html</a></p> <p>Note in the docs:</p> <blockquote> <p>When a signal arrives during an I/O operation, it is possible that the I/O operation raises an exception after the signal handler returns. This is dependent on the underlying Unix system’s semantics regarding interrupted system calls.</p> </blockquote> <p>You may need to catch I/O exceptions for the broken pipe and/or file write if you don't sys.exit from your handler.</p>
1
2009-05-20T07:52:44Z
[ "python", "cgi" ]
Making a python cgi script to finish gracefully
886,653
<p>I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and as a result no cleanup code gets executed. How can i force the script to always finish.</p>
2
2009-05-20T07:44:14Z
886,956
<p>The script is probably not killed silently; you just don't see the exception which python throws. I suggest to wrap the whole script in <code>try-except</code> and write any exception to a log file.</p> <p>This way, you can see what really happens. The <code>logging</code> module is your friend.</p>
1
2009-05-20T09:08:04Z
[ "python", "cgi" ]
Making a python cgi script to finish gracefully
886,653
<p>I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and as a result no cleanup code gets executed. How can i force the script to always finish.</p>
2
2009-05-20T07:44:14Z
887,004
<p>You may be able to use the atexit module.</p> <p><a href="http://docs.python.org/library/atexit.html" rel="nofollow">http://docs.python.org/library/atexit.html</a></p> <p>From the documentation:</p> <blockquote> <p>The atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.</p> <p>Note: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.</p> <p>This is an alternate interface to the functionality provided by the sys.exitfunc variable.</p> </blockquote>
0
2009-05-20T09:18:45Z
[ "python", "cgi" ]
Controling bars width in matplotlib with per-month data
886,716
<p>When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month.</p> <p>I tried to set the minor ticks locator to MonthLocator() without effect.</p> <p><strong>[edit]</strong></p> <p>Maybe an example will be more explicit, here is an <code>ipython -pylab</code> example of what I mean :</p> <pre><code>x = [datetime.datetime(2008, 1, 1, 0, 0), datetime.datetime(2008, 2, 1, 0, 0), datetime.datetime(2008, 3, 1, 0, 0), datetime.datetime(2008, 4, 1, 0, 0), datetime.datetime(2008, 5, 1, 0, 0), datetime.datetime(2008, 6, 1, 0, 0), datetime.datetime(2008, 7, 1, 0, 0), datetime.datetime(2008, 8, 1, 0, 0), datetime.datetime(2008, 9, 1, 0, 0), datetime.datetime(2008, 10, 1, 0, 0), datetime.datetime(2008, 11, 1, 0, 0), datetime.datetime(2008, 12, 1, 0, 0)] y = cos(numpy.arange(12) * 2) bar(x, y) </code></pre> <p>This gives 12 2 pixels wide bars, I would like them to be wider and extend from month to month.</p>
6
2009-05-20T08:03:25Z
888,141
<p>Just use the <code>width</code> keyword argument:</p> <pre><code>bar(x, y, width=30) </code></pre> <p>Or, since different months have different numbers of days, to make it look good you can use a sequence:</p> <pre><code>bar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30]) </code></pre>
12
2009-05-20T14:10:31Z
[ "python", "matplotlib" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch of an untrusted script. (Too expensive.)</p> <p>I wonder if it's possible to restrict Python from accessing the file system and interacting with other programs and so on.</p>
2
2009-05-20T08:50:11Z
886,914
<p>Try searching for "sandboxing python", e.g.:</p> <p><a href="http://wiki.python.org/moin/SandboxedPython" rel="nofollow">http://wiki.python.org/moin/SandboxedPython</a></p> <p><a href="http://wiki.python.org/moin/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29" rel="nofollow">http://wiki.python.org/moin/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20(i.e.%20Sandbox)</a></p>
1
2009-05-20T08:54:45Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch of an untrusted script. (Too expensive.)</p> <p>I wonder if it's possible to restrict Python from accessing the file system and interacting with other programs and so on.</p>
2
2009-05-20T08:50:11Z
886,945
<p>Consider using a chroot jail. Not only is this very secure, well-supported and tested but it also applies to external applications you run from python.</p>
4
2009-05-20T09:05:05Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch of an untrusted script. (Too expensive.)</p> <p>I wonder if it's possible to restrict Python from accessing the file system and interacting with other programs and so on.</p>
2
2009-05-20T08:50:11Z
887,091
<p>You could run jython and use the sandboxing mechanism from the JVM. The sandboxing in the JVM is very strong very well understood and more or less well documented. It will take some time to define exactly what you want to allow and what you dnt want to allow, but you should be able to get a very strong security from that ...</p> <p>On the other side, jython is not 100% compatible with cPython ...</p>
2
2009-05-20T09:44:35Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch of an untrusted script. (Too expensive.)</p> <p>I wonder if it's possible to restrict Python from accessing the file system and interacting with other programs and so on.</p>
2
2009-05-20T08:50:11Z
887,104
<p>There are 4 things you may try:</p> <ul> <li>As you already mentioned, using a virtual machine or some other form of virtualisation (perhaps solaris zones are lightweight enough?). If the script breaks the OS there then you don't care.</li> <li>Using chroot, which puts a shell session into a virtual root directory, separate from the main OS root directory.</li> <li>Using systrace. Think of this as a firewall for system calls.</li> <li>Using a "jail", which builds upon systrace, giving each jail it's own process table etc.</li> </ul> <p>Systrace has been compromised recently, so be aware of that.</p>
4
2009-05-20T09:48:15Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch of an untrusted script. (Too expensive.)</p> <p>I wonder if it's possible to restrict Python from accessing the file system and interacting with other programs and so on.</p>
2
2009-05-20T08:50:11Z
5,289,924
<p>could you not just run as a user which has no access to anything but the scripts in that directory?</p>
1
2011-03-13T14:18:06Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
887,405
<p>I don't know much about this package <a href="http://code.astraw.com/projects/motmot/" rel="nofollow">Motmot</a> or how it compares to OpenCV, but I have imported and used a class or two from it. Much of the image processing is done via numpy arrays and might be similar enough to how you've used Matlab to meet your needs.</p>
0
2009-05-20T11:33:41Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
889,535
<p>You probably would be well served by <a href="http://www.scipy.org/" rel="nofollow">SciPy</a>. Here is the <a href="http://www.scipy.org/Getting%5FStarted" rel="nofollow">introductory tutorial</a> for SciPy. It has a lot of similarities to Matlab. Especially the included matplotlib package, which is explicitly made to emulate the Matlab plotting functions. I don't believe SciPy has equivalents for the functions you mentioned. There are some things which are similar. For example, <a href="http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stsci.image.threshhold.html#scipy.stsci.image.threshhold" rel="nofollow">threshold</a> is a very simple version of graythresh. It doesn't implement "Otsu's" method, it just does a simple threshold, but that might be close enough.</p> <p>I'm sorry that I don't know of any tutorials which are closer to the task you described. But if you are accustomed to Matlab, and you want to do this in Python, <a href="http://www.scipy.org/" rel="nofollow">SciPy</a> is a good starting point.</p>
2
2009-05-20T18:39:16Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
930,145
<p>I've acquired image from FW camera using .NET and IronPython. On CPython I would checkout ctypes library, unless you find any library support for grabbing.</p>
0
2009-05-30T17:20:31Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
930,299
<p>documentation: A few years ago I used OpenCV wrapped for Python quite a lot. OpenCV is extensively documented, ships with many examples, and there's even a <a href="http://oreilly.com/catalog/9780596516130/" rel="nofollow">book</a>. The Python wrappers I was using were thin enough so that very little wrapper specific documentation was required (and this is typical for many other wrapped libraries). I imagine that a few minutes looking at an example, like the PyCV unit tests would be all you need, and then you could focus on the OpenCV documentation that suited your needs.</p> <p>analysis: As for whether there's a better library than OpenCV, my somewhat outdated opinion is that OpenCV is great if you want to do fairly advanced stuff (e.g. object tracking), but it is possibly overkill for your needs. It sounds like scipy <a href="http://docs.scipy.org/doc/scipy-0.7.x/reference/tutorial/ndimage.html" rel="nofollow">ndimage</a> combined with some basic numpy array manipulation might be enough.</p> <p>acquisition: The options I know of for acquisition are OpenCV, Motmot, or using ctypes to directly interface to the drivers. Of these, I've never used Motmot because I had trouble installing it. The other methods I found fairly straightforward, though I don't remember the details (which is a good thing, since it means it was easy).</p>
7
2009-05-30T18:34:25Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
930,318
<p>OpenCV is probably your best bet for a library; you have your choice of wrappers for them. I looked at the SWIG wrapper that comes with the standard OpenCV install, but ended up using <a href="http://code.google.com/p/ctypes-opencv/">ctypes-opencv</a> because the memory management seemed cleaner.</p> <p>They are both very thin wrappers around the C code, so any C references you can find will be applicable to the Python. </p> <p>OpenCV is huge and not especially well documented, but there are some decent samples included in the samples directory that you can use to get started. A searchable OpenCV API reference is <a href="http://www.cs.indiana.edu/cgi-pub/oleykin/website/OpenCVHelp/">here</a>.</p> <p>You didn't mention if you were looking for online or print sources, but I have the <a href="http://oreilly.com/catalog/9780596516130/">O'Reilly</a> book and it's quite good (examples in C, but easily translatable).</p> <p>The <a href="http://www.cs.indiana.edu/cgi-pub/oleykin/website/OpenCVHelp/ref/OpenCVRef%5FCv.htm#decl%5FcvFindContours">FindContours</a> function is a bit similar to regionprops; it will get you a list of the connected components, which you can then inspect to get their info.</p> <p>For thresholding you can try <a href="http://www.cs.indiana.edu/cgi-pub/oleykin/website/OpenCVHelp/ref/OpenCVRef%5FCv.htm#decl%5FcvThreshold">Threshold</a>. I was sure you could pass a flag to it to use Otsu's method, but it doesn't seem to be listed in the docs there.</p> <p>I haven't come across specific functions corresponding to gray2ind, but they may be in there.</p>
13
2009-05-30T18:48:31Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
3,696,260
<p>I've started a website on this subject: <a href="http://pythonvision.org" rel="nofollow" title="pythonvision.org">pythonvision.org</a>. It has some tutorials, &amp;c and some links to software. There are more links and tutorials there.</p>
4
2010-09-12T19:33:17Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper for <a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">OpenCV</a> apparently), but I can't find any appropriate tutorials.</p> <p>My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass.</p> <p>Previously, I've used Matlab's <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Tootlbox</a> without any problems. The functions I would like to find an equivalent in Python are <a href="http://www.mathworks.com/help/images/ref/graythresh.html" rel="nofollow">graythresh</a>, <a href="http://www.mathworks.com/help/images/ref/regionprops.html" rel="nofollow">regionprops</a> and <a href="http://www.mathworks.com/help/images/ref/gray2ind.html" rel="nofollow">gray2ind</a>.</p> <p>Thanks!</p>
19
2009-05-20T10:45:29Z
10,910,941
<p>Foreword: This book is more for people who want a good hands on introduction into computer or machine vision, even though it covers what the original question asked.</p> <h2>[BOOK]: <a href="http://programmingcomputervision.com/" rel="nofollow"><strong>Programming Computer Vision with Python</strong></a></h2> <p>At the moment you can download the final draft from the book's website <strong>for free as pdf</strong>:</p> <p><strong><a href="http://programmingcomputervision.com/" rel="nofollow">http://programmingcomputervision.com/</a></strong></p> <p>From the introduction:</p> <p>The idea behind this book is to give an easily accessible entry point to hands-on computer vision with enough understanding of the underlying theory and algorithms to be a foundation for students, researchers and enthusiasts.</p> <p>What you need to know</p> <ul> <li>Basic programming experience. You need to know how to use an editor and run scripts, how to structure code as well as basic data types. Familiarity with Python or other scripting style languages like Ruby or Matlab will help.</li> <li>Basic mathematics. To make full use of the examples it helps if you know about matrices, vectors, matrix multiplication, the standard mathematical functions and concepts like derivatives and gradients. Some of the more advanced mathe- matical examples can be easily skipped.</li> </ul> <p>What you will learn</p> <ul> <li>Hands-on programming with images using Python.</li> <li>Computer vision techniques behind a wide variety of real-world applications.</li> <li>Many of the fundamental algorithms and how to implement and apply them your- self.</li> </ul>
0
2012-06-06T08:45:48Z
[ "python", "matlab", "computer-vision" ]
Synchronising multiple threads in python
887,346
<p>I have a problem where I need <code>x</code> threads to wait until they have all reached a synchronization point. My solution uses the <code>synchronise</code> method below which is called by each threaded function when they need to synchronise.</p> <p>Is there a better way to do this?</p> <pre><code>thread_count = 0 semaphore = threading.Semaphore() event = threading.Event() def synchronise(count): """ All calls to this method will block until the last (count) call is made """ with semaphore: thread_count += 1 if thread_count == count: event.set() event.wait() def threaded_function(): # Do something # Block until 4 threads have reached this point synchronise(4) # Continue doing something else </code></pre>
6
2009-05-20T11:12:34Z
887,432
<p>The functionality you want is called a "<a href="http://en.wikipedia.org/wiki/Barrier%5F%28computer%5Fscience%29" rel="nofollow">barrier</a>". (Unfortunately that term has 2 meanings when talking about threading. So if you <a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-GB%3Aofficial&amp;hs=dq4&amp;q=barrier%2Bthreading%2Bpython&amp;btnG=Search" rel="nofollow">Google</a> it, just ignore articles that talk about "<a href="http://en.wikipedia.org/wiki/Memory%5Fbarrier" rel="nofollow">memory barriers</a>" - that's a very different thing).</p> <p>Your code looks quite reasonable - it's simple and safe.</p> <p>I couldn't find any "standard" implementations of barriers for Python, so I suggest you keep using your code.</p>
2
2009-05-20T11:40:53Z
[ "python", "multithreading", "synchronize" ]
Synchronising multiple threads in python
887,346
<p>I have a problem where I need <code>x</code> threads to wait until they have all reached a synchronization point. My solution uses the <code>synchronise</code> method below which is called by each threaded function when they need to synchronise.</p> <p>Is there a better way to do this?</p> <pre><code>thread_count = 0 semaphore = threading.Semaphore() event = threading.Event() def synchronise(count): """ All calls to this method will block until the last (count) call is made """ with semaphore: thread_count += 1 if thread_count == count: event.set() event.wait() def threaded_function(): # Do something # Block until 4 threads have reached this point synchronise(4) # Continue doing something else </code></pre>
6
2009-05-20T11:12:34Z
887,538
<p>There are many ways to synchronize threads. Many.</p> <p>In addition to synchronize, you can do things like the following.</p> <ol> <li><p>Break your tasks into two steps around the synchronization point. Start threads doing the pre-sync step. Then use "join" to wait until all threads finish step 1. Start new threads doing the post-sync step. I prefer this, over synchronize.</p></li> <li><p>Create a queue; acquire a synchronization lock. Start all threads. Each thread puts an entry in the queue and waits on the synchronization lock. The "main" thread sits in a loop dequeueing items from the queue. When all threads have put an item in the queue, the "main" thread releases the synchronization lock. All other threads are now free to run again.</p></li> </ol> <p>There are a number of interprocess communication (IPC) techniques -- all of which can be used for thread synchronization.</p>
1
2009-05-20T12:05:05Z
[ "python", "multithreading", "synchronize" ]
Synchronising multiple threads in python
887,346
<p>I have a problem where I need <code>x</code> threads to wait until they have all reached a synchronization point. My solution uses the <code>synchronise</code> method below which is called by each threaded function when they need to synchronise.</p> <p>Is there a better way to do this?</p> <pre><code>thread_count = 0 semaphore = threading.Semaphore() event = threading.Event() def synchronise(count): """ All calls to this method will block until the last (count) call is made """ with semaphore: thread_count += 1 if thread_count == count: event.set() event.wait() def threaded_function(): # Do something # Block until 4 threads have reached this point synchronise(4) # Continue doing something else </code></pre>
6
2009-05-20T11:12:34Z
25,559,884
<p>Note that Barrier has been implemented <a href="https://docs.python.org/3/whatsnew/3.2.html#threading" rel="nofollow">as of Python 3.2</a></p> <p>Example of using barriers:</p> <pre><code>from threading import Barrier, Thread def get_votes(site): ballots = conduct_election(site) all_polls_closed.wait() # do not count until all polls are closed totals = summarize(ballots) publish(site, totals) all_polls_closed = Barrier(len(sites)) for site in sites: Thread(target=get_votes, args=(site,)).start() </code></pre>
2
2014-08-29T00:17:02Z
[ "python", "multithreading", "synchronize" ]
Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?
887,388
<p>Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy?</p> <pre><code>SELECT * FROM foo WHERE foo.bar IN (1,2,3)</code></pre> <p>I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that doesn't use plain text?</p> <pre><code>select([foo], in(foo.c.bar, [1, 2, 3]))</code></pre> <pre><code>select([foo]).in(foo.c.bar, [1, 2, 3])</code></pre>
11
2009-05-20T11:27:26Z
887,402
<pre><code>select([foo], foo.c.bar.in_([1, 2, 3])) </code></pre> <p>You can use the <a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.ColumnElement.in_" rel="nofollow"><code>.in_()</code></a> method with Columns or with Instrumented attributes. Both work.</p> <p><a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">It is mentioned here</a> on SQLAlchemy's first tutorial.</p>
14
2009-05-20T11:32:30Z
[ "python", "sqlalchemy" ]
Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?
887,388
<p>Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy?</p> <pre><code>SELECT * FROM foo WHERE foo.bar IN (1,2,3)</code></pre> <p>I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that doesn't use plain text?</p> <pre><code>select([foo], in(foo.c.bar, [1, 2, 3]))</code></pre> <pre><code>select([foo]).in(foo.c.bar, [1, 2, 3])</code></pre>
11
2009-05-20T11:27:26Z
27,309,357
<p>The .in_() operator now lives in the <strong>ColumnOperators</strong> class, documented @ <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.in_" rel="nofollow">http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.in_</a></p> <p>Example usage:</p> <pre><code>ids_to_select = ["1", "2", "3"] query(Model).filter(Model.id.in_(ids_to_select)).all() </code></pre>
4
2014-12-05T05:27:37Z
[ "python", "sqlalchemy" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
887,564
<p>You can use <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a> to change access and modify time but not the creation date.</p>
13
2009-05-20T12:15:28Z
[ "python", "linux", "file", "date" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
887,652
<p>I am not a UNIX expert, so maybe I'm wrong, but I think that UNIX (or Linux) don't store file creation time.</p>
2
2009-05-20T12:34:29Z
[ "python", "linux", "file", "date" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
887,688
<p>Linux and Unix file system stores :</p> <blockquote> <p>File access, change and modification time (remember UNIX or Linux never stores file creation time, this is favorite question asked in UNIX/Linux sys admin job interview)</p> </blockquote> <p><a href="http://www.cyberciti.biz/tips/understanding-unixlinux-filesystem-inodes.html">Understanding UNIX / Linux file systems</a></p>
13
2009-05-20T12:44:51Z
[ "python", "linux", "file", "date" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
32,943,250
<p>Check out <a href="http://docs.python.org/2/library/os.html#os.utime" rel="nofollow">os.utime</a></p> <pre><code>os.utime(file_path,(new_atime,new_mtime)) </code></pre>
1
2015-10-05T07:25:15Z
[ "python", "linux", "file", "date" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,116
<p>Because interpretting from bytecode directly is faster. It avoids the need to do lexing, for one thing.</p>
7
2009-05-20T14:07:17Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,117
<p>Because you can compile to a <code>.pyc</code> once and interpret from it many times.</p> <p>So if you're running a script many times you only have the overhead of parsing the source code once.</p>
8
2009-05-20T14:07:35Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,119
<p>Nearly no interpreter really interprets code <em>directly</em>, line by line – it's simply too inefficient. Almost all interpreters use some intermediate representation which can be executed easily. Also, small optimizations can be performed on this intermediate code.</p> <p>Python furthermore stores this code which has a huge advantage for the next time this code gets executed: Python doesn't have to parse the code anymore; parsing is the slowest part in the compile process. Thus, a bytecode representation reduces execution overhead quite substantially.</p>
31
2009-05-20T14:07:45Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,159
<p>Re-lexing and parsing the source code over and over, rather than doing it just once (most often on the first <code>import</code>), would obviously be a silly and pointless waste of effort.</p>
6
2009-05-20T14:12:39Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
1,184,282
<p>I doubt very much that the reason is performance, albeit be it a nice side effect. I would say that it's only natural to think a VM built around some high-level assembly language would be more practical than to find and replace text in some source code string.</p> <p>Edit:</p> <p>Okay, clearly, who ever put a -1 vote on my post without leaving a reasonable comment to explain knows very little about virtual machines (run-time environments).</p> <p><a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Erik-Meijer-and-Lars-Bak-Inside-V8-A-Javascript-Virtual-Machine/" rel="nofollow">http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Erik-Meijer-and-Lars-Bak-Inside-V8-A-Javascript-Virtual-Machine/</a></p>
-1
2009-07-26T11:03:26Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
1,189,344
<p>Although there is a small efficiency aspect to it (you can store the bytecode on disk or in memory), its mostly engineering: it allows you separate parsing from interpreting. Parsers can often be nasty creatures, full of edge-cases and having to conform to esoteric rules like using just the right amount of lookahead and resolving shift-reduce problems. By contrast, interpreting is really simple: its just a big switch statement using the bytecode's opcode.</p>
2
2009-07-27T16:55:51Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Make Emacs use UTF-8 with Python Interactive Mode
888,406
<p>When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8:</p> <pre><code>$ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' </code></pre> <p>This works the same for python2.5.</p> <p>But inside Emacs, the encoding is US-ASCII.</p> <pre><code>Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.stdout.encoding 'US-ASCII' </code></pre> <p>How do I make Emacs communicate with Python so that sys.stdout knows to use UTF-8?</p> <p><hr /></p> <p>Edit: Since I don't have the rep to edit the accepted answer, here is precisely what worked for me on Aquaemacs 1.6, Mac OS 10.5.6.</p> <p>In the python-mode-hook, I added the line</p> <pre><code>(setenv "LANG" "en_GB.UTF-8") </code></pre> <p>Apparently, Mac OS requires "UTF-8", while dfa says that Ubuntu requires "UTF8".</p> <p>Additionally, I had to set the input/output encoding by doing C-x RET p and then typing "utf-8" twice. I should probably find out how to set this permanently.</p> <p>Thanks to dfa and Jouni for collectively helping me find the answer.</p> <p>Here is my final python-mode-hook:</p> <pre><code>(add-hook 'python-mode-hook (lambda () (set (make-variable-buffer-local 'beginning-of-defun-function) 'py-beginning-of-def-or-class) (define-key py-mode-map "\C-c\C-z" 'py-shell) (setq outline-regexp "def\\|class ") (setenv "LANG" "en_GB.UTF-8"))) ; &lt;-- *this* line is new </code></pre>
7
2009-05-20T14:50:56Z
888,464
<p>check your environment variables:</p> <pre><code>$ LANG="en_US.UTF8" python -c "import sys; print sys.stdout.encoding" UTF-8 $ LANG="en_US" python -c "import sys; print sys.stdout.encoding" ANSI_X3.4-1968 </code></pre> <p>in your python hook, try:</p> <pre><code>(setenv "LANG" "en_US.UTF8") </code></pre>
7
2009-05-20T15:00:14Z
[ "python", "emacs", "encoding", "utf-8", "terminal" ]