title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python with Netbeans 6.5
462,068
<p>Can you give me some links or explain how to configure an existing python project onto Netbeans? I'm trying it these days and it continues to crash also code navigation doesn't work well and I've problems with debugging. Surely these problems are related to my low eperience about python and I need support also in trivial things as organizing source folders, imports ecc,, thank you very much. Valerio</p>
1
2009-01-20T16:37:53Z
462,107
<p>Python support is in beta, and as someone who works with NB for a past 2 years, I can say that even a release versions are buggy and sometimes crashes. Early Ruby support was also very shaky.</p>
1
2009-01-20T16:48:32Z
[ "python", "netbeans", "project" ]
Packet sniffing in Python (Windows)
462,439
<p>What is the best way to sniff network packets using Python?</p> <p>I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).</p> <p>Does anyone know of a better solution?</p> <p>UPD:</p> <p>After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.</p> <p>I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: <a href="http://trac.secdev.org/scapy/ticket/166" rel="nofollow">http://trac.secdev.org/scapy/ticket/166</a>, hope they can do something with it.</p> <p>Anyways, just thought I'd let y'all know.</p>
5
2009-01-20T18:18:33Z
462,447
<p>Use <a href="http://sourceforge.net/projects/pylibpcap/">python-libpcap</a>.</p> <pre><code>import pcap p = pcap.pcapObject() dev = pcap.lookupdev() p.open_live(dev, 1600, 0, 100) #p.setnonblock(1) try: for pktlen, data, timestamp in p: print "[%s] Got data: %s" % (time.strftime('%H:%M', time.localtime(timestamp)), data) except KeyboardInterrupt: print '%s' % sys.exc_type print 'shutting down' print ('%d packets received, %d packets dropped' ' %d packets dropped by interface') % p.stats() </code></pre>
9
2009-01-20T18:20:59Z
[ "python", "sniffing", "sniffer" ]
Packet sniffing in Python (Windows)
462,439
<p>What is the best way to sniff network packets using Python?</p> <p>I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).</p> <p>Does anyone know of a better solution?</p> <p>UPD:</p> <p>After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.</p> <p>I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: <a href="http://trac.secdev.org/scapy/ticket/166" rel="nofollow">http://trac.secdev.org/scapy/ticket/166</a>, hope they can do something with it.</p> <p>Anyways, just thought I'd let y'all know.</p>
5
2009-01-20T18:18:33Z
462,473
<p>Another option is <a href="http://code.google.com/p/pypcap/" rel="nofollow">pypcap</a>.</p> <p>To parse the results, <a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a> is very slick.</p>
1
2009-01-20T18:26:40Z
[ "python", "sniffing", "sniffer" ]
Packet sniffing in Python (Windows)
462,439
<p>What is the best way to sniff network packets using Python?</p> <p>I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).</p> <p>Does anyone know of a better solution?</p> <p>UPD:</p> <p>After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.</p> <p>I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: <a href="http://trac.secdev.org/scapy/ticket/166" rel="nofollow">http://trac.secdev.org/scapy/ticket/166</a>, hope they can do something with it.</p> <p>Anyways, just thought I'd let y'all know.</p>
5
2009-01-20T18:18:33Z
462,497
<p>Using <a href="http://code.google.com/p/pypcap/" rel="nofollow">pypcap</a>:</p> <pre><code>import dpkt, pcap pc = pcap.pcap() # construct pcap object pc.setfilter('icmp') # filter out unwanted packets for timestamp, packet in pc: print dpkt.ethernet.Ethernet(packet) </code></pre> <p>output sample:</p> <pre><code>Ethernet(src='\x00\x03G\xb2M\xe4', dst='\x00\x03G\x06h\x18', data=IP(src='\n\x00\x01\x1c', dst='\n\x00\x01\x10', sum=39799, len=60, p=1, ttl=128, id=35102, data=ICMP(sum=24667, type=8, data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi')))) Ethernet(src='\x00\x03G\x06h\x18', dst='\x00\x03G\xb2M\xe4', data=IP(src='\n\x00\x01\x10', dst='\n\x00\x01\x1c', sum=43697, len=60, p=1, ttl=255, id=64227, data=ICMP(sum=26715, data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi')))) </code></pre>
7
2009-01-20T18:31:15Z
[ "python", "sniffing", "sniffer" ]
Packet sniffing in Python (Windows)
462,439
<p>What is the best way to sniff network packets using Python?</p> <p>I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).</p> <p>Does anyone know of a better solution?</p> <p>UPD:</p> <p>After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.</p> <p>I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: <a href="http://trac.secdev.org/scapy/ticket/166" rel="nofollow">http://trac.secdev.org/scapy/ticket/166</a>, hope they can do something with it.</p> <p>Anyways, just thought I'd let y'all know.</p>
5
2009-01-20T18:18:33Z
32,301,251
<h1>The hard way</h1> <p>You can sniff all of the IP packets using a raw socket.<br> Raw socket is a socket the sends and receives data in binary.<br> Binary in python is represented in a string which looks like this <code>\x00\xff</code>... every <code>\x..</code> is a byte.<br> To read an IP packet you need to analyze the received packet in binary according to the IP protocol.</p> <p>This is and image of the format of the IP protocol with the sized in bits of every header.</p> <p><a href="http://cfs13.blog.daum.net/image/6/blog/2008/04/26/19/15/481300a2a7674&amp;filename=IP_Header.png"><img src="http://cfs13.blog.daum.net/image/6/blog/2008/04/26/19/15/481300a2a7674&amp;filename=IP_Header.png" alt="IP protocol format"></a></p> <p>This tutorial might help you understand the proccess of understanding a raw packet and splitting it to headers: <a href="http://www.binarytides.com/python-packet-sniffer-code-linux/">http://www.binarytides.com/python-packet-sniffer-code-linux/</a></p> <h1>The easy way</h1> <p>Another method to sniff IP packets very easily is to use the scapy module.</p> <pre><code>from scapy.all import * sniff(filter="ip", prn=lambda x:x.sprintf("{IP:%IP.src% -&gt; %IP.dst%\n}") </code></pre> <p>This code will print for you the source IP and the destination IP for every IP packet. You can do much more with scapy by reading it's documentation here: <a href="http://www.secdev.org/projects/scapy/doc/usage.html">http://www.secdev.org/projects/scapy/doc/usage.html</a></p> <p>It depends on the goal you are trying to achieve but if you need to build a project the one it's features is sniffing IP packets then I recommend to use scapy for more stable scripts. </p>
5
2015-08-30T21:19:05Z
[ "python", "sniffing", "sniffer" ]
Packet sniffing in Python (Windows)
462,439
<p>What is the best way to sniff network packets using Python?</p> <p>I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).</p> <p>Does anyone know of a better solution?</p> <p>UPD:</p> <p>After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.</p> <p>I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: <a href="http://trac.secdev.org/scapy/ticket/166" rel="nofollow">http://trac.secdev.org/scapy/ticket/166</a>, hope they can do something with it.</p> <p>Anyways, just thought I'd let y'all know.</p>
5
2009-01-20T18:18:33Z
34,158,773
<p>you can use raw sockets, with your interface ip address (in admin mode),</p> <pre><code>import socket s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP) s.bind(("YOUR_INTERFACE_IP",0)) s.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1) s.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON) while True: data = s.recvfrom(10000) print data </code></pre>
2
2015-12-08T14:45:49Z
[ "python", "sniffing", "sniffer" ]
Can I get the matrix determinant using Numpy?
462,500
<p>I read in the manual of Numpy that there is function <code>det(M)</code> that can calculate the determinant. However, I can't find the <code>det()</code> method in Numpy.</p> <p>By the way, I use Python 2.5. There should be no compatibility problems with Numpy.</p>
29
2009-01-20T18:32:16Z
462,514
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.det.html"><code>numpy.linalg.det</code></a> to compute the determinant of an array:</p> <pre><code>In [1]: import numpy In [2]: M = [[1, 2], [3, 4]] In [3]: print numpy.linalg.det(M) Out[3]: -2.0000000000000004 </code></pre>
51
2009-01-20T18:35:26Z
[ "python", "numpy" ]
Can I get the matrix determinant using Numpy?
462,500
<p>I read in the manual of Numpy that there is function <code>det(M)</code> that can calculate the determinant. However, I can't find the <code>det()</code> method in Numpy.</p> <p>By the way, I use Python 2.5. There should be no compatibility problems with Numpy.</p>
29
2009-01-20T18:32:16Z
19,317,237
<p>For <strong>large arrays</strong> underflow/overflow may occur when using <code>numpy.linalg.det</code>, or you may get <code>inf</code> or <code>-inf</code> as an answer.</p> <p>In many of these cases you can use <code>numpy.linalg.slogdet</code> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.slogdet.html">see documentation</a>), which returns:</p> <pre><code>(sign, logdet) </code></pre> <p>where <code>sign</code> is the sign and <code>logdet</code> the logarithm of the determinant, such that you can calculate the determinant <code>det</code> doing:</p> <pre><code>det = np.exp(logdet) </code></pre>
14
2013-10-11T11:37:57Z
[ "python", "numpy" ]
Is it possible to make text translucent in wxPython?
462,933
<p>I am adding some wx.StaticText objects on top of my main wx.Frame, which already has a background image applied. However, the StaticText always seems to draw with a solid (opaque) background color, hiding the image. I have tried creating a wx.Color object and changing the alpha value there, but that yields no results. Is there any way I can put text on the frame and have the background shine through? And furthermore, is it possible to make the text itself translucent? Thanks.</p>
1
2009-01-20T20:20:18Z
464,706
<p>You probably need some graphics rendering widget. As far as I know, in wxPython you can use either built-in wxGraphicsContext or pyCairo directly. Cairo is more powerful. However, I don't know the details.</p>
1
2009-01-21T10:19:09Z
[ "python", "wxpython", "transparency", "opacity" ]
Is it possible to make text translucent in wxPython?
462,933
<p>I am adding some wx.StaticText objects on top of my main wx.Frame, which already has a background image applied. However, the StaticText always seems to draw with a solid (opaque) background color, hiding the image. I have tried creating a wx.Color object and changing the alpha value there, but that yields no results. Is there any way I can put text on the frame and have the background shine through? And furthermore, is it possible to make the text itself translucent? Thanks.</p>
1
2009-01-20T20:20:18Z
598,202
<p>I would try aggdraw into a small canvas.</p> <p>Any Static Text uses the platform's native label machinery, so you don't get that sort of control over it.</p>
0
2009-02-28T15:53:54Z
[ "python", "wxpython", "transparency", "opacity" ]
Schwartzian sort example in "Text Processing in Python"
463,032
<p>I was browsing through "Text Processing in Python" and tried its <a href="http://gnosis.cx/TPiP/038.code" rel="nofollow">example</a> about Schwartzian sort. </p> <p>I used following structure for sample data which also contains empty lines. I sorted this data by fifth column:<br /> 383230 -49 -78 1 <strong>100034</strong> '06 text' 9562 'text' 720 'text' 867<br /> 335067 -152 -18 3 <strong>100030</strong> 'text' 2400 'text' 2342 'text' 696<br /> 136592 21 230 3 <strong>100035</strong> '03. text' 10368 'text' 1838 'text' 977 </p> <p>Code used for Schwartzian sorting:</p> <pre><code>for n in range(len(lines)): # Create the transform lst = string.split(lines[n]) if len(lst) &gt;= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) lines.sort() # Native sort for n in range(len(lines)): # Restore original lines lines[n] = lines[n][1] open('tmp.schwartzian','w').writelines(lines) </code></pre> <p>I don't get how the author intended that short or empty lines should go to end of file by using this code. Lines are sorted after the if-else structure, thus raising empty lines to top of file. Short lines of course work as supposed with the custom sort (fourth_word function) as implemented in the example. </p> <p>This is now bugging me, so any ideas? If I'm correct about this then how would you ensure that short lines actually stay at end of file?</p> <p><strong>EDIT:</strong> I noticed the square brackets around '\377'. This messed up sort() so I removed those brackets and output started working. </p> <pre><code>else: # Short lines to end lines[n] = (['\377'], lines[n]) print type(lines[n][0]) &gt;&gt;&gt; (type 'list') </code></pre> <p>I accepted nosklo's answer for good clarification about the meaning of '\377' and for his improved algorithm. Many thanks for the other answers also!</p> <p>If curious, I used 2 MB sample file which took 0.95 secs with the custom sort and 0.09 with the Schwartzian sort while creating identical output files. It works!</p>
0
2009-01-20T20:47:26Z
463,081
<p>I don't know what is the question, so I'll try to clarify things in a general way.</p> <p>This algorithm sorts lines by getting the 4th field and placing it in front of the lines. Then built-in <code>sort()</code> will use this field to sort. Later the original line is restored.</p> <p>The lines empty or shorter than 5 fields fall into the <code>else</code> part of this structure:</p> <pre><code>if len(lst) &gt;= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) </code></pre> <p>It adds a <code>['\377']</code> into the first field of the list to sort. The algorithm does that in hope that '\377' (the last char in ascii table) will be <em>bigger</em> than any string found in the 5th field. So the original line should go to bottom when doing the sort.</p> <p>I hope that clarifies the question. If not, perhaps you should indicate exaclty what is it that you want to know.</p> <p>A better, generic version of the same algorithm:</p> <pre><code>sort_by_field(list_of_str, field_number, separator=' ', defaultvalue='\xFF') # decorates each value: for i, line in enumerate(list_of_str)): fields = line.split(separator) try: # places original line as second item: list_of_str[i] = (fields[field_number], line) except IndexError: list_of_str[i] = (defaultvalue, line) list_of_str.sort() # sorts list, in place # undecorates values: for i, group in enumerate(list_of_str)) list_of_str[i] = group[1] # the second item is original line </code></pre> <p>The algorithm you provided is equivalent to this one.</p>
1
2009-01-20T20:58:59Z
[ "python" ]
Schwartzian sort example in "Text Processing in Python"
463,032
<p>I was browsing through "Text Processing in Python" and tried its <a href="http://gnosis.cx/TPiP/038.code" rel="nofollow">example</a> about Schwartzian sort. </p> <p>I used following structure for sample data which also contains empty lines. I sorted this data by fifth column:<br /> 383230 -49 -78 1 <strong>100034</strong> '06 text' 9562 'text' 720 'text' 867<br /> 335067 -152 -18 3 <strong>100030</strong> 'text' 2400 'text' 2342 'text' 696<br /> 136592 21 230 3 <strong>100035</strong> '03. text' 10368 'text' 1838 'text' 977 </p> <p>Code used for Schwartzian sorting:</p> <pre><code>for n in range(len(lines)): # Create the transform lst = string.split(lines[n]) if len(lst) &gt;= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) lines.sort() # Native sort for n in range(len(lines)): # Restore original lines lines[n] = lines[n][1] open('tmp.schwartzian','w').writelines(lines) </code></pre> <p>I don't get how the author intended that short or empty lines should go to end of file by using this code. Lines are sorted after the if-else structure, thus raising empty lines to top of file. Short lines of course work as supposed with the custom sort (fourth_word function) as implemented in the example. </p> <p>This is now bugging me, so any ideas? If I'm correct about this then how would you ensure that short lines actually stay at end of file?</p> <p><strong>EDIT:</strong> I noticed the square brackets around '\377'. This messed up sort() so I removed those brackets and output started working. </p> <pre><code>else: # Short lines to end lines[n] = (['\377'], lines[n]) print type(lines[n][0]) &gt;&gt;&gt; (type 'list') </code></pre> <p>I accepted nosklo's answer for good clarification about the meaning of '\377' and for his improved algorithm. Many thanks for the other answers also!</p> <p>If curious, I used 2 MB sample file which took 0.95 secs with the custom sort and 0.09 with the Schwartzian sort while creating identical output files. It works!</p>
0
2009-01-20T20:47:26Z
463,085
<p>An empty line won't pass the test</p> <pre><code>if len(lst) &gt;= 4: </code></pre> <p>so it will have ['\377'] as its sort key, not the 5th column of your data, which is <code>lst[4]</code> ( <code>lst[0]</code> is the first column).</p>
0
2009-01-20T20:59:29Z
[ "python" ]
Schwartzian sort example in "Text Processing in Python"
463,032
<p>I was browsing through "Text Processing in Python" and tried its <a href="http://gnosis.cx/TPiP/038.code" rel="nofollow">example</a> about Schwartzian sort. </p> <p>I used following structure for sample data which also contains empty lines. I sorted this data by fifth column:<br /> 383230 -49 -78 1 <strong>100034</strong> '06 text' 9562 'text' 720 'text' 867<br /> 335067 -152 -18 3 <strong>100030</strong> 'text' 2400 'text' 2342 'text' 696<br /> 136592 21 230 3 <strong>100035</strong> '03. text' 10368 'text' 1838 'text' 977 </p> <p>Code used for Schwartzian sorting:</p> <pre><code>for n in range(len(lines)): # Create the transform lst = string.split(lines[n]) if len(lst) &gt;= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) lines.sort() # Native sort for n in range(len(lines)): # Restore original lines lines[n] = lines[n][1] open('tmp.schwartzian','w').writelines(lines) </code></pre> <p>I don't get how the author intended that short or empty lines should go to end of file by using this code. Lines are sorted after the if-else structure, thus raising empty lines to top of file. Short lines of course work as supposed with the custom sort (fourth_word function) as implemented in the example. </p> <p>This is now bugging me, so any ideas? If I'm correct about this then how would you ensure that short lines actually stay at end of file?</p> <p><strong>EDIT:</strong> I noticed the square brackets around '\377'. This messed up sort() so I removed those brackets and output started working. </p> <pre><code>else: # Short lines to end lines[n] = (['\377'], lines[n]) print type(lines[n][0]) &gt;&gt;&gt; (type 'list') </code></pre> <p>I accepted nosklo's answer for good clarification about the meaning of '\377' and for his improved algorithm. Many thanks for the other answers also!</p> <p>If curious, I used 2 MB sample file which took 0.95 secs with the custom sort and 0.09 with the Schwartzian sort while creating identical output files. It works!</p>
0
2009-01-20T20:47:26Z
463,120
<p>Well, it will sort short lines <em>almost</em> at the end, but not quite always. </p> <p>Actually, both the "naive" and the schwartzian version are flawed (in different ways). Nosklo and wbg already explained the algorithm, and you probably learn more if you try to find the error in the schwartzian version yourself, therefore I will give you only a hint for now:</p> <blockquote> <p>Long lines that contain certain text in the fourth column will sort later than short lines.</p> </blockquote> <p>Add a comment if you need more help.</p>
0
2009-01-20T21:07:02Z
[ "python" ]
Schwartzian sort example in "Text Processing in Python"
463,032
<p>I was browsing through "Text Processing in Python" and tried its <a href="http://gnosis.cx/TPiP/038.code" rel="nofollow">example</a> about Schwartzian sort. </p> <p>I used following structure for sample data which also contains empty lines. I sorted this data by fifth column:<br /> 383230 -49 -78 1 <strong>100034</strong> '06 text' 9562 'text' 720 'text' 867<br /> 335067 -152 -18 3 <strong>100030</strong> 'text' 2400 'text' 2342 'text' 696<br /> 136592 21 230 3 <strong>100035</strong> '03. text' 10368 'text' 1838 'text' 977 </p> <p>Code used for Schwartzian sorting:</p> <pre><code>for n in range(len(lines)): # Create the transform lst = string.split(lines[n]) if len(lst) &gt;= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) lines.sort() # Native sort for n in range(len(lines)): # Restore original lines lines[n] = lines[n][1] open('tmp.schwartzian','w').writelines(lines) </code></pre> <p>I don't get how the author intended that short or empty lines should go to end of file by using this code. Lines are sorted after the if-else structure, thus raising empty lines to top of file. Short lines of course work as supposed with the custom sort (fourth_word function) as implemented in the example. </p> <p>This is now bugging me, so any ideas? If I'm correct about this then how would you ensure that short lines actually stay at end of file?</p> <p><strong>EDIT:</strong> I noticed the square brackets around '\377'. This messed up sort() so I removed those brackets and output started working. </p> <pre><code>else: # Short lines to end lines[n] = (['\377'], lines[n]) print type(lines[n][0]) &gt;&gt;&gt; (type 'list') </code></pre> <p>I accepted nosklo's answer for good clarification about the meaning of '\377' and for his improved algorithm. Many thanks for the other answers also!</p> <p>If curious, I used 2 MB sample file which took 0.95 secs with the custom sort and 0.09 with the Schwartzian sort while creating identical output files. It works!</p>
0
2009-01-20T20:47:26Z
464,815
<p>Not directly related to the question, but note that in recent versions of python (since 2.3 or 2.4 I think), the transform and untransform can be performed automatically using the <code>key</code> argument to <code>sort()</code> or <code>sorted()</code>. eg:</p> <pre><code>def key_func(line): lst = string.split(line) if len(lst) &gt;= 4: return lst[4] else: return '\377' lines.sort(key=key_func) </code></pre>
2
2009-01-21T10:53:14Z
[ "python" ]
Schwartzian sort example in "Text Processing in Python"
463,032
<p>I was browsing through "Text Processing in Python" and tried its <a href="http://gnosis.cx/TPiP/038.code" rel="nofollow">example</a> about Schwartzian sort. </p> <p>I used following structure for sample data which also contains empty lines. I sorted this data by fifth column:<br /> 383230 -49 -78 1 <strong>100034</strong> '06 text' 9562 'text' 720 'text' 867<br /> 335067 -152 -18 3 <strong>100030</strong> 'text' 2400 'text' 2342 'text' 696<br /> 136592 21 230 3 <strong>100035</strong> '03. text' 10368 'text' 1838 'text' 977 </p> <p>Code used for Schwartzian sorting:</p> <pre><code>for n in range(len(lines)): # Create the transform lst = string.split(lines[n]) if len(lst) &gt;= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) lines.sort() # Native sort for n in range(len(lines)): # Restore original lines lines[n] = lines[n][1] open('tmp.schwartzian','w').writelines(lines) </code></pre> <p>I don't get how the author intended that short or empty lines should go to end of file by using this code. Lines are sorted after the if-else structure, thus raising empty lines to top of file. Short lines of course work as supposed with the custom sort (fourth_word function) as implemented in the example. </p> <p>This is now bugging me, so any ideas? If I'm correct about this then how would you ensure that short lines actually stay at end of file?</p> <p><strong>EDIT:</strong> I noticed the square brackets around '\377'. This messed up sort() so I removed those brackets and output started working. </p> <pre><code>else: # Short lines to end lines[n] = (['\377'], lines[n]) print type(lines[n][0]) &gt;&gt;&gt; (type 'list') </code></pre> <p>I accepted nosklo's answer for good clarification about the meaning of '\377' and for his improved algorithm. Many thanks for the other answers also!</p> <p>If curious, I used 2 MB sample file which took 0.95 secs with the custom sort and 0.09 with the Schwartzian sort while creating identical output files. It works!</p>
0
2009-01-20T20:47:26Z
8,031,908
<p>Although the used of the Schwartzian transform is pretty outdated for Python it is worth mentioning that you could have written the code this way to avoid the possibility of a line with line[4] starting with <code>\377</code> being sorted into the wrong place</p> <pre><code>for n in range(len(lines)): lst = lines[n].split() if len(lst)&gt;4: lines[n] = ((0, lst[4]), lines[n]) else: lines[n] = ((1,), lines[n]) </code></pre> <p>Since tuples are compared elementwise, the tuples starting with <code>1</code> will <code>always</code> be sorted to the bottom.</p> <p>Also note that the test should be <code>len(list)&gt;4</code> instead of <code>&gt;=</code></p> <p>The same logic applies when using the modern equivalent AKA the <code>key=</code> function</p> <pre><code>def key_func(line): lst = line.split() if len(lst)&gt;4: return 0, lst[4] else: return 1, lines.sort(key=key_func) </code></pre>
0
2011-11-07T01:36:14Z
[ "python" ]
UnicodeEncodeError with BeautifulSoup 3.1.0.1 and Python 2.5.2
463,215
<p>With BeautifulSoup 3.1.0.1 and Python 2.5.2, and trying to parse a web page in French. However, as soon as I call findAll, I get the following error:</p> <p><em>UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1146: ordinal not in range(128)</em></p> <p>Below is the code I am currently running:</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html") soup = BeautifulSoup(page, fromEncoding="latin1") r = soup.findAll("table") print r </code></pre> <p>Does anybody have an idea why? </p> <p>Thanks!</p> <p><strong>UPDATE</strong>: As resquested, below is the full Traceback </p> <pre><code>Traceback (most recent call last): File "[...]\test.py", line 6, in &lt;module&gt; print r UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128) </code></pre>
4
2009-01-20T21:33:25Z
463,382
<p>Here is another idea. Your terminal is not capable of displaying an unicode string from Python. The interpreter tries to convert it to ASCII first. You should encode it explicitly before printing. I don't know the exact semantics of <code>soup.findAll()</code>. But it is probably something like:</p> <pre><code>for t in soup.findAll("table"): print t.encode('latin1') </code></pre> <p>If <code>t</code> really is a string. Maybe its just another object from which you have to build the data that you want to display.</p>
11
2009-01-20T22:24:20Z
[ "python", "encoding", "screen-scraping", "beautifulsoup" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
463,630
<pre><code>isinstance(n, int) </code></pre> <p>If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this):</p> <pre><code>type(n) is int </code></pre> <p>this:</p> <pre><code>return int(n) == n </code></pre> <p>isn't such a good idea, as cross-type comparisons can be true - notably <code>int(3.0)==3.0</code></p>
21
2009-01-21T00:06:11Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
463,635
<pre><code>if type(n) is int </code></pre> <p>This checks if <code>n</code> is a Python int, and <em>only</em> an int. It won't accept subclasses of <code>int</code>.</p> <p>Type-checking, however, does not fit the "Python way". You better use <code>n</code> as an int, and if it throws an exception, catch it and act upon it.</p>
3
2009-01-21T00:08:19Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
463,833
<p>Don't type check. The whole point of duck typing is that you shouldn't have to. For instance, what if someone did something like this:</p> <pre><code>class MyInt(int): # ... extra stuff ... </code></pre>
1
2009-01-21T01:32:11Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
463,953
<p>Yeah, as Evan said, don't type check. Just try to use the value:</p> <pre><code>def myintfunction(value): """ Please pass an integer """ return 2 + value </code></pre> <p>That doesn't have a typecheck. It is much better! Let's see what happens when I try it:</p> <pre><code>&gt;&gt;&gt; myintfunction(5) 7 </code></pre> <p>That works, because it is an integer. Hm. Lets try some text.</p> <pre><code>&gt;&gt;&gt; myintfunction('text') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in myintfunction TypeError: unsupported operand type(s) for +: 'int' and 'str' </code></pre> <p>It shows an error, TypeError, which is what it should do anyway. If caller wants to catch that, it is possible. </p> <p>What would you do if you did a typecheck? Show an error right? So you don't have to typecheck because the error is already showing up automatically.</p> <p>Plus since you didn't typecheck, you have your function working with other types:</p> <p>Floats:</p> <pre><code>&gt;&gt;&gt; print myintfunction(2.2) 4.2 </code></pre> <p>Complex numbers:</p> <pre><code>&gt;&gt;&gt; print myintfunction(5j) (2+5j) </code></pre> <p>Decimals:</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; myintfunction(decimal.Decimal('15')) Decimal("17") </code></pre> <p>Even completely arbitrary objects that can add numbers!</p> <pre><code>&gt;&gt;&gt; class MyAdderClass(object): ... def __radd__(self, value): ... print 'got some value: ', value ... return 25 ... &gt;&gt;&gt; m = MyAdderClass() &gt;&gt;&gt; print myintfunction(m) got some value: 2 25 </code></pre> <p>So you clearly get nothing by typechecking. And lose a lot.</p> <hr> <h1>UPDATE:</h1> <p>Since you've edited the question, it is now clear that your application calls some upstream routine that makes sense only with ints. </p> <p>That being the case, I still think you should pass the parameter <strong>as received</strong> to the upstream function. The upstream function will deal with it correctly e.g. raising an error if it needs to. I highly <strong>doubt that</strong> your function that deals with IPs will behave strangely if you pass it a float. If you can give us the name of the library we can check that for you.</p> <p>But... If the upstream function will behave incorrectly and kill some kids if you pass it a float (I still highly doubt it), then just just call <code>int()</code> on it:</p> <pre><code>def myintfunction(value): """ Please pass an integer """ return upstreamfunction(int(value)) </code></pre> <p>You're still not typechecking, so you get most benefits of not typechecking.</p> <hr> <p>If even after all that, you really want to type check, despite it reducing your application's readability and performance for absolutely no benefit, use an <code>assert</code> to do it.</p> <pre><code>assert isinstance(...) assert type() is xxxx </code></pre> <p>That way we can turn off <code>assert</code>s and remove this <code>&lt;sarcasm&gt;</code><em>feature</em><code>&lt;/sarcasm&gt;</code> from the program by calling it as</p> <pre><code>python -OO program.py </code></pre>
17
2009-01-21T02:50:17Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
682,400
<p>Programming in Python and performing typechecking as you might in other languages does seem like choosing a screwdriver to bang a nail in with. It is more elegant to use Python's exception handling features.</p> <p>From an interactive command line, you can run a statement like:</p> <pre><code>int('sometext') </code></pre> <p>That will generate an error - ipython tells me:</p> <pre><code>&lt;type 'exceptions.ValueError'&gt;: invalid literal for int() with base 10: 'sometext' </code></pre> <p>Now you can write some code like:</p> <pre><code>try: int(myvar) + 50 except ValueError: print "Not a number" </code></pre> <p>That can be customised to perform whatever operations are required AND to catch any errors that are expected. It looks a bit convoluted but fits the syntax and idioms of Python and results in very readable code (once you become used to speaking Python).</p>
1
2009-03-25T16:34:53Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
1,789,397
<p>I would be tempted to to something like:</p> <pre><code>def check_and_convert(x): x = int(x) assert 0 &lt;= x &lt;= 255, "must be between 0 and 255 (inclusive)" return x class IPv4(object): """IPv4 CIDR prefixes is A.B.C.D/E where A-D are integers in the range 0-255, and E is an int in the range 0-32.""" def __init__(self, a, b, c, d, e=0): self.a = check_and_convert(a) self.b = check_and_convert(a) self.c = check_and_convert(a) self.d = check_and_convert(a) assert 0 &lt;= x &lt;= 32, "must be between 0 and 32 (inclusive)" self.e = int(e) </code></pre> <p>That way when you are using it anything can be passed in yet you only store a valid integer. </p>
0
2009-11-24T11:14:35Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
8,256,603
<p>how about:</p> <pre><code>def ip(string): subs = string.split('.') if len(subs) != 4: raise ValueError("incorrect input") out = tuple(int(v) for v in subs if 0 &lt;= int(v) &lt;= 255) if len(out) != 4: raise ValueError("incorrect input") return out </code></pre> <p>ofcourse there is the standard isinstance(3, int) function ...</p>
0
2011-11-24T11:53:15Z
[ "python", "typing", "dynamic-typing" ]
How can I type-check variables in Python?
463,604
<p>I have a Python function that takes a numeric argument that <strong>must</strong> be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?</p> <p>My first reaction is to do something like this:</p> <pre><code>def isInteger(n): return int(n) == n </code></pre> <p>But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon. </p> <p>Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?</p> <p>EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.</p>
20
2009-01-20T23:58:45Z
38,092,489
<p>Python now supports <a href="https://en.wikipedia.org/wiki/Gradual_typing" rel="nofollow">gradual typing</a> via the <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">typing module</a> and <a href="http://mypy-lang.org/" rel="nofollow">mypy</a>. The <code>typing</code> module is a part of the stdlib as of Python 3.5 and can be downloaded <a href="https://pypi.python.org/pypi/typing" rel="nofollow">from PyPi</a> if you need backports for Python 2 or previous version of Python 3. You can install <code>mypy</code> by running <code>pip install mypy-lang</code> from the command line.</p> <p>In short, if you want to verify that some function takes in an int, a float, and returns a string, you would annotate your function like so:</p> <pre><code>def foo(param1: int, param2: float) -&gt; str: return "testing {0} {1}".format(param1, param2) </code></pre> <p>If your file was named <code>test.py</code>, you could then typecheck once you've installed mypy by running <code>mypy test.py</code> from the command line.</p> <p>If you're using an older version of Python without support for function annotations, you can use type comments to accomplish the same effect:</p> <pre><code>def foo(param1, param2): # type: (int, float) -&gt; str return "testing {0} {1}".format(param1, param2) </code></pre> <p>You use the same command <code>mypy test.py</code> for Python 3 files, and <code>mypy --py2 test.py</code> for Python 2 files.</p> <p>The type annotations are ignored entirely by the Python interpreter at runtime, so they impose no overhead -- the usual workflow is to work on your code and run mypy periodically to catch mistakes and errors. Some IDEs, such as PyCharm, will understand type hints and can alert you to problems and type mismatches in your code while you're directly editing.</p> <p>If, for some reason, you need the types to be checked at runtime, you should follow the advice listed in the other answers (eg use <code>isinstance</code>, <code>issubclass</code>, and the like).</p> <p>For more information and details, see the <a href="http://mypy-lang.org/" rel="nofollow">mypy website</a>, the <a href="http://mypy.readthedocs.io/en/latest/faq.html" rel="nofollow">mypy FAQ</a>, and <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">PEP 484</a>.</p>
0
2016-06-29T07:00:10Z
[ "python", "typing", "dynamic-typing" ]
Python - Doing absolute imports from a subfolder
463,643
<p>Basically I'm asking the same question as this guy: <a href="http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python">http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python</a></p> <p>But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers).</p> <p>I know that you can do this by using sys.path, but I would prefer a cleaner method.</p> <p>Example:</p> <pre><code>App __init__.py Package_A --__init__.py --Module_A.py Package_B --__init__.py --Module_B.py </code></pre> <p>How would I import Module_A into Module_B?</p>
11
2009-01-21T00:10:47Z
463,691
<p>If I'm <a href="http://www.python.org/dev/peps/pep-0328/" rel="nofollow">reading</a> <a href="http://docs.python.org/whatsnew/2.5.html" rel="nofollow">correctly</a>, in Python 2.5 or higher:</p> <pre><code>from ..Module_B import Module_B </code></pre> <p>I thought I was well-versed in Python but I had no idea that was possible in version 2.5.</p>
2
2009-01-21T00:27:19Z
[ "python", "python-import" ]
Python - Doing absolute imports from a subfolder
463,643
<p>Basically I'm asking the same question as this guy: <a href="http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python">http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python</a></p> <p>But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers).</p> <p>I know that you can do this by using sys.path, but I would prefer a cleaner method.</p> <p>Example:</p> <pre><code>App __init__.py Package_A --__init__.py --Module_A.py Package_B --__init__.py --Module_B.py </code></pre> <p>How would I import Module_A into Module_B?</p>
11
2009-01-21T00:10:47Z
463,727
<p>If you are then importing Module_B in to App, you would</p> <p>Module_B.py: import ModuleA</p> <p>App.py (which also imports ModuleA which is now by default in your Pythonpath)</p> <pre><code>import Module_B.Module_B </code></pre> <p>Another alternative, is to update __init__.py (the one in Module_A/App folder) to:</p> <pre><code>import os import sys sys.path.extend('%s../' % os.getcwd()) import ModuleA </code></pre> <p>Another alternative, is to add your folder to the PYTHONPATH environment var.</p>
0
2009-01-21T00:42:43Z
[ "python", "python-import" ]
Python - Doing absolute imports from a subfolder
463,643
<p>Basically I'm asking the same question as this guy: <a href="http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python">http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python</a></p> <p>But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers).</p> <p>I know that you can do this by using sys.path, but I would prefer a cleaner method.</p> <p>Example:</p> <pre><code>App __init__.py Package_A --__init__.py --Module_A.py Package_B --__init__.py --Module_B.py </code></pre> <p>How would I import Module_A into Module_B?</p>
11
2009-01-21T00:10:47Z
463,904
<pre><code>main.py setup.py app/ -&gt; __init__.py package_a/ -&gt; __init__.py module_a.py package_b/ -&gt; __init__.py module_b.py </code></pre> <ol> <li>You run <code>python main.py</code>.</li> <li><code>main.py</code> does: <code>import app.package_a.module_a</code></li> <li><code>module_a.py</code> does <code>import app.package_b.module_b</code></li> </ol> <p>Alternatively 2 or 3 could use: <code>from app.package_a import module_a</code></p> <p>That will work as long as you have <code>app</code> in your PYTHONPATH. <code>main.py</code> could be anywhere then.</p> <p>So you write a <code>setup.py</code> to copy (install) the whole app package and subpackages to the target system's python folders, and <code>main.py</code> to target system's script folders.</p>
10
2009-01-21T02:15:30Z
[ "python", "python-import" ]
Django missing translation of some strings. Any idea why?
463,714
<p>I have a medium sized Django project, (running on AppEngine if it makes any difference), and have all the strings living in .po files like they should.</p> <p>I'm seeing strange behavior where certain strings just don't translate. They show up in the .po file when I run make_messages, with the correct file locations marked where my {% trans %} tags are. The translations are in place and look correct compared to other strings on either side of them. But when I display the page in question, about 1/4 of the strings simply don't translate.</p> <p>Digging into the relevant generated .mo file, I don't see either the msgid or the msgstr present. </p> <p>Has anybody seen anything similar to this? Any idea what might be happening? </p> <ul> <li>trans tags look correct</li> <li>.po files look correct</li> <li>no errors during compile_messages</li> </ul>
7
2009-01-21T00:38:19Z
463,741
<p>Ugh. Django, you're killing me.</p> <p>Here's what was happening:</p> <p><a href="http://blog.e-shell.org/124">http://blog.e-shell.org/124</a></p> <p>For some reason only Django knows, it decided to decorate some of my translations with the comment '# fuzzy'. It seems to have chosen which ones to mark randomly.</p> <p>Anyway, #fuzzy means this: "don't translate this, even though here's the translation:"</p> <p>I'll leave this here in case some other poor soul comes across it in the future.</p>
8
2009-01-21T00:54:59Z
[ "python", "django", "internationalization", "translation" ]
Django missing translation of some strings. Any idea why?
463,714
<p>I have a medium sized Django project, (running on AppEngine if it makes any difference), and have all the strings living in .po files like they should.</p> <p>I'm seeing strange behavior where certain strings just don't translate. They show up in the .po file when I run make_messages, with the correct file locations marked where my {% trans %} tags are. The translations are in place and look correct compared to other strings on either side of them. But when I display the page in question, about 1/4 of the strings simply don't translate.</p> <p>Digging into the relevant generated .mo file, I don't see either the msgid or the msgstr present. </p> <p>Has anybody seen anything similar to this? Any idea what might be happening? </p> <ul> <li>trans tags look correct</li> <li>.po files look correct</li> <li>no errors during compile_messages</li> </ul>
7
2009-01-21T00:38:19Z
463,928
<p>The fuzzy marker is added to the .po file by makemessages. When you have a new string (with no translations), it looks for similar strings, and includes them as the translation, with the fuzzy marker. This means, this is a crude match, so don't display it to the user, but it could be a good start for the human translator.</p> <p>It isn't a Django behavior, it comes from the gettext facility.</p>
10
2009-01-21T02:31:43Z
[ "python", "django", "internationalization", "translation" ]
Possible to view method/function docs in NetBeans (Python plugin)?
463,806
<p>I just started trying out NetBeans 6.5 with Python support. I like that the IDE provides the docstring documentation for a function/method in a popup when it's auto-completing, but is there any other way to view docstrings, either by mousing over a function/method name, or clicking somewhere? I just can not seem to find a way to do this. The best I can seem to do is "Go to source" in the right-click menu. If you know the trick (or can point out the obvious thing I'm missing), I'd really appreciate knowing it!</p>
1
2009-01-21T01:19:13Z
474,589
<p>I received the following answer from Tor Norbye at Sun:</p> <blockquote> <p>Hold the ctrl key (or Cmd on Mac) and then hover.</p> <p>Also, Ctrl-Shift-Space (e.g. code completion + shift) will display -just- the completion doc (which means it doesn't just look at the prefix of the caret, but the whole identifier and left hand side type if it can resolve it, to compute one specific match rather than many).</p> </blockquote>
2
2009-01-23T21:17:45Z
[ "python", "ide", "netbeans", "documentation" ]
Possible to view method/function docs in NetBeans (Python plugin)?
463,806
<p>I just started trying out NetBeans 6.5 with Python support. I like that the IDE provides the docstring documentation for a function/method in a popup when it's auto-completing, but is there any other way to view docstrings, either by mousing over a function/method name, or clicking somewhere? I just can not seem to find a way to do this. The best I can seem to do is "Go to source" in the right-click menu. If you know the trick (or can point out the obvious thing I'm missing), I'd really appreciate knowing it!</p>
1
2009-01-21T01:19:13Z
4,689,073
<p>You can also use this keyboard shortcut on Mac. Shift + Meta + Backslash</p>
1
2011-01-14T08:09:10Z
[ "python", "ide", "netbeans", "documentation" ]
Using DPAPI with Python?
463,832
<p>Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python?</p> <p>I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow.</p> <p><strong>EDIT:</strong> I've taken the example code pointed to by "dF" and tweaked it into a standalone library which can be simply used at a high level to crypt and decrypt using DPAPI in user mode. Simply call dpapi.cryptData(text_to_encrypt) which returns an encrypted string, or the reverse decryptData(encrypted_data_string), which returns the plain text. Here's the library:</p> <pre><code># DPAPI access library # This file uses code originally created by Crusher Joe: # http://article.gmane.org/gmane.comp.python.ctypes/420 # from ctypes import * from ctypes.wintypes import DWORD LocalFree = windll.kernel32.LocalFree memcpy = cdll.msvcrt.memcpy CryptProtectData = windll.crypt32.CryptProtectData CryptUnprotectData = windll.crypt32.CryptUnprotectData CRYPTPROTECT_UI_FORBIDDEN = 0x01 extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd" class DATA_BLOB(Structure): _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))] def getData(blobOut): cbData = int(blobOut.cbData) pbData = blobOut.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw def Win32CryptProtectData(plainText, entropy): bufferIn = c_buffer(plainText, len(plainText)) blobIn = DATA_BLOB(len(plainText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def Win32CryptUnprotectData(cipherText, entropy): bufferIn = c_buffer(cipherText, len(cipherText)) blobIn = DATA_BLOB(len(cipherText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def cryptData(text): return Win32CryptProtectData(text, extraEntropy) def decryptData(cipher_text): return Win32CryptUnprotectData(cipher_text, extraEntropy) </code></pre>
13
2009-01-21T01:30:50Z
463,840
<p>The easiest way would be to use <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">Iron Python</a>.</p>
2
2009-01-21T01:34:50Z
[ "python", "windows", "security", "encryption", "dpapi" ]
Using DPAPI with Python?
463,832
<p>Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python?</p> <p>I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow.</p> <p><strong>EDIT:</strong> I've taken the example code pointed to by "dF" and tweaked it into a standalone library which can be simply used at a high level to crypt and decrypt using DPAPI in user mode. Simply call dpapi.cryptData(text_to_encrypt) which returns an encrypted string, or the reverse decryptData(encrypted_data_string), which returns the plain text. Here's the library:</p> <pre><code># DPAPI access library # This file uses code originally created by Crusher Joe: # http://article.gmane.org/gmane.comp.python.ctypes/420 # from ctypes import * from ctypes.wintypes import DWORD LocalFree = windll.kernel32.LocalFree memcpy = cdll.msvcrt.memcpy CryptProtectData = windll.crypt32.CryptProtectData CryptUnprotectData = windll.crypt32.CryptUnprotectData CRYPTPROTECT_UI_FORBIDDEN = 0x01 extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd" class DATA_BLOB(Structure): _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))] def getData(blobOut): cbData = int(blobOut.cbData) pbData = blobOut.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw def Win32CryptProtectData(plainText, entropy): bufferIn = c_buffer(plainText, len(plainText)) blobIn = DATA_BLOB(len(plainText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def Win32CryptUnprotectData(cipherText, entropy): bufferIn = c_buffer(cipherText, len(cipherText)) blobIn = DATA_BLOB(len(cipherText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def cryptData(text): return Win32CryptProtectData(text, extraEntropy) def decryptData(cipher_text): return Win32CryptUnprotectData(cipher_text, extraEntropy) </code></pre>
13
2009-01-21T01:30:50Z
463,852
<p>I have been using <code>CryptProtectData</code> and <code>CryptUnprotectData</code> through ctypes, with the code from</p> <p><a href="http://article.gmane.org/gmane.comp.python.ctypes/420">http://article.gmane.org/gmane.comp.python.ctypes/420</a></p> <p>and it has been working well.</p>
8
2009-01-21T01:37:54Z
[ "python", "windows", "security", "encryption", "dpapi" ]
Using DPAPI with Python?
463,832
<p>Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python?</p> <p>I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow.</p> <p><strong>EDIT:</strong> I've taken the example code pointed to by "dF" and tweaked it into a standalone library which can be simply used at a high level to crypt and decrypt using DPAPI in user mode. Simply call dpapi.cryptData(text_to_encrypt) which returns an encrypted string, or the reverse decryptData(encrypted_data_string), which returns the plain text. Here's the library:</p> <pre><code># DPAPI access library # This file uses code originally created by Crusher Joe: # http://article.gmane.org/gmane.comp.python.ctypes/420 # from ctypes import * from ctypes.wintypes import DWORD LocalFree = windll.kernel32.LocalFree memcpy = cdll.msvcrt.memcpy CryptProtectData = windll.crypt32.CryptProtectData CryptUnprotectData = windll.crypt32.CryptUnprotectData CRYPTPROTECT_UI_FORBIDDEN = 0x01 extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd" class DATA_BLOB(Structure): _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))] def getData(blobOut): cbData = int(blobOut.cbData) pbData = blobOut.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw def Win32CryptProtectData(plainText, entropy): bufferIn = c_buffer(plainText, len(plainText)) blobIn = DATA_BLOB(len(plainText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def Win32CryptUnprotectData(cipherText, entropy): bufferIn = c_buffer(cipherText, len(cipherText)) blobIn = DATA_BLOB(len(cipherText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return getData(blobOut) else: return "" def cryptData(text): return Win32CryptProtectData(text, extraEntropy) def decryptData(cipher_text): return Win32CryptUnprotectData(cipher_text, extraEntropy) </code></pre>
13
2009-01-21T01:30:50Z
1,562,366
<p>Also, pywin32 implements CryptProtectData and CryptUnprotectData in the win32crypt module.</p>
4
2009-10-13T19:20:07Z
[ "python", "windows", "security", "encryption", "dpapi" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
463,971
<p>If you are going to use Python, I recommend using <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for this. </p> <p>Specifically <a href="http://twistedmatrix.com/trac/wiki/TwistedRunner" rel="nofollow">Twisted Runner</a>. </p>
2
2009-01-21T02:59:40Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
463,981
<p>Can you elaborate what you mean by <em>in parallel</em>? It sounds like you need to implement some sort of locking in the queue so your entries are not selected twice, etc and the commands run only once.</p> <p>Most queue systems cheat -- they just write a giant to-do list, then select e.g. ten items, work them, and select the next ten items. There's no parallelization.</p> <p>If you provide some more details, I'm sure we can help you out.</p>
-2
2009-01-21T03:08:43Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
464,007
<p>GNU make (and perhaps other implementations as well) has the -j argument, which governs how many jobs it will run at once. When a job completes, make will start another one.</p>
7
2009-01-21T03:31:22Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
464,012
<p>Well, if they are largely independent of each other, I'd think in terms of:</p> <pre><code>Initialize an array of jobs pending (queue, ...) - 200 entries Initialize an array of jobs running - empty while (jobs still pending and queue of jobs running still has space) take a job off the pending queue launch it in background if (queue of jobs running is full) wait for a job to finish remove from jobs running queue while (queue of jobs is not empty) wait for job to finish remove from jobs running queue </code></pre> <p>Note that the tail test in the main loop means that if the 'jobs running queue' has space when the while loop iterates - preventing premature termination of the loop. I think the logic is sound.</p> <p>I can see how to do that in C fairly easily - it wouldn't be all that hard in Perl, either (and therefore not too hard in the other scripting languages - Python, Ruby, Tcl, etc). I'm not at all sure I'd want to do it in shell - the <code>wait</code> command in shell waits for all children to terminate, rather than for some child to terminate.</p>
4
2009-01-21T03:34:12Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
464,029
<p>On the shell, <code>xargs</code> can be used to queue parallel command processing. For example, for having always 3 sleeps in parallel, sleeping for 1 second each, and executing 10 sleeps in total do</p> <pre><code>echo {1..10} | xargs -d ' ' -n1 -P3 sh -c 'sleep 1s' _ </code></pre> <p>And it would sleep for 4 seconds in total. If you have a list of names, and want to pass the names to commands executed, again executing 3 commands in parallel, do</p> <pre><code>cat names | xargs -n1 -P3 process_name </code></pre> <p>Would execute the command <code>process_name alice</code>, <code>process_name bob</code> and so on.</p>
41
2009-01-21T03:53:00Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
464,038
<p>I would imagine you could do this using make and the make -j xx command.</p> <p>Perhaps a makefile like this</p> <pre><code>all : usera userb userc.... usera: imapsync usera userb: imapsync userb .... </code></pre> <p>make -j 10 -f makefile</p>
38
2009-01-21T03:58:50Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
464,039
<p>In python, you could try:</p> <pre><code>import Queue, os, threading # synchronised queue queue = Queue.Queue(0) # 0 means no maximum size # do stuff to initialise queue with strings # representing os commands queue.put('sleep 10') queue.put('echo Sleeping..') # etc # or use python to generate commands, e.g. # for username in ['joe', 'bob', 'fred']: # queue.put('imapsync %s' % username) def go(): while True: try: # False here means no blocking: raise exception if queue empty command = queue.get(False) # Run command. python also has subprocess module which is more # featureful but I am not very familiar with it. # os.system is easy :-) os.system(command) except Queue.Empty: return for i in range(10): # change this to run more/fewer threads threading.Thread(target=go).start() </code></pre> <p>Untested...</p> <p>(of course, python itself is single-threaded. You should still get the benefit of multiple threads in terms of waiting for IO, though.)</p>
3
2009-01-21T03:59:01Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
464,059
<p>Python's <a href="http://docs.python.org/dev/library/multiprocessing.html" rel="nofollow">multiprocessing module</a> would seem to fit your issue nicely. It's a high-level package that supports threading by process.</p>
1
2009-01-21T04:10:43Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
628,543
<p>For this kind of job PPSS is written: Parallel processing shell script. Google for this name and you will find it, I won't linkspam.</p>
12
2009-03-10T00:31:35Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
2,148,784
<p><a href="https://savannah.nongnu.org/projects/parallel/">Parallel</a> is made exatcly for this purpose.</p> <pre><code>cat userlist | parallel imapsync </code></pre> <p>One of the beauties of <a href="https://savannah.nongnu.org/projects/parallel/">Parallel</a> compared to other solutions is that it makes sure output is not mixed. Doing <code>traceroute</code> in <a href="https://savannah.nongnu.org/projects/parallel/">Parallel</a> works fine for example:</p> <pre><code>(echo foss.org.my; echo www.debian.org; echo www.freenetproject.org) | parallel traceroute </code></pre>
24
2010-01-27T17:00:56Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
<p>I have a list/queue of 200 commands that I need to run in a shell on a Linux server. </p> <p>I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. </p> <p>When a process finishes I want the next command to be "popped" from the queue and executed.</p> <p>Does anyone have code to solve this problem?</p> <p><strong>Further elaboration:</strong></p> <p>There's 200 pieces of work that need to be done, in a queue of some sort. I want to have at most 10 pieces of work going on at once. When a thread finishes a piece of work it should ask the queue for the next piece of work. If there's no more work in the queue, the thread should die. When all the threads have died it means all the work has been done.</p> <p>The actual problem I'm trying to solve is using <code>imapsync</code> to synchronize 200 mailboxes from an old mail server to a new mail server. Some users have large mailboxes and take a long time tto sync, others have very small mailboxes and sync quickly.</p>
42
2009-01-21T02:54:45Z
7,236,743
<p><a href="https://savannah.gnu.org/projects/parallel" rel="nofollow">https://savannah.gnu.org/projects/parallel</a> (gnu parallel) and pssh might help.</p>
2
2011-08-29T22:30:14Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
django application configuration
464,010
<p>I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the location tag in the latter. Django and Python are based on simplicity but this is one huge oversight from the Django folks to not provide more guidance in this area. I had a basic page running in the Django dev server but could not get the stylesheet to load. So i decided to install mod_python and try to use apache in my dev environment and I'm even more frustrated. I can't seem find a good example anywhere on the web or in books regarding how to create a realistic directory structure and then based on that strucure, how to configure neccessary settings. Everything in tutorials is as usual not realistic or very helpful. Too simple. If someone here could share how they have their Django directory and settings configured that would be FANTASTIC!</p>
0
2009-01-21T03:32:58Z
464,069
<p>There's a lot to your question, so I'll try to boil it down to this: </p> <ol> <li><p>The tutorial is aimed at getting you to use the framework and to be up and running with as little configuration as possible. No server to configure, etc. If you are trying to load CSS with the dev server, you will need to pull the CSS from somewhere "beyond" the dev server. For example, on my Mac, I launch the dev server, but load the CSS from the built-in apache server.</p></li> <li><p>There is more info available about using Apache and mod-python here: <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/#howto-deployment-modpython" rel="nofollow">mod_python and apache setup info</a></p></li> <li><p>I'm not sure what you mean by "creating the directory structure", but most of the core application files are typically created by running the <code>django-admin.py</code> script, by running <code>startproject</code> and <code>startapp</code>. This is demonstrated in the tutorial.</p></li> </ol> <p>You can also ask questions on the IRC #django channel! If you are looking for a book on the subject, you can also check out the <a href="http://www.djangobook.com/" rel="nofollow">Django Book</a>.</p>
0
2009-01-21T04:15:23Z
[ "python", "django" ]
django application configuration
464,010
<p>I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the location tag in the latter. Django and Python are based on simplicity but this is one huge oversight from the Django folks to not provide more guidance in this area. I had a basic page running in the Django dev server but could not get the stylesheet to load. So i decided to install mod_python and try to use apache in my dev environment and I'm even more frustrated. I can't seem find a good example anywhere on the web or in books regarding how to create a realistic directory structure and then based on that strucure, how to configure neccessary settings. Everything in tutorials is as usual not realistic or very helpful. Too simple. If someone here could share how they have their Django directory and settings configured that would be FANTASTIC!</p>
0
2009-01-21T03:32:58Z
464,453
<p>Don't use Apache for development, that'll make you tear your hair out restarting Apache every fifteen seconds (<strong>EDIT</strong>: or you could just use PythonDebug On).</p> <p><a href="http://docs.djangoproject.com/en/dev/howto/static-files/#limiting-use-to-debug-true" rel="nofollow">This technique</a> is how to get your media (stylesheets, etc) loading via the development server. If you used that exact snippet, you'd need to set MEDIA_URL to '/site_media/' and MEDIA_ROOT to '/path/to/media' (obviously this latter is likely to need changing to wherever your media files actually are).</p>
1
2009-01-21T08:35:45Z
[ "python", "django" ]
django application configuration
464,010
<p>I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the location tag in the latter. Django and Python are based on simplicity but this is one huge oversight from the Django folks to not provide more guidance in this area. I had a basic page running in the Django dev server but could not get the stylesheet to load. So i decided to install mod_python and try to use apache in my dev environment and I'm even more frustrated. I can't seem find a good example anywhere on the web or in books regarding how to create a realistic directory structure and then based on that strucure, how to configure neccessary settings. Everything in tutorials is as usual not realistic or very helpful. Too simple. If someone here could share how they have their Django directory and settings configured that would be FANTASTIC!</p>
0
2009-01-21T03:32:58Z
467,836
<p>Thanks guys. After doing some more searching I found exactly what i was looking for <a href="http://rob.cogit8.org/blog/2008/Jun/20/django-and-relativity/" rel="nofollow">here</a>. It's an example project directory structure and settings.py. If you view the comments there you can see a lot of others were confused about this as well and found the example helpful. It would be nice if Django created a recommended dir structure so you know where to store css, js, django app files, template files, etc. </p>
1
2009-01-22T02:09:42Z
[ "python", "django" ]
django application configuration
464,010
<p>I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the location tag in the latter. Django and Python are based on simplicity but this is one huge oversight from the Django folks to not provide more guidance in this area. I had a basic page running in the Django dev server but could not get the stylesheet to load. So i decided to install mod_python and try to use apache in my dev environment and I'm even more frustrated. I can't seem find a good example anywhere on the web or in books regarding how to create a realistic directory structure and then based on that strucure, how to configure neccessary settings. Everything in tutorials is as usual not realistic or very helpful. Too simple. If someone here could share how they have their Django directory and settings configured that would be FANTASTIC!</p>
0
2009-01-21T03:32:58Z
3,304,468
<p>We just built and released (under Apache2) Djenesis at OSCON2010:</p> <ul> <li><a href="http://code.google.com/p/djenesis/" rel="nofollow">Djenesis on Google Code</a></li> </ul> <p>The two goals of Djenesis are to</p> <ul> <li>ease bootstrapping new projects based on your</li> <li>provide a default project template based on dozens of Django-based, web-specific applications</li> </ul> <p>More details about the features/benefits/tutorial as well as the code are on Google Code.</p>
1
2010-07-21T22:43:43Z
[ "python", "django" ]
How are POST and GET variables handled in Python?
464,040
<p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
103
2009-01-21T03:59:03Z
464,060
<p>It somewhat depends on what you use as a CGI framework, but they are available in dictionaries accessible to the program. I'd point you to the docs, but I'm not getting through to python.org right now. But <a href="http://mail.python.org/pipermail/python-list/2008-April/485712.html" rel="nofollow">this note on mail.python.org will give you a first pointer</a>. Look at the CGI and URLLIB Python libs for more.</p> <p><strong>Update</strong></p> <p>Okay, that link busted. Here's the <a href="https://docs.python.org/2/library/wsgiref.html" rel="nofollow">basic wsgi ref</a></p>
2
2009-01-21T04:11:28Z
[ "python", "post", "get" ]
How are POST and GET variables handled in Python?
464,040
<p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
103
2009-01-21T03:59:03Z
464,086
<p>Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.</p> <p>In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.</p>
-1
2009-01-21T04:30:44Z
[ "python", "post", "get" ]
How are POST and GET variables handled in Python?
464,040
<p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
103
2009-01-21T03:59:03Z
464,087
<p>They are stored in the CGI fieldstorage object.</p> <pre><code>import cgi form = cgi.FieldStorage() print "The user entered %s" % form.getvalue("uservalue") </code></pre>
25
2009-01-21T04:31:44Z
[ "python", "post", "get" ]
How are POST and GET variables handled in Python?
464,040
<p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
103
2009-01-21T03:59:03Z
464,977
<p>suppose you're posting a html form with this:</p> <pre><code>&lt;input type="text" name="username"&gt; </code></pre> <p>If using <a href="http://docs.python.org/library/cgi.html">raw cgi</a>:</p> <pre><code>import cgi form = cgi.FieldStorage() print form["username"] </code></pre> <p>If using <a href="http://docs.djangoproject.com/">Django</a>, <a href="http://pylonshq.com/">Pylons</a>, <a href="http://flask.pocoo.org/">Flask</a> or <a href="http://www.pylonsproject.org/projects/pyramid/about">Pyramid</a>: </p> <pre><code>print request.GET['username'] # for GET form method print request.POST['username'] # for POST form method </code></pre> <p>Using <a href="http://turbogears.org/">Turbogears</a>, <a href="http://www.cherrypy.org/">Cherrypy</a>:</p> <pre><code>from cherrypy import request print request.params['username'] </code></pre> <p><a href="http://webpy.org">Web.py</a>:</p> <pre><code>form = web.input() print form.username </code></pre> <p><a href="http://werkzeug.pocoo.org/">Werkzeug</a>:</p> <pre><code>print request.form['username'] </code></pre> <p>If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:</p> <pre><code>def index(self, username): print username </code></pre> <p><a href="https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction">Google App Engine</a>:</p> <pre><code>class SomeHandler(webapp2.RequestHandler): def post(self): name = self.request.get('username') # this will get the value from the field named username self.response.write(name) # this will write on the document </code></pre> <p>So you really will have to choose one of those frameworks.</p>
187
2009-01-21T11:53:01Z
[ "python", "post", "get" ]
How are POST and GET variables handled in Python?
464,040
<p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
103
2009-01-21T03:59:03Z
11,353,284
<p>I've found nosklo's answer very extensive and useful! For those, like myself, who might find accessing the raw request data directly also useful, I would like to add the way to do that:</p> <pre><code>import os, sys # the query string, which contains the raw GET data # (For example, for http://example.com/myscript.py?a=b&amp;c=d&amp;e # this is "a=b&amp;c=d&amp;e") os.getenv("QUERY_STRING") # the raw POST data sys.stdin.read() </code></pre>
21
2012-07-05T22:15:06Z
[ "python", "post", "get" ]
How are POST and GET variables handled in Python?
464,040
<p>In PHP you can just use <code>$_POST</code> for POST and <code>$_GET</code> for GET (Query string) variables. What's the equivalent in Python?</p>
103
2009-01-21T03:59:03Z
27,893,309
<p>I know this is an old question. Yet it's surprising that no good answer was given.</p> <p>First of all the question is completely valid without mentioning the framework. The CONTEXT is PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveniently populated. In PHP, $_GET and $_POST are also convenience variables. They are parsed from QUERY_URI and php://input respectively.</p> <p>In Python, these functions would be os.getenv('QUERY_STRING') and sys.stdin.read(). Remember to import os and sys modules.</p> <p>We have to be careful with the word "CGI" here, especially when talking about two languages and their commonalities when interfacing with a web server. 1. CGI, as a protocol, defines the data transport mechanism in the HTTP protocol. 2. Python can be configured to run as a CGI-script in Apache. 3. The cgi module in Python offers some convenience functions.</p> <p>Since the HTTP protocol is language-independent, and that Apache's CGI extension is also language-independent, getting the GET and POST parameters should bear only syntax differences across languages.</p> <p>Here's the Python routine to populate a GET dictionary:</p> <pre><code>GET={} args=os.getenv("QUERY_STRING").split('&amp;') for arg in args: t=arg.split('=') if len(t)&gt;1: k,v=arg.split('='); GET[k]=v </code></pre> <p>and for POST:</p> <pre><code>POST={} args=sys.stdin.read().split('&amp;') for arg in args: t=arg.split('=') if len(t)&gt;1: k, v=arg.split('='); POST[k]=v </code></pre> <p>You can now access the fields as following:</p> <pre><code>print GET.get('user_id') print POST.get('user_name') </code></pre> <p>I must also point out that the cgi module doesn't work well. Consider this HTTP request:</p> <pre><code>POST / test.py?user_id=6 user_name=Bob&amp;age=30 </code></pre> <p>Using cgi.FieldStorage().getvalue('user_id') will cause a null pointer exception because the module blindly checks the POST data, ignoring the fact that a POST request can carry GET parameters too. </p>
13
2015-01-11T23:26:51Z
[ "python", "post", "get" ]
Python - Hits per minute implementation?
464,314
<p>This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?</p> <p>I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas?</p>
2
2009-01-21T07:14:19Z
464,322
<p>A common pattern for solving this in other languages is to let the thing being measured simply increment an integer. Then you leave it to the listening client to determine intervals and frequencies.</p> <p>So you basically do <em>not</em> let the socket server know about stuff like "minutes", because that's a feature the observer calculates. Then you can also support multiple listeners with different interval resolution.</p> <p>I suppose you want some kind of ring-buffer structure to do the rolling logging. </p>
3
2009-01-21T07:19:56Z
[ "python" ]
Python - Hits per minute implementation?
464,314
<p>This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?</p> <p>I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas?</p>
2
2009-01-21T07:14:19Z
464,329
<p>For what it's worth, your implementation above won't work if you don't receive a packet every second, as the next second entry won't necessarily be reset to 0.</p> <p>Either way, afaik the "correct" way to do this, ala logs analysis, is to keep a limited record of all the queries you receive. So just chuck the query, time received etc. into a database, and then simple database queries will give you the use over a minute, or any minute in the past. Not sure whether this is too heavyweight for you, though.</p>
1
2009-01-21T07:24:35Z
[ "python" ]
Python - Hits per minute implementation?
464,314
<p>This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?</p> <p>I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas?</p>
2
2009-01-21T07:14:19Z
464,347
<p>When you say the last minute, do you mean the exact last seconds or the last full minute from x:00 to x:59? The latter will be easier to implement and would probably give accurate results. You have one prev variable holding the value of the hits for the previous minute. Then you have a current value that increments every time there is a new hit. You return the value of prev to the users. At the change of the minute you swap prev with current and reset current.</p> <p>If you want higher analysis you could split the minute in 2 to 6 slices. You need a variable or list entry for every slice. Let's say you have 6 slices of 10 seconds. You also have an index variable pointing to the current slice (0..5). For every hit you increment a temp variable. When the slice is over, you replace the value of the indexed variable with the value of temp, reset temp and move the index forward. You return the sum of the slice variables to the users.</p>
1
2009-01-21T07:35:51Z
[ "python" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,350
<p>This is simply merging. Treat each list as if it were a stack, and continuously pop the smaller of the two stack heads, adding the item to the result list, until one of the stacks is empty. Then add all remaining items to the resulting list.</p>
24
2009-01-21T07:36:52Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,357
<p>Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster. The idea is described wery well in post by Barry Kelly.</p>
0
2009-01-21T07:39:55Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,367
<pre><code>def compareDate(obj1, obj2): if obj1.getDate() &lt; obj2.getDate(): return -1 elif obj1.getDate() &gt; obj2.getDate(): return 1 else: return 0 list = list1 + list2 list.sort(compareDate) </code></pre> <p>Will sort the list in place. Define your own function for comparing two objects, and pass that function into the built in sort function.</p> <p>Do NOT use bubble sort, it has horrible performance.</p>
0
2009-01-21T07:44:39Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,373
<p>Use the 'merge' step of merge sort, it runs in O(n) time.</p> <p>From <a href="http://en.wikipedia.org/wiki/Merge_sort" rel="nofollow">wikipedia</a> (pseudo-code):</p> <pre><code>function merge(left,right) var list result while length(left) &gt; 0 and length(right) &gt; 0 if first(left) ≤ first(right) append first(left) to result left = rest(left) else append first(right) to result right = rest(right) end while while length(left) &gt; 0 append left to result while length(right) &gt; 0 append right to result return result </code></pre>
2
2009-01-21T07:49:13Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,454
<p>This is simple merging of two sorted lists. Take a look at the sample code below which merges two sorted lists of integers.</p> <pre><code>#!/usr/bin/env python ## merge.py -- Merge two sorted lists -*- Python -*- ## Time-stamp: "2009-01-21 14:02:57 ghoseb" l1 = [1, 3, 4, 7] l2 = [0, 2, 5, 6, 8, 9] def merge_sorted_lists(l1, l2): """Merge sort two sorted lists Arguments: - `l1`: First sorted list - `l2`: Second sorted list """ sorted_list = [] # Copy both the args to make sure the original lists are not # modified l1 = l1[:] l2 = l2[:] while (l1 and l2): if (l1[0] &lt;= l2[0]): # Compare both heads item = l1.pop(0) # Pop from the head sorted_list.append(item) else: item = l2.pop(0) sorted_list.append(item) # Add the remaining of the lists sorted_list.extend(l1 if l1 else l2) return sorted_list if __name__ == '__main__': print merge_sorted_lists(l1, l2) </code></pre> <p>This should work fine with datetime objects. Hope this helps.</p>
3
2009-01-21T08:36:40Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,538
<p>People seem to be over complicating this.. Just combine the two lists, then sort them:</p> <pre><code>&gt;&gt;&gt; l1 = [1, 3, 4, 7] &gt;&gt;&gt; l2 = [0, 2, 5, 6, 8, 9] &gt;&gt;&gt; l1.extend(l2) &gt;&gt;&gt; sorted(l1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>..or shorter (and without modifying <code>l1</code>):</p> <pre><code>&gt;&gt;&gt; sorted(l1 + l2) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.</p> <p>If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of <code>datetime</code> objects)</p> <p>Using the <code>timeit.Timer().repeat()</code> (which repeats the functions 1000000 times), I loosely benchmarked it against <a href="http://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python#464454">ghoseb's</a> solution, and <code>sorted(l1+l2)</code> is substantially quicker:</p> <p><code>merge_sorted_lists</code> took..</p> <pre><code>[9.7439379692077637, 9.8844599723815918, 9.552299976348877] </code></pre> <p><code>sorted(l1+l2)</code> took..</p> <pre><code>[2.860386848449707, 2.7589840888977051, 2.7682540416717529] </code></pre>
81
2009-01-21T09:14:08Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
464,767
<p>There is a slight flaw in <a href="http://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python#464454">ghoseb's</a> solution, making it O(n**2), rather than O(n).<br /> The problem is that this is performing:</p> <pre><code>item = l1.pop(0) </code></pre> <p>With linked lists or deques this would be an O(1) operation, so wouldn't affect complexity, but since python lists are implemented as vectors, this copies the rest of the elements of l1 one space left, an O(n) operation. Since this is done each pass through the list, it turns an O(n) algorithm into an O(n**2) one. This can be corrected by using a method that doesn't alter the source lists, but just keeps track of the current position.</p> <p>I've tried out benchmarking a corrected algorithm vs a simple sorted(l1+l2) as suggested by <a href="http://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python#464538">dbr</a></p> <pre><code>def merge(l1,l2): if not l1: return list(l2) if not l2: return list(l1) # l2 will contain last element. if l1[-1] &gt; l2[-1]: l1,l2 = l2,l1 it = iter(l2) y = it.next() result = [] for x in l1: while y &lt; x: result.append(y) y = it.next() result.append(x) result.append(y) result.extend(it) return result </code></pre> <p>I've tested these with lists generated with</p> <pre><code>l1 = sorted([random.random() for i in range(NITEMS)]) l2 = sorted([random.random() for i in range(NITEMS)]) </code></pre> <p>For various sizes of list, I get the following timings (repeating 100 times):</p> <pre><code># items: 1000 10000 100000 1000000 merge : 0.079 0.798 9.763 109.044 sort : 0.020 0.217 5.948 106.882 </code></pre> <p>So in fact, it looks like dbr is right, just using sorted() is preferable unless you're expecting very large lists, though it does have worse algorithmic complexity. The break even point being at around a million items in each source list (2 million total).</p> <p>One advantage of the merge approach though is that it is trivial to rewrite as a generator, which will use substantially less memory (no need for an intermediate list).</p> <p><strong>[Edit]</strong> I've retried this with a situation closer to the question - using a list of objects containing a field "<code>date</code>" which is a datetime object. The above algorithm was changed to compare against <code>.date</code> instead, and the sort method was changed to:</p> <pre><code>return sorted(l1 + l2, key=operator.attrgetter('date')) </code></pre> <p>This does change things a bit. The comparison being more expensive means that the number we perform becomes more important, relative to the constant-time speed of the implementation. This means merge makes up lost ground, surpassing the sort() method at 100,000 items instead. Comparing based on an even more complex object (large strings or lists for instance) would likely shift this balance even more.</p> <pre><code># items: 1000 10000 100000 1000000[1] merge : 0.161 2.034 23.370 253.68 sort : 0.111 1.523 25.223 313.20 </code></pre> <p>[1]: Note: I actually only did 10 repeats for 1,000,000 items and scaled up accordingly as it was pretty slow.</p>
10
2009-01-21T10:36:56Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
465,043
<blockquote> <p>is there a smarter way to do this in Python</p> </blockquote> <p>This hasn't been mentioned, so I'll go ahead - there is a <a href="http://svn.python.org/view/python/trunk/Lib/heapq.py?view=markup">merge stdlib function</a> in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of course, if you want to implement your own, the merge of merge-sort is the way to go.</p> <pre><code>&gt;&gt;&gt; list1 = [1, 5, 8, 10, 50] &gt;&gt;&gt; list2 = [3, 4, 29, 41, 45, 49] &gt;&gt;&gt; from heapq import merge &gt;&gt;&gt; list(merge(list1, list2)) [1, 3, 4, 5, 8, 10, 29, 41, 45, 49, 50] </code></pre>
68
2009-01-21T12:16:08Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
465,232
<pre><code>from datetime import datetime from itertools import chain from operator import attrgetter class DT: def __init__(self, dt): self.dt = dt list1 = [DT(datetime(2008, 12, 5, 2)), DT(datetime(2009, 1, 1, 13)), DT(datetime(2009, 1, 3, 5))] list2 = [DT(datetime(2008, 12, 31, 23)), DT(datetime(2009, 1, 2, 12)), DT(datetime(2009, 1, 4, 15))] list3 = sorted(chain(list1, list2), key=attrgetter('dt')) for item in list3: print item.dt </code></pre> <p>The output:</p> <pre><code>2008-12-05 02:00:00 2008-12-31 23:00:00 2009-01-01 13:00:00 2009-01-02 12:00:00 2009-01-03 05:00:00 2009-01-04 15:00:00 </code></pre> <p>I bet this is faster than any of the fancy pure-Python merge algorithms, even for large data. Python 2.6's <code>heapq.merge</code> is a whole another story.</p>
4
2009-01-21T13:10:00Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
482,848
<p>Long story short, unless <code>len(l1 + l2) ~ 1000000</code> use:</p> <pre><code>L = l1 + l2 L.sort() </code></pre> <p><img src="http://i.stack.imgur.com/XsRdj.png" alt="merge vs. sort comparison"></p> <p>Description of the figure and source code can be found <a href="http://stackoverflow.com/questions/464960/code-golf-combining-multiple-sorted-lists-into-a-single-sorted-list#464967">here</a>. </p> <p>The figure was generated by the following command:</p> <pre><code>$ python make-figures.py --nsublists 2 --maxn=0x100000 -s merge_funcs.merge_26 -s merge_funcs.sort_builtin </code></pre>
44
2009-01-27T10:09:03Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
10,074,770
<p>Recursive implementation is below. Average performance is O(n).</p> <pre><code>def merge_sorted_lists(A, B, sorted_list = None): if sorted_list == None: sorted_list = [] slice_index = 0 for element in A: if element &lt;= B[0]: sorted_list.append(element) slice_index += 1 else: return merge_sorted_lists(B, A[slice_index:], sorted_list) return sorted_list + B </code></pre> <p>or generator with improved space complexity:</p> <pre><code>def merge_sorted_lists_as_generator(A, B): slice_index = 0 for element in A: if element &lt;= B[0]: slice_index += 1 yield element else: for sorted_element in merge_sorted_lists_as_generator(B, A[slice_index:]): yield sorted_element return for element in B: yield element </code></pre>
0
2012-04-09T14:32:18Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
10,162,814
<p>Python's sort implementation "timsort" is specifically optimized for lists that contain ordered sections. Plus, it's written in C. </p> <p><a href="http://bugs.python.org/file4451/timsort.txt" rel="nofollow">http://bugs.python.org/file4451/timsort.txt</a><br> <a href="http://en.wikipedia.org/wiki/Timsort" rel="nofollow">http://en.wikipedia.org/wiki/Timsort</a></p> <p>As people have mentioned, it may call the comparison function more times by some constant factor (but maybe call it more times in a shorter period in many cases!).</p> <blockquote> <p>I would never rely on this, however. – Daniel Nadasi</p> </blockquote> <p>I believe the Python developers are committed to keeping timsort, or at least keeping a sort that's O(n) in this case.</p> <blockquote> <p>Generalized sorting (i.e. leaving apart radix sorts from limited value domains)<br> cannot be done in less than O(n log n) on a serial machine. – Barry Kelly</p> </blockquote> <p>Right, sorting in the general case can't be faster than that. But since O() is an upper bound, timsort being O(n log n) on arbitrary input doesn't contradict its being O(n) given sorted(L1) + sorted(L2).</p>
2
2012-04-15T14:20:36Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
18,675,785
<p>If you want to do it in a manner more consistent with learning what goes on in the iteration try this</p> <pre><code>def merge_arrays(a, b): l= [] while len(a) &gt; 0 and len(b)&gt;0: if a[0] &lt; b[0]: l.append(a.pop(0)) else:l.append(b.pop(0)) l.extend(a+b) print( l ) </code></pre>
1
2013-09-07T17:04:13Z
[ "python", "list", "sorting" ]
Combining two sorted lists in Python
464,342
<p>I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?</p>
46
2009-01-21T07:33:47Z
25,581,987
<pre><code>import random n=int(input("Enter size of table 1")); #size of list 1 m=int(input("Enter size of table 2")); # size of list 2 tb1=[random.randrange(1,101,1) for _ in range(n)] # filling the list with random tb2=[random.randrange(1,101,1) for _ in range(m)] # numbers between 1 and 100 tb1.sort(); #sort the list 1 tb2.sort(); # sort the list 2 fus=[]; # creat an empty list print(tb1); # print the list 1 print('------------------------------------'); print(tb2); # print the list 2 print('------------------------------------'); i=0;j=0; # varialbles to cross the list while(i&lt;n and j&lt;m): if(tb1[i]&lt;tb2[j]): fus.append(tb1[i]); i+=1; else: fus.append(tb2[j]); j+=1; if(i&lt;n): fus+=tb1[i:n]; if(j&lt;m): fus+=tb2[j:m]; print(fus); # this code is used to merge two sorted lists in one sorted list (FUS) without #sorting the (FUS) </code></pre>
1
2014-08-30T11:43:39Z
[ "python", "list", "sorting" ]
unit testing for an application server
464,543
<p>I wrote an application server (using python &amp; twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to the app server and makes the necessary requests (the communication protocol is some in-house XML), store in a static way the received XML and then write some tests on those static data using unitest.</p> <p>My question is: Is this a correct approach and if yes, what kind of tests are covered with this approach?</p> <p>Also, using this method has several disadvantages, like: not being able to access the database layer in order to build/rebuild the schema, when will the test client going to connect to the server: per each unit test or before running the test suite?</p>
2
2009-01-21T09:15:42Z
464,596
<p>haven't used twisted before, and the twisted/trial documentation isn't stellar from what I just saw, but it'll likely take you 2-3 days to implement correctly the test system you describe above. Now, like I said I have no idea about Trial, but I GUESS you could probably get it working in 1-2 days, since you already have a Twisted application. Now if Trial gives you more coverage in less time, I'd go with Trial.</p> <p>But remember this is just an answer from a very cursory look at the docs</p>
0
2009-01-21T09:35:17Z
[ "python", "unit-testing", "twisted" ]
unit testing for an application server
464,543
<p>I wrote an application server (using python &amp; twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to the app server and makes the necessary requests (the communication protocol is some in-house XML), store in a static way the received XML and then write some tests on those static data using unitest.</p> <p>My question is: Is this a correct approach and if yes, what kind of tests are covered with this approach?</p> <p>Also, using this method has several disadvantages, like: not being able to access the database layer in order to build/rebuild the schema, when will the test client going to connect to the server: per each unit test or before running the test suite?</p>
2
2009-01-21T09:15:42Z
464,870
<p><strong>"My question is: Is this a correct approach?"</strong></p> <p>It's what you chose. You made a lot of excuses, so I'm assuming that your pretty well fixed on this course. It's not the best, but you've already listed all your reasons for doing it (and then asked follow-up questions on this specific course of action). "correct" doesn't enter into it anymore, so there's no answer to this question.</p> <p><strong>"what kind of tests are covered with this approach?"</strong></p> <p>They call it "black-box" testing. The application server is a black box that has a few inputs and outputs, and you can't test any of it's internals. It's considered one acceptable form of testing because it tests the bottom-line external interfaces for acceptable behavior.</p> <p>If you have problems, it turns out to be useless for doing diagnostic work. You'll find that you need to also to white-box testing on the internal structures. </p> <p><strong>"not being able to access the database layer in order to build/rebuild the schema,"</strong> </p> <p>Why not? This is Python. Write a separate tool that imports that layer and does database builds.</p> <p><strong>"when will the test client going to connect to the server: per each unit test or before running the test suite?"</strong></p> <p>Depends on the intent of the test. Depends on your use cases. What happens in the "real world" with your actual intended clients?</p> <p>You'll want to test client-like behavior, making connections the way clients make connections.</p> <p>Also, you'll want to test abnormal behavior, like clients dropping connections or doing things out of order, or unconnected.</p>
1
2009-01-21T11:15:34Z
[ "python", "unit-testing", "twisted" ]
unit testing for an application server
464,543
<p>I wrote an application server (using python &amp; twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to the app server and makes the necessary requests (the communication protocol is some in-house XML), store in a static way the received XML and then write some tests on those static data using unitest.</p> <p>My question is: Is this a correct approach and if yes, what kind of tests are covered with this approach?</p> <p>Also, using this method has several disadvantages, like: not being able to access the database layer in order to build/rebuild the schema, when will the test client going to connect to the server: per each unit test or before running the test suite?</p>
2
2009-01-21T09:15:42Z
465,422
<p>I think you chose the wrong direction. It's true that the Trial docs is very light. But Trial is base on unittest and only add some stuff to deal with the reactor loop and the asynchronous calls (it's not easy to write tests that deal with deffers). All your tests that are not including deffer/asynchronous call will be exactly like normal unittest.</p> <p>The Trial command is a test runner (a bit like nose), so you don't have to write test suites for your tests. You will save time with it. On top of that, the Trial command can output profiling and coverage information. Just do Trial -h for more info.</p> <p>But in any way the first thing you should ask yourself is which kind of tests do you need the most, unit tests, integration tests or system tests (black-box). It's possible to do all with Trial but it's not necessary allways the best fit.</p>
1
2009-01-21T14:01:38Z
[ "python", "unit-testing", "twisted" ]
unit testing for an application server
464,543
<p>I wrote an application server (using python &amp; twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to the app server and makes the necessary requests (the communication protocol is some in-house XML), store in a static way the received XML and then write some tests on those static data using unitest.</p> <p>My question is: Is this a correct approach and if yes, what kind of tests are covered with this approach?</p> <p>Also, using this method has several disadvantages, like: not being able to access the database layer in order to build/rebuild the schema, when will the test client going to connect to the server: per each unit test or before running the test suite?</p>
2
2009-01-21T09:15:42Z
500,629
<p>You should use Trial. It really isn't very hard. Trial's documentation could stand to be improved, but if you know how to use the standard library unit test, the only difference is that instead of writing</p> <pre><code>import unittest </code></pre> <p>you should write</p> <pre><code>from twisted.trial import unittest </code></pre> <p>... and then you can return Deferreds from your <code>test_</code> methods. Pretty much everything else is the same.</p> <p>The one other difference is that instead of building a giant test object at the bottom of your module and then running</p> <pre><code>python your/test_module.py </code></pre> <p>you can simply define your test cases and then run</p> <pre><code>trial your.test_module </code></pre> <p>If you don't care about reactor integration at all, in fact, you can just run <code>trial</code> on a set of existing Python unit tests. Trial supports the standard library '<code>unittest</code>' module.</p>
2
2009-02-01T11:25:33Z
[ "python", "unit-testing", "twisted" ]
Python regular expressions - how to capture multiple groups from a wildcard expression?
464,736
<p>I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:</p> <p><code>re.search("(\w)*", "abcdefg").groups</code>()</p> <p>this returns the list ('g',)</p> <p>I need it to return ('a','b','c','d','e','f','g',)</p> <p>Is that possible? How can I do it? </p>
29
2009-01-21T10:29:31Z
464,755
<pre><code>re.findall(r"\w","abcdefg") </code></pre>
34
2009-01-21T10:33:24Z
[ "python", "regex", "lexical-analysis" ]
Python regular expressions - how to capture multiple groups from a wildcard expression?
464,736
<p>I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:</p> <p><code>re.search("(\w)*", "abcdefg").groups</code>()</p> <p>this returns the list ('g',)</p> <p>I need it to return ('a','b','c','d','e','f','g',)</p> <p>Is that possible? How can I do it? </p>
29
2009-01-21T10:29:31Z
464,879
<p>In addition to <a href="http://stackoverflow.com/questions/464736/python-regular-expressions-how-to-capture-multiple-groups-from-a-wildcard-expre#464755">Douglas Leeder's solution</a>, here is the explanation:</p> <p>In regular expressions the group count is fixed. Placing a quantifier behind a group does not increase group count (imagine all other group indexes increment because an eralier group matched more than once).</p> <p>Groups with quantifiers are the way of making a complex sub-expression atomic, when there is need to match it more than once. The regex engine has no other way than saving the last match only to the group. In short: There is no way to achieve what you want with a single "unarmed" regular expression, and you have to find another way.</p>
23
2009-01-21T11:19:08Z
[ "python", "regex", "lexical-analysis" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
464,882
<p>Have a look at <a href="http://docs.python.org/library/itertools.html#itertools.combinations">itertools.combinations</a>:</p> <blockquote> <pre><code>itertools.combinations(iterable, r) </code></pre> <p>Return r length subsequences of elements from the input iterable.</p> <p>Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.</p> </blockquote> <p>Since 2.6, batteries are included!</p>
146
2009-01-21T11:20:04Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
5,898,031
<p><a href="http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list/464882#464882">This answer</a> missed one aspect: the OP asked for ALL combinations... not just combinations of length "r".</p> <p>So you'd either have to loop through all lengths "L":</p> <pre><code>import itertools stuff = [1, 2, 3] for L in range(0, len(stuff)+1): for subset in itertools.combinations(stuff, L): print(subset) </code></pre> <p>Or -- if you want to get snazzy (or bend the brain of whoever reads your code after you) -- you can generate the chain of "combinations()" generators, and iterate through that:</p> <pre><code>from itertools import chain, combinations def all_subsets(ss): return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1))) for subset in all_subsets(stuff): print(subset) </code></pre>
327
2011-05-05T12:56:24Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
6,542,458
<p>Here's a lazy one-liner, also using itertools:</p> <pre><code>def combinations(items): return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) ) # alternative: ...in product([0,1], repeat=len(items)) ) </code></pre> <p>Main idea behind this answer: there are 2^N combinations -- same as the number of binary strings of length N. For each binary string, you pick all elements corresponding to a "1".</p> <pre><code>items=abc * mask=### | V 000 -&gt; 001 -&gt; c 010 -&gt; b 011 -&gt; bc 100 -&gt; a 101 -&gt; a c 110 -&gt; ab 111 -&gt; abc </code></pre> <p>Things to consider:</p> <ul> <li>This requires that you can call <code>len(...)</code> on <code>items</code> (workaround: if <code>items</code> is something like an iterable like a generator, turn it into a list first with <code>items=list(_itemsArg)</code>)</li> <li>This requires that the order of iteration on <code>items</code> is not random (workaround: don't be insane)</li> <li>This requires that the items are unique, or else <code>{2,2,1}</code> and <code>{2,1,1}</code> will both collapse to <code>{2,1}</code> (workaround: use <code>collections.Counter</code> as a drop-in replacement for <code>set</code>; it's basically a multiset... though you may need to later use <code>tuple(sorted(Counter(...).elements()))</code> if you need it to be hashable)</li> </ul> <hr> <p><strong>Demo</strong></p> <pre><code>&gt;&gt;&gt; list(combinations(range(4))) [set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}, {0}, {0, 3}, {0, 2}, {0, 2, 3}, {0, 1}, {0, 1, 3}, {0, 1, 2}, {0, 1, 2, 3}] &gt;&gt;&gt; list(combinations('abcd')) [set(), {'d'}, {'c'}, {'c', 'd'}, {'b'}, {'b', 'd'}, {'c', 'b'}, {'c', 'b', 'd'}, {'a'}, {'a', 'd'}, {'a', 'c'}, {'a', 'c', 'd'}, {'a', 'b'}, {'a', 'b', 'd'}, {'a', 'c', 'b'}, {'a', 'c', 'b', 'd'}] </code></pre>
23
2011-07-01T00:21:10Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
7,140,454
<p>Using list comprehension:</p> <pre><code>def selfCombine( list2Combine, length ): listCombined = str( ['list2Combine[i' + str( i ) + ']' for i in range( length )] ).replace( "'", '' ) \ + 'for i0 in range(len( list2Combine ) )' if length &gt; 1: listCombined += str( [' for i' + str( i ) + ' in range( i' + str( i - 1 ) + ', len( list2Combine ) )' for i in range( 1, length )] )\ .replace( "', '", ' ' )\ .replace( "['", '' )\ .replace( "']", '' ) listCombined = '[' + listCombined + ']' listCombined = eval( listCombined ) return listCombined list2Combine = ['A', 'B', 'C'] listCombined = selfCombine( list2Combine, 2 ) </code></pre> <p>Output would be:</p> <pre><code>['A', 'A'] ['A', 'B'] ['A', 'C'] ['B', 'B'] ['B', 'C'] ['C', 'C'] </code></pre>
1
2011-08-21T19:10:24Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
7,173,919
<p>I agree with Dan H that Ben indeed asked for <strong>all</strong> combinations. <code>itertools.combinations()</code> does not give all combinations.</p> <p>Another issue is, if the input iterable is big, it is perhaps better to return a generator instead of everything in a list:</p> <pre><code>iterable = range(10) for s in xrange(len(iterable)+1): for comb in itertools.combinations(iterable, s): yield comb </code></pre>
11
2011-08-24T10:24:55Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
23,743,696
<p>Here is one using recursion:</p> <pre><code>&gt;&gt;&gt; import copy &gt;&gt;&gt; def combinations(target,data): ... for i in range(len(data)): ... new_target = copy.copy(target) ... new_data = copy.copy(data) ... new_target.append(data[i]) ... new_data = data[i+1:] ... print new_target ... combinations(new_target, ... new_data) ... ... &gt;&gt;&gt; target = [] &gt;&gt;&gt; data = ['a','b','c','d'] &gt;&gt;&gt; &gt;&gt;&gt; combinations(target,data) ['a'] ['a', 'b'] ['a', 'b', 'c'] ['a', 'b', 'c', 'd'] ['a', 'b', 'd'] ['a', 'c'] ['a', 'c', 'd'] ['a', 'd'] ['b'] ['b', 'c'] ['b', 'c', 'd'] ['b', 'd'] ['c'] ['c', 'd'] ['d'] </code></pre>
8
2014-05-19T17:25:51Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
24,402,296
<p>This one-liner gives you all the combinations (between <code>0</code> and <code>n</code> items if the original list/set contains <code>n</code> distinct elements) and uses the native method <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations"><code>itertools.combinations</code></a>:</p> <pre><code>from itertools import combinations input = ['a', 'b', 'c', 'd'] output = sum([map(list, combinations(input, i)) for i in range(len(input) + 1)], []) </code></pre> <hr> <p>The output will be:</p> <pre><code>[[], ['a'], ['b'], ['c'], ['d'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'c'], ['b', 'd'], ['c', 'd'], ['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'c', 'd'], ['b', 'c', 'd'], ['a', 'b', 'c', 'd']] </code></pre> <hr> <p>Try it online:</p> <p><a href="http://ideone.com/COghfX">http://ideone.com/COghfX</a></p>
12
2014-06-25T07:08:01Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
29,092,176
<p><strong>You can generating all combinations of a list in python using this simple code</strong></p> <pre><code>import itertools a = [1,2,3,4] for i in xrange(0,len(a)+1): print list(itertools.combinations(a,i)) </code></pre> <p><strong>Result would be :</strong></p> <pre><code>[()] [(1,), (2,), (3,), (4,)] [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] [(1, 2, 3, 4)] </code></pre>
8
2015-03-17T05:52:28Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
29,981,889
<p>This code employs a simple algorithm with nested lists...</p> <pre><code># FUNCTION getCombos: To generate all combos of an input list, consider the following sets of nested lists... # # [ [ [] ] ] # [ [ [] ], [ [A] ] ] # [ [ [] ], [ [A],[B] ], [ [A,B] ] ] # [ [ [] ], [ [A],[B],[C] ], [ [A,B],[A,C],[B,C] ], [ [A,B,C] ] ] # [ [ [] ], [ [A],[B],[C],[D] ], [ [A,B],[A,C],[B,C],[A,D],[B,D],[C,D] ], [ [A,B,C],[A,B,D],[A,C,D],[B,C,D] ], [ [A,B,C,D] ] ] # # There is a set of lists for each number of items that will occur in a combo (including an empty set). # For each additional item, begin at the back of the list by adding an empty list, then taking the set of # lists in the previous column (e.g., in the last list, for sets of 3 items you take the existing set of # 3-item lists and append to it additional lists created by appending the item (4) to the lists in the # next smallest item count set. In this case, for the three sets of 2-items in the previous list. Repeat # for each set of lists back to the initial list containing just the empty list. # def getCombos(listIn = ['A','B','C','D','E','F'] ): listCombos = [ [ [] ] ] # list of lists of combos, seeded with a list containing only the empty list listSimple = [] # list to contain the final returned list of items (e.g., characters) for item in listIn: listCombos.append([]) # append an emtpy list to the end for each new item added for index in xrange(len(listCombos)-1, 0, -1): # set the index range to work through the list for listPrev in listCombos[index-1]: # retrieve the lists from the previous column listCur = listPrev[:] # create a new temporary list object to update listCur.append(item) # add the item to the previous list to make it current listCombos[index].append(listCur) # list length and append it to the current list itemCombo = '' # Create a str to concatenate list items into a str for item in listCur: # concatenate the members of the lists to create itemCombo += item # create a string of items listSimple.append(itemCombo) # add to the final output list return [listSimple, listCombos] # END getCombos() </code></pre>
-1
2015-05-01T05:07:03Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
32,555,515
<p>Below is a "standard recursive answer", similar to the other similar answer <a href="http://stackoverflow.com/a/23743696/711085">http://stackoverflow.com/a/23743696/711085</a> . (We don't realistically have to worry about running out of stack space since there's no way we could process all N! permutations.)</p> <p>It visits every element in turn, and either takes it or leaves it (we can directly see the 2^N cardinality from this algorithm).</p> <pre><code>def combs(xs, i=0): if i==len(xs): yield () return for c in combs(xs,i+1): yield c yield c+(xs[i],) </code></pre> <hr> <p>Demo:</p> <pre><code>&gt;&gt;&gt; list( combs(range(5)) ) [(), (0,), (1,), (1, 0), (2,), (2, 0), (2, 1), (2, 1, 0), (3,), (3, 0), (3, 1), (3, 1, 0), (3, 2), (3, 2, 0), (3, 2, 1), (3, 2, 1, 0), (4,), (4, 0), (4, 1), (4, 1, 0), (4, 2), (4, 2, 0), (4, 2, 1), (4, 2, 1, 0), (4, 3), (4, 3, 0), (4, 3, 1), (4, 3, 1, 0), (4, 3, 2), (4, 3, 2, 0), (4, 3, 2, 1), (4, 3, 2, 1, 0)] &gt;&gt;&gt; list(sorted( combs(range(5)), key=len)) [(), (0,), (1,), (2,), (3,), (4,), (1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1), (4, 1, 0), (4, 2, 0), (4, 2, 1), (4, 3, 0), (4, 3, 1), (4, 3, 2), (3, 2, 1, 0), (4, 2, 1, 0), (4, 3, 1, 0), (4, 3, 2, 0), (4, 3, 2, 1), (4, 3, 2, 1, 0)] &gt;&gt;&gt; len(set(combs(range(5)))) 32 </code></pre>
0
2015-09-13T23:28:46Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
32,555,776
<p>Here is yet another solution (one-liner), involving using the <code>itertools.combinations</code> function, but here we use a double list comprehension (as opposed to a for loop or sum):</p> <pre><code>def combs(x): return [c for i in range(len(x)+1) for c in combinations(x,i)] </code></pre> <hr> <p>Demo:</p> <pre><code>&gt;&gt;&gt; combs([1,2,3,4]) [(), (1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)] </code></pre>
2
2015-09-14T00:13:02Z
[ "python", "combinations" ]
Python code to pick out all possible combinations from a list?
464,864
<p>I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. </p> <p>I've found <a href="http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/">some code</a> (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.</p> <p>The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. </p> <p>Does anyone know of a better way? Using map(), maybe?</p>
123
2009-01-21T11:13:40Z
37,092,698
<pre><code>def combinations(iterable, r): # combinations('ABCD', 2) --&gt; AB AC AD BC BD CD # combinations(range(4), 3) --&gt; 012 013 023 123 pool = tuple(iterable) n = len(pool) if r &gt; n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) x = [2, 3, 4, 5, 1, 6, 4, 7, 8, 3, 9] for i in combinations(x, 2): print i </code></pre>
0
2016-05-07T19:17:02Z
[ "python", "combinations" ]
Parsing Functions
464,970
<p>I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....</p> <p><em>EDIT</em></p> <p>This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?</p>
0
2009-01-21T11:49:51Z
464,987
<p>Take a look at <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a>. It should help you keep your parser specification clean.</p>
0
2009-01-21T11:55:53Z
[ "python", "parsing" ]
Parsing Functions
464,970
<p>I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....</p> <p><em>EDIT</em></p> <p>This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?</p>
0
2009-01-21T11:49:51Z
465,013
<p>Check out <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a>, it allows for definition of the grammar directly in Python code:</p> <p>Assuming a function call is just <code>somename()</code>:</p> <pre><code>&gt;&gt;&gt; from pyparsing import * &gt;&gt;&gt; grammar = Word(alphas + "_", alphanums + "_")("func_name") + "()" + StringEnd() &gt;&gt;&gt; grammar.parseString("ab()\n")["func_name"] "ab" </code></pre>
2
2009-01-21T12:06:42Z
[ "python", "parsing" ]
Parsing Functions
464,970
<p>I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....</p> <p><em>EDIT</em></p> <p>This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?</p>
0
2009-01-21T11:49:51Z
465,022
<p>It all depends on what code you are parsing. </p> <p>If you are parsing Python syntax, use the <code>parser</code> module from Python: <a href="http://docs.python.org/library/parser.html" rel="nofollow">http://docs.python.org/library/parser.html</a></p> <p>A quite complete list of parser libraries available for Python you can find at: <a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">http://nedbatchelder.com/text/python-parsers.html</a></p>
0
2009-01-21T12:08:41Z
[ "python", "parsing" ]
Parsing Functions
464,970
<p>I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....</p> <p><em>EDIT</em></p> <p>This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?</p>
0
2009-01-21T11:49:51Z
465,113
<p>Once you get the name of the function, use a dispatch dict to run the function:</p> <pre><code>def mysum(...): ... def myotherstuff(...): ... # create dispatch dict: myfunctions = {'sum': mysum, 'stuff': myotherstuff} # run your parser: function_name, parameters = parse_result(line) # run the function: myfunctions[function_name](parameters) </code></pre> <p>Alternatively create a class with the commands:</p> <pre><code>class Commands(object): def do_sum(self, ...): ... def do_stuff(self, ...): ... def run(self, funcname, params): getattr(self, 'do_' + funcname)(params) cmd = Commands() function_name, parameters = parse_result(line) cmd.run(function_name, parameters) </code></pre> <p>You could also look at the <a href="http://docs.python.org/library/cmd" rel="nofollow">cmd module</a> in the stdlib to do your class. It can provide you with a command-line interface for your language, with tab command completion, automatically.</p>
3
2009-01-21T12:37:12Z
[ "python", "parsing" ]
Writing unit tests in Django / Python
465,065
<p>I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how.</p> <p>I'm writing a Django application, and so far have only created the models (and customised the admin application). This is how I've written the skeletons of my tests so far:</p> <pre><code>class ModelTests(TestCase): fixtures = ['initial_data.json',] def setUp(self): pass def testSSA(self): ssa = SSA.objects.create(name="sdfsdf", cost_center=1111, street_num=8, street_name="dfsdfsf Street", suburb="sdfsdfsdf", post_code=3333) def testResident(self): pass def testSSA_Client(self): pass </code></pre> <p>I planned to write a function to test each model within the ModelTests class. Is this a good way of writing tests? Also, what exactly should I be testing for? That creating a model with all of the fields completed works? That a half complete model fails? That any special cases are tested (like a null and is_required=False)? I've trust in the ORM, which as far as I'm aware is heavily tested, so I shouldn't need to test all of the methods should I?</p> <p>What do I need to test for a web application written in Django/Python? Some examples would be nice.</p>
28
2009-01-21T12:22:24Z
465,242
<p>I'm not exactly sure of the specifics of what you're trying to test here, I'd need more code snippets for this, but I can give you some general advice.</p> <p>First, read the unit testing chapter of "Dive into Python" (it's free online! <a href="http://diveintopython3.ep.io/unit-testing.html" rel="nofollow">http://diveintopython3.ep.io/unit-testing.html</a>), it's a great explanation of unit testing in general, what you need to do, and why.</p> <p>Second, with regards to TDD, it is a valuable practice, but be careful about growing too dependent on it as I've found it can lead to over-specifying software and further on to having software that can not be re-developed and adapted to new tasks. This is just my experience, mind. Also, providing you don't use it dogmatically TDD is valuable.</p> <p>Third, it strikes me that the best piece of advice for your specific situation is to <em>strive to test your logic, but not the logic of frameworks that you depend on</em>. That means that often testing half-complete models fail etc. etc. may not be appropriate, since that is not your logic, but django's, and so should already be tested. More valuable would be to test a few expected cases, instantiations that you expect, exceptions that you expect etc. to make sure your model specification is sound, and then move on to the more substantial logic of your application.</p>
9
2009-01-21T13:12:53Z
[ "python", "django", "unit-testing" ]
Writing unit tests in Django / Python
465,065
<p>I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how.</p> <p>I'm writing a Django application, and so far have only created the models (and customised the admin application). This is how I've written the skeletons of my tests so far:</p> <pre><code>class ModelTests(TestCase): fixtures = ['initial_data.json',] def setUp(self): pass def testSSA(self): ssa = SSA.objects.create(name="sdfsdf", cost_center=1111, street_num=8, street_name="dfsdfsf Street", suburb="sdfsdfsdf", post_code=3333) def testResident(self): pass def testSSA_Client(self): pass </code></pre> <p>I planned to write a function to test each model within the ModelTests class. Is this a good way of writing tests? Also, what exactly should I be testing for? That creating a model with all of the fields completed works? That a half complete model fails? That any special cases are tested (like a null and is_required=False)? I've trust in the ORM, which as far as I'm aware is heavily tested, so I shouldn't need to test all of the methods should I?</p> <p>What do I need to test for a web application written in Django/Python? Some examples would be nice.</p>
28
2009-01-21T12:22:24Z
465,264
<p>Presumably you've already read Testing <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">Django Applications</a>.</p> <p>Start testing the normal use cases of your application, creating a new user, adding a blog entry, etc. Just your typical CRUD operations first, then move out to the edge cases. Basically your building confidence in your application that anything you later change will not break how I expect the application to behave.</p> <p>Simulate GET/POST requests on your URLs and observe the responses (headers, status codes and content). Did your application render the correct view? Using the correct template? In the sections where your application throws exceptions, attempt to trigger them (e.g. view/edit a non-existent record to raise ObjectDoesNotExist).</p> <p>It's usually worth putting in a tracking system (e.g. Trac), so you can add a new test for every logged defect.</p>
4
2009-01-21T13:24:11Z
[ "python", "django", "unit-testing" ]
Writing unit tests in Django / Python
465,065
<p>I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how.</p> <p>I'm writing a Django application, and so far have only created the models (and customised the admin application). This is how I've written the skeletons of my tests so far:</p> <pre><code>class ModelTests(TestCase): fixtures = ['initial_data.json',] def setUp(self): pass def testSSA(self): ssa = SSA.objects.create(name="sdfsdf", cost_center=1111, street_num=8, street_name="dfsdfsf Street", suburb="sdfsdfsdf", post_code=3333) def testResident(self): pass def testSSA_Client(self): pass </code></pre> <p>I planned to write a function to test each model within the ModelTests class. Is this a good way of writing tests? Also, what exactly should I be testing for? That creating a model with all of the fields completed works? That a half complete model fails? That any special cases are tested (like a null and is_required=False)? I've trust in the ORM, which as far as I'm aware is heavily tested, so I shouldn't need to test all of the methods should I?</p> <p>What do I need to test for a web application written in Django/Python? Some examples would be nice.</p>
28
2009-01-21T12:22:24Z
465,684
<p><strong>Is a function to test each model within the ModelTests class a good way of writing tests?</strong></p> <p>No.</p> <p><strong>What exactly should I be testing for?</strong></p> <ul> <li><p>That creating a model with all of the fields completed works? </p></li> <li><p>That a half complete model fails? </p></li> <li><p>That any special cases are tested (like a null and is_required=False)? </p></li> <li><p>I've trust in the ORM, which as far as I'm aware is heavily tested, so I shouldn't need to test all of the methods should I?</p></li> </ul> <p>Not much of that.</p> <p>You might test validation rules, but that isn't meaningful until you've defined some Form objects. Then you have something to test -- does the form enforce all the rules. You'll need at least one TestCase class for each form. A function will be a scenario -- different combinations of inputs that are allowed or not allowed.</p> <p>For each Model class, you'll need at least one TestCase class definition. TestCases are cheap, define lots of them. </p> <p>Your model embodies your "business entity" definitions. Your models will have methods that implement business rules. Your methods will do things like summarize, filter, calculate, aggregate, reduce, all kinds of things. You'll have functions for each of these features of a model class.</p> <p>You're not testing Django. You're testing how your business rules actually work in Django.</p> <p>Later, when you have more stuff in your application (forms, views, urls, etc.) you'll want to use the Django unittest client to exercise each method for each url. Again, one TestCase per </p>
36
2009-01-21T15:08:38Z
[ "python", "django", "unit-testing" ]
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
465,144
<p>I need to batch create images with text. Requirements:</p> <ol> <li>arbitrary size of bitmap</li> <li>PNG format</li> <li>transparent background</li> <li>black text anti-aliased against transparency</li> <li>adjustable character spacing</li> <li>adjustable text position (x and y coordinates where text begins)</li> <li>TrueType and/or Type1 support</li> <li>Unix command line tool or Python library</li> </ol> <p>So far I've evaluated the following:</p> <ul> <li><a href="http://www.pythonware.com/library/pil/" rel="nofollow">Python Imaging Library</a>: fails 5.</li> <li><a href="http://www.imagemagick.org/" rel="nofollow">ImageMagick</a> ("caption" option): hard to figure out 6.</li> <li><a href="http://www.cairographics.org/documentation/pycairo/" rel="nofollow">PyCairo</a>: fails 5.</li> <li><a href="http://www.w3.org/Graphics/SVG/" rel="nofollow">SVG</a> + <a href="http://www.imagemagick.org/script/convert.php" rel="nofollow">ImageMagick convert</a>: most promising, although requires multiple tools</li> </ul> <p>The problem with PIL is that e.g. the default spacing for Verdana is way too sparse. I need the text to be a bit tighter, but there's no way to adjust it in PIL.</p> <p>In ImageMagick I haven't found an easy way to specify where in the image the text begins (I'm using -size WIDTHxHEIGHT and caption:'TEXT'). Adding a transparent border will move the text away from the corner it's achored to, but</p> <ul> <li>image size needs to be adjusted accordingly since border adds to the extents</li> <li>it's not possible to adjust horizontal and vertical offset independently</li> </ul> <p>Have I missed some obvious alternatives or failed to find necessary features from the above mentioned?</p>
3
2009-01-21T12:45:55Z
465,381
<p>(5) indeed looks tricky, short of inserting dummy narrow-spaces into the string (which will break kerning) or using something much higher-level like the SVG or HTML/CSS renderer.</p> <p>However, if you don't mind getting your hands dirty, it looks quite easy to hack PIL's freetype renderer into adding horizontal space. See <a href="http://svn.effbot.org/public/pil/_imagingft.c" rel="nofollow">_imagingft.c</a>; after the following code in both font_getsize and font_render:</p> <pre><code>if (kerning &amp;&amp; last_index &amp;&amp; index) { FT_Vector delta; FT_Get_Kerning(self-&gt;face, last_index, index, ft_kerning_default, &amp;delta); x += delta.x &gt;&gt; 6; } </code></pre> <p>Add:</p> <pre><code>if (last_index &amp;&amp; index) { x += tracking; } </code></pre> <p>Try it with a plain integer for tracking (probably quite large judging by that '>>6') first; compile and see if it works. The next step would be to get the tracking value into the C function from Python, for which you would have to change the ParseTuple call in font_render to:</p> <pre><code>long tracking; if (!PyArg_ParseTuple(args, "Ol|il:render", &amp;string, &amp;id, &amp;mask, &amp;tracking)) return NULL; </code></pre> <p>And in font_getsize:</p> <pre><code>long tracking; if (!PyArg_ParseTuple(args, "O|l:getsize", &amp;string, &amp;tracking)) return NULL; </code></pre> <p>Then look at what Python interface you want. This is a trivial but quite tedious case of adding the extra 'tracking' argument through each level of the interface, for example:</p> <pre><code>def truetype(filename, size, index=0, encoding="", tracking= 0): # added optional tracking "Load a truetype font file." try: return FreeTypeFont(filename, size, index, encoding, tracking) # added tracking ... class FreeTypeFont: "FreeType font wrapper (requires _imagingft service)" def __init__(self, file, size, index=0, encoding="", tracking= 0): # added tracking import _imagingft self.font = _imagingft.getfont(file, size, index, encoding) self.tracking= tracking # add this line ... def getmask2(self, text, mode="", fill=Image.core.fill): size, offset = self.font.getsize(text, self.tracking) # use tracking im = fill("L", size, 0) self.font.render(text, im.id, mode=="1", self.tracking) # use tracking return im, offset </code></pre> <p>I haven't tested any of this! If it works, might be worth submitting as a patch.</p>
3
2009-01-21T13:51:57Z
[ "python", "fonts", "bitmap", "spacing", "unix" ]
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
465,144
<p>I need to batch create images with text. Requirements:</p> <ol> <li>arbitrary size of bitmap</li> <li>PNG format</li> <li>transparent background</li> <li>black text anti-aliased against transparency</li> <li>adjustable character spacing</li> <li>adjustable text position (x and y coordinates where text begins)</li> <li>TrueType and/or Type1 support</li> <li>Unix command line tool or Python library</li> </ol> <p>So far I've evaluated the following:</p> <ul> <li><a href="http://www.pythonware.com/library/pil/" rel="nofollow">Python Imaging Library</a>: fails 5.</li> <li><a href="http://www.imagemagick.org/" rel="nofollow">ImageMagick</a> ("caption" option): hard to figure out 6.</li> <li><a href="http://www.cairographics.org/documentation/pycairo/" rel="nofollow">PyCairo</a>: fails 5.</li> <li><a href="http://www.w3.org/Graphics/SVG/" rel="nofollow">SVG</a> + <a href="http://www.imagemagick.org/script/convert.php" rel="nofollow">ImageMagick convert</a>: most promising, although requires multiple tools</li> </ul> <p>The problem with PIL is that e.g. the default spacing for Verdana is way too sparse. I need the text to be a bit tighter, but there's no way to adjust it in PIL.</p> <p>In ImageMagick I haven't found an easy way to specify where in the image the text begins (I'm using -size WIDTHxHEIGHT and caption:'TEXT'). Adding a transparent border will move the text away from the corner it's achored to, but</p> <ul> <li>image size needs to be adjusted accordingly since border adds to the extents</li> <li>it's not possible to adjust horizontal and vertical offset independently</li> </ul> <p>Have I missed some obvious alternatives or failed to find necessary features from the above mentioned?</p>
3
2009-01-21T12:45:55Z
465,391
<p>Here's the SVG + ImageMagick solution:</p> <p>Programmatically create SVG documents based on this template, replacing "TEXT HERE" with the desired text content:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"&gt; &lt;svg version="1.0" width="152px" height="50px"&gt; &lt;text style="font-size: 22px; font-weight:bold; font-family: Verdana-Bold; letter-spacing: -1.3%;"&gt; &lt;tspan x="10" y="39"&gt;TEXT HERE&lt;/tspan&gt; &lt;/text&gt; &lt;/svg&gt; </code></pre> <p>Convert the documents to background-transparent PNGs with ImageMagick's <code>convert</code>:</p> <pre><code>$ convert -background none input.svg output.png </code></pre>
2
2009-01-21T13:53:48Z
[ "python", "fonts", "bitmap", "spacing", "unix" ]
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
465,144
<p>I need to batch create images with text. Requirements:</p> <ol> <li>arbitrary size of bitmap</li> <li>PNG format</li> <li>transparent background</li> <li>black text anti-aliased against transparency</li> <li>adjustable character spacing</li> <li>adjustable text position (x and y coordinates where text begins)</li> <li>TrueType and/or Type1 support</li> <li>Unix command line tool or Python library</li> </ol> <p>So far I've evaluated the following:</p> <ul> <li><a href="http://www.pythonware.com/library/pil/" rel="nofollow">Python Imaging Library</a>: fails 5.</li> <li><a href="http://www.imagemagick.org/" rel="nofollow">ImageMagick</a> ("caption" option): hard to figure out 6.</li> <li><a href="http://www.cairographics.org/documentation/pycairo/" rel="nofollow">PyCairo</a>: fails 5.</li> <li><a href="http://www.w3.org/Graphics/SVG/" rel="nofollow">SVG</a> + <a href="http://www.imagemagick.org/script/convert.php" rel="nofollow">ImageMagick convert</a>: most promising, although requires multiple tools</li> </ul> <p>The problem with PIL is that e.g. the default spacing for Verdana is way too sparse. I need the text to be a bit tighter, but there's no way to adjust it in PIL.</p> <p>In ImageMagick I haven't found an easy way to specify where in the image the text begins (I'm using -size WIDTHxHEIGHT and caption:'TEXT'). Adding a transparent border will move the text away from the corner it's achored to, but</p> <ul> <li>image size needs to be adjusted accordingly since border adds to the extents</li> <li>it's not possible to adjust horizontal and vertical offset independently</li> </ul> <p>Have I missed some obvious alternatives or failed to find necessary features from the above mentioned?</p>
3
2009-01-21T12:45:55Z
465,544
<p>From a quick glance, <a href="http://www.pango.org/" rel="nofollow">Pango</a> has support for <a href="http://library.gnome.org/devel/pango/unstable/pango-Text-Attributes.html#pango-attr-letter-spacing-new" rel="nofollow">letter spacing</a>. Pango has Python bindings and is integrated with Cairo.</p>
2
2009-01-21T14:36:45Z
[ "python", "fonts", "bitmap", "spacing", "unix" ]