title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Getting total/free RAM from within Python | 1,204,378 | <p>From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?</p>
<p>Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.</p>
| 9 | 2009-07-30T03:52:42Z | 21,589,439 | <p>In windows I use this method. It's kinda hacky but it works using standard os library:</p>
<pre><code>import os
process = os.popen('wmic memorychip get capacity')
result = process.read()
process.close()
totalMem = 0
for m in result.split(" \r\n")[1:-1]:
totalMem += int(m)
print totalMem / (1024**3)
</code></pre>
| 1 | 2014-02-05T21:58:24Z | [
"python",
"wxpython"
] |
removing extensions in subdirectories | 1,204,617 | <p>I need to remove the extension ".tex":</p>
<pre><code>./1-aoeeu/1.tex
./2-thst/2.tex
./3-oeu/3.tex
./4-uoueou/4.tex
./5-aaa/5.tex
./6-oeua/6.tex
./7-oue/7.tex
</code></pre>
<p>Please, do it with some tools below:</p>
<ol>
<li><p>Sed and find</p></li>
<li><p>Ruby </p></li>
<li><p>Python</p></li>
</ol>
<p><strong>My Poor Try:</strong> </p>
<pre><code>$find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +
</code></pre>
| 1 | 2009-07-30T05:31:03Z | 1,204,638 | <p>A Python script to do the same:</p>
<pre><code>import os.path, shutil
def remove_ext(arg, dirname, fnames):
argfiles = (os.path.join(dirname, f) for f in fnames if f.endswith(arg))
for f in argfiles:
shutil.move(f, f[:-len(arg)])
os.path.walk('/some/path', remove_ext, '.tex')
</code></pre>
| 4 | 2009-07-30T05:39:09Z | [
"python",
"ruby",
"sed",
"find"
] |
removing extensions in subdirectories | 1,204,617 | <p>I need to remove the extension ".tex":</p>
<pre><code>./1-aoeeu/1.tex
./2-thst/2.tex
./3-oeu/3.tex
./4-uoueou/4.tex
./5-aaa/5.tex
./6-oeua/6.tex
./7-oue/7.tex
</code></pre>
<p>Please, do it with some tools below:</p>
<ol>
<li><p>Sed and find</p></li>
<li><p>Ruby </p></li>
<li><p>Python</p></li>
</ol>
<p><strong>My Poor Try:</strong> </p>
<pre><code>$find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +
</code></pre>
| 1 | 2009-07-30T05:31:03Z | 1,204,663 | <p>One way, not necessarily the fastest (but at least the quickest developed):</p>
<p><code><pre>
pax> for i in *.c */*.c */*/*.c ; do
...> j=$(echo "$i" | sed 's/\.c$//')
...> echo mv "$i" "$j"
...> done
</pre></code></p>
<p>It's equivalent since your maxdepth is 2. The script is just echoing the <code>mv</code> command at the moment (for test purposes) and working on C files (since I had no <code>tex</code> files to test with).</p>
<p>Or, you can use find with all its power thus:</p>
<p><code><pre>
pax> find . -maxdepth 2 -name '*.tex' | while read line ; do
...> j=$(echo "$line" | sed 's/\.tex$//')
...> mv "$line" "$j"
...> done
</pre></code></p>
| 1 | 2009-07-30T05:48:12Z | [
"python",
"ruby",
"sed",
"find"
] |
removing extensions in subdirectories | 1,204,617 | <p>I need to remove the extension ".tex":</p>
<pre><code>./1-aoeeu/1.tex
./2-thst/2.tex
./3-oeu/3.tex
./4-uoueou/4.tex
./5-aaa/5.tex
./6-oeua/6.tex
./7-oue/7.tex
</code></pre>
<p>Please, do it with some tools below:</p>
<ol>
<li><p>Sed and find</p></li>
<li><p>Ruby </p></li>
<li><p>Python</p></li>
</ol>
<p><strong>My Poor Try:</strong> </p>
<pre><code>$find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +
</code></pre>
| 1 | 2009-07-30T05:31:03Z | 1,204,694 | <p>Using <code>bash</code>, <code>find</code> and <code>mv</code> from your base directory. </p>
<pre><code> for i in $(find . -type f -maxdepth 2 -name "*.tex");
do
mv $i $(echo "$i" | sed 's|.tex$||');
done
</code></pre>
<p><hr /></p>
<p><strong>Variation 2</strong> based on other answers here.</p>
<pre><code>find . -type f -maxdepth 2 -name "*.tex" | while read line;
do
mv "$line" "${line%%.tex}";
done
</code></pre>
<p><hr /></p>
<p>PS: I did not get the part about escaping '<code>.</code>' by <code>pax</code>...</p>
| 0 | 2009-07-30T05:57:08Z | [
"python",
"ruby",
"sed",
"find"
] |
removing extensions in subdirectories | 1,204,617 | <p>I need to remove the extension ".tex":</p>
<pre><code>./1-aoeeu/1.tex
./2-thst/2.tex
./3-oeu/3.tex
./4-uoueou/4.tex
./5-aaa/5.tex
./6-oeua/6.tex
./7-oue/7.tex
</code></pre>
<p>Please, do it with some tools below:</p>
<ol>
<li><p>Sed and find</p></li>
<li><p>Ruby </p></li>
<li><p>Python</p></li>
</ol>
<p><strong>My Poor Try:</strong> </p>
<pre><code>$find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +
</code></pre>
| 1 | 2009-07-30T05:31:03Z | 1,204,724 | <p>Using "for i in" may cause "too many parameters" errrors</p>
<p>A better approach is to pipe find onto the next process.</p>
<p>Example:</p>
<pre><code>find . -type f -name "*.tex" | while read file
do
mv $file ${file%%tex}g
done
</code></pre>
<p>(Note: Wont handle files with spaces)</p>
| 0 | 2009-07-30T06:07:28Z | [
"python",
"ruby",
"sed",
"find"
] |
removing extensions in subdirectories | 1,204,617 | <p>I need to remove the extension ".tex":</p>
<pre><code>./1-aoeeu/1.tex
./2-thst/2.tex
./3-oeu/3.tex
./4-uoueou/4.tex
./5-aaa/5.tex
./6-oeua/6.tex
./7-oue/7.tex
</code></pre>
<p>Please, do it with some tools below:</p>
<ol>
<li><p>Sed and find</p></li>
<li><p>Ruby </p></li>
<li><p>Python</p></li>
</ol>
<p><strong>My Poor Try:</strong> </p>
<pre><code>$find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +
</code></pre>
| 1 | 2009-07-30T05:31:03Z | 1,207,202 | <p>There's an excellent Perl rename script that ships with some distributions, and otherwise you can find it on the web. (I'm not sure where it resides officially, but <a href="http://tips.webdesign10.com/files/rename.pl.txt" rel="nofollow">this is it</a>). Check if your rename was written by Larry Wall (AUTHOR section of <code>man rename</code>). It will let you do something like:</p>
<pre><code>find . [-maxdepth 2] -name "*.tex" -exec rename 's/\.tex//' '{}' \;
</code></pre>
<p>Using -exec is simplest here because there's only one action to perform, and it's not too expensive to invoke rename multiple times. If you need to do multiple things, use the "while read" form:</p>
<pre><code>find . [-maxdepth 2] -name "*.tex" | while read texfile; do rename 's/\.tex//' $texfile; done
</code></pre>
<p>If you have something you want to invoke only once:</p>
<pre><code>find . [-maxdepth 2] -name "*.tex" | xargs rename 's/\.tex//'
</code></pre>
<p>That last one makes clear how useful rename is - if everything's already in the same place, you've got a quick regexp renamer.</p>
| 0 | 2009-07-30T15:01:39Z | [
"python",
"ruby",
"sed",
"find"
] |
TypeError: can't multiply sequence by non-int of type 'str' | 1,204,744 | <pre><code>>>>
Enter muzzle velocity (m/2): 60
Enter angle (degrees): 45
Traceback (most recent call last):
File "F:/Python31/Lib/idlelib/test", line 9, in <module>
range()
File "F:/Python31/Lib/idlelib/test", line 7, in range
Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)
TypeError: can't multiply sequence by non-int of type 'str'
</code></pre>
<p>I'm only new, so don't be too harsh if this is really obvious, but why am i getting this error?</p>
| 1 | 2009-07-30T06:15:35Z | 1,204,759 | <pre><code>>>> '60' * '60'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
</code></pre>
<p>You are trying to multiply two strings together. You must convert the string input from the user to a number using <code>int()</code> or <code>float()</code>.</p>
<p>Also, I'm not sure what you're doing with <code>decimal</code>; it looks like you're trying to call the module (the type is <em>in</em> the module, <code>decimal.Decimal</code>) but there's not much point in converting to a Decimal <em>after</em> doing some floating point math and <em>then</em> converting back to a <code>float</code>.</p>
<p>In the future, post the code that causes the problem (and keep the interaction and traceback). But first try and shrink the code as much as possible while making sure it still causes the error. This is an important step in debugging.</p>
| 5 | 2009-07-30T06:20:53Z | [
"python"
] |
TypeError: can't multiply sequence by non-int of type 'str' | 1,204,744 | <pre><code>>>>
Enter muzzle velocity (m/2): 60
Enter angle (degrees): 45
Traceback (most recent call last):
File "F:/Python31/Lib/idlelib/test", line 9, in <module>
range()
File "F:/Python31/Lib/idlelib/test", line 7, in range
Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)
TypeError: can't multiply sequence by non-int of type 'str'
</code></pre>
<p>I'm only new, so don't be too harsh if this is really obvious, but why am i getting this error?</p>
| 1 | 2009-07-30T06:15:35Z | 1,204,807 | <p>You should convert the data you get from console to integers:</p>
<pre><code>x = int(x)
y = int(y)
Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)
</code></pre>
| 3 | 2009-07-30T06:33:59Z | [
"python"
] |
TypeError: can't multiply sequence by non-int of type 'str' | 1,204,744 | <pre><code>>>>
Enter muzzle velocity (m/2): 60
Enter angle (degrees): 45
Traceback (most recent call last):
File "F:/Python31/Lib/idlelib/test", line 9, in <module>
range()
File "F:/Python31/Lib/idlelib/test", line 7, in range
Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2)
TypeError: can't multiply sequence by non-int of type 'str'
</code></pre>
<p>I'm only new, so don't be too harsh if this is really obvious, but why am i getting this error?</p>
| 1 | 2009-07-30T06:15:35Z | 1,204,961 | <p>You are using raw_input() for getting the input.
Instead use input(). It will return an Int. Make sure that you input only numbers or input() will raise an error (say in case of a string).
Also, it would be nice if you name your variables properly. x and y don't convey much. (velocity and angle would be so much better)</p>
| 0 | 2009-07-30T07:21:39Z | [
"python"
] |
Scheduling issues in python | 1,205,328 | <p>I'm using python to interface a hardware usb sniffer device with the python API provided by the vendor and I'm trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled again (my read loop gets all the attention).</p>
<p>The code looks much like this:</p>
<pre><code>from threading import Thread
import time
usb_device = 0
def usb_dump(usb_device):
while True:
#time.sleep(0.001)
packet = ReadUSBDevice(usb_device)
print "packet pid: %s" % packet.pid
class DumpThread(Thread):
def run(self):
usb_dump()
usb_device = OpenUSBDevice()
t = DumpThread()
t.start()
print "Sleep 1"
time.sleep(1)
print "End"
CloseUSBDevice(usb_device)
sys.exit(0)
</code></pre>
<p>(I could paste actual code, but since you need the hardware device I figure it won't help much).</p>
<p>I'm expecting this code to start dumping usb packets for about a second before the main thread terminates the entire program. However, all I see is "Sleep 1" and then the <code>usb_dump()</code> procedure runs forever. If I uncomment the "time.sleep(0.001)" statement in the inner loop of the <code>usb_dump()</code> procedure things start working the way I expect, but then the python code becomes unable to keep up with all the packets coming in :-(</p>
<p>The vendor tells me that this is an python scheduler problem and not their api's fault and therefor won't help me:</p>
<blockquote>
<p>«However, it seems like you are experiencing some nuances when using threading in Python. By putting the time.sleep in the DumpThread thread, you are explicitly signaling to the Python threading system to give up control. Otherwise, it is up the Python interpreter to determine when to switch threads and it usually does that after a certain number of byte code instructions have been executed.»</p>
</blockquote>
<p>Can somebody confirm that python is the problem here? Is there another way to make the DumpThread release control? Any other ideas?</p>
| 0 | 2009-07-30T08:55:10Z | 1,205,371 | <p>I think the vendor is correct. Assuming this is CPython, there is no true parallel threading; only one thread can execute at a time. This is because of the implementation of the <a href="http://docs.python.org/glossary.html#term-global-interpreter-lock" rel="nofollow">global interpreter lock</a>.</p>
<p>You may be able to achieve an acceptable solution by using the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module, which effectively sidesteps the garbage collector's lock by spawning true sub-processes.</p>
<p>Another possibility that may help is to modify the scheduler's <a href="http://docs.python.org/library/sys.html#sys.setcheckinterval" rel="nofollow">switching behaviour</a>.</p>
| 0 | 2009-07-30T09:04:40Z | [
"python",
"multithreading",
"scheduling"
] |
Scheduling issues in python | 1,205,328 | <p>I'm using python to interface a hardware usb sniffer device with the python API provided by the vendor and I'm trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled again (my read loop gets all the attention).</p>
<p>The code looks much like this:</p>
<pre><code>from threading import Thread
import time
usb_device = 0
def usb_dump(usb_device):
while True:
#time.sleep(0.001)
packet = ReadUSBDevice(usb_device)
print "packet pid: %s" % packet.pid
class DumpThread(Thread):
def run(self):
usb_dump()
usb_device = OpenUSBDevice()
t = DumpThread()
t.start()
print "Sleep 1"
time.sleep(1)
print "End"
CloseUSBDevice(usb_device)
sys.exit(0)
</code></pre>
<p>(I could paste actual code, but since you need the hardware device I figure it won't help much).</p>
<p>I'm expecting this code to start dumping usb packets for about a second before the main thread terminates the entire program. However, all I see is "Sleep 1" and then the <code>usb_dump()</code> procedure runs forever. If I uncomment the "time.sleep(0.001)" statement in the inner loop of the <code>usb_dump()</code> procedure things start working the way I expect, but then the python code becomes unable to keep up with all the packets coming in :-(</p>
<p>The vendor tells me that this is an python scheduler problem and not their api's fault and therefor won't help me:</p>
<blockquote>
<p>«However, it seems like you are experiencing some nuances when using threading in Python. By putting the time.sleep in the DumpThread thread, you are explicitly signaling to the Python threading system to give up control. Otherwise, it is up the Python interpreter to determine when to switch threads and it usually does that after a certain number of byte code instructions have been executed.»</p>
</blockquote>
<p>Can somebody confirm that python is the problem here? Is there another way to make the DumpThread release control? Any other ideas?</p>
| 0 | 2009-07-30T08:55:10Z | 1,205,415 | <p>I'm assuming you wrote a Python C module that exposes the ReadUSBDevice function, and that it's intended to block until a USB packet is received, then return it.</p>
<p>The native ReadUSBDevice implementation needs to release the Python GIL while it's waiting for a USB packet, and then reacquire it when it receives one. This allows other Python threads to run while you're executing native code.</p>
<p><a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock</a></p>
<p>While you've unlocked the GIL, you can't access Python. Release the GIL, run the blocking function, then when you know you have something to return back to Python, re-acquire it.</p>
<p>If you don't do this, then no other Python threads can execute while your native blocking is going on. If this is a vendor-supplied Python module, failing to release the GIL during native blocking activity is a bug.</p>
<p>Note that if you're receiving many packets, and actually processing them in Python, then other threads should still run. Multiple threads which are actually running Python code won't run in parallel, but it'll frequently switch between threads, giving them all a chance to run. This doesn't work if native code is blocking without releasing the GIL.</p>
<p>edit: I see you mentioned this is a vendor-supplied library. If you don't have source, a quick way to see if they're releasing the GIL: start the ReadUSBDevice thread while no USB activity is happening, so ReadUSBDevice simply sits around waiting for data. If they're releasing the GIL, the other threads should run unimpeded. If they're not, it'll block the whole interpreter. That would be a serious bug.</p>
| 2 | 2009-07-30T09:15:37Z | [
"python",
"multithreading",
"scheduling"
] |
Scheduling issues in python | 1,205,328 | <p>I'm using python to interface a hardware usb sniffer device with the python API provided by the vendor and I'm trying to read (usb packets) from the device in a separate thread in an infinite loop (which works fine). The problem is that my main loop does not seem to ever get scheduled again (my read loop gets all the attention).</p>
<p>The code looks much like this:</p>
<pre><code>from threading import Thread
import time
usb_device = 0
def usb_dump(usb_device):
while True:
#time.sleep(0.001)
packet = ReadUSBDevice(usb_device)
print "packet pid: %s" % packet.pid
class DumpThread(Thread):
def run(self):
usb_dump()
usb_device = OpenUSBDevice()
t = DumpThread()
t.start()
print "Sleep 1"
time.sleep(1)
print "End"
CloseUSBDevice(usb_device)
sys.exit(0)
</code></pre>
<p>(I could paste actual code, but since you need the hardware device I figure it won't help much).</p>
<p>I'm expecting this code to start dumping usb packets for about a second before the main thread terminates the entire program. However, all I see is "Sleep 1" and then the <code>usb_dump()</code> procedure runs forever. If I uncomment the "time.sleep(0.001)" statement in the inner loop of the <code>usb_dump()</code> procedure things start working the way I expect, but then the python code becomes unable to keep up with all the packets coming in :-(</p>
<p>The vendor tells me that this is an python scheduler problem and not their api's fault and therefor won't help me:</p>
<blockquote>
<p>«However, it seems like you are experiencing some nuances when using threading in Python. By putting the time.sleep in the DumpThread thread, you are explicitly signaling to the Python threading system to give up control. Otherwise, it is up the Python interpreter to determine when to switch threads and it usually does that after a certain number of byte code instructions have been executed.»</p>
</blockquote>
<p>Can somebody confirm that python is the problem here? Is there another way to make the DumpThread release control? Any other ideas?</p>
| 0 | 2009-07-30T08:55:10Z | 1,205,524 | <p>Your vendor would be right if yours was <strong>pure python</strong> code; however, C extensions may release the <a href="http://effbot.org/pyfaq/what-is-the-global-interpreter-lock.htm" rel="nofollow">GIL</a>, and therefore allows for actual multithreading.</p>
<p>In particular, time.sleep <strong>does</strong> release the GIL (you can check it directly from the source code, <a href="http://svn.python.org/view/python/trunk/Modules/timemodule.c?view=markup" rel="nofollow">here</a> - look at <code>floatsleep</code> implementation); so your code should not have any problem.
As a further proof, I have made also a simple test, just removing the calls to USB, and it actually works as expected:</p>
<pre><code>from threading import Thread
import time
import sys
usb_device = 0
def usb_dump():
for i in range(100):
time.sleep(0.001)
print "dumping usb"
class DumpThread(Thread):
def run(self):
usb_dump()
t = DumpThread()
t.start()
print "Sleep 1"
time.sleep(1)
print "End"
sys.exit(0)
</code></pre>
<p>Finally, just a couple of notes on the code you posted:</p>
<ul>
<li>usb_device is not being passed to the thread. You need to pass it as a parameter or (argh!) tell the thread to get it from the global namespace.</li>
<li>Instead of forcing sys.exit(), it could be better to just signal the thread to stop, and then closing USB device. I suspect your code could get some multithreading issue, as it is now.</li>
<li>If you need just a periodic poll, threading.Timer class may be a better solution for you.</li>
</ul>
<p>[<em>Update</em>] About the latest point: as told in the comment, I think a <code>Timer</code> would better fit the semantic of your function (a periodic poll) and would automatically avoid issues with the GIL not being released by the vendor code.</p>
| 3 | 2009-07-30T09:35:48Z | [
"python",
"multithreading",
"scheduling"
] |
Debugging Ruby/Python/Groovy | 1,205,343 | <p>I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :)</p>
<p>The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Python, Groovy).</p>
<p>Java is easy to debug because there is a clear relationship between lines of code, and fairly fine-grained behaviour, e.g. manipulate an array using a for loop:</p>
<pre><code>for ( int i=0; i < array1.size(); i++ )
{
if ( meetsSomeCriterion(array1.elementAt(i) )
{
array2.add( array1.elementAt(i) );
}
}
</code></pre>
<p>so you can set a breakpoint on the test in the loop and see what happens next. (I know there are better ways to write this; it's just to illustrate the point.)</p>
<p>In languages like Ruby the idiomatic style seems to favour higher-level one-liner coding, e.g. from <a href="http://rubyquiz.com/quiz113.html" rel="nofollow">http://rubyquiz.com/quiz113.html</a></p>
<pre><code>quiz.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
</code></pre>
<p>I'm wondering if you can suggest any effective techniques for debugging this, for example if you changed the regular expression ... would you still use the traditional debugger, and step into/over the chained methods? Or is there a better way?</p>
<p>Thanks!</p>
| 1 | 2009-07-30T08:57:59Z | 1,422,698 | <p>If I were to debug your example, the first thing I would do is break it down into multiple steps. I don't care if it's "pythonic" or "the ruby way" or "tclish" or whatever, code like that can be difficult to debug. </p>
<p>That's not to say I don't write code like that. Once it's been debugged it is sometimes OK to join it all into a single line but I find myself leaning more toward readability and maintainability and less toward writing concise code. If the one-liner approach is genuinely more readable I'll go with it, but if it's not, I don't.</p>
| 3 | 2009-09-14T16:48:35Z | [
"python",
"ruby",
"debugging",
"groovy",
"dynamic-languages"
] |
Debugging Ruby/Python/Groovy | 1,205,343 | <p>I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :)</p>
<p>The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Python, Groovy).</p>
<p>Java is easy to debug because there is a clear relationship between lines of code, and fairly fine-grained behaviour, e.g. manipulate an array using a for loop:</p>
<pre><code>for ( int i=0; i < array1.size(); i++ )
{
if ( meetsSomeCriterion(array1.elementAt(i) )
{
array2.add( array1.elementAt(i) );
}
}
</code></pre>
<p>so you can set a breakpoint on the test in the loop and see what happens next. (I know there are better ways to write this; it's just to illustrate the point.)</p>
<p>In languages like Ruby the idiomatic style seems to favour higher-level one-liner coding, e.g. from <a href="http://rubyquiz.com/quiz113.html" rel="nofollow">http://rubyquiz.com/quiz113.html</a></p>
<pre><code>quiz.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
</code></pre>
<p>I'm wondering if you can suggest any effective techniques for debugging this, for example if you changed the regular expression ... would you still use the traditional debugger, and step into/over the chained methods? Or is there a better way?</p>
<p>Thanks!</p>
| 1 | 2009-07-30T08:57:59Z | 1,422,710 | <p>If I have to debug such a line as the one you posted I find that nothing helps as much as breaking it into stand-alone statements. That way you can see what each method receives as a parameter , and what it returns. </p>
<p>Such statements make code hard to maintain.</p>
| 0 | 2009-09-14T16:51:33Z | [
"python",
"ruby",
"debugging",
"groovy",
"dynamic-languages"
] |
Debugging Ruby/Python/Groovy | 1,205,343 | <p>I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :)</p>
<p>The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Python, Groovy).</p>
<p>Java is easy to debug because there is a clear relationship between lines of code, and fairly fine-grained behaviour, e.g. manipulate an array using a for loop:</p>
<pre><code>for ( int i=0; i < array1.size(); i++ )
{
if ( meetsSomeCriterion(array1.elementAt(i) )
{
array2.add( array1.elementAt(i) );
}
}
</code></pre>
<p>so you can set a breakpoint on the test in the loop and see what happens next. (I know there are better ways to write this; it's just to illustrate the point.)</p>
<p>In languages like Ruby the idiomatic style seems to favour higher-level one-liner coding, e.g. from <a href="http://rubyquiz.com/quiz113.html" rel="nofollow">http://rubyquiz.com/quiz113.html</a></p>
<pre><code>quiz.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
</code></pre>
<p>I'm wondering if you can suggest any effective techniques for debugging this, for example if you changed the regular expression ... would you still use the traditional debugger, and step into/over the chained methods? Or is there a better way?</p>
<p>Thanks!</p>
| 1 | 2009-07-30T08:57:59Z | 1,422,717 | <p>Combining multiple actions into a single line is all well and good, when you can still look at the line in question and know that it's going to do exactly what you want it to do. The minute you get to the point where you can't look at the code and go "yeah, ok, it does xyz, there's no way it couldn't" is when you should consider breaking it into individual pieces.</p>
<p>I give the same advice to people with long procs/methods. If you can't look at the code and know exactly what it's doing in all situations, then break it up. You can break up each of the "non-obvious" bits of code into it's own method and write tests for that piece alone. Then, you can use that method in your original method and know it's going to work... plus your original method is now easier to understand.</p>
<p>Along the same lines, you can break your "scan(/(?:\d*.)?\d{1,3}-?/)" code off into another method and test that by itself. The original code can then use that method, and it should be much easier to understand and know it's working.</p>
| 2 | 2009-09-14T16:52:51Z | [
"python",
"ruby",
"debugging",
"groovy",
"dynamic-languages"
] |
Filter by property | 1,205,375 | <p>Is it possible to filter by property?</p>
<p>i have a method in my model:</p>
<pre><code>@property
def myproperty(self):
[..]
</code></pre>
<p>and now i want to filter by this property like:</p>
<pre><code>MyModel.objects.filter(myproperty=[..])
</code></pre>
<p>is this somehow possible?</p>
| 44 | 2009-07-30T09:06:23Z | 1,205,389 | <p>Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.</p>
| 41 | 2009-07-30T09:09:45Z | [
"python",
"django"
] |
Filter by property | 1,205,375 | <p>Is it possible to filter by property?</p>
<p>i have a method in my model:</p>
<pre><code>@property
def myproperty(self):
[..]
</code></pre>
<p>and now i want to filter by this property like:</p>
<pre><code>MyModel.objects.filter(myproperty=[..])
</code></pre>
<p>is this somehow possible?</p>
| 44 | 2009-07-30T09:06:23Z | 1,205,416 | <p>I might be misunderstanding your original question, but there is a <a href="http://docs.python.org/library/functions.html#filter">filter</a> builtin in python.</p>
<pre><code>filtered = filter(myproperty, MyModel.objects)
</code></pre>
<p>But it's better to use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension</a>:</p>
<pre><code>filtered = [x for x in MyModel.objects if x.myproperty()]
</code></pre>
<p>or even better, a <a href="http://docs.python.org/tutorial/classes.html#generator-expressions">generator expression</a>:</p>
<pre><code>filtered = (x for x in MyModel.objects if x.myproperty())
</code></pre>
| 19 | 2009-07-30T09:15:41Z | [
"python",
"django"
] |
Filter by property | 1,205,375 | <p>Is it possible to filter by property?</p>
<p>i have a method in my model:</p>
<pre><code>@property
def myproperty(self):
[..]
</code></pre>
<p>and now i want to filter by this property like:</p>
<pre><code>MyModel.objects.filter(myproperty=[..])
</code></pre>
<p>is this somehow possible?</p>
| 44 | 2009-07-30T09:06:23Z | 19,334,674 | <p>i know it is an old question, but for the sake of those jumping here i think it is useful to read the question below and the relative answer:</p>
<p><a href="http://stackoverflow.com/questions/14617834/how-to-customize-admin-filter-in-django-1-4">How to customize admin filter in Django 1.4</a></p>
| 1 | 2013-10-12T13:23:40Z | [
"python",
"django"
] |
Filter by property | 1,205,375 | <p>Is it possible to filter by property?</p>
<p>i have a method in my model:</p>
<pre><code>@property
def myproperty(self):
[..]
</code></pre>
<p>and now i want to filter by this property like:</p>
<pre><code>MyModel.objects.filter(myproperty=[..])
</code></pre>
<p>is this somehow possible?</p>
| 44 | 2009-07-30T09:06:23Z | 27,139,492 | <p>PLEASE someone correct me, but I guess I have found a solution, at least for my own case.</p>
<p>I want to work on all those elements whose properties are exactly equal to ... whatever. </p>
<p>But I have several models, and this routine should work for all models. And it does:</p>
<pre><code>def selectByProperties(modelType, specify):
clause = "SELECT * from %s" % modelType._meta.db_table
if len(specify) > 0:
clause += " WHERE "
for field, eqvalue in specify.items():
clause += "%s = '%s' AND " % (field, eqvalue)
clause = clause [:-5] # remove last AND
print clause
return modelType.objects.raw(clause)
</code></pre>
<p>With this universal subroutine, I can select all those elements which exactly equal my dictionary of 'specify' (propertyname,propertyvalue) combinations.</p>
<p>The first parameter takes a (models.Model), </p>
<p>the second a dictionary like:
{"property1" : "77" , "property2" : "12"}</p>
<p>And it creates an SQL statement like</p>
<pre><code>SELECT * from appname_modelname WHERE property1 = '77' AND property2 = '12'
</code></pre>
<p>and returns a QuerySet on those elements.</p>
<p>This is a test function:</p>
<pre><code>from myApp.models import myModel
def testSelectByProperties ():
specify = {"property1" : "77" , "property2" : "12"}
subset = selectByProperties(myModel, specify)
nameField = "property0"
## checking if that is what I expected:
for i in subset:
print i.__dict__[nameField],
for j in specify.keys():
print i.__dict__[j],
print
</code></pre>
<p>And? What do you think?</p>
| 2 | 2014-11-26T00:46:02Z | [
"python",
"django"
] |
Filter by property | 1,205,375 | <p>Is it possible to filter by property?</p>
<p>i have a method in my model:</p>
<pre><code>@property
def myproperty(self):
[..]
</code></pre>
<p>and now i want to filter by this property like:</p>
<pre><code>MyModel.objects.filter(myproperty=[..])
</code></pre>
<p>is this somehow possible?</p>
| 44 | 2009-07-30T09:06:23Z | 35,282,445 | <p>Looks like <a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations" rel="nofollow">using F() with annotations</a> will be my solution to this.</p>
<p>It's not going to filter by <code>@property</code>, since <code>F</code> talks to the databse before objects are brought into python. But still putting it here as an answer since my reason for wanting filter by property was really wanting to filter objects by the result of simple arithmetic on two different fields.</p>
<p>so, something along the lines of:</p>
<pre><code>companies = Company.objects\
.annotate(chairs_needed=F('num_employees') - F('num_chairs'))\
.filter(chairs_needed__lt=4)
</code></pre>
<p>rather than defining the property to be:</p>
<pre><code>@property
def chairs_needed(self):
return self.num_employees - self.num_chairs
</code></pre>
<p>then doing a list comprehension across all objects.</p>
| 2 | 2016-02-09T01:28:33Z | [
"python",
"django"
] |
Filter by property | 1,205,375 | <p>Is it possible to filter by property?</p>
<p>i have a method in my model:</p>
<pre><code>@property
def myproperty(self):
[..]
</code></pre>
<p>and now i want to filter by this property like:</p>
<pre><code>MyModel.objects.filter(myproperty=[..])
</code></pre>
<p>is this somehow possible?</p>
| 44 | 2009-07-30T09:06:23Z | 36,996,962 | <p>Riffing off @TheGrimmScientist's suggested workaround, you can make these "sql properties" by defining them on the Manager or the QuerySet, and reuse/chain/compose them:</p>
<p>With a Manager:</p>
<pre><code>class CompanyManager(models.Manager):
def with_chairs_needed(self):
return self.annotate(chairs_needed=F('num_employees') - F('num_chairs'))
class Company(models.Model):
# ...
objects = CompanyManager()
Company.objects.with_chairs_needed().filter(chairs_needed__lt=4)
</code></pre>
<p>With a QuerySet: </p>
<pre><code>class CompanyQuerySet(models.QuerySet):
def many_employees(self, n=50):
return self.filter(num_employees__gte=n)
def needs_fewer_chairs_than(self, n=5):
return self.with_chairs_needed().filter(chairs_needed__lt=n)
def with_chairs_needed(self):
return self.annotate(chairs_needed=F('num_employees') - F('num_chairs'))
class Company(models.Model):
# ...
objects = CompanyQuerySet.as_manager()
Company.objects.needs_fewer_chairs_than(4).many_employees()
</code></pre>
<p>See <a href="https://docs.djangoproject.com/en/1.9/topics/db/managers/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/db/managers/</a> for more.
Note that I am going off the documentation and have not tested the above. </p>
| 0 | 2016-05-03T06:17:56Z | [
"python",
"django"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 1,205,515 | <p>Several options are available:</p>
<ol>
<li><p>Call <a href="http://msdn.microsoft.com/en-us/library/aa365461%28VS.85%29.aspx">QueryDosDevice</a> with a NULL lpDeviceName to list all DOS devices. Then use CreateFile and <a href="http://msdn.microsoft.com/en-us/library/aa363256%28VS.85%29.aspx">GetCommConfig</a> with each device name in turn to figure out whether it's a serial port.</p></li>
<li><p>Call <a href="http://msdn.microsoft.com/en-us/library/ms792959.aspx">SetupDiGetClassDevs</a> with a ClassGuid of GUID_DEVINTERFACE_COMPORT.</p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/aa389762%28VS.85%29.aspx">WMI is also available to C/C++ programs</a>.</p></li>
</ol>
<p>There's some conversation on the <a href="http://groups.google.com/group/microsoft.public.win32.programmer.kernel/browse%5Fthread/thread/9c1bb578bd9cb309">win32 newsgroup</a> and a CodeProject, er, <a href="http://www.codeproject.com/KB/system/setupdi.aspx">project</a>.</p>
| 6 | 2009-07-30T09:33:41Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 3,018,813 | <p>I just created the following, based on reading through the C++ source to <a href="http://www.naughter.com/enumser.html" rel="nofollow">EnumSerialPorts</a> and seeing the function <code>GetDefaultCommConfig()</code>. It looked like the simplest method using simple ANSI C and a single API call for each possible COM port.</p>
<pre><code>#include <stdio.h>
#include <windows.h>
#include <winbase.h>
BOOL COM_exists( int port)
{
char buffer[7];
COMMCONFIG CommConfig;
DWORD size;
if (! (1 <= port && port <= 255))
{
return FALSE;
}
snprintf( buffer, sizeof buffer, "COM%d", port);
size = sizeof CommConfig;
// COM port exists if GetDefaultCommConfig returns TRUE
// or changes <size> to indicate COMMCONFIG buffer too small.
return (GetDefaultCommConfig( buffer, &CommConfig, &size)
|| size > sizeof CommConfig);
}
int main()
{
int i;
for (i = 1; i < 256; ++i)
{
if (COM_exists( i))
{
printf( "COM%d exists\n", i);
}
}
return 0;
}
</code></pre>
| 3 | 2010-06-10T21:49:32Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 3,018,890 | <p>The PySerial project provides a <a href="http://web.archive.org/web/20150906231735/http://pyserial.sourceforge.net/examples.html" rel="nofollow">couple of solutions</a>.</p>
| 4 | 2010-06-10T22:05:30Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 8,844,967 | <p>There's an example in the pyserial distro now that does this called scanwin32.py</p>
<p><a href="http://pyserial.sourcearchive.com/documentation/2.5/scanwin32_8py_source.html" rel="nofollow">http://pyserial.sourcearchive.com/documentation/2.5/scanwin32_8py_source.html</a></p>
| 1 | 2012-01-13T01:55:34Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 16,944,571 | <p>This is definitely fairly late, but it proved helpful to me!</p>
<p><a href="http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/" rel="nofollow">http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/</a></p>
<p>Particularly this example:</p>
<pre><code>import re
def full_port_name(portname):
""" Given a port-name (of the form COM7,
COM12, CNCA0, etc.) returns a full
name suitable for opening with the
Serial class.
"""
m = re.match('^COM(\d+)$', portname)
if m and int(m.group(1)) < 10:
return portname
return '\\\\.\\' + portname
</code></pre>
| 3 | 2013-06-05T15:58:29Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 25,539,425 | <p>Using pySerial with Python:</p>
<pre><code>import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
print p
</code></pre>
| 20 | 2014-08-28T01:37:32Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 29,284,793 | <p>I think WMI is the way to go since it's pretty easy to get going and it has minimal code. It saves you from having to dig inside the registry and gives you some guarantee that it will work for more general situations in the future.</p>
<p>You can install everything needed with <code>pip install pypiwin32 WMI</code> and it works out-of-the-box.</p>
<p><strong>Code</strong></p>
<pre><code>import wmi
query = "SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%(COM%)'"
coms = wmi.WMI().query(query)
for com in coms:
print(com.Name)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Communications Port (COM1)
mbed Serial Port (COM3)
mbed Serial Port (COM5)
</code></pre>
<p>My guess is that your serial port is some sort of Plug 'n Play so this should work fine. For some reason <code>Win32_SerialPort</code> doesn't work for all ports.</p>
| 1 | 2015-03-26T17:13:45Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Listing serial (COM) ports on Windows? | 1,205,383 | <p>I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's <a href="http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this post about using WMI</a>, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.</p>
<p>I currently know of two other approaches:</p>
<ol>
<li><p>Reading the information in the <code>HARDWARE\\DEVICEMAP\\SERIALCOMM</code> registry key. This looks like a great option, but is it <strong>robust</strong>? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.</p></li>
<li><p>Tryint to call <code>CreateFile</code> on <code>COMN</code> with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.</p></li>
</ol>
<p>Any other methods/ideas/experience to share?</p>
<p><strong>Edit:</strong> by the way, here's a simple Python implementation of reading the port names from registry:</p>
<pre><code>import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
</code></pre>
| 23 | 2009-07-30T09:08:22Z | 31,887,738 | <p>Nowadays there's a Powershell one-liner for that.</p>
<pre><code>[System.IO.Ports.SerialPort]::GetPortNames()
</code></pre>
| 2 | 2015-08-07T22:53:24Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] |
Neural net input/output | 1,205,449 | <p>Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types </p>
<p>i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out </p>
<p>if someone could provide examples in python that would be a big help</p>
| 3 | 2009-07-30T09:22:31Z | 1,205,509 | <p>You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for "x has a certain property p" -1 for "x doesn't have the property p" if your units' range is in [-1, 1])</p>
<p>The way you encode your input and the way you decode your output depends on what you want to train the neural network for. </p>
<p>Moreover, there are many "neural networks" algoritms and learning rules for different tasks( Back propagation, boltzman machines, self organizing maps). </p>
| 3 | 2009-07-30T09:32:33Z | [
"python",
"neural-network"
] |
Neural net input/output | 1,205,449 | <p>Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types </p>
<p>i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out </p>
<p>if someone could provide examples in python that would be a big help</p>
| 3 | 2009-07-30T09:22:31Z | 1,206,597 | <p>More complex data usually means adding more neurons in the input and output layers.</p>
<p>You can feed each "field" of your register, properly encoded as a real value (normalized, etc.) to each input neuron, or maybe you can even decompose even further into bit fields, assigning saturated inputs of 1 or 0 to the neurons... for the output, it depends on how you train the neural network, it will try to mimic the training set outputs.</p>
| 0 | 2009-07-30T13:26:16Z | [
"python",
"neural-network"
] |
Neural net input/output | 1,205,449 | <p>Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types </p>
<p>i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out </p>
<p>if someone could provide examples in python that would be a big help</p>
| 3 | 2009-07-30T09:22:31Z | 1,207,505 | <p>Your features must be decomposed into parts that can be represented as real numbers. The magic of a Neural Net is it's a black box, the correct associations will be made (with internal weights) during the training</p>
<p><hr /></p>
<p><strong>Inputs</strong></p>
<p>Choose as few features as are needed to accurately describe the situation, then decompose each into a set of real valued numbers.</p>
<ul>
<li>Weather: [temp today, humidity today, temp yesterday, humidity yesterday...] <em>the association between today's temp and today's humidity is made internally</em></li>
<li>Team stats: [ave height, ave weight, max height, top score,...]</li>
<li>Dice: <em>not sure I understand this one, do you mean how to encode discrete values?*</em></li>
<li>Complex number: [a,<em>ai</em>,b,<em>bi</em>,...]</li>
</ul>
<p>* Discrete valued features are tricky, but can still still be encoded as (0.0,1.0). The problem is they don't provide a gradient to learn the threshold on.</p>
<p><hr /></p>
<p><strong>Outputs</strong></p>
<p>You decide what you want the output to mean, and then encode your training examples in that format. The fewer output values, the easier to train.</p>
<ul>
<li>Weather: [tomorrow's chance of rain, tomorrow's temp,...] **</li>
<li>Team stats: [chance of winning, chance of winning by more than 20,...]</li>
<li>Complex number: [x,<em>xi</em>,...]</li>
</ul>
<p>** Here your <em>training</em> vectors would be: 1.0 if it rained the next day, 0.0 if it didn't</p>
<p><hr /></p>
<p>Of course, whether or not the problem can actually be modeled by a neural net is a different question.</p>
| 2 | 2009-07-30T15:46:57Z | [
"python",
"neural-network"
] |
Neural net input/output | 1,205,449 | <p>Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types </p>
<p>i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out </p>
<p>if someone could provide examples in python that would be a big help</p>
| 3 | 2009-07-30T09:22:31Z | 20,683,280 | <p>You have to add the number of units for input and output you need for the problem. If the unknown function to approximate depends on <em>n</em> parameter, you will have n input units. The number of output units depends on the nature of the funcion. For real functions with n real parameters you will have one output unit.</p>
<p>Some problems, for example in forecasting of time series, you will have m output units for the m succesive values of the function. The encoding is important and depends on the choosen algorithm. For example, in backpropagation for feedforward nets, is better to transform, if possible, the greater number of features in discrete inputs, as for classification tasks.</p>
<p>Other aspect of the encoding is that you have to evaluate the number of input and hidden units in function of the amount of data. Too many units related to data may give poor approximation due the course ff dimensionality problem. In some cases, you may to aggregate some of the input data in some way to avoid that problem or use some reduction mechanism as PCA.</p>
| 0 | 2013-12-19T13:41:09Z | [
"python",
"neural-network"
] |
Django - Repeating a form field n times in one form | 1,205,626 | <p>I have a Django form with several fields in it one of which needs to be repeated n times (where n is not known at design time) how would I go about coding this (if it is possible at all)?</p>
<p>e.g. instead of :-</p>
<pre><code>Class PaymentsForm(forms.form):
invoice = forms.CharField(widget=ValueHiddenInput())
total = forms.CharField(widget=ValueHiddenInput())
item_name_1 = forms.CharField(widget=ValueHiddenInput())
item_name_2 = forms.CharField(widget=ValueHiddenInput())
.
.
.
item_name_n = forms.CharField(widget=ValueHiddenInput())
</code></pre>
<p>I need something like :- </p>
<pre><code>Class PaymentsForm(forms.form):
invoice = forms.CharField(widget=ValueHiddenInput())
total = forms.CharField(widget=ValueHiddenInput())
item_name[n] = forms.CharField(widget=ValueHiddenInput())
</code></pre>
<p>Thanks,<br />
Richard.</p>
| 4 | 2009-07-30T10:00:57Z | 1,205,637 | <p>Use <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/" rel="nofollow">formsets</a>.</p>
| 3 | 2009-07-30T10:02:50Z | [
"python",
"django",
"django-forms"
] |
Django - Repeating a form field n times in one form | 1,205,626 | <p>I have a Django form with several fields in it one of which needs to be repeated n times (where n is not known at design time) how would I go about coding this (if it is possible at all)?</p>
<p>e.g. instead of :-</p>
<pre><code>Class PaymentsForm(forms.form):
invoice = forms.CharField(widget=ValueHiddenInput())
total = forms.CharField(widget=ValueHiddenInput())
item_name_1 = forms.CharField(widget=ValueHiddenInput())
item_name_2 = forms.CharField(widget=ValueHiddenInput())
.
.
.
item_name_n = forms.CharField(widget=ValueHiddenInput())
</code></pre>
<p>I need something like :- </p>
<pre><code>Class PaymentsForm(forms.form):
invoice = forms.CharField(widget=ValueHiddenInput())
total = forms.CharField(widget=ValueHiddenInput())
item_name[n] = forms.CharField(widget=ValueHiddenInput())
</code></pre>
<p>Thanks,<br />
Richard.</p>
| 4 | 2009-07-30T10:00:57Z | 1,205,767 | <p>You can create the repeated fields in the <code>__init__</code> method of your form:</p>
<pre><code>class PaymentsForm(forms.Form):
invoice = forms.CharField(widget=forms.HiddenInput())
total = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(PaymentsForm, self).__init__(*args, **kwargs)
for i in xrange(10):
self.fields['item_name_%d' % i] = forms.CharField(widget=forms.HiddenInput())
</code></pre>
<p>More about dynamic forms can be found e.g. <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/">here</a></p>
<p>edit: to answer the question in your comment: just give the number of repetitions as an argument to the <code>__init__</code> method, something like this:</p>
<pre><code> def __init__(self, repetitions, *args, **kwargs):
super(PaymentsForm, self).__init__(*args, **kwargs)
for i in xrange(repetitions):
self.fields['item_name_%d' % i] = forms.CharField(widget=forms.HiddenInput())
</code></pre>
<p>and then in your view (or wherever you create the form):</p>
<pre><code>payments_form = PaymentsForm(10)
</code></pre>
| 8 | 2009-07-30T10:34:46Z | [
"python",
"django",
"django-forms"
] |
How do I get monotonic time durations in python? | 1,205,722 | <p>I want to log how long something takes in real walltime. Currently I'm doing this:</p>
<pre><code>startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
</code></pre>
<p>But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.</p>
<p>I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system.</p>
<p>I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().</p>
| 38 | 2009-07-30T10:23:55Z | 1,205,762 | <p>That function is simple enough that you can use ctypes to access it:</p>
<pre><code>#!/usr/bin/env python
__all__ = ["monotonic_time"]
import ctypes, os
CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)
]
librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_gettime = librt.clock_gettime
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
def monotonic_time():
t = timespec()
if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
return t.tv_sec + t.tv_nsec * 1e-9
if __name__ == "__main__":
print monotonic_time()
</code></pre>
| 59 | 2009-07-30T10:33:40Z | [
"python",
"linux",
"benchmarking",
"clock"
] |
How do I get monotonic time durations in python? | 1,205,722 | <p>I want to log how long something takes in real walltime. Currently I'm doing this:</p>
<pre><code>startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
</code></pre>
<p>But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.</p>
<p>I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system.</p>
<p>I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().</p>
| 38 | 2009-07-30T10:23:55Z | 4,486,117 | <p>As pointed out in <a href="http://stackoverflow.com/questions/3657289/linux-clock-gettimeclock-monotonic-strange-non-monotonic-behavior">this question</a>, avoiding NTP readjustments on Linux requires CLOCK_MONOTONIC_RAW. That's defined as 4 on Linux (since 2.6.28).</p>
<p>Portably getting the correct constant #defined in a C header from Python is tricky; there is h2py, but that doesn't really help you get the value at runtime.</p>
| 8 | 2010-12-20T01:03:00Z | [
"python",
"linux",
"benchmarking",
"clock"
] |
How do I get monotonic time durations in python? | 1,205,722 | <p>I want to log how long something takes in real walltime. Currently I'm doing this:</p>
<pre><code>startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
</code></pre>
<p>But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.</p>
<p>I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system.</p>
<p>I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().</p>
| 38 | 2009-07-30T10:23:55Z | 14,416,514 | <p>Now, in Python 3.3 you would use <a href="http://www.python.org/dev/peps/pep-0418/#time-monotonic">time.monotonic</a>.</p>
| 19 | 2013-01-19T16:49:11Z | [
"python",
"linux",
"benchmarking",
"clock"
] |
How can I get non-blocking socket connect()'s? | 1,205,863 | <p>I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.</p>
<p>Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:</p>
<p>The async stuff works like a charm, but when I connect to 100 hosts, and I get 100 timeouts (timeout = 10 secs) then I wait 1000 seconds, just to find out all my connections failed.</p>
<p>Is there any way to also get non blocking socket connects?
My socket is already set to nonBlocking, but calls to connect() are still blocking.</p>
<p>Reducing the timeout is not an acceptable solution.</p>
<p>I am doing this in Python, but I guess the programming language doesnt really matter in this case.</p>
<p>Do I really need to use threads?</p>
| 9 | 2009-07-30T10:58:16Z | 1,205,944 | <p>Did you look at the <a href="http://docs.python.org/library/asyncore.html#module-asyncore" rel="nofollow">asyncore</a> module? Might be just what you need.</p>
| 0 | 2009-07-30T11:15:18Z | [
"python",
"sockets",
"asynchronous",
"nonblocking"
] |
How can I get non-blocking socket connect()'s? | 1,205,863 | <p>I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.</p>
<p>Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:</p>
<p>The async stuff works like a charm, but when I connect to 100 hosts, and I get 100 timeouts (timeout = 10 secs) then I wait 1000 seconds, just to find out all my connections failed.</p>
<p>Is there any way to also get non blocking socket connects?
My socket is already set to nonBlocking, but calls to connect() are still blocking.</p>
<p>Reducing the timeout is not an acceptable solution.</p>
<p>I am doing this in Python, but I guess the programming language doesnt really matter in this case.</p>
<p>Do I really need to use threads?</p>
| 9 | 2009-07-30T10:58:16Z | 1,205,978 | <p>Use the <a href="http://docs.python.org/library/select.html"><code>select</code></a> module. This allows you to wait for I/O completion on multiple non-blocking sockets. Here's <a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000600000000000000000">some more information</a> on select. From the linked-to page:</p>
<blockquote>
<p>In C, coding <code>select</code> is fairly complex.
In Python, it's a piece of cake, but
it's close enough to the C version
that if you understand select in
Python, you'll have little trouble
with it in C.</p>
</blockquote>
<pre><code>ready_to_read, ready_to_write, in_error = select.select(
potential_readers,
potential_writers,
potential_errs,
timeout)
</code></pre>
<blockquote>
<p>You pass <code>select</code> three lists: the first
contains all sockets that you might
want to try reading; the second all
the sockets you might want to try
writing to, and the last (normally
left empty) those that you want to
check for errors. You should note that
a socket can go into more than one
list. The <code>select</code> call is blocking, but
you can give it a timeout. This is
generally a sensible thing to do -
give it a nice long timeout (say a
minute) unless you have good reason to
do otherwise.</p>
<p>In return, you will get three lists.
They have the sockets that are
actually readable, writeable and in
error. Each of these lists is a subset
(possibly empty) of the corresponding
list you passed in. And if you put a
socket in more than one input list, it
will only be (at most) in one output
list.</p>
<p>If a socket is in the output readable
list, you can be
as-close-to-certain-as-we-ever-get-in-this-business
that a <code>recv</code> on that socket will return
something. Same idea for the writeable
list. You'll be able to <code>send</code>
something. Maybe not all you want to,
but something is better than nothing.
(Actually, any reasonably healthy
socket will return as writeable - it
just means outbound network buffer
space is available.)</p>
<p>If you have a "server" socket, put it
in the potential_readers list. If it
comes out in the readable list, your
accept will (almost certainly) work.
If you have created a new socket to
connect to someone else, put it in the
potential_writers list. If it shows up
in the writeable list, you have a
decent chance that it has connected.</p>
</blockquote>
| 8 | 2009-07-30T11:21:52Z | [
"python",
"sockets",
"asynchronous",
"nonblocking"
] |
How can I get non-blocking socket connect()'s? | 1,205,863 | <p>I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.</p>
<p>Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:</p>
<p>The async stuff works like a charm, but when I connect to 100 hosts, and I get 100 timeouts (timeout = 10 secs) then I wait 1000 seconds, just to find out all my connections failed.</p>
<p>Is there any way to also get non blocking socket connects?
My socket is already set to nonBlocking, but calls to connect() are still blocking.</p>
<p>Reducing the timeout is not an acceptable solution.</p>
<p>I am doing this in Python, but I guess the programming language doesnt really matter in this case.</p>
<p>Do I really need to use threads?</p>
| 9 | 2009-07-30T10:58:16Z | 1,206,726 | <p>You need to parallelize the connects as well, since the sockets block when you set a timeout. Alternatively, you could not set a timeout, and use the select module.</p>
<p>You can do this with the dispatcher class in the <a href="http://docs.python.org/library/asyncore.html#module-asyncore">asyncore</a> module. Take a look at the basic <a href="http://docs.python.org/library/asyncore.html#asyncore-example-basic-http-client">http client example</a>. Multiple instances of that class won't block each other on connect. You can do this just as easily using threads, and I think makes tracking socket timeouts easier, but since you're already using asynchronous methods you might as well stay on the same track. </p>
<p>As an example, the following works on all my linux systems</p>
<pre><code>import asyncore, socket
class client(asyncore.dispatcher):
def __init__(self, host):
self.host = host
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, 22))
def handle_connect(self):
print 'Connected to', self.host
def handle_close(self):
self.close()
def handle_write(self):
self.send('')
def handle_read(self):
print ' ', self.recv(1024)
clients = []
for i in range(50, 100):
clients.append(client('cluster%d' % i))
asyncore.loop()
</code></pre>
<p>Where in cluster50 - cluster100, there are numerous machines that are unresponsive, or nonexistent. This immediately starts printing:</p>
<pre><code>Connected to cluster50
SSH-2.0-OpenSSH_4.3
Connected to cluster51
SSH-2.0-OpenSSH_4.3
Connected to cluster52
SSH-2.0-OpenSSH_4.3
Connected to cluster60
SSH-2.0-OpenSSH_4.3
Connected to cluster61
SSH-2.0-OpenSSH_4.3
...
</code></pre>
<p>This however does not take into account getaddrinfo, which has to block. If you're having issues resolving the dns queries, everything has to wait. You probably need to gather the dns queries separately on your own, and use the ip addresses in your async loop</p>
<p>If you want a bigger toolkit than asyncore, take a look at <a href="http://twistedmatrix.com/trac/">Twisted Matrix</a>. It's a bit heavy to get into, but it is the best network programming toolkit you can get for python.</p>
| 4 | 2009-07-30T13:47:23Z | [
"python",
"sockets",
"asynchronous",
"nonblocking"
] |
How can I get non-blocking socket connect()'s? | 1,205,863 | <p>I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.</p>
<p>Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:</p>
<p>The async stuff works like a charm, but when I connect to 100 hosts, and I get 100 timeouts (timeout = 10 secs) then I wait 1000 seconds, just to find out all my connections failed.</p>
<p>Is there any way to also get non blocking socket connects?
My socket is already set to nonBlocking, but calls to connect() are still blocking.</p>
<p>Reducing the timeout is not an acceptable solution.</p>
<p>I am doing this in Python, but I guess the programming language doesnt really matter in this case.</p>
<p>Do I really need to use threads?</p>
| 9 | 2009-07-30T10:58:16Z | 1,206,741 | <p>Use <a href="http://twistedmatrix.com" rel="nofollow">twisted</a>.</p>
<p>It is an asynchronous networking engine written in Python, supporting numerous protocols, and you can add your own. It can be used to develop clients and servers. It doesn't block on connect.</p>
| 4 | 2009-07-30T13:49:15Z | [
"python",
"sockets",
"asynchronous",
"nonblocking"
] |
How can I get non-blocking socket connect()'s? | 1,205,863 | <p>I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.</p>
<p>Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:</p>
<p>The async stuff works like a charm, but when I connect to 100 hosts, and I get 100 timeouts (timeout = 10 secs) then I wait 1000 seconds, just to find out all my connections failed.</p>
<p>Is there any way to also get non blocking socket connects?
My socket is already set to nonBlocking, but calls to connect() are still blocking.</p>
<p>Reducing the timeout is not an acceptable solution.</p>
<p>I am doing this in Python, but I guess the programming language doesnt really matter in this case.</p>
<p>Do I really need to use threads?</p>
| 9 | 2009-07-30T10:58:16Z | 1,211,859 | <p>Unfortunately there are is no example code which shows the bug, so it's a bit hard to see where this block comes from.</p>
<p>He does something like:</p>
<pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.connect(("www.nonexistingname.org", 80))
</code></pre>
<p>The socket module uses getaddrinfo internally, which is a blocking operation, especially when the hostname does not exists. A standard compliant dns client will wait some time to see if the name really does not exists or if there are just some slow dns servers involved.</p>
<p>The solution is to connect to ip-addresses only or use a dns client which allows non-blocking requests, like <a href="http://pydns.sourceforge.net/index.html">pydns</a>.</p>
| 6 | 2009-07-31T10:40:47Z | [
"python",
"sockets",
"asynchronous",
"nonblocking"
] |
Creating a new input event dispatcher in Pyglet (infra red input) | 1,206,628 | <p>I recently asked this question in the pyglet-users group, but got response, so I'm trying here instead.</p>
<p>I would like to extend Pyglet to be able to use an infra red input device supported by lirc. I've used pyLirc before ( <a href="http://pylirc.mccabe.nu/" rel="nofollow">http://pylirc.mccabe.nu/</a> ) with PyGame and I want to rewrite my application to use Pyglet instead.</p>
<p>To see if a button was pressed you would typically poll pyLirc to see if there is any button presses in its queue.</p>
<p>My question is, what is the correct way in Pyglet to integrate pyLirc?</p>
<p>I would prefer if it works in the same was as the current window keyboard/mouse events, but I'm not sure where to start.</p>
<p>I know I can create a new EventDispatcher, in which I can register the
new types of events and dispatch them after polling, like so:</p>
<pre><code>class pyLircDispatcher(pyglet.event.EventDispatcher):
def poll(self):
codes = pylirc.nextcode()
if codes is not None:
for code in codes:
self.dispatch_event('on_irbutton', code)
def on_irbutton(self, code):
pass
</code></pre>
<p>But how do I integrate that into the application's main loop to keep on calling poll() if I use pyglet.app.run() and how do I attach this eventdispatcher to my window so it works the same as the mouse and keyboard dispatchers?</p>
<p>I see that I can set up a scheduler to call poll() at regular intervals with pyglet.clock.schedule_interval, but is this the correct way to do it?</p>
| 1 | 2009-07-30T13:30:53Z | 1,242,726 | <p>The correct way is whatever works. You can always change it later if you find a better way.</p>
| 1 | 2009-08-07T03:23:08Z | [
"python",
"pyglet"
] |
Creating a new input event dispatcher in Pyglet (infra red input) | 1,206,628 | <p>I recently asked this question in the pyglet-users group, but got response, so I'm trying here instead.</p>
<p>I would like to extend Pyglet to be able to use an infra red input device supported by lirc. I've used pyLirc before ( <a href="http://pylirc.mccabe.nu/" rel="nofollow">http://pylirc.mccabe.nu/</a> ) with PyGame and I want to rewrite my application to use Pyglet instead.</p>
<p>To see if a button was pressed you would typically poll pyLirc to see if there is any button presses in its queue.</p>
<p>My question is, what is the correct way in Pyglet to integrate pyLirc?</p>
<p>I would prefer if it works in the same was as the current window keyboard/mouse events, but I'm not sure where to start.</p>
<p>I know I can create a new EventDispatcher, in which I can register the
new types of events and dispatch them after polling, like so:</p>
<pre><code>class pyLircDispatcher(pyglet.event.EventDispatcher):
def poll(self):
codes = pylirc.nextcode()
if codes is not None:
for code in codes:
self.dispatch_event('on_irbutton', code)
def on_irbutton(self, code):
pass
</code></pre>
<p>But how do I integrate that into the application's main loop to keep on calling poll() if I use pyglet.app.run() and how do I attach this eventdispatcher to my window so it works the same as the mouse and keyboard dispatchers?</p>
<p>I see that I can set up a scheduler to call poll() at regular intervals with pyglet.clock.schedule_interval, but is this the correct way to do it?</p>
| 1 | 2009-07-30T13:30:53Z | 1,262,678 | <p>It's probably too late for the OP, but I'll reply anyway in case it's helpful to anyone else.</p>
<p>Creating the event dispatcher and using pyglet.clock.schedule_interval to call poll() at regular intervals is a good way to do it.</p>
<p>To attach the event dispatcher to your window, you need to create an instance of the dispatcher and then call its <a href="http://www.pyglet.org/doc/api/pyglet.event.EventDispatcher-class.html#push%5Fhandlers" rel="nofollow">push_handlers</a> method:</p>
<pre><code>dispatcher.push_handlers(window)
</code></pre>
<p>Then you can treat the events just like any other events coming into the window.</p>
| 1 | 2009-08-11T20:18:55Z | [
"python",
"pyglet"
] |
Django ORM for desktop application | 1,206,793 | <p>Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>?</p>
| 11 | 2009-07-30T13:58:56Z | 1,206,816 | <p>Yes it is. The Commonsense Computing Project at the MIT media lab does that for ConceptNet,
a semantic network. You can get the source here: <a href="http://pypi.python.org/pypi/ConceptNet/4.0b3" rel="nofollow">http://pypi.python.org/pypi/ConceptNet/4.0b3</a></p>
| 3 | 2009-07-30T14:04:29Z | [
"python",
"django",
"orm"
] |
Django ORM for desktop application | 1,206,793 | <p>Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>?</p>
| 11 | 2009-07-30T13:58:56Z | 1,206,820 | <p>The Django people are sensible people with a philosophy of decoupling things. So yes, in theory you should be perfectly able to use Django's ORM in a standalone application. </p>
<p>Here's one guide I found: <a href="http://jystewart.net/process/2008/02/using-the-django-orm-as-a-standalone-component/">Django ORM as a standalone component</a>.</p>
| 11 | 2009-07-30T14:05:39Z | [
"python",
"django",
"orm"
] |
Django ORM for desktop application | 1,206,793 | <p>Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>?</p>
| 11 | 2009-07-30T13:58:56Z | 1,206,837 | <p>I would suggest using SQLAlchemy and a declarative layer on top of it such as <a href="http://elixir.ematia.de/trac/wiki" rel="nofollow" title="Elixir">Elixir</a> if you prefer a Django-like syntax.</p>
| 4 | 2009-07-30T14:07:59Z | [
"python",
"django",
"orm"
] |
Django ORM for desktop application | 1,206,793 | <p>Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>?</p>
| 11 | 2009-07-30T13:58:56Z | 1,211,122 | <p>I would suggest another ORM for a desktop application maybe SQLAlchemy or SQLObject.
It i possible to use the django ORM but I think other ORM are a better ones if you are going to use them standalone.</p>
| 0 | 2009-07-31T07:19:32Z | [
"python",
"django",
"orm"
] |
Django ORM for desktop application | 1,206,793 | <p>Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>?</p>
| 11 | 2009-07-30T13:58:56Z | 4,714,471 | <p><a href="http://www.python-camelot.com/" rel="nofollow">Camelot</a> seems promising if you want to do Python desktop apps using a DB. It uses SQLAlchemy though. Haven't tried it yet.</p>
| 0 | 2011-01-17T14:53:23Z | [
"python",
"django",
"orm"
] |
Django ORM for desktop application | 1,206,793 | <p>Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>?</p>
| 11 | 2009-07-30T13:58:56Z | 7,949,881 | <p>The peewee ORM has a declarative syntax that should be familiar to django users, and can be used as a standalone. Here are the project <a href="http://charlesleifer.com/docs/peewee/" rel="nofollow">docs</a></p>
| 1 | 2011-10-31T03:57:53Z | [
"python",
"django",
"orm"
] |
Importing the entire Python standard library | 1,206,832 | <p>I need a way to import the entire Python standard library into my program.</p>
<p>While this may seems like a bad idea, I want to do this is so py2exe will package the entire standard library with my program, so my users could import from it in the shell that I give them.</p>
<p>Is there an easy way to do this?</p>
<p>Bonus points: I would prefer that this action will NOT import the packages I have installed in site-packages and which did not come with Python. However, this is not critical.</p>
| 4 | 2009-07-30T14:06:50Z | 1,206,924 | <p>Hey, I just thought of something: I only need a list of all the modules in stdlib, and then I'll automatically generate a Python script that imports each of them "manually", like this:</p>
<pre><code>import re
import math
import time
# ...
</code></pre>
<p>And then include that with my program.</p>
<p>So all I need now is an easily formatted list of all the modules/packages in stdlib. Now how do I get that?</p>
<p><strong>UPDATE:</strong></p>
<p>I got the list like this: I installed Python 2.6 on a virtual machine, then ran in IDLE:</p>
<pre><code>import pkgutil
stuff = [thing[1] for thing in pkgutil.iter_modules()]
stuff.sort() # To make it easy to look through
print(stuff)
</code></pre>
<p>Then copy pasted the output into my IDE, and made a little script to write:</p>
<pre><code>if False:
import re
import email
import time
# ...
</code></pre>
<p>Into a Python module which I import in my program.</p>
<p>It works! py2exe packs the entire stdlib.</p>
<p><strong>UPDATE:</strong></p>
<p>I created a package that does this. I would upload it here but since I don't see any upload button, you can get it off my project folder:</p>
<p><a href="http://github.com/cool-RR/PythonTurtle/tree/master" rel="nofollow">http://github.com/cool-RR/PythonTurtle/tree/master</a></p>
<p>It's in the folder <code>src</code>, the package is called <code>almostimportstdlib</code> and it's documented.</p>
| 2 | 2009-07-30T14:23:01Z | [
"python",
"import",
"packaging",
"py2exe"
] |
Importing the entire Python standard library | 1,206,832 | <p>I need a way to import the entire Python standard library into my program.</p>
<p>While this may seems like a bad idea, I want to do this is so py2exe will package the entire standard library with my program, so my users could import from it in the shell that I give them.</p>
<p>Is there an easy way to do this?</p>
<p>Bonus points: I would prefer that this action will NOT import the packages I have installed in site-packages and which did not come with Python. However, this is not critical.</p>
| 4 | 2009-07-30T14:06:50Z | 1,206,973 | <p>I created a zip file from all the Python standard library and then added it to <code>sys.path</code> when the program started.</p>
<p>You can have a look at the sources <a href="http://svn.berlios.de/svnroot/repos/sconsexe/trunk/" rel="nofollow">here</a> (abandoned project)</p>
| 1 | 2009-07-30T14:29:34Z | [
"python",
"import",
"packaging",
"py2exe"
] |
How to change a GtkTreeView style in Python? | 1,207,250 | <p>I have an app written in python that presents some of its data in a tree view. By default, the tree view is a floaty white affair with little floaty triangles to expand the nodes.</p>
<p>Is it possible to change this style to be more like a Windows explorer tree view? Specifically, I'd like to have vertical lines indicating parentage of the nodes.</p>
<p>If this is possible, how would it be done?</p>
| 2 | 2009-07-30T15:09:07Z | 1,207,847 | <p>you need to create a custom <code>CellRenderer</code>s for this. the below links might help.</p>
<p><a href="http://www.pygtk.org/pygtk2tutorial/ch-TreeViewWidget.html" rel="nofollow">http://www.pygtk.org/pygtk2tutorial/ch-TreeViewWidget.html</a></p>
<p><a href="http://www.pygtk.org/pygtk2tutorial/sec-CellRenderers.html" rel="nofollow">http://www.pygtk.org/pygtk2tutorial/sec-CellRenderers.html</a></p>
| 1 | 2009-07-30T16:46:20Z | [
"python",
"gtk",
"pygtk",
"gtktreeview"
] |
How to change a GtkTreeView style in Python? | 1,207,250 | <p>I have an app written in python that presents some of its data in a tree view. By default, the tree view is a floaty white affair with little floaty triangles to expand the nodes.</p>
<p>Is it possible to change this style to be more like a Windows explorer tree view? Specifically, I'd like to have vertical lines indicating parentage of the nodes.</p>
<p>If this is possible, how would it be done?</p>
| 2 | 2009-07-30T15:09:07Z | 1,208,692 | <p>For lines linking the arrows there is a method in gtk.TreeView for that, see <a href="http://library.gnome.org/devel/pygtk/stable/class-gtktreeview.html#method-gtktreeview--set-enable-tree-lines" rel="nofollow">http://library.gnome.org/devel/pygtk/stable/class-gtktreeview.html#method-gtktreeview--set-enable-tree-lines</a></p>
| 3 | 2009-07-30T19:10:08Z | [
"python",
"gtk",
"pygtk",
"gtktreeview"
] |
Is there a Python shortcut for variable checking and assignment? | 1,207,333 | <p>I'm finding myself typing the following a lot (developing for Django, if that's relevant):</p>
<pre><code>if testVariable then:
myVariable = testVariable
else:
# something else
</code></pre>
<p>Alternatively, and more commonly (i.e. building up a parameters list)</p>
<pre><code>if 'query' in request.POST.keys() then:
myVariable = request.POST['query']
else:
# something else, probably looking at other keys
</code></pre>
<p>Is there a shortcut I just don't know about that simplifies this? Something with the kind of logic <code>myVariable = assign_if_exists(testVariable)</code>?</p>
| 6 | 2009-07-30T15:23:27Z | 1,207,353 | <p>The first instance is stated oddly... Why set a boolean to another boolean? </p>
<p>What you may mean is to set myVariable to testVariable when testVariable is not a zero length string or not None or not something that happens to evaluate to False.</p>
<p>If so, I prefer the more explicit formulations</p>
<pre><code>myVariable = testVariable if bool(testVariable) else somethingElse
myVariable = testVariable if testVariable is not None else somethingElse
</code></pre>
<p>When indexing into a dictionary, simply use <code>get</code>.</p>
<pre><code>myVariable = request.POST.get('query',"No Query")
</code></pre>
| 7 | 2009-07-30T15:27:20Z | [
"python",
"django",
"idioms"
] |
Is there a Python shortcut for variable checking and assignment? | 1,207,333 | <p>I'm finding myself typing the following a lot (developing for Django, if that's relevant):</p>
<pre><code>if testVariable then:
myVariable = testVariable
else:
# something else
</code></pre>
<p>Alternatively, and more commonly (i.e. building up a parameters list)</p>
<pre><code>if 'query' in request.POST.keys() then:
myVariable = request.POST['query']
else:
# something else, probably looking at other keys
</code></pre>
<p>Is there a shortcut I just don't know about that simplifies this? Something with the kind of logic <code>myVariable = assign_if_exists(testVariable)</code>?</p>
| 6 | 2009-07-30T15:23:27Z | 1,207,359 | <p>Assuming you want to leave myVariable untouched to its previous value in the "not exist" case,</p>
<pre><code>myVariable = testVariable or myVariable
</code></pre>
<p>deals with the first case, and</p>
<pre><code>myVariable = request.POST.get('query', myVariable)
</code></pre>
<p>deals with the second one. Neither has much to do with "exist", though (which is hardly a Python concept;-): the first one is about true or false, the second one about presence or absence of a key in a collection.</p>
| 24 | 2009-07-30T15:28:59Z | [
"python",
"django",
"idioms"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 1,207,427 | <p>You need to take a copy of the list and iterate over it first, or the iteration will fail with what may be unexpected results.</p>
<p>For example (depends on what type of list):</p>
<pre><code>for tup in somelist[:]:
etc....
</code></pre>
<p>An example:</p>
<pre><code>>>> somelist = range(10)
>>> for x in somelist:
... somelist.remove(x)
>>> somelist
[1, 3, 5, 7, 9]
>>> somelist = range(10)
>>> for x in somelist[:]:
... somelist.remove(x)
>>> somelist
[]
</code></pre>
| 117 | 2009-07-30T15:38:32Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 1,207,460 | <p>Your best approach for such an example would be a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension</a></p>
<pre><code>somelist = [tup for tup in somelist if determine(tup)]
</code></pre>
<p>In cases where you're doing something more complex than calling a <code>determine</code> function, I prefer constructing a new list and simply appending to it as I go. For example</p>
<pre><code>newlist = []
for tup in somelist:
# lots of code here, possibly setting things up for calling determine
if determine(tup):
newlist.append(tup)
somelist = newlist
</code></pre>
<p>Copying the list using <code>remove</code> might make your code look a little cleaner, as described in one of the answers below. You should definitely not do this for extremely large lists, since this involves first copying the entire list, and also performing an <code>O(n)</code> <code>remove</code> operation for each element being removed, making this an <code>O(n^2)</code> algorithm.</p>
<pre><code>for tup in somelist[:]:
# lots of code here, possibly setting things up for calling determine
if determine(tup):
newlist.append(tup)
</code></pre>
| 39 | 2009-07-30T15:41:30Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 1,207,461 | <p>You can use a list comprehension to create a new list containing only the elements you don't want to remove:</p>
<pre><code>somelist = [x for x in somelist if not determine(x)]
</code></pre>
<p>Or, by assigning to the slice <code>somelist[:]</code>, you can mutate the existing list to contain only the items you want:</p>
<pre><code>somelist[:] = [x for x in somelist if not determine(x)]
</code></pre>
<p>This approach could be useful if there are other references to <code>somelist</code> that need to reflect the changes.</p>
<p>Instead of a comprehension, you could also use <code>itertools</code>. In Python 2:</p>
<pre><code>from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
</code></pre>
<p>Or in Python 3:</p>
<pre><code>from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
</code></pre>
| 359 | 2009-07-30T15:41:33Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 1,207,485 | <pre><code>for i in xrange(len(somelist) - 1, -1, -1):
if some_condition(somelist, i):
del somelist[i]
</code></pre>
<p>You need to go backwards otherwise it's a bit like sawing off the tree-branch that you are sitting on :-)</p>
| 58 | 2009-07-30T15:44:59Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 1,207,500 | <p>For those that like functional programming:</p>
<pre><code>somelist[:] = filter(lambda tup: not determine(tup), somelist)
</code></pre>
<p>or</p>
<pre><code>from itertools import ifilterfalse
somelist[:] = list(ifilterfalse(determine, somelist))
</code></pre>
| 29 | 2009-07-30T15:46:46Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 1,208,792 | <p>The answers suggesting list comprehensions are ALMOST correct -- except that they build a completely new list and then give it the same name the old list as, they do NOT modify the old list in place. That's different from what you'd be doing by selective removal, as in @Lennart's suggestion -- it's faster, but if your list is accessed via multiple references the fact that you're just reseating one of the references and NOT altering the list object itself can lead to subtle, disastrous bugs.</p>
<p>Fortunately, it's extremely easy to get both the speed of list comprehensions AND the required semantics of in-place alteration -- just code:</p>
<pre><code>somelist[:] = [tup for tup in somelist if determine(tup)]
</code></pre>
<p>Note the subtle difference with other answers: this one is NOT assigning to a barename - it's assigning to a list slice that just happens to be the entire list, thereby replacing the list <em>contents</em> <strong>within the same Python list object</strong>, rather than just reseating one reference (from previous list object to new list object) like the other answers.</p>
| 376 | 2009-07-30T19:28:27Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 4,639,072 | <p>You might want to use filter() available as the built-in.</p>
<p><a href="http://docs.python.org/library/functions.html#filter" rel="nofollow">http://docs.python.org/library/functions.html#filter</a></p>
| 2 | 2011-01-09T12:20:34Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 25,363,359 | <p>If you want to do anything else during the iteration, it may be nice to get both the index (which guarantees you being able to reference it, for example if you have a list of dicts) and the actual list item contents.</p>
<pre><code>inlist = [{'field1':10, 'field2':20}, {'field1':30, 'field2':15}]
for idx, i in enumerate(inlist):
do some stuff with i['field1']
if somecondition:
xlist.append(idx)
for i in reversed(xlist): del inlist[i]
</code></pre>
<p><code>enumerate</code> gives you access to the item and the index at once. <code>reversed</code> is so that the indices that you're going to later delete don't change on you. </p>
| 2 | 2014-08-18T12:30:16Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 31,350,162 | <p>You can try for-looping in reverse so for some_list you'll do something like:</p>
<pre><code>list_len = len(some_list)
for i in range(list_len):
reverse_i = list_len - 1 - i
cur = some_list[reverse_i]
# some logic with cur element
if some_condition:
some_list.pop(reverse_i)
</code></pre>
<p>This way the index is aligned and doesn't suffer from the list updates (regardless whether you pop cur element or not).</p>
| 0 | 2015-07-10T20:58:49Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 34,238,688 | <p><strong>The <a href="https://docs.python.org/2/tutorial/controlflow.html#for-statements" rel="nofollow">official Python 2 tutorial 4.2. "for Statements"</a> says</strong>:</p>
<blockquote>
<p>If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:</p>
</blockquote>
<pre><code>>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
</code></pre>
<p>which is what was suggested at: <a href="http://stackoverflow.com/a/1207427/895245">http://stackoverflow.com/a/1207427/895245</a></p>
<p><strong>The <a href="https://docs.python.org/2/reference/compound_stmts.html#for" rel="nofollow">Python 2 documentation 7.3. "The for statement"</a> gives the same advice</strong>:</p>
<blockquote>
<p>Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,</p>
</blockquote>
<pre><code>for x in a[:]:
if x < 0: a.remove(x)
</code></pre>
| 7 | 2015-12-12T10:18:22Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 34,310,158 | <p>I needed to do something similar and in my case the problem was memory - I needed to merge multiple dataset objects within a list, after doing some stuff with them, as a new object, and needed to get rid of each entry I was merging to avoid duplicating all of them and blowing up memory. In my case having the objects in a dictionary instead of a list worked fine:</p>
<p>```</p>
<pre><code>k = range(5)
v = ['a','b','c','d','e']
d = {key:val for key,val in zip(k, v)}
print d
for i in range(5):
print d[i]
d.pop(i)
print d
</code></pre>
<p>```</p>
| 1 | 2015-12-16T10:56:37Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 36,096,883 | <p>It might be smart to also just create a new list if the current list item meets the desired criteria. </p>
<p>so:</p>
<pre><code>for item in originalList:
if (item != badValue):
newList.append(item)
</code></pre>
<p>and to avoid having to re-code the entire project with the new lists name:</p>
<pre><code>originalList[:] = newList[:]
</code></pre>
| 1 | 2016-03-19T01:41:18Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 37,277,264 | <p>TLDR:</p>
<p>I wrote a library that allows you to do this:</p>
<pre><code>from fluidIter import FluidIterable
fSomeList = FluidIterable(someList)
for tup in fSomeList:
if determine(tup):
# remove 'tup' without "breaking" the iteration
fSomeList.remove(tup)
# tup has also been removed from 'someList'
# as well as 'fSomeList'
</code></pre>
<p>It's best to use another method if possible that doesn't require modifying your iterable while iterating over it, but for some algorithms it might not be that straight forward. And so if you are sure that you really do want the code pattern described in the original question, it is possible.</p>
<p>Should work on all mutable sequences not just lists.</p>
<hr>
<p>Full answer:</p>
<p>Edit: The last code example in this answer gives a use case for <strong><em>why</em></strong> you might sometimes want to modify a list in place rather than use a list comprehension. The first part of the answers serves as tutorial of <strong><em>how</em></strong> an array can be modified in place.</p>
<p>The solution follows on from <a href="http://stackoverflow.com/a/6260097/4451578">this</a> answer (for a related question) from senderle. Which explains how the the array index is updated while iterating through a list that has been modified. The solution below is designed to correctly track the array index even if the list is modified.</p>
<p>Download <code>fluidIter.py</code> from <a href="https://github.com/alanbacon/FluidIterator" rel="nofollow">here</a> <code>https://github.com/alanbacon/FluidIterator</code>, it is just a single file so no need to install git. There is no installer so you will need to make sure that the file is in the python path your self. The code has been written for python 3 and is untested on python 2.</p>
<pre><code>from fluidIter import FluidIterable
l = [0,1,2,3,4,5,6,7,8]
fluidL = FluidIterable(l)
for i in fluidL:
print('initial state of list on this iteration: ' + str(fluidL))
print('current iteration value: ' + str(i))
print('popped value: ' + str(fluidL.pop(2)))
print(' ')
print('Final List Value: ' + str(l))
</code></pre>
<p>This will produce the following output:</p>
<pre><code>initial state of list on this iteration: [0, 1, 2, 3, 4, 5, 6, 7, 8]
current iteration value: 0
popped value: 2
initial state of list on this iteration: [0, 1, 3, 4, 5, 6, 7, 8]
current iteration value: 1
popped value: 3
initial state of list on this iteration: [0, 1, 4, 5, 6, 7, 8]
current iteration value: 4
popped value: 4
initial state of list on this iteration: [0, 1, 5, 6, 7, 8]
current iteration value: 5
popped value: 5
initial state of list on this iteration: [0, 1, 6, 7, 8]
current iteration value: 6
popped value: 6
initial state of list on this iteration: [0, 1, 7, 8]
current iteration value: 7
popped value: 7
initial state of list on this iteration: [0, 1, 8]
current iteration value: 8
popped value: 8
Final List Value: [0, 1]
</code></pre>
<p>Above we have used the <code>pop</code> method on the fluid list object. Other common iterable methods are also implemented such as <code>del fluidL[i]</code>, <code>.remove</code>, <code>.insert</code>, <code>.append</code>, <code>.extend</code>. The list can also be modified using slices (<code>sort</code> and <code>reverse</code> methods are not implemented).</p>
<p>The only condition is that you must only modify the list in place, if at any point <code>fluidL</code> or <code>l</code> were reassigned to a different list object the code would not work. The original <code>fluidL</code> object would still be used by the for loop but would become out of scope for us to modify.</p>
<p>i.e.</p>
<pre><code>fluidL[2] = 'a' # is OK
fluidL = [0, 1, 'a', 3, 4, 5, 6, 7, 8] # is not OK
</code></pre>
<p>If we want to access the current index value of the list we cannot use enumerate, as this only counts how many times the for loop has run. Instead we will use the iterator object directly.</p>
<pre><code>fluidArr = FluidIterable([0,1,2,3])
# get iterator first so can query the current index
fluidArrIter = fluidArr.__iter__()
for i, v in enumerate(fluidArrIter):
print('enum: ', i)
print('current val: ', v)
print('current ind: ', fluidArrIter.currentIndex)
print(fluidArr)
fluidArr.insert(0,'a')
print(' ')
print('Final List Value: ' + str(fluidArr))
</code></pre>
<p>This will output the following:</p>
<pre><code>enum: 0
current val: 0
current ind: 0
[0, 1, 2, 3]
enum: 1
current val: 1
current ind: 2
['a', 0, 1, 2, 3]
enum: 2
current val: 2
current ind: 4
['a', 'a', 0, 1, 2, 3]
enum: 3
current val: 3
current ind: 6
['a', 'a', 'a', 0, 1, 2, 3]
Final List Value: ['a', 'a', 'a', 'a', 0, 1, 2, 3]
</code></pre>
<p>The <code>FluidIterable</code> class just provides a wrapper for the original list object. The original object can be accessed as a property of the fluid object like so:</p>
<pre><code>originalList = fluidArr.fixedIterable
</code></pre>
<p>More examples / tests can be found in the <code>if __name__ is "__main__":</code> section at the bottom of <code>fluidIter.py</code>. These are worth looking at because they explain what happens in various situations. Such as: Replacing a large sections of the list using a slice. Or using (and modifying) the same iterable in nested for loops.</p>
<p>As I stated to start with: this is a complicated solution that will hurt the readability of your code and make it more difficult to debug. Therefore other solutions such as the list comprehensions mentioned in David Raznick's <a href="http://stackoverflow.com/a/1207461/4451578">answer</a> should be considered first. That being said, I have found times where this class has been useful to me and has been easier to use than keeping track of the indices of elements that need deleting.</p>
<hr>
<p>Edit: As mentioned in the comments, this answer does not really present a problem for which this approach provides a solution. I will try to address that here:</p>
<p>List comprehensions provide a way to generate a new list but these approaches tend to look at each element in isolation rather than the current state of the list as a whole.</p>
<p>i.e.</p>
<pre><code>newList = [i for i in oldList if testFunc(i)]
</code></pre>
<p>But what if the result of the <code>testFunc</code> depends on the elements that have been added to <code>newList</code> already? Or the elements still in <code>oldList</code> that might be added next? There might still be a way to use a list comprehension but it will begin to lose it's elegance, and for me it feels easier to modify a list in place.</p>
<p>The code below is one example of an algorithm that suffers from the above problem. The algorithm will reduce a list so that no element is a multiple of any other element.</p>
<pre><code>randInts = [70, 20, 61, 80, 54, 18, 7, 18, 55, 9]
fRandInts = FluidIterable(randInts)
fRandIntsIter = fRandInts.__iter__()
# for each value in the list (outer loop)
# test against every other value in the list (inner loop)
for i in fRandIntsIter:
print(' ')
print('outer val: ', i)
innerIntsIter = fRandInts.__iter__()
for j in innerIntsIter:
innerIndex = innerIntsIter.currentIndex
# skip the element that the outloop is currently on
# because we don't want to test a value against itself
if not innerIndex == fRandIntsIter.currentIndex:
# if the test element, j, is a multiple
# of the reference element, i, then remove 'j'
if j%i == 0:
print('remove val: ', j)
# remove element in place, without breaking the
# iteration of either loop
del fRandInts[innerIndex]
# end if multiple, then remove
# end if not the same value as outer loop
# end inner loop
# end outerloop
print('')
print('final list: ', randInts)
</code></pre>
<p>The output and the final reduced list are shown below</p>
<pre><code>outer val: 70
outer val: 20
remove val: 80
outer val: 61
outer val: 54
outer val: 18
remove val: 54
remove val: 18
outer val: 7
remove val: 70
outer val: 55
outer val: 9
remove val: 18
final list: [20, 61, 7, 55, 9]
</code></pre>
| 0 | 2016-05-17T13:15:10Z | [
"python",
"iteration"
] |
Remove items from a list while iterating in Python | 1,207,406 | <p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p>
| 447 | 2009-07-30T15:36:42Z | 39,293,411 | <p>One possible solution, useful if you don't want to use comprehensions:</p>
<pre><code>alist = ['good', 'bad', 'good', 'bad', 'good']
i = 0
for x in alist[:]:
if x == 'bad':
alist.pop(i)
i -= 1
else:
# do something cool with x or just print x
print x
i += 1
</code></pre>
| 0 | 2016-09-02T13:16:37Z | [
"python",
"iteration"
] |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | <p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
| 258 | 2009-07-30T15:41:11Z | 1,207,479 | <pre><code>title = u"Klüft skräms inför pÃ¥ fédéral électoral groÃe"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
</code></pre>
| 369 | 2009-07-30T15:44:32Z | [
"python",
"string",
"unicode",
"type-conversion"
] |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | <p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
| 258 | 2009-07-30T15:41:11Z | 1,207,496 | <p>Here is an example:</p>
<pre><code>>>> u = u'â¬â¬â¬'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'
</code></pre>
| 42 | 2009-07-30T15:46:26Z | [
"python",
"string",
"unicode",
"type-conversion"
] |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | <p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
| 258 | 2009-07-30T15:41:11Z | 1,207,634 | <p>Well, if you're willing/ready to switch to Python 3 (which you may not be due to the backwards incompatibility with some Python 2 code), you don't have to do any converting; all text in Python 3 is represented with Unicode strings, which also means that there's no more usage of the <code>u'<text>'</code> syntax. You also have what are, in effect, strings of bytes, which are used to represent data (which may be an encoded string).</p>
<p><a href="http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit" rel="nofollow">http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit</a></p>
<p>(Of course, if you're currently using Python 3, then the problem is likely something to do with how you're attempting to save the text to a file.)</p>
| 2 | 2009-07-30T16:09:31Z | [
"python",
"string",
"unicode",
"type-conversion"
] |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | <p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
| 258 | 2009-07-30T15:41:11Z | 1,207,836 | <p>If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first <em>encode</em> it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending on the character), etc. To convert that string into a particular encoding, you can use:</p>
<pre><code>>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'
</code></pre>
<p>This raw string of bytes can be written to a file. However, note that when reading it back, you must know what encoding it is in and decode it using that same encoding.</p>
<p>When writing to files, you can get rid of this manual encode/decode process by using the <a href="http://docs.python.org/library/codecs.html">codecs</a> module. So, to open a file that encodes all Unicode strings into <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>, use:</p>
<pre><code>import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string) # Stored on disk as UTF-8
</code></pre>
<p>Do note that anything else that is using these files must understand what encoding the file is in if they want to read them. If you are the only one doing the reading/writing this isn't a problem, otherwise make sure that you write in a form understandable by whatever else uses the files.</p>
<p>In Python 3, this form of file access is the default, and the built-in <code>open</code> function will take an encoding parameter and always translate to/from Unicode strings (the default string object in Python 3) for files opened in text mode.</p>
| 75 | 2009-07-30T16:44:54Z | [
"python",
"string",
"unicode",
"type-conversion"
] |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | <p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
| 258 | 2009-07-30T15:41:11Z | 1,211,102 | <p>You can use encode to ASCII if you don't need to translate the non-ASCII characters:</p>
<pre><code>>>> a=u"aaaà çççñññ"
>>> type(a)
<type 'unicode'>
>>> a.encode('ascii','ignore')
'aaa'
>>> a.encode('ascii','replace')
'aaa???????'
>>>
</code></pre>
| 178 | 2009-07-31T07:13:09Z | [
"python",
"string",
"unicode",
"type-conversion"
] |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | <p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
| 258 | 2009-07-30T15:41:11Z | 13,073,070 | <pre><code>>>> text=u'abcd'
>>> str(text)
'abcd'
</code></pre>
<p>If a simple conversion.</p>
| 60 | 2012-10-25T16:27:20Z | [
"python",
"string",
"unicode",
"type-conversion"
] |
How to workaround lack of multiple ao.lock? | 1,207,497 | <p>I'm programming a simple pyS60 app, not really done anything with python or using multiple threads before so this is all a bit new to me.
In order to keep the app open, I set an e32.Ao_lock to wait() after the body of the application is initialised, and then signal the lock on the exit_key_handler.</p>
<p>One of the tasks the program may do is open a third party app, UpCode. This scans a barcode and copies the barcode string to the clipboard. When I close UpCode, my application should resume and paste the input from the clipboard.
I know this can be accomplished using Ao.lock, but I've already called an instance of this. Ideally my application would regain focus after noticing something had been pasted to the clipboard.
Can I accomplish what I need with one of the sleep or timer functions?</p>
<p>You can find the full script <a href="http://www.moppy.co.uk/scanscrobble.py" rel="nofollow">here</a>, and I've abbreviated it to the necessary parts below:</p>
<pre><code>lock=e32.Ao_lock()
# Quit the script
def quit():
lock.signal()
# Callback function will be called when the requested service is complete.
def launch_app_callback(trans_id, event_id, input_params):
if trans_id != appmanager_id and event_id != scriptext.EventCompleted:
print "Error in servicing the request"
print "Error code is: " + str(input_params["ReturnValue"]["ErrorCode"])
if "ErrorMessage" in input_params["ReturnValue"]:
print "Error message is: " + input_params["ReturnValue"]["ErrorMessage"]
else:
print "\nWaiting for UpCode to close"
#lock.signal()
# launch UpCode to scan barcode and get barcode from clipboard
def scan_barcode():
msg('Launching UpCode to scan barcode.\nPlease exit UpCode after the barcode has been copied to the clipboard')
# Load appmanage service
appmanager_handle = scriptext.load('Service.AppManager', 'IAppManager')
# Make a request to query the required information in asynchronous mode
appmanager_id = appmanager_handle.call('LaunchApp', {'ApplicationID': u's60uid://0x2000c83e'}, callback=launch_app_callback)
#lock.wait()
#print "Request complete!"
barcode = clipboard.Get()
return barcode
# handle the selection made from the main body listbox
def handle_selection():
if (lb.current() == 0):
barcode = scan_barcode()
elif (lb.current() ==1):
barcode = clipboard.Get()
elif (lb.current() ==2):
barcode = input_barcode()
found = False
if is_barcode(barcode):
found, mbid, album, artist = identify_release(barcode)
else:
msg('Valid barcode not found. Please try again/ another method/ another CD')
return
if found:
go = appuifw.query(unicode('Found: ' + artist + ' - ' + album + '\nScrobble it?'), 'query')
if (go == 1):
now = datetime.datetime.utcnow()
scrobble_tracks(mbid, album, artist, now)
else:
appuifw.note(u'Scrobbling cancelled', 'info')
else:
appuifw.note(u'No match found for this barcode.', 'info')
# Set the application body up
appuifw.app.exit_key_handler = quit
appuifw.app.title = u"ScanScrobbler"
entries = [(u"Scan a barcode", u"Opens UpCode for scanning"),
(u"Submit barcode from clipboard", u"If you've already copied a barcode there"),
(u"Enter barcode by hand", u"Using numeric keypad")
]
lb = appuifw.Listbox(entries, handle_selection)
appuifw.app.body = lb
lock.wait()
</code></pre>
<p>Any and all help appreciated.</p>
| 1 | 2009-07-30T15:46:27Z | 3,085,134 | <p>I solved this problem by defining a separate second lock, and making sure only one was waiting at a time. It seems to work without any problem. Current code can be found <a href="http://code.google.com/p/scanscrobbler/" rel="nofollow">hosted on google code</a></p>
| 0 | 2010-06-21T13:41:24Z | [
"python",
"multithreading",
"locking",
"nokia",
"pys60"
] |
Check absolute paths in Python | 1,207,954 | <p>How can I check whether two file paths point to the same file in Python?</p>
| 9 | 2009-07-30T17:04:34Z | 1,207,974 | <p>You want to use <a href="http://docs.python.org/library/os.path.html"><code>os.path.abspath(path)</code></a> to normalize each path for comparison.</p>
<pre><code>os.path.abspath(foo) == os.path.abspath(bar)
</code></pre>
| 6 | 2009-07-30T17:07:36Z | [
"python",
"path"
] |
Check absolute paths in Python | 1,207,954 | <p>How can I check whether two file paths point to the same file in Python?</p>
| 9 | 2009-07-30T17:04:34Z | 1,207,984 | <p>A simple string compare should work:</p>
<pre><code>import os
print os.path.abspath(first) == os.path.abspath(second)
</code></pre>
<p>Credit to Andrew, he corrected my initial post which included a call to <code>os.path.normpath</code>: this is unneeded because the implementation of <code>os.path.abspath</code> does it for you.</p>
| 3 | 2009-07-30T17:09:26Z | [
"python",
"path"
] |
Check absolute paths in Python | 1,207,954 | <p>How can I check whether two file paths point to the same file in Python?</p>
| 9 | 2009-07-30T17:04:34Z | 1,207,987 | <pre><code>$ touch foo
$ ln -s foo bar
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> help(os.path.samefile)
Help on function samefile in module posixpath:
samefile(f1, f2)
Test whether two pathnames reference the same actual file
>>> os.path.samefile("foo", "bar")
True
</code></pre>
| 23 | 2009-07-30T17:10:04Z | [
"python",
"path"
] |
Check absolute paths in Python | 1,207,954 | <p>How can I check whether two file paths point to the same file in Python?</p>
| 9 | 2009-07-30T17:04:34Z | 3,178,889 | <p>On Windows systems, there is no <code>samefile</code> function and you also have to worry about case. The <code>normcase</code> function from <code>os.path</code> can be combined with <code>abspath</code> to handle this case.</p>
<pre><code>from os.path import abspath, normcase
def are_paths_equivalent(path1, path2):
return normcase(abspath(path1)) == normcase(abspath(path2))
</code></pre>
<p>This will consider "C:\SPAM\Eggs.txt" to be equivalent to "c:\spam\eggs.txt" on Windows.</p>
<p>Note that unlike <code>samefile</code>, all methods based on normalizing and comparing paths will not be aware of cases where completely different paths refer to the same file. On Windows, this means that if you use SUBST, MKLINK or mounted network shares to create multiple distinct paths to the same file, none of these solutions will be able to say "that's the same file". Hopefully that's not too much of a problem most of the time.</p>
| 0 | 2010-07-05T10:51:50Z | [
"python",
"path"
] |
Check absolute paths in Python | 1,207,954 | <p>How can I check whether two file paths point to the same file in Python?</p>
| 9 | 2009-07-30T17:04:34Z | 5,176,531 | <p>May be one can use os.path.relpath(path1, path2) as workaround for os.path.samefile(path1, path2) on Windows?</p>
<p>If os.path.relpath(path1, path2) returns '.' than path1 and path2 point to the same place</p>
| 0 | 2011-03-03T04:06:39Z | [
"python",
"path"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 1,208,112 | <p>request.POST is just a dictionary-like object, so just index into it with dict syntax.</p>
<p>Assuming your form field is fred, you could do something like this:</p>
<pre><code>if 'fred' in request.POST:
mydata = request.POST['fred']
</code></pre>
<p>Alternately, use a form object to deal with the POST data.</p>
| -3 | 2009-07-30T17:31:31Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 1,208,285 | <p>The HTTP POST payload is just a flat bunch of bytes. Django (like most frameworks) decodes it into a dictionary from either URL encoded parameters, or MIME-multipart encoding. If you just dump the JSON data in the POST content, Django won't decode it. Either do the JSON decoding from the full POST content (not the dictionary); or put the JSON data into a MIME-multipart wrapper.</p>
<p>In short, show the JavaScript code. The problem seems to be there.</p>
| 5 | 2009-07-30T18:03:45Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 3,020,756 | <p>If you are posting JSON to Django, I think you want <code>request.body</code> (<code>request.raw_post_data</code> on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.</p>
<p>Here is an example using JavaScript, <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>, jquery-json and Django.</p>
<p>JavaScript:</p>
<pre><code>var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
allDay: calEvent.allDay };
$.ajax({
url: '/event/save-json/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(myEvent),
dataType: 'text',
success: function(result) {
alert(result.Result);
}
});
</code></pre>
<p>Django:</p>
<pre><code>def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.body
return HttpResponse("OK")
</code></pre>
<p>Django < 1.4:</p>
<pre><code> def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.raw_post_data
return HttpResponse("OK")
</code></pre>
| 147 | 2010-06-11T06:56:22Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 3,244,765 | <p>I had the same problem. I had been posting a complex JSON response, and I couldn't read my data using the request.POST dictionary.</p>
<p>My JSON POST data was:</p>
<pre><code>//JavaScript code:
//Requires json2.js and jQuery.
var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
json_response = JSON.stringify(response); // proper serialization method, read
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
$.post('url',json_response);
</code></pre>
<p>In this case you need to use method provided by aurealus. Read the request.body and deserialize it with the json stdlib.</p>
<pre><code>#Django code:
import json
def save_data(request):
if request.method == 'POST':
json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4
try:
data = json_data['data']
except KeyError:
HttpResponseServerError("Malformed data!")
HttpResponse("Got json data")
</code></pre>
| 35 | 2010-07-14T09:13:29Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 10,990,800 | <p><code>request.raw_response</code> is now deprecated. Use <code>request.body</code> instead to process non-conventional form data such as XML payloads, binary images, etc.</p>
<p><a href="https://docs.djangoproject.com/en/dev/ref/request-response/">Django documentation on the issue</a>.</p>
| 22 | 2012-06-12T05:06:01Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 20,122,297 | <p><code>request.raw_post_data</code> has been deprecated. Use <code>request.body</code> instead</p>
| 5 | 2013-11-21T13:28:39Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 23,008,197 | <p><strong>Method 1</strong></p>
<p>Client : Send as <code>JSON</code></p>
<pre><code>$.ajax({
url: 'example.com/ajax/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
processData: false,
data: JSON.stringify({'name':'John', 'age': 42}),
...
});
//Sent as a JSON object {'name':'John', 'age': 42}
</code></pre>
<p>Server :</p>
<pre><code>data = json.loads(request.body) # {'name':'John', 'age': 42}
</code></pre>
<p><strong>Method 2</strong></p>
<p>Client : Send as <code>x-www-form-urlencoded</code> <br>
(Note: <code>contentType</code> & <code>processData</code> have changed, <code>JSON.stringify</code> is not needed)</p>
<pre><code>$.ajax({
url: 'example.com/ajax/',
type: 'POST',
data: {'name':'John', 'age': 42},
contentType: 'application/x-www-form-urlencoded; charset=utf-8', //Default
processData: true,
});
//Sent as a query string name=John&age=42
</code></pre>
<p>Server : </p>
<pre><code>data = request.POST # will be <QueryDict: {u'name':u'John', u'age': 42}>
</code></pre>
<hr>
<p>Changed in 1.5+ : <a href="https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests">https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests</a></p>
<blockquote>
<p><strong>Non-form data in HTTP requests</strong>
: <br>request.POST will no longer include data posted via HTTP requests with
non form-specific content-types in the header. In prior versions, data
posted with content-types other than multipart/form-data or
application/x-www-form-urlencoded would still end up represented in
the request.POST attribute. Developers wishing to access the raw POST
data for these cases, should use the request.body attribute instead.</p>
</blockquote>
<p>Probably related </p>
<ul>
<li><a href="https://groups.google.com/forum/#!msg/django-developers/s8OZ9yNh-8c/yWeY138TpFEJ">https://groups.google.com/forum/#!msg/django-developers/s8OZ9yNh-8c/yWeY138TpFEJ</a></li>
<li><a href="https://code.djangoproject.com/ticket/17942">https://code.djangoproject.com/ticket/17942</a> . Fixed in 1.7</li>
<li><a href="http://homakov.blogspot.in/2012/06/x-www-form-urlencoded-vs-json-pros-and.html">http://homakov.blogspot.in/2012/06/x-www-form-urlencoded-vs-json-pros-and.html</a></li>
</ul>
| 21 | 2014-04-11T09:07:42Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 24,939,871 | <p>on django 1.6 python 3.3</p>
<p>client</p>
<pre><code>$.ajax({
url: '/urll/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(json_object),
dataType: 'json',
success: function(result) {
alert(result.Result);
}
});
</code></pre>
<p>server</p>
<pre><code>def urll(request):
if request.is_ajax():
if request.method == 'POST':
print ('Raw Data:', request.body)
print ('type(request.body):', type(request.body)) # this type is bytes
print(json.loads(request.body.decode("utf-8")))
</code></pre>
| 5 | 2014-07-24T17:06:46Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 27,599,561 | <pre><code>html code
file name : view.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/view/',
data: {
'fruit': selected
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
Django code:
Inside views.py
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
</code></pre>
| 2 | 2014-12-22T09:07:32Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 29,273,926 | <p>Using Angular you should add header to request or add it to module config
headers: <code>{'Content-Type': 'application/x-www-form-urlencoded'}</code></p>
<pre><code>$http({
url: url,
method: method,
timeout: timeout,
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
</code></pre>
| -1 | 2015-03-26T08:29:18Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Where's my JSON data in my incoming Django request? | 1,208,067 | <p>I'm trying to process incoming JSON/Ajax requests with Django/Python.</p>
<p><a href="https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax"><code>request.is_ajax()</code></a> is <code>True</code> on the request, but I have no idea where the payload is with the JSON data.</p>
<p><code>request.POST.dir</code> contains this:</p>
<pre><code>['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
</code></pre>
<p>There are apparently no keys in the request post keys.</p>
<p>When I look at the POST in <a href="http://en.wikipedia.org/wiki/Firebug">Firebug</a>, there is JSON data being sent up in the request.</p>
| 94 | 2009-07-30T17:22:53Z | 34,495,127 | <p>Its important to remember Python 3 has a different way to represent strings - they are byte arrays.</p>
<p>Using Django 1.9 and Python 2.7 and sending the JSON data in the main body (not a header) you would use something like:</p>
<pre><code>mydata = json.loads(request.body)
</code></pre>
<p>But for Django 1.9 and Python 3.4 you would use:</p>
<pre><code>mydata = json.loads(request.body.decode("utf-8"))
</code></pre>
<p>I just went through this learning curve making my first Py3 Django app!</p>
| 2 | 2015-12-28T14:11:44Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | <p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p>
<p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p>
<p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p>
<pre><code>from numpy import *
def comb(a,b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
</code></pre>
<p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p>
<pre><code>def combs(a,m):
return reduce(comb,[a]*m)
</code></pre>
<p>And then I evaluate my function like this:</p>
<pre><code>values = combs(np.arange(0,1,0.1),6)
for val in values:
print F(val)
</code></pre>
<p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p>
<p>Do you know any more efficient way of doing this with numpy? </p>
<p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
| 73 | 2009-07-30T17:32:27Z | 1,208,739 | <p><a href="http://docs.python.org/library/itertools.html#itertools.combinations">itertools.combinations</a> is in general the fastest way to get combinations from a Python container (if you do in fact want combinations, i.e., arrangements WITHOUT repetitions and independent of order; that's not what your code appears to be doing, but I can't tell whether that's because your code is buggy or because you're using the wrong terminology).</p>
<p>If you want something different than combinations perhaps other iterators in itertools, <code>product</code> or <code>permutations</code>, might serve you better. For example, it looks like your code is roughly the same as:</p>
<pre><code>for val in itertools.product(np.arange(0, 1, 0.1), repeat=6):
print F(val)
</code></pre>
<p>All of these iterators yield tuples, not lists or numpy arrays, so if your F is picky about getting specifically a numpy array you'll have to accept the extra overhead of constructing or clearing and re-filling one at each step.</p>
| 26 | 2009-07-30T19:19:11Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | <p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p>
<p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p>
<p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p>
<pre><code>from numpy import *
def comb(a,b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
</code></pre>
<p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p>
<pre><code>def combs(a,m):
return reduce(comb,[a]*m)
</code></pre>
<p>And then I evaluate my function like this:</p>
<pre><code>values = combs(np.arange(0,1,0.1),6)
for val in values:
print F(val)
</code></pre>
<p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p>
<p>Do you know any more efficient way of doing this with numpy? </p>
<p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
| 73 | 2009-07-30T17:32:27Z | 1,235,363 | <p>Here's a pure-numpy implementation. It's ca. 5Ã faster than using itertools.</p>
<pre><code>
import numpy as np
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = n / arrays[0].size
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m,1:])
for j in xrange(1, arrays[0].size):
out[j*m:(j+1)*m,1:] = out[0:m,1:]
return out
</code></pre>
| 114 | 2009-08-05T19:48:42Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | <p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p>
<p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p>
<p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p>
<pre><code>from numpy import *
def comb(a,b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
</code></pre>
<p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p>
<pre><code>def combs(a,m):
return reduce(comb,[a]*m)
</code></pre>
<p>And then I evaluate my function like this:</p>
<pre><code>values = combs(np.arange(0,1,0.1),6)
for val in values:
print F(val)
</code></pre>
<p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p>
<p>Do you know any more efficient way of doing this with numpy? </p>
<p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
| 73 | 2009-07-30T17:32:27Z | 7,481,643 | <p>It looks like you want a grid to evaluate your function, in which case you can use <code>numpy.ogrid</code> (open) or <code>numpy.mgrid</code> (fleshed out):</p>
<pre><code>import numpy
my_grid = numpy.mgrid[[slice(0,1,0.1)]*6]
</code></pre>
| 6 | 2011-09-20T07:37:36Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | <p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p>
<p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p>
<p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p>
<pre><code>from numpy import *
def comb(a,b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
</code></pre>
<p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p>
<pre><code>def combs(a,m):
return reduce(comb,[a]*m)
</code></pre>
<p>And then I evaluate my function like this:</p>
<pre><code>values = combs(np.arange(0,1,0.1),6)
for val in values:
print F(val)
</code></pre>
<p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p>
<p>Do you know any more efficient way of doing this with numpy? </p>
<p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
| 73 | 2009-07-30T17:32:27Z | 25,463,061 | <p>You can do something like this</p>
<pre><code>import numpy as np
def cartesian_coord(*arrays):
grid = np.meshgrid(*arrays)
coord_list = [entry.ravel() for entry in grid]
points = np.vstack(coord_list).T
return points
a = np.arange(4) # fake data
print(cartesian_coord(*6*[a])
</code></pre>
<p>which gives</p>
<pre><code>array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 2],
...,
[3, 3, 3, 3, 3, 1],
[3, 3, 3, 3, 3, 2],
[3, 3, 3, 3, 3, 3]])
</code></pre>
| 5 | 2014-08-23T14:38:44Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | <p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p>
<p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p>
<p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p>
<pre><code>from numpy import *
def comb(a,b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
</code></pre>
<p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p>
<pre><code>def combs(a,m):
return reduce(comb,[a]*m)
</code></pre>
<p>And then I evaluate my function like this:</p>
<pre><code>values = combs(np.arange(0,1,0.1),6)
for val in values:
print F(val)
</code></pre>
<p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p>
<p>Do you know any more efficient way of doing this with numpy? </p>
<p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
| 73 | 2009-07-30T17:32:27Z | 25,655,090 | <p>The following numpy implementation should be approx. 2x the speed of the given answer:</p>
<pre><code>def cartesian2(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
</code></pre>
| 8 | 2014-09-03T23:22:41Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | <p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p>
<p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p>
<p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p>
<pre><code>from numpy import *
def comb(a,b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
</code></pre>
<p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p>
<pre><code>def combs(a,m):
return reduce(comb,[a]*m)
</code></pre>
<p>And then I evaluate my function like this:</p>
<pre><code>values = combs(np.arange(0,1,0.1),6)
for val in values:
print F(val)
</code></pre>
<p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p>
<p>Do you know any more efficient way of doing this with numpy? </p>
<p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
| 73 | 2009-07-30T17:32:27Z | 34,931,627 | <p>Here's yet another way, using pure NumPy, no recursion, no list comprehension, and no explicit for loops. It's about 20% slower than the original answer, and it's based on np.meshgrid.</p>
<pre><code>def cartesian(*arrays):
mesh = np.meshgrid(*arrays) # standard numpy meshgrid
dim = len(mesh) # number of dimensions
elements = mesh[0].size # number of elements, any index will do
flat = np.concatenate(mesh).ravel() # flatten the whole meshgrid
reshape = np.reshape(flat, (dim, elements)).T # reshape and transpose
return reshape
</code></pre>
<p>For example,</p>
<pre><code>x = np.arange(3)
a = cartesian(x, x, x, x, x)
print(a)
</code></pre>
<p>gives</p>
<pre><code>[[0 0 0 0 0]
[0 0 0 0 1]
[0 0 0 0 2]
...,
[2 2 2 2 0]
[2 2 2 2 1]
[2 2 2 2 2]]
</code></pre>
| 1 | 2016-01-21T18:33:29Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.