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
Django or CodeIgniter for Turn-Key Web Application
690,856
<p>I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's FogBugz.</p> <p>I'm a Python programmer, and I could fly over the project with Django. There are several reasons I prefer PHP though:</p> <p>1) Django installation, and configuration assumes you have access to a shell (my target is not the programmer type). Although I could offer installation service, but not on their servers.</p> <p>2) Django runs only on some specific hosts that must take special care to enable it. Installing mod_python/mod_wsgi, and most likely the minority of my potential clients would have root access, or even a cpanel.</p> <p>3) Using PHP would mean I could run it on their existing server. I would have no need to move them to a Django-enabled server, and no downtime for their emails, while the DNS updates.</p> <p>On the other hand, I have very little experience with PHP. Smarty as a templating language looks nice, and works similarly to Django templates. It doesn't offer template inheritance though, except in a very hackish way in which I wish not to use as it could break the application if the designer messes them up. What do you think? Thanks in advance!</p>
8
2009-03-27T18:05:22Z
691,231
<p>Deployment is clearly a problem for all non-PHP based web apps, but I think things are getting better with the DreamHost/Engineyard type ISP's who provide Ruby/Python etc. out of the box. It also looks like there's going to be a lot of discussion at PyCon this week about ways to fix deployment problems. The growth in popularity of Django, Turbogears, and Pylons is driving demand for better deployment solutions.</p> <p>That said, if your target market are people hosting on the very low end $12 a year type ISP's then I don't think you have much choice other than PHP.</p> <p>Finally, one thing I disagree with you is running PHP and Django on the same server. I'm running a few PHP apps on my server with Apache and dozens of Django sites with mod_wsgi in daemon mode. Running it that way means the Python interpreter doesn't use up ram in the Apache workers and vice versa, the PHP interpreter isn't contaminating my mod_wsgi daemons :)</p>
4
2009-03-27T19:46:19Z
[ "php", "python", "django", "codeigniter" ]
Django or CodeIgniter for Turn-Key Web Application
690,856
<p>I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's FogBugz.</p> <p>I'm a Python programmer, and I could fly over the project with Django. There are several reasons I prefer PHP though:</p> <p>1) Django installation, and configuration assumes you have access to a shell (my target is not the programmer type). Although I could offer installation service, but not on their servers.</p> <p>2) Django runs only on some specific hosts that must take special care to enable it. Installing mod_python/mod_wsgi, and most likely the minority of my potential clients would have root access, or even a cpanel.</p> <p>3) Using PHP would mean I could run it on their existing server. I would have no need to move them to a Django-enabled server, and no downtime for their emails, while the DNS updates.</p> <p>On the other hand, I have very little experience with PHP. Smarty as a templating language looks nice, and works similarly to Django templates. It doesn't offer template inheritance though, except in a very hackish way in which I wish not to use as it could break the application if the designer messes them up. What do you think? Thanks in advance!</p>
8
2009-03-27T18:05:22Z
691,549
<p>If you want your application to be mainstream then your almost forced to go with PHP. Going from Django to PHP is alot easier than going from PHP to Django. You know the standards, you just need to learn the PHP syntax and functions.</p> <p>I would definitely use a PHP framework. Symfony and akelos are very similar to Rails (close to Django). On the other than theres Code Igniter which does what it should - organise your code.</p>
3
2009-03-27T21:34:50Z
[ "php", "python", "django", "codeigniter" ]
Django or CodeIgniter for Turn-Key Web Application
690,856
<p>I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's FogBugz.</p> <p>I'm a Python programmer, and I could fly over the project with Django. There are several reasons I prefer PHP though:</p> <p>1) Django installation, and configuration assumes you have access to a shell (my target is not the programmer type). Although I could offer installation service, but not on their servers.</p> <p>2) Django runs only on some specific hosts that must take special care to enable it. Installing mod_python/mod_wsgi, and most likely the minority of my potential clients would have root access, or even a cpanel.</p> <p>3) Using PHP would mean I could run it on their existing server. I would have no need to move them to a Django-enabled server, and no downtime for their emails, while the DNS updates.</p> <p>On the other hand, I have very little experience with PHP. Smarty as a templating language looks nice, and works similarly to Django templates. It doesn't offer template inheritance though, except in a very hackish way in which I wish not to use as it could break the application if the designer messes them up. What do you think? Thanks in advance!</p>
8
2009-03-27T18:05:22Z
692,907
<p>Based on your own conclusions, I would go with CodeIgniter. It seems like there would be a ton of work helping your customers install your web app, and I assume you don't want that.</p> <p>Build a simple-to-install web app so that you can concentrate your efforts on making it better and selling it, instead of working extra as a sysadmin or writing extensive installation tutorials.</p> <p>(With that said, FogBugz wasn't easy to install on our Linux server, even though it is written in PHP. It took me and my colleague (both programmers!) more than a full work day to install. So I think there will always be problems with installation of self-hosted web apps.)</p>
2
2009-03-28T15:06:57Z
[ "php", "python", "django", "codeigniter" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
691,057
<p>Check out the <a href="http://pypi.python.org/pypi/IPy/">IPy</a> module. If has a function <code>iptype()</code> that seems to do what you want:</p> <pre><code>&gt;&gt;&gt; from IPy import IP &gt;&gt;&gt; ip = IP('127.0.0.0/30') &gt;&gt;&gt; ip.iptype() 'PRIVATE' </code></pre>
27
2009-03-27T18:55:23Z
[ "python", "network-programming", "ip-address" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
692,457
<p>If you want to avoid importing a module you can just apply a simple regex:</p> <ul> <li>^127.\d{123}.\d{123}.\d{123}$</li> <li>^10.\d{123}.\d{123}.\d{123}$</li> <li>^192.168.\d{123}$</li> <li>^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{123}.[0-9]{123}$</li> </ul>
2
2009-03-28T08:33:51Z
[ "python", "network-programming", "ip-address" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
712,860
<p>A few days after asking this question, I found out about this Google project, <a href="http://code.google.com/p/ipaddr-py/source/browse/trunk/ipaddr.py" rel="nofollow">ipaddr-py</a>, which appears to have some of the same functionality with respect to determining if an address is private (<code>is_rfc1918</code>). Apparently this will be standard in Python 3.1.</p>
2
2009-04-03T07:23:27Z
[ "python", "network-programming", "ip-address" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
8,339,939
<p>You can check that yourself using <a href="http://tools.ietf.org/html/rfc1918">http://tools.ietf.org/html/rfc1918</a> and <a href="http://tools.ietf.org/html/rfc3330">http://tools.ietf.org/html/rfc3330</a>. If you have 127.0.0.1 you just need to <code>&amp;</code> it with the mask (lets say <code>255.0.0.0</code>) and see if the value matches any of the private network's <a href="http://en.wikipedia.org/wiki/Network_address">network address</a>. So using <a href="http://docs.python.org/2/library/socket.html#socket.inet_pton">inet_pton</a> you can do: <code>127.0.0.1 &amp; 255.0.0.0 = 127.0.0.0</code></p> <p>Here is the code that illustrates that:</p> <pre><code>from struct import unpack from socket import AF_INET, inet_pton def lookup(ip): f = unpack('!I',inet_pton(AF_INET,ip))[0] private = ( [ 2130706432, 4278190080 ], # 127.0.0.0, 255.0.0.0 http://tools.ietf.org/html/rfc3330 [ 3232235520, 4294901760 ], # 192.168.0.0, 255.255.0.0 http://tools.ietf.org/html/rfc1918 [ 2886729728, 4293918720 ], # 172.16.0.0, 255.240.0.0 http://tools.ietf.org/html/rfc1918 [ 167772160, 4278190080 ], # 10.0.0.0, 255.0.0.0 http://tools.ietf.org/html/rfc1918 ) for net in private: if (f &amp; net[1]) == net[0]: return True return False # example print(lookup("127.0.0.1")) print(lookup("192.168.10.1")) print(lookup("10.10.10.10")) print(lookup("172.17.255.255")) # outputs True True True True </code></pre> <p>another implementation is to compute the int values of all private blocks:</p> <pre><code>from struct import unpack from socket import AF_INET, inet_pton lookup = "127.0.0.1" f = unpack('!I',inet_pton(AF_INET,lookup))[0] private = (["127.0.0.0","255.0.0.0"],["192.168.0.0","255.255.0.0"],["172.16.0.0","255.240.0.0"],["10.0.0.0","255.0.0.0"]) for net in private: mask = unpack('!I',inet_aton(net[1]))[0] p = unpack('!I',inet_aton(net[0]))[0] if (f &amp; mask) == p: print lookup + " is private" </code></pre>
18
2011-12-01T10:36:41Z
[ "python", "network-programming", "ip-address" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
28,532,296
<p>This is the fixed version of the regex approach suggested by @Kurt including the fix recommended by @RobEvans</p> <ul> <li>^127.\d{1,3}.\d{1,3}.\d{1,3}$ </li> <li>^10.\d{1,3}.\d{1,3}.\d{1,3}$</li> <li>^192.168.\d{1,3}.\d{1,3}$</li> <li><p>^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$</p> <pre><code>def is_ip_private(ip): # https://en.wikipedia.org/wiki/Private_network priv_lo = re.compile("^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$") priv_24 = re.compile("^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$") priv_20 = re.compile("^192\.168\.\d{1,3}.\d{1,3}$") priv_16 = re.compile("^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$") return priv_lo.match(ip) or priv_24.match(ip) or priv_20.match(ip) or priv_16.match(ip) </code></pre></li> </ul>
2
2015-02-15T23:03:15Z
[ "python", "network-programming", "ip-address" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
31,036,423
<p>Since Python 3.3 there is an <a href="https://docs.python.org/3/library/ipaddress.html">ipaddress module</a> in the stdlib that you can use.</p> <pre><code>&gt;&gt;&gt; import ipaddress &gt;&gt;&gt; ipaddress.ip_address('192.168.0.1').is_private True </code></pre> <p>If using Python 2.6 or higher I would strongly recommend to use <a href="https://pypi.python.org/pypi/py2-ipaddress/">a backport of this module</a>.</p>
11
2015-06-24T20:30:24Z
[ "python", "network-programming", "ip-address" ]
How do you determine if an IP address is private, in Python?
691,045
<p>In Python, what is the best way to determine if an IP address (e.g., <code>'127.0.0.1'</code> or <code>'10.98.76.6'</code>) is on a <a href="http://en.wikipedia.org/wiki/Private%5Fnetwork">private network</a>? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?</p>
16
2009-03-27T18:51:53Z
39,656,628
<p>I find this in <a href="https://github.com/wmetcalf/cuckoo-master/blob/master/modules/processing/network.py" rel="nofollow">cuckoo</a>.There is no need to install new modules.Just import two built-in modules: socket and struct. And use function below.</p> <pre><code>def _is_private_ip(self, ip): """Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block. """ networks = [ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "255.255.255.255/32", "224.0.0.0/4", ] for network in networks: try: ipaddr = struct.unpack("&gt;I", socket.inet_aton(ip))[0] netaddr, bits = network.split("/") network_low = struct.unpack("&gt;I", socket.inet_aton(netaddr))[0] network_high = network_low | 1 &lt;&lt; (32 - int(bits)) - 1 if ipaddr &lt;= network_high and ipaddr &gt;= network_low: return True except Exception,err: continue return False </code></pre>
0
2016-09-23T08:53:01Z
[ "python", "network-programming", "ip-address" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,169
<p>Python takes a "we're all consenting adults" approach to information hiding. It's OK to use variables as though they were constants, and trust that users of your code won't do something stupid. </p>
28
2009-03-27T19:24:07Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,171
<p>"Is there a better alternative to just simply returning a list of tuples?"</p> <p>Nope. It works really well.</p>
4
2009-03-27T19:24:29Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,187
<p>"Is there a better alternative to just simply returning a list of tuples?"</p> <p>That's the approach used by the "tokenize" module for parsing Python source code. Returning a simple list of tuples can work very well.</p>
2
2009-03-27T19:30:49Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,230
<p>In many situations, exp. when parsing long input streams, you may find it more useful to implement you tokenizer as a generator function. This way you can easily iterate over all the tokens without the need for lots of memory to build the list of tokens first.</p> <p>For generator see the <a href="http://www.python.org/dev/peps/pep-0255/">original proposal</a> or other online docs</p>
10
2009-03-27T19:45:28Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,271
<p>"Is there a better alternative to just simply returning a list of tuples"</p> <p>I had to implement a tokenizer, but it required a more complex approach than a list of tuples, therefore I implemented a class for each token. You can then return a list of class instances, or if you want to save resources, you can return something implementing the iterator interface and generate the next token while you progress in the parsing.</p>
0
2009-03-27T19:56:48Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,591
<p>Thanks for your help, I've started to bring these ideas together, and I've come up with the following. Is there anything terribly wrong with this implementation (particularly I'm concerned about passing a file object to the tokenizer):</p> <pre><code>class Tokenizer(object): def __init__(self,file): self.file = file def __get_next_character(self): return self.file.read(1) def __peek_next_character(self): character = self.file.read(1) self.file.seek(self.file.tell()-1,0) return character def __read_number(self): value = "" while self.__peek_next_character().isdigit(): value += self.__get_next_character() return value def next_token(self): character = self.__peek_next_character() if character.isdigit(): return self.__read_number() </code></pre>
7
2009-03-27T21:48:18Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
691,963
<p>I have recently built a tokenizer, too, and passed through some of your issues.</p> <p>Token types are declared as "constants", i.e. variables with ALL_CAPS names, at the module level. For example,</p> <pre><code>_INTEGER = 0x0007 _FLOAT = 0x0008 _VARIABLE = 0x0009 </code></pre> <p>and so on. I have used an underscore in front of the name to point out that somehow those fields are "private" for the module, but I really don't know if this is typical or advisable, not even how much Pythonic. (Also, I'll probably ditch numbers in favour of strings, because during debugging they are much more readable.)</p> <p>Tokens are returned as named tuples.</p> <pre><code>from collections import namedtuple Token = namedtuple('Token', ['value', 'type']) # so that e.g. somewhere in a function/method I can write... t = Token(n, _INTEGER) # ...and return it properly </code></pre> <p>I have used named tuples because the tokenizer's client code (e.g. the parser) seems a little clearer while using names (e.g. token.value) instead of indexes (e.g. token[0]).</p> <p>Finally, I've noticed that sometimes, especially writing tests, I prefer to pass a string to the tokenizer instead of a file object. I call it a "reader", and have a specific method to open it and let the tokenizer access it through the same interface.</p> <pre><code>def open_reader(self, source): """ Produces a file object from source. The source can be either a file object already, or a string. """ if hasattr(source, 'read'): return source else: from io import StringIO return StringIO(source) </code></pre>
2
2009-03-28T01:20:48Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
692,432
<p>When I start something new in Python I usually look first at some modules or libraries to use. There's 90%+ chance that there already is somthing available.</p> <p>For tokenizers and parsers this is certainly so. Have you looked at <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> ?</p>
1
2009-03-28T08:16:06Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
693,818
<p>There's an undocumented class in the <code>re</code> module called <code>re.Scanner</code>. It's very straightforward to use for a tokenizer:</p> <pre><code>import re scanner=re.Scanner([ (r"[0-9]+", lambda scanner,token:("INTEGER", token)), (r"[a-z_]+", lambda scanner,token:("IDENTIFIER", token)), (r"[,.]+", lambda scanner,token:("PUNCTUATION", token)), (r"\s+", None), # None == skip token. ]) results, remainder=scanner.scan("45 pigeons, 23 cows, 11 spiders.") print results </code></pre> <p>will result in</p> <pre><code>[('INTEGER', '45'), ('IDENTIFIER', 'pigeons'), ('PUNCTUATION', ','), ('INTEGER', '23'), ('IDENTIFIER', 'cows'), ('PUNCTUATION', ','), ('INTEGER', '11'), ('IDENTIFIER', 'spiders'), ('PUNCTUATION', '.')] </code></pre> <p>I used re.Scanner to write a pretty nifty configuration/structured data format parser in only a couple hundred lines.</p>
46
2009-03-29T00:01:04Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
1,176,838
<p>I've implemented a tokenizer for a C-like programming language. What I did was to split up the creation of tokens into two layers:</p> <ul> <li>a <em>surface scanner</em>: This one actually reads the text and uses regular expression to split it up into only the most primitve tokens (operators, identifiers, numbers,...); this one yields tuples (tokenname, scannedstring, startpos, endpos).</li> <li>a <em>tokenizer</em>: This consumes the tuples from the first layer, turning them into token objects (named tuples would do as well, I think). Its purpose is to detect some long-range dependencies in the token stream, particularly strings (with their opening and closing quotes) and comments (with their opening an closing lexems; - yes, I wanted to retain comments!) and coerce them into single tokens. The resulting stream of token objects is then returned to a consuming parser.</li> </ul> <p>Both are generators. The benefits of this approach were:</p> <ul> <li>Reading of the raw text is done only in the most primitive way, with simple regexps - fast and clean.</li> <li>The second layer is already implemented as a primitive parser, to detect string literals and comments - re-use of parser technology. </li> <li>You don't have to strain the surface scanner with complex detections.</li> <li>But the real parser gets tokens on the semantic level of the language to be parsed (again strings, comments).</li> </ul> <p>I feel quite happy with this layered approach.</p>
1
2009-07-24T10:28:01Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
1,176,867
<p>I'd turn to the excellent <em><a href="http://books.google.com/books?id=GxKWdn7u4w8C" rel="nofollow">Text Processing in Python</a></em> by David Mertz</p>
2
2009-07-24T10:36:27Z
[ "python", "coding-style", "tokenize" ]
Pythonic way to implement a tokenizer
691,148
<p>I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?</p> <p>I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.</p> <p>Listing Token Types:</p> <p>In Java, for example, I would have a list of fields like so:</p> <pre><code>public static final int TOKEN_INTEGER = 0 </code></pre> <p>But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.</p> <p>Returning Tokens From The Tokenizer:</p> <p>Is there a better alternative to just simply returning a list of tuples e.g. </p> <pre><code>[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? </code></pre> <p>Cheers,</p> <p>Pete</p>
11
2009-03-27T19:20:43Z
16,143,071
<p>This being a late answer, there is now something in the official documentation: <a href="http://docs.python.org/3.2/library/re.html#writing-a-tokenizer" rel="nofollow">Writing a tokenizer</a> with the <code>re</code> standard library. This is content in the Python 3 documentation that isn't in the Py 2.7 docs. But it is still applicable to older Pythons.</p> <p>This includes both short code, easy setup, and writing a generator as several answers here have proposed.</p> <p>If the docs are not Pythonic, I don't know what is :-)</p>
1
2013-04-22T08:57:53Z
[ "python", "coding-style", "tokenize" ]
How do I order referenced objects from a Google App Engine Datastore query?
691,217
<p>I have <code>Exhibit</code> objects which reference <code>Gallery</code> objects both of which are stored in the Google App Engine Datastore.</p> <p>How do I order the <code>Exhibit</code> collection on each <code>Gallery</code> object when I get around to iterating over the values (ultimately in a Django template)?</p> <p>i.e. this does not work</p> <pre><code> class Gallery(db.Model): title = db.StringProperty() position = db.IntegerProperty() class Exhibit(db.Model): gallery = db.ReferenceProperty(Gallery, collection_name='exhibits') title = db.StringProperty() position = db.IntegerProperty() galleries = db.GqlQuery('SELECT * FROM Gallery ORDER BY position') for gallery in galleries: gallery.exhibits.order('position') # ... send galleries off the the Django template </code></pre> <p>When rendered in the template, the galleries are correctly ordered but the exhibits are not.</p>
3
2009-03-27T19:40:03Z
691,556
<p>Instead of relying on the collection property App Engine creates, you need to construct your own query:</p> <blockquote> <p>exhibits = Exhibit.all().filter("gallery =", gallery).order("position")</p> </blockquote> <p>Or equivalently, in GQL:</p> <blockquote> <p>exhibits = db.GqlQuery("SELECT * FROM Exhibit WHERE gallery = :1 ORDER BY position", gallery)</p> </blockquote> <p>If you want to be able to do this from inside the template, rather than passing in a list-of-lists of exhibits, you can define a simple method on the Gallery object that executes this query, and reference it from the template (Eg, {{gallery.exhibits_by_position}} will execute exhibits_by_position() on the Gallery object, which can then perform the query above).</p> <p>If you're concerned about the speed implications of this, don't worry: The collection property App Engine creates is simply syntactic sugar for this.</p>
4
2009-03-27T21:36:18Z
[ "python", "google-app-engine", "gae-datastore" ]
Passing functions which have multiple return values as arguments in Python
691,267
<p>So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.</p> <pre><code>a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) </code></pre> <p>...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.</p> <p>Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?</p>
9
2009-03-27T19:55:29Z
691,274
<pre><code>printa(*cord()) </code></pre> <p>The <code>*</code> here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.</p> <p>It's basically the reverse of the <code>*</code> you might use to capture all non-keyword arguments in a function definition:</p> <pre><code>def fn(*args): # args is now a tuple of the non-keyworded arguments print args fn(1, 2, 3, 4, 5) </code></pre> <p>prints <code>(1, 2, 3, 4, 5)</code></p> <pre><code>fn(*[1, 2, 3, 4, 5]) </code></pre> <p>does the same.</p>
17
2009-03-27T19:56:57Z
[ "python", "return-value", "function-calls" ]
Passing functions which have multiple return values as arguments in Python
691,267
<p>So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.</p> <pre><code>a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) </code></pre> <p>...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.</p> <p>Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?</p>
9
2009-03-27T19:55:29Z
691,280
<p>Try this:</p> <pre><code>&gt;&gt;&gt; def cord(): ... return (1, 1) ... &gt;&gt;&gt; def printa(y, x): ... print a[y][x] ... &gt;&gt;&gt; a=[[1,2],[3,4]] &gt;&gt;&gt; printa(*cord()) 4 </code></pre> <p>The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:</p> <pre><code>&gt;&gt;&gt; a = {'a' : 2, 'b' : 3} &gt;&gt;&gt; def foo(a, b): ... print a, b ... &gt;&gt;&gt; foo(**a) 2 3 </code></pre>
6
2009-03-27T19:58:47Z
[ "python", "return-value", "function-calls" ]
Passing functions which have multiple return values as arguments in Python
691,267
<p>So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.</p> <pre><code>a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) </code></pre> <p>...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.</p> <p>Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?</p>
9
2009-03-27T19:55:29Z
691,744
<p>Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples. A statement like </p> <pre><code>x,y = cord() </code></pre> <p>does that, but directly using the return value as you did in </p> <pre><code>printa(cord()) </code></pre> <p>doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".</p>
2
2009-03-27T22:56:10Z
[ "python", "return-value", "function-calls" ]
Python: Retrieve Image from MSSQL
691,288
<p>Dear All, I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image!</p> <p>The following is my code:</p> <pre><code>#!/usr/bin/python import _mssql mssql=_mssql.connect('&lt;ServerIP&gt;','&lt;UserID&gt;','&lt;Password&gt;') mssql.select_db('&lt;Database&gt;') x=1 while x==1: query="select TOP 1 * from table;" if mssql.query(query): rows=mssql.fetch_array() rowNumbers = rows[0][1] #print "Number of rows fetched: " + str(rowNumbers) for row in rows: for i in range(rowNumbers): FILE=open('/home/images/' + str(row[2][i][1]) + '-' + str(row[2][i][2]).strip() + ' (' + str(row[2][i][0]) + ').jpg','wb') FILE.write(row[2][i][4]) FILE.close() print 'Successfully downloaded image: ' + str(row[2][i][0]) + '\t' + str(row[2][i][2]).strip() + '\t' + str(row[2][i][1]) else: print mssql.errmsg() print mssql.stdmsg() mssql.close() </code></pre>
2
2009-03-27T20:03:56Z
692,031
<p>It's kind of hard to tell what the problem is when you're using a database like this. Your query isn't explicitly selecting any columns, so we have no idea what your table structure is, or what types the columns are. I suspect the table format is not what you're expecting, or the columntype is incorrect for your data.</p> <p>Also your code doesn't even look like it would run. You have "for row in rows:" and then don't indent after that. Maybe post your schema?</p>
1
2009-03-28T02:15:14Z
[ "python", "sql-server", "file-io" ]
Python: Retrieve Image from MSSQL
691,288
<p>Dear All, I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image!</p> <p>The following is my code:</p> <pre><code>#!/usr/bin/python import _mssql mssql=_mssql.connect('&lt;ServerIP&gt;','&lt;UserID&gt;','&lt;Password&gt;') mssql.select_db('&lt;Database&gt;') x=1 while x==1: query="select TOP 1 * from table;" if mssql.query(query): rows=mssql.fetch_array() rowNumbers = rows[0][1] #print "Number of rows fetched: " + str(rowNumbers) for row in rows: for i in range(rowNumbers): FILE=open('/home/images/' + str(row[2][i][1]) + '-' + str(row[2][i][2]).strip() + ' (' + str(row[2][i][0]) + ').jpg','wb') FILE.write(row[2][i][4]) FILE.close() print 'Successfully downloaded image: ' + str(row[2][i][0]) + '\t' + str(row[2][i][2]).strip() + '\t' + str(row[2][i][1]) else: print mssql.errmsg() print mssql.stdmsg() mssql.close() </code></pre>
2
2009-03-27T20:03:56Z
2,490,838
<p>If your using freetds (I think you are): Search in your freetds.conf for the 'text size' setting.. standard its at 63 kb</p>
0
2010-03-22T08:44:38Z
[ "python", "sql-server", "file-io" ]
Handling output of python socket recv
691,345
<p>Apologies for the noob Python question but I've been stuck on this for far too long.</p> <p>I'm using python sockets to receive some data from a server. I do this:</p> <pre><code> data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) </code></pre> <p>The output on the console is this:</p> <blockquote> <p>data is <br/> repr(data) is '\x00\x00\x00\x01'</p> </blockquote> <p>I want to turn this string containing essentially a 4 byte number into an int - or actually what would be a long in C. How can I turn this data object into a numerical value that I can easily manage?</p>
3
2009-03-27T20:26:51Z
691,365
<p>You probably want to use <a href="http://docs.python.org/library/struct.html#module-struct" rel="nofollow">struct</a>.</p> <p>The code would look something like:</p> <pre><code>import struct data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) myint = struct.unpack("!i", data)[0] </code></pre>
8
2009-03-27T20:32:52Z
[ "python", "sockets" ]
Is there a method in python that's like os.path.split for other delimiters?
691,740
<p>I want to use something like this:</p> <pre><code>os.path.split("C:\\a\\b\\c") </code></pre> <p>With this kind of output:</p> <p>('C:\a\b', 'c')</p> <p><hr /></p> <p>However I want it to work on other delimiters like this:</p> <pre><code>method ('a_b_c_d') </code></pre> <p>With this kind of output:</p> <p>('a_b_c', 'd')</p>
0
2009-03-27T22:55:11Z
691,748
<pre><code>&gt;&gt;&gt; 'a_b_c_d'.rsplit('_', 1) ['a_b_c', 'd'] </code></pre> <blockquote> <p>Help on built-in function rsplit:</p> <p>rsplit(...) <code>S.rsplit([sep [,maxsplit]])</code> -> list of strings</p> <p>Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator.</p> </blockquote>
15
2009-03-27T22:56:46Z
[ "python", "string" ]
Is there a method in python that's like os.path.split for other delimiters?
691,740
<p>I want to use something like this:</p> <pre><code>os.path.split("C:\\a\\b\\c") </code></pre> <p>With this kind of output:</p> <p>('C:\a\b', 'c')</p> <p><hr /></p> <p>However I want it to work on other delimiters like this:</p> <pre><code>method ('a_b_c_d') </code></pre> <p>With this kind of output:</p> <p>('a_b_c', 'd')</p>
0
2009-03-27T22:55:11Z
691,753
<pre><code>string.split(separator) </code></pre>
0
2009-03-27T22:58:18Z
[ "python", "string" ]
Is it bad form to call a classmethod as a method from an instance?
692,040
<p>Ex.</p> <p>If I have something like this:</p> <pre><code>class C(object): @classmethod def f(cls, x): return x + x </code></pre> <p>This will work:</p> <pre><code>c = C() c.f(2) 4 </code></pre> <p>But is that bad form? Should I only call</p> <pre><code>C.f() </code></pre> <p>or </p> <pre><code>c.__class__.f() </code></pre> <p>Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.</p> <p>?</p>
20
2009-03-28T02:21:05Z
692,054
<p>It's mainly just confusing looking. If I were using your class and saw this, it would make me wonder what other surprises are in there, it just looks like bad design.</p> <p>Is there a reason it's not just a staticmethod?</p>
3
2009-03-28T02:29:35Z
[ "python", "class-method" ]
Is it bad form to call a classmethod as a method from an instance?
692,040
<p>Ex.</p> <p>If I have something like this:</p> <pre><code>class C(object): @classmethod def f(cls, x): return x + x </code></pre> <p>This will work:</p> <pre><code>c = C() c.f(2) 4 </code></pre> <p>But is that bad form? Should I only call</p> <pre><code>C.f() </code></pre> <p>or </p> <pre><code>c.__class__.f() </code></pre> <p>Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.</p> <p>?</p>
20
2009-03-28T02:21:05Z
692,057
<p><code>C.f()</code> is clearer than <code>c_instance.f()</code>, and <code>c_instance.__class__.f()</code> is just ugly. Since clarity and beauty are dearly loved characteristics in the python community, I'd tend to say that C.f() is the best route. </p> <p>Is there any particular reason you even want to call it in either of the other ways?</p>
1
2009-03-28T02:31:12Z
[ "python", "class-method" ]
Is it bad form to call a classmethod as a method from an instance?
692,040
<p>Ex.</p> <p>If I have something like this:</p> <pre><code>class C(object): @classmethod def f(cls, x): return x + x </code></pre> <p>This will work:</p> <pre><code>c = C() c.f(2) 4 </code></pre> <p>But is that bad form? Should I only call</p> <pre><code>C.f() </code></pre> <p>or </p> <pre><code>c.__class__.f() </code></pre> <p>Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.</p> <p>?</p>
20
2009-03-28T02:21:05Z
692,072
<p>If you have an instance of C already, why do you need f() to be a class method? Not only is it bad form, its usually not necessary. Someone on the net says: "This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case."</p> <p>Although, page 484 of <a href="http://books.google.com/books?id=nEJ-jcYF2fMC&amp;printsec=frontcover&amp;dq=learning%2Bpython&amp;ei=BY%5FNSfCpJ4KEygSFkODeCA" rel="nofollow">learning python</a> notes that you can call the method either way and it will be exactly the same as long as you pass the same instance in.</p>
2
2009-03-28T02:41:35Z
[ "python", "class-method" ]
Is it bad form to call a classmethod as a method from an instance?
692,040
<p>Ex.</p> <p>If I have something like this:</p> <pre><code>class C(object): @classmethod def f(cls, x): return x + x </code></pre> <p>This will work:</p> <pre><code>c = C() c.f(2) 4 </code></pre> <p>But is that bad form? Should I only call</p> <pre><code>C.f() </code></pre> <p>or </p> <pre><code>c.__class__.f() </code></pre> <p>Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.</p> <p>?</p>
20
2009-03-28T02:21:05Z
692,195
<p>I don't recall using a classmethod like this from outside the class, but it is certainly ok for an instance method to call a classmethod on itself (e.g. <code>self.foo()</code> where <code>foo</code> is a classmethod). This makes sure that inheritance acts as expected, and will call <code>.foo()</code> in the right subclass instead of the base class.</p>
5
2009-03-28T04:28:11Z
[ "python", "class-method" ]
Is it bad form to call a classmethod as a method from an instance?
692,040
<p>Ex.</p> <p>If I have something like this:</p> <pre><code>class C(object): @classmethod def f(cls, x): return x + x </code></pre> <p>This will work:</p> <pre><code>c = C() c.f(2) 4 </code></pre> <p>But is that bad form? Should I only call</p> <pre><code>C.f() </code></pre> <p>or </p> <pre><code>c.__class__.f() </code></pre> <p>Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.</p> <p>?</p>
20
2009-03-28T02:21:05Z
692,388
<p>If you are tempted to call a class method from an instance you probably don't need a class method.</p> <p>In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction).</p> <pre><code>class C(object): @staticmethod def f(x): return x + x </code></pre> <p>this way it's "good form" to do both</p> <pre><code>c = C() c.f(2) </code></pre> <p>and</p> <pre><code>C.f(2) </code></pre>
20
2009-03-28T07:35:40Z
[ "python", "class-method" ]
How do I track an animated object in Python?
692,259
<p>I want to automate playing a video game with Python. I want to write a script that can grab the screen image, diff it with the next frame and track an object to click on. What libraries would be useful for this other than PIL?</p>
1
2009-03-28T05:14:57Z
692,302
<p>There are a few options here. The brute force diff'ing approach will lead to a lot of frustration unless what you're tracking is very consistent. For this you could use any number of genetic approaches to train your program what to follow. After enough generations it would do the right thing reliably. If the thing you want to track is visually obvious (like a red ball on a white screen) then you could detect it yourself through simple brute force scanning of the bitmap.</p> <p>Another approach would be just looking at the memory of the running app, and figuring out what area is controlling the position of your object. For some more info and ideas on this, see how mumble got 3D positional audio working in various games.</p> <p><a href="http://mumble.sourceforge.net/HackPositionalAudio" rel="nofollow">http://mumble.sourceforge.net/HackPositionalAudio</a></p>
0
2009-03-28T05:43:24Z
[ "python", "animation", "image-manipulation" ]
How do I track an animated object in Python?
692,259
<p>I want to automate playing a video game with Python. I want to write a script that can grab the screen image, diff it with the next frame and track an object to click on. What libraries would be useful for this other than PIL?</p>
1
2009-03-28T05:14:57Z
692,396
<p>Answer would depend on the platform and game too. e.g. I did once similar things for helicopter flash game, as it was very simple 2d game with well defined colored maze It was on widows with copy to clipboard and win32 key events using win32api bindings for python.</p>
0
2009-03-28T07:41:06Z
[ "python", "animation", "image-manipulation" ]
Upgraded to ubuntu 9.04 django test are now slow
692,294
<p>Upgraded my laptop to Ubuntu 9.04 and runing latest trunk of django and my test suite has tripled in time to run.</p> <pre><code>Python2.6 Mysql Django 1.1 beta 1 SVN-10137 </code></pre>
0
2009-03-28T05:36:45Z
695,544
<p>Quote from the Official Jaunty IRC (#ubuntu+1 on Freenode)</p> <blockquote> <p>Jaunty is NOT RELEASED and NOT SUPPORTED. It will most certainly break your system.</p> </blockquote>
3
2009-03-29T22:47:52Z
[ "python", "django", "ubuntu", "testing", "ubuntu-9.04" ]
Upgraded to ubuntu 9.04 django test are now slow
692,294
<p>Upgraded my laptop to Ubuntu 9.04 and runing latest trunk of django and my test suite has tripled in time to run.</p> <pre><code>Python2.6 Mysql Django 1.1 beta 1 SVN-10137 </code></pre>
0
2009-03-28T05:36:45Z
695,764
<p>You should verify that your tests are running in a transaction. Is MySQL using the InnoDB or MyISAM backend? If you were using InnoDB before and now MyISAM there is no transaction support in MyISAM.</p>
0
2009-03-30T01:28:04Z
[ "python", "django", "ubuntu", "testing", "ubuntu-9.04" ]
Resolving dependency in python between modules
692,506
<p>I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. </p> <p>When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my interpreter to m1's location.</p> <p>Thanks J</p>
-2
2009-03-28T09:33:53Z
692,520
<p>It's not <em>entirely</em> clear what your specific problem is (give more details!), but you may find these useful (further Googling will help you reach concrete answers for your specific needs):</p> <ul> <li>The PYTHONPATH environment variable</li> <li>.pth files in directories that appear in PYTHONPATH</li> <li>Manipulating sys.path before importing</li> </ul> <p>However, if m2 depends on m1, and they're distributed together, perhaps it's a better idea to place them in the same directory tree using <a href="http://www.packtpub.com/article/writing-a-package-in-python" rel="nofollow">packages</a>.</p>
3
2009-03-28T09:46:32Z
[ "python", "dependencies" ]
Resolving dependency in python between modules
692,506
<p>I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. </p> <p>When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my interpreter to m1's location.</p> <p>Thanks J</p>
-2
2009-03-28T09:33:53Z
692,521
<p>If you can't modify the shell environment, you can append any directories you want the interpreter to search for modules to <code>sys.path</code> from within your script. In fact, the <code>PYTHONPATH</code> environment variable is read and used to initialize <code>sys.path</code>.</p>
2
2009-03-28T09:49:57Z
[ "python", "dependencies" ]
Resolving dependency in python between modules
692,506
<p>I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. </p> <p>When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my interpreter to m1's location.</p> <p>Thanks J</p>
-2
2009-03-28T09:33:53Z
692,525
<p>What's possible depends on the details of the modules, but usually you can just import the specifics objects needed from the modules, like this:</p> <p>in B.py</p> <pre><code>from A import classA1, funA1 </code></pre> <p>in A.py</p> <pre><code>from B import classB1, funB1 </code></pre> <p>so that you only import what's needed. If the dependencies are more complex, this may not work, but in general it should be possible (unless you actually have real mutual, recursive dependencies at the object level which you can't resolve!).</p>
0
2009-03-28T09:52:36Z
[ "python", "dependencies" ]
How can you find unused functions in Python code?
693,070
<p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p> <p>I've seen these two references: <a href="http://stackoverflow.com/questions/245963">Find unused code</a> and <a href="http://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p> <p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
37
2009-03-28T16:42:42Z
693,120
<p>Because of the fairly strict way python code is presented, would it be that hard to build a list of functions based on a regex looking for <code>def function_name(..)</code> ?</p> <p>And then search for each name and tot up how many times it features in the code. It wouldn't naturally take comments into account but as long as you're having a look at functions with less than two or three instances...</p> <p>It's a bit Spartan but it sounds like a nice sleepy-weekend task =)</p>
1
2009-03-28T17:11:40Z
[ "python", "refactoring", "dead-code" ]
How can you find unused functions in Python code?
693,070
<p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p> <p>I've seen these two references: <a href="http://stackoverflow.com/questions/245963">Find unused code</a> and <a href="http://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p> <p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
37
2009-03-28T16:42:42Z
693,183
<p><a href="http://www.logilab.org/857" rel="nofollow">pylint</a> can do what you want.</p>
19
2009-03-28T17:39:45Z
[ "python", "refactoring", "dead-code" ]
How can you find unused functions in Python code?
693,070
<p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p> <p>I've seen these two references: <a href="http://stackoverflow.com/questions/245963">Find unused code</a> and <a href="http://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p> <p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
37
2009-03-28T16:42:42Z
693,356
<p>I'm not sure if this is helpful, but you might try using the <a href="http://nedbatchelder.com/code/modules/coverage.html" rel="nofollow">coverage</a>, <a href="http://darcs.idyll.org/~t/projects/figleaf/doc/" rel="nofollow">figleaf</a> or other similar modules, which record which parts of your source code is used as you actually run your scripts/application.</p>
4
2009-03-28T19:21:31Z
[ "python", "refactoring", "dead-code" ]
How can you find unused functions in Python code?
693,070
<p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p> <p>I've seen these two references: <a href="http://stackoverflow.com/questions/245963">Find unused code</a> and <a href="http://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p> <p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
37
2009-03-28T16:42:42Z
693,404
<p>unless you know that your code uses reflection, as you said, I would go for a trivial grep. Do not underestimate the power of the asterisk in vim as well (performs a search of the word you have under your cursor in the file), albeit this is limited only to the file you are currently editing.</p> <p>Another solution you could implement is to have a very good testsuite (seldomly happens, unfortunately) and then wrap the routine with a deprecation routine. if you get the deprecation output, it means that the routine was called, so it's still used somewhere. This works even for reflection behavior, but of course you can never be sure if you don't trigger the situation when your routine call is performed.</p>
1
2009-03-28T19:44:15Z
[ "python", "refactoring", "dead-code" ]
How can you find unused functions in Python code?
693,070
<p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p> <p>I've seen these two references: <a href="http://stackoverflow.com/questions/245963">Find unused code</a> and <a href="http://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p> <p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
37
2009-03-28T16:42:42Z
9,824,998
<p>In python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are <strong>coverage</strong> and <strong>figleaf</strong>. They have the drawback that you have to run all possible branches of your code in order to find unused parts, but they also have the advantage that you get very reliable results.</p> <p>Alternatively, you can use static code analyzers, that just look at your code, but don't actually run it. This has the advantage that they run much faster, but due to python's dynamic nature the results are not 100% percent accurate and you might want to double-check them. Two tools that come to mind here are <strong>pyflakes</strong> and <strong>vulture</strong>. They are complementary: Pyflakes finds unused imports and unused local variables while vulture finds unused functions, methods, classes, variables and attributes.</p> <p>The tools are all available at the Python Package Index <a href="http://pypi.python.org/pypi">http://pypi.python.org/pypi</a>.</p>
29
2012-03-22T15:06:44Z
[ "python", "refactoring", "dead-code" ]
Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development?
693,459
<p>I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax".</p> <p>If it matters, Python is installed in this format:</p> <pre><code>/Program Files /Python /2.6 python.exe and everything else /3.0 python.exe and everything else </code></pre> <p>I'm wondering if anyone else has experienced this and what they did to correct the problem.</p>
8
2009-03-28T20:23:37Z
718,086
<p>Yep- it's actually very easy. The scripts in the plugin use 'print' as a keyword which has been changed in Python 3; you just have to convert all 'print' statements in the console.py and platform_ info.py files under the 'python1' folder in your NetBeans installation directory to use parenthesis. For instance, in platform_info.py the first print line says:</p> <pre><code>print "platform.name="+ "Jython " + version </code></pre> <p>Change it to:</p> <pre><code>print("platform.name="+ "Jython " + version) </code></pre> <p>And do this for all print statements. Then go into the NetBeans and import your Python30 directory into the Python Platform Manager; it will work just fine.</p> <p>I haven't run into any other issues yet, but there might be some other small syntax issues in the plugin; they should be very easy to fix.</p>
5
2009-04-05T00:05:55Z
[ "python", "ide", "netbeans" ]
Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development?
693,459
<p>I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax".</p> <p>If it matters, Python is installed in this format:</p> <pre><code>/Program Files /Python /2.6 python.exe and everything else /3.0 python.exe and everything else </code></pre> <p>I'm wondering if anyone else has experienced this and what they did to correct the problem.</p>
8
2009-03-28T20:23:37Z
719,479
<p>It doesn't let me comment back here so I'll answer your comment in an post.</p> <p>Yes, it will let you use Python 2.x as well; the 'print' method was both a keyword and function prior to Python 3, so the parenthesis were optional. As on 3 they are required, so this change is backwards compatible.</p>
2
2009-04-05T18:58:09Z
[ "python", "ide", "netbeans" ]
Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development?
693,459
<p>I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax".</p> <p>If it matters, Python is installed in this format:</p> <pre><code>/Program Files /Python /2.6 python.exe and everything else /3.0 python.exe and everything else </code></pre> <p>I'm wondering if anyone else has experienced this and what they did to correct the problem.</p>
8
2009-03-28T20:23:37Z
719,512
<p>There are some issues with debugging, btw- I'll let you all know when I successfully figure out what has to be updated here.</p>
0
2009-04-05T19:19:31Z
[ "python", "ide", "netbeans" ]
Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development?
693,459
<p>I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax".</p> <p>If it matters, Python is installed in this format:</p> <pre><code>/Program Files /Python /2.6 python.exe and everything else /3.0 python.exe and everything else </code></pre> <p>I'm wondering if anyone else has experienced this and what they did to correct the problem.</p>
8
2009-03-28T20:23:37Z
1,284,595
<p>Thank you Ben Flynn for the solution to integrate python30 with netbeans 6.71</p> <p>However, this piece of code :</p> <pre><code>def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while b &lt; n: print (b, end=' ') a, b = b, a+b fib(2000) </code></pre> <p>Which is an example code from a help site, runs with out error from the IDE, but the editor complains:</p> <pre><code>Internal parser error "no viable alternative at input'=' " </code></pre> <p>Which suggests it is parsing against python2.5.1</p>
0
2009-08-16T15:49:05Z
[ "python", "ide", "netbeans" ]
Has anyone successfully configured NetBeans for Python (specifically Python 3.0) development?
693,459
<p>I was able to configure NetBeans for 2.6.1 by going to to the Python Platform Manager, creating a new platform, and pointing NetBeans at python.exe where I installed 2.6.1. However, when I follow the exact same steps for 3.0, I get an error in the NetBeans console that says "SyntaxError: invalid syntax".</p> <p>If it matters, Python is installed in this format:</p> <pre><code>/Program Files /Python /2.6 python.exe and everything else /3.0 python.exe and everything else </code></pre> <p>I'm wondering if anyone else has experienced this and what they did to correct the problem.</p>
8
2009-03-28T20:23:37Z
1,325,561
<p>Starting at version 3.0, the print statement has to be written as a function...</p> <p>your </p> <p>print (b, end=' ')</p> <p>becomes </p> <p>print("end= ", b)</p>
0
2009-08-25T01:07:27Z
[ "python", "ide", "netbeans" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,636
<p>By "alter" I assume you mean "negate" (but you should have said that).</p> <p>I notice that you're iterating over each element of a two-dimensional array (a list of lists) and treating each element as a list of three elements... but in fact each element is just a number, in your question as stated. So I would do something like this:</p> <pre><code>my_list = [[-n for n in l] for l in my_list] </code></pre>
3
2009-03-28T22:18:45Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,641
<p>Try this:</p> <pre><code>my_list = [[-a, -b, -c] for [a, b, c] in my_list] </code></pre> <p>Note that this creates a new list, rather than altering the list.</p>
3
2009-03-28T22:20:16Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,674
<p>As others have noted, there are two "levels" of lists and one "level" of ints, so two loops gives you an int, not another list.</p> <p>For comparison, the loop version should be:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>That also fixes the bounds for your range. The upper bound is exclusive, not inclusive.</p>
1
2009-03-28T22:36:22Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,682
<p>Although Constantin's answer is correct, I would make two improvements:</p> <ol> <li>Generality is not always the best way. What if the altering function should work on lists?</li> <li>Using <code>enumerate</code> and indexing is not as fast as creating a list copy and assigning it in-place using <code>[:]</code> slicing.</li> </ol> <p>So here's my alternative, which also modifies the list and all inner lists in-place:</p> <pre><code>def lst_apply(lst, func, lvl): if lvl: for x in lst: lst_apply(x, func, lvl - 1) else: lst[:] = [func(x) for x in lst] &gt;&gt;&gt; lst_apply(my_list, lambda x: -x, 1) &gt;&gt;&gt; my_list [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]] </code></pre> <p>I still believe, though, that the best approach here is:</p> <pre><code>def simple_apply(lst, func): lst[:] = [[func(x) for x in y] for y in lst] </code></pre> <p><code>timeit</code> results:</p> <ul> <li><code>simple_apply</code>: 4.0s</li> <li><code>lst_apply</code>: 5.4s</li> <li><code>alter_elements</code>: 11.5s</li> </ul>
1
2009-03-28T22:43:35Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,723
<p>It's possible to code a more general solution to this problem. The following works in Python 3.0, <em>regardless of the level of nesting</em>.</p> <p>Let's define <code>recursive_map</code>:</p> <pre><code>import collections def recursive_map(f, iterable): for e in iterable: if isinstance(e, collections.Iterable): yield recursive_map(f, e) else: yield f(e) </code></pre> <p>Now, the requested negation function can be coded as follows:</p> <pre><code>import functools import operator negate = functools.partial(recursive_map, operator.neg) </code></pre> <p>Thus, for some collection of arbitrarily nested <em>iterables</em> <code>x</code>, we calculate its negation <code>y</code> like this:</p> <pre><code>y = negate(x) </code></pre> <p><hr /></p> <p><strong>Addendum:</strong></p> <p>As noted by user <a href="http://stackoverflow.com/users/77028/chradcliffe">chradcliffe</a>, the above <code>negate</code> function yields a generator which may contain other generators which ..., etc. To expand/evaluate all these generators, we need to apply <code>list()</code> to all of them. So we define another general mapping function, this time one that works on the iterables themselves.</p> <pre><code>def recursive_iter_map(f, iterable): def rec(e): if isinstance(e, collections.Iterable): return recursive_iter_map(f, e) else: return e return f(map(rec, iterable)) </code></pre> <p>Now,</p> <pre><code>all_lists = functools.partial(recursive_iter_map, list) y = all_lists(negate(x)) </code></pre> <p>will actually negate every element right away and return the complete list.</p> <p>Note that we can regard a nested collection of iterables as a <em>tree</em>. Each iterable is a subtree, while non-iterables are leaves. Hence the first function I defined works on leaves, and the second function works on non-leaves.</p>
6
2009-03-28T23:05:53Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,811
<p>It is ugly but you can modify the list in-place with a list comprehension if you really want to.</p> <pre><code>&gt;&gt;&gt; my_list = [[1,2,3],[4,5,6],[7,8,9]] &gt;&gt;&gt; [[slist.__setitem__(i, -n) for i, n in enumerate(slist)] for slist in my_list] [[None, None, None], [None, None, None], [None, None, None]] &gt;&gt;&gt; my_list [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]] </code></pre> <h3>Explicit <code>for</code> loops</h3> <p>Using explicit <code>for</code> loops, as shown in other answers, is considered better style when side-effects are involved, however. I think a nice form for the <code>for</code> loop style is:</p> <pre><code>for nested_list in my_list: for i, x in enumerate(nested_list): nested_list[i] = -x </code></pre>
1
2009-03-28T23:57:13Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,834
<p>Another option is to use the built-in <code>map</code> function:</p> <pre><code>&gt;&gt;&gt; my_list = [[1,2,3],[4,5,6],[7,8,9]] &gt;&gt;&gt; neg = lambda x: -x &gt;&gt;&gt; f = lambda x: map(neg, x) &gt;&gt;&gt; map(f, my_list) [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]] </code></pre>
11
2009-03-29T00:09:02Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
693,876
<p>Many answers are about creating altered <em>copy</em> of list, but literal meaning of question is about in-place modification of list.</p> <p>Here is my version of best-of-breed in-place list altering solution:</p> <pre><code>def alter_elements(lst, func): for i, item in enumerate(lst): if isinstance(item, list): alter_elements(item, func) else: lst[i] = func(item) </code></pre> <p>Test run:</p> <pre><code>&gt;&gt;&gt; sample = [[1,2,3],[4,5,6],[7,8,9]] &gt;&gt;&gt; alter_elements(sample, lambda x: -x) &gt;&gt;&gt; print sample &gt;&gt;&gt; [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]] </code></pre> <p>No list copies. No hardcoded bounds. No list comprehensions with side-effects.</p>
7
2009-03-29T00:37:37Z
[ "python" ]
Alter all values in a Python list of lists?
693,630
<p>Let's say I have a list like:</p> <pre><code>my_list = [[1,2,3],[4,5,6],[7,8,9]] </code></pre> <p>How do I alter every value in the list without doing?:</p> <pre><code>for x in range(0, 3): for y in range(0, 3): my_list[x][y] = -my_list[x][y] </code></pre> <p>I have tried to simplify this by doing</p> <pre><code>my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list] </code></pre> <p>but the values remain the same.</p>
4
2009-03-28T22:15:04Z
694,290
<p>If you have a 3x3 array of numbers, and you want to perform a transformation on every element of it, I suspect you may be better served in the long run by using a numerical library like NumPy/SciPy, and using the matrix routines it provides. If you are in any way interested in high performance, then this would be a necessity. Much of python's flexibility can be foregone at the array element level in exchange for optimised numerical algorithm speed.</p>
0
2009-03-29T07:57:39Z
[ "python" ]
Python module for VBox?
693,752
<p>I want to make some python scripts to create an "Appliance" with VirtualBox. However, I can't find any documentation anywhere on making calls to VBoxService.exe. Well, I've found stuff that works from OUTSIDE the Machine, but nothing from working from inside the machine.</p> <p>Does anyone know anything about this? If there's a library for another language like C I'd be okay with it, though Python would be heavily preferred.</p>
2
2009-03-28T23:20:16Z
694,365
<p>Consider using <A HREF="http://www.libvirt.org" rel="nofollow">libvirt</A>. The VirtualBox support is bleeding-edge (not in any release, may not even be in source control yet, but is available as a set of patches on the mailing list) -- but this single API, available for C, Python and several other languages, lets you control virtual machines and images running in Qemu/KVM, Xen, LXC (Linux Containers), UML (User-Mode Linux), OpenVZ and others.</p> <p>I build and administer virtual appliances (in an automated QA context) using libvirt with the qemu/KVM backend, and it meets my needs very well.</p> <p>libvirt can be configured to allow remote access (such as controlling or querying VBoxService or libvirtd from within one of the VMs, which you appear to want to do -- though I question the wisdom and utility), with numerous authentication and transport options available.</p> <p>[Caveat: libvirt principally targets Unixlike operating systems; it can be built for win32, but YMMV]</p>
2
2009-03-29T09:13:21Z
[ "python", "virtualbox" ]
Best practice for two way hashing in python?
693,826
<p>I want to allow users to validate their email address by clicking on a link. The link would look something like</p> <p><a href="http://www.example.com/verifyemail?id=some-random-string" rel="nofollow">http://www.example.com/verifyemail?id=some-random-string</a></p> <p>When I am sending this email, I want to be able to easily generate this 'some-random-string' from row id of user, an integer. and when user clicks on this link, generate that integer back.</p> <p>Only requirement is this 'some-random-string' should be as opaque and non-guessable to the user as possible.</p> <p><hr /></p> <p>Finally, this is what I settled on</p> <pre><code>def p3_encrypt_safe(plain, key): return base64.urlsafe_b64encode(p3_encrypt(plain, key)) </code></pre> <p>used the nice crypto library from <a href="http://www.nightsong.com/phr/crypto/p3.py" rel="nofollow">http://www.nightsong.com/phr/crypto/p3.py</a> addition of base64 safe encoding is mine.</p>
1
2009-03-29T00:06:00Z
693,838
<p>Use encryption, that's exactly what it's designed for. Blowfish, AES, even DES3 if you don't need particularly high security.</p> <p>Alternatively, you could compute an SHA-256 or SHA-512 (or whatever) hash of the email address and store it in a database along with the email address itself. That way you can just look up the email address using the hash as a key.</p>
3
2009-03-29T00:10:10Z
[ "python" ]
Best practice for two way hashing in python?
693,826
<p>I want to allow users to validate their email address by clicking on a link. The link would look something like</p> <p><a href="http://www.example.com/verifyemail?id=some-random-string" rel="nofollow">http://www.example.com/verifyemail?id=some-random-string</a></p> <p>When I am sending this email, I want to be able to easily generate this 'some-random-string' from row id of user, an integer. and when user clicks on this link, generate that integer back.</p> <p>Only requirement is this 'some-random-string' should be as opaque and non-guessable to the user as possible.</p> <p><hr /></p> <p>Finally, this is what I settled on</p> <pre><code>def p3_encrypt_safe(plain, key): return base64.urlsafe_b64encode(p3_encrypt(plain, key)) </code></pre> <p>used the nice crypto library from <a href="http://www.nightsong.com/phr/crypto/p3.py" rel="nofollow">http://www.nightsong.com/phr/crypto/p3.py</a> addition of base64 safe encoding is mine.</p>
1
2009-03-29T00:06:00Z
694,304
<p>Your best choice is to generate a hash (one-way function) of some of the user's data. For example, to generate a hash of user's row id, you could use something like:</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; hashlib.sha1('3').hexdigest() '77de68daecd823babbb58edb1c8e14d7106e83bb' </code></pre> <p>However, basing your pseudorandom string only on a row id is not very secure, as the user could easily reverse the hash (try <a href="http://www.google.pl/search?q=77de68daecd823babbb58edb1c8e14d7106e83bb" rel="nofollow">googling 77de68daecd823babbb58edb1c8e14d7106e83bb</a>) of such a short string.</p> <p>A simple solution here is to "salt" the hashed string, i.e. add the same secret string to every value that is hashed. For example:</p> <pre><code>&gt;&gt;&gt; hashlib.sha1('3' + 'email@of.user' + 'somestringconstant').hexdigest() 'b3ca694a9987f39783a324f00cfe8279601decd3' </code></pre> <p>If you <a href="http://www.google.pl/search?q=b3ca694a9987f39783a324f00cfe8279601decd3" rel="nofollow">google b3ca694a9987f39783a324f00cfe8279601decd3</a>, probably the only result will be a link to this answer :-), which is not a proof, but a good hint that this hash is quite unique.</p>
5
2009-03-29T08:18:36Z
[ "python" ]
why doesn't subprocess.Popen(...) always return?
694,000
<p>I hope this is a simple python question.</p> <p>When I try the following in the python interpreter:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>It will run the <code>ls -l</code>, but I need to hit "return" to get a new >>> prompt.</p> <p>However, when I try the following:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... p.wait() ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>Then the <code>ls -l</code> will be run with a >>> prompt immediately present.</p> <p>One other variation:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd, stdout=subprocess.PIPE) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>This will give me an immediate new prompt.</p> <p>The last example is closest to what I want. My goal is to launch a child process, wait for it to finish and then use its stdout in my parent process by referring to <code>p.stdout</code> while letting stderr just print to wherever it would otherwise.</p> <p>Right now in my actual application, the last version just hangs at the: <code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE)</code> with or without a <code>p.wait()</code>.</p> <p>Thanks,</p> <p>Charlie</p>
5
2009-03-29T02:18:09Z
694,021
<p>I may have answered my own question. I believe that in the final case, I need to explicitly read from p.stdout in order for my process to continue.</p> <p>ie:</p> <pre><code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE) output = p.stdout.readlines() .... </code></pre> <p>Thanks all</p>
6
2009-03-29T02:35:19Z
[ "python", "subprocess" ]
why doesn't subprocess.Popen(...) always return?
694,000
<p>I hope this is a simple python question.</p> <p>When I try the following in the python interpreter:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>It will run the <code>ls -l</code>, but I need to hit "return" to get a new >>> prompt.</p> <p>However, when I try the following:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... p.wait() ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>Then the <code>ls -l</code> will be run with a >>> prompt immediately present.</p> <p>One other variation:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd, stdout=subprocess.PIPE) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>This will give me an immediate new prompt.</p> <p>The last example is closest to what I want. My goal is to launch a child process, wait for it to finish and then use its stdout in my parent process by referring to <code>p.stdout</code> while letting stderr just print to wherever it would otherwise.</p> <p>Right now in my actual application, the last version just hangs at the: <code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE)</code> with or without a <code>p.wait()</code>.</p> <p>Thanks,</p> <p>Charlie</p>
5
2009-03-29T02:18:09Z
694,074
<p>In the first variation, <code>test()</code> returns immediately after starting the process, but before its output is sent to the console.</p> <p>If you look at the output you <em>do</em> get the prompt, immediately before the output of <code>ls</code>. </p> <pre><code>&gt;&gt;&gt; test(['ls', '-l']) &gt;&gt;&gt; total 0 &lt;----- test() returns, new propmpt --rw-r--r-- 1 foo bar 7 Mar 24 17:38 etc etc </code></pre> <p>In the second variation, <code>test()</code> is waiting for the process to terminate before it returns. </p> <p>In the third version, you're right that you may have to read from the child process's <code>stdout</code> for it to continue.</p>
8
2009-03-29T03:47:51Z
[ "python", "subprocess" ]
why doesn't subprocess.Popen(...) always return?
694,000
<p>I hope this is a simple python question.</p> <p>When I try the following in the python interpreter:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>It will run the <code>ls -l</code>, but I need to hit "return" to get a new >>> prompt.</p> <p>However, when I try the following:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... p.wait() ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>Then the <code>ls -l</code> will be run with a >>> prompt immediately present.</p> <p>One other variation:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd, stdout=subprocess.PIPE) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>This will give me an immediate new prompt.</p> <p>The last example is closest to what I want. My goal is to launch a child process, wait for it to finish and then use its stdout in my parent process by referring to <code>p.stdout</code> while letting stderr just print to wherever it would otherwise.</p> <p>Right now in my actual application, the last version just hangs at the: <code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE)</code> with or without a <code>p.wait()</code>.</p> <p>Thanks,</p> <p>Charlie</p>
5
2009-03-29T02:18:09Z
21,903,956
<p>Just use communicate() method.No need to return.</p> <pre><code>&gt;&gt;&gt; test(['ls', '-l']) &gt;&gt;&gt; &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd).communicate() ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre>
0
2014-02-20T09:46:46Z
[ "python", "subprocess" ]
why doesn't subprocess.Popen(...) always return?
694,000
<p>I hope this is a simple python question.</p> <p>When I try the following in the python interpreter:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>It will run the <code>ls -l</code>, but I need to hit "return" to get a new >>> prompt.</p> <p>However, when I try the following:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd) ... p.wait() ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>Then the <code>ls -l</code> will be run with a >>> prompt immediately present.</p> <p>One other variation:</p> <pre><code>&gt;&gt;&gt; import process &gt;&gt;&gt; def test(cmd): ... p = subprocess.Popen(cmd, stdout=subprocess.PIPE) ... &gt;&gt;&gt; test(['ls', '-l']) </code></pre> <p>This will give me an immediate new prompt.</p> <p>The last example is closest to what I want. My goal is to launch a child process, wait for it to finish and then use its stdout in my parent process by referring to <code>p.stdout</code> while letting stderr just print to wherever it would otherwise.</p> <p>Right now in my actual application, the last version just hangs at the: <code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE)</code> with or without a <code>p.wait()</code>.</p> <p>Thanks,</p> <p>Charlie</p>
5
2009-03-29T02:18:09Z
25,453,263
<p>Here is a command that pings Google forever, so it needs to be manually terminated to retrieve the output.</p> <p>See the <a href="https://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3" rel="nofollow">subprocess documentation</a> for instructions on converting os.popen() method calls to full subprocess.Popen classes.</p> <pre><code>host = "www.google.com" command = "ping %s -t"%host #p = os.popen(command) -- using Popen instead of os.popen() to allow calling terminate() p = Popen(command, stdout=subprocess.PIPE) time.sleep(5) print "term" p.terminate() pingResultSoFar = p.communicate()[0] # get what has been printed to standard out so far print pingResultSoFar </code></pre>
0
2014-08-22T18:17:12Z
[ "python", "subprocess" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,006
<p>Since <code>roll_die</code> returns a value, you can add those values.</p> <p>Try this.</p> <pre><code>roll1.roll_die() + roll2.roll_die() </code></pre> <p>What happens?</p>
1
2009-03-29T02:22:54Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,016
<p>You can just sum the numbers. In case you want to sum the outcome of <em>n</em> rolls, consider adding this function to the class:</p> <pre><code>def sum_of_n_rolls(self, n) return sum(self.roll_die() for _ in range(n)) </code></pre> <p>Also, consider renaming *roll_die* to just <em>roll</em>. It's obvious that it's not about rolling a rock, since the method is part of the class <em>Die</em>.</p> <p><hr /></p> <p><strong>Edit</strong>: I now read you need to print intermediate rolls. Consider:</p> <pre><code>def n_rolls(self, n): return [self.roll_die() for _ in range(n)] </code></pre> <p>Now you can roll a 7-sided die 10 times:</p> <pre><code>rolls = Die(7).n_rolls(10) print(rolls, sum(rolls)) </code></pre>
0
2009-03-29T02:30:02Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,020
<p>You can store the results in a list:</p> <pre><code>rolls = [Die(n).roll_die() for n in (6, 4, 12)] </code></pre> <p>then you can show the individual results</p> <pre><code>&gt;&gt;&gt; print rolls [5, 2, 6] </code></pre> <p>or sum them</p> <pre><code>&gt;&gt;&gt; print sum(rolls) 13 </code></pre> <p>Or, instead, you could keep a running total:</p> <pre><code>total = 0 for n in (6, 4, 12): value = Die(n).roll_die() print "Rolled a", value total += value print "Total is", total </code></pre> <p>(edited to reflect the changes/clarifications to the question)</p>
10
2009-03-29T02:32:52Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,022
<p>I'm not sure exactly where you're confused. The simplest thing you need to do is separate the concept of a specific die you're going to roll (the object) with the action (rolling it). I would start here:</p> <pre><code>d6 = Die() #create die 1 with the default side of 6 d4 = Die(4) #create die 2 with 4 sides d12 = Die(12) #create die 3 with 12 sides roll1 = d6.roll_die() roll2 = d4.roll_die() roll3 = d12.roll_die() print "%d\n%d\n%d\nsum = %d" % (roll1, roll2, roll3, roll1 + roll2 + roll3) </code></pre> <p>... and then get fancier with lists, etc.</p>
3
2009-03-29T02:37:16Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,034
<p>Guess I'd do something like this:</p> <pre><code># Create dice sides = [6,4,12] dice = [Die(s) for s in sides] # Roll dice rolls = [die.roll_die() for die in dice] # Print rolls for roll in rolls: print roll </code></pre> <p>You can also combine a few of these steps if you like:</p> <pre><code>for num_sides in [6,4,12]: print Die(num_sides).roll_die() </code></pre>
0
2009-03-29T02:56:51Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,039
<p>It may also be useful to just store the last roll so you can get it whenever you want.</p> <pre><code>def __init__(self, s = 6): self.sides = s self.last_roll = None def roll_die(self): self.last_roll = random.randint(1,self.sides) return self.last_roll </code></pre>
3
2009-03-29T03:01:03Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
694,217
<p>If I understood you correctly you want a class attribute.</p> <p><strong>UPDATE:</strong> Added a way for automatically reseting the total</p> <pre><code>import random class Die(): _total = 0 @classmethod def total(cls): t = cls._total cls._total = 0 return t def __init__(self, s=6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) self.__class__._total += x return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() print Die.total() print "--" print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() print Die.total() </code></pre>
0
2009-03-29T06:36:33Z
[ "python", "class", "sum" ]
Understanding Python Class instances
694,002
<p>I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. </p> <p>*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() </code></pre>
2
2009-03-29T02:19:23Z
695,507
<p>Let's get crazy :) (combined with my last answer as well)</p> <pre><code>class Die(): def __init__(self, s = 6): self.sides = s self.last_roll = None def roll_die(self): self.last_roll = random.randint(1,self.sides) return self.last_roll dice = map(Die, (6, 4, 12)) rolls = map(Die.roll_die, dice) print rolls print sum(rolls) </code></pre>
0
2009-03-29T22:26:23Z
[ "python", "class", "sum" ]
Bad Pickle get error
694,192
<p>I have been using a flash card program called Mnemosyne which uses python script. A short time ago my database of flash cards became inaccessible after my computer froze and I had to shut it down manually. Whenever I try to load the data base containing my cards I get this error. </p> <pre> Invalid file format Traceback(innermost last): File "mnemosyne\core\mnemosyne_core.pyc", line 1012, in load_database BadPickleGet: 577" </pre> <p>Help would be greatly appreciated. </p>
0
2009-03-29T06:08:20Z
695,936
<p>(Whilst CLayton's copy may be a binary distribution, the source to mnemosyne is freely available.)</p> <p>It's not much help though: line 1012 is just:</p> <pre><code>db = cPickle.load(infile) </code></pre> <p>Where ‘infile’ is the stored database file. So there's something corrupt in your database file. (BadPickleGet is a specific subclass of UnpicklingError, which is what you expect when the input is broken.)</p> <p>You could maybe change mnemosyne_core.py to use the plain Python pickle module instead of cPickle, allowing you to add debugging to pickle.py and work out exactly what it is in the file it doesn't like. But to be honest, if the file became corrupt due to a hardware fault/hard power down the chances are the contents are either truncated, unreadable or just total garbage.</p> <p>Prepare to be going through those early cards all over again...</p>
1
2009-03-30T03:40:52Z
[ "python", "pickle" ]
Detect in python which keys are pressed
694,296
<p>I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, </p> <p>I want to know which keys are pressed now and display a list of them.</p> <p>I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on the keyboard.</p> <p>How do I do this in python? How do I capture keyboard events?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/365110/cross-platform-keylogger">Cross platform keylogger</a></li> <li><a href="http://stackoverflow.com/questions/676713/is-there-a-cross-platform-python-low-level-api-to-capture-or-generate-keyboard-ev">Is there a cross-platform python low-level API to capture or generate keyboard events?</a></li> </ul> <p><strong>EDIT</strong></p> <p>Just so you know I'm not trying to make a keylogger. I'm trying to make a diagnoses tool (I split water on my laptop and the keyboard is starting to get crazy sometime!!)</p>
18
2009-03-29T08:11:26Z
694,311
<p><a href="https://sourceforge.net/p/pykeylogger/wiki/Main_Page/" rel="nofollow">PyKeylogger</a> mentioned in <a href="http://stackoverflow.com/questions/365110/cross-platform-keylogger/365225#365225">the related question</a> might do the job.</p>
4
2009-03-29T08:25:45Z
[ "python", "events", "keyboard" ]
Detect in python which keys are pressed
694,296
<p>I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, </p> <p>I want to know which keys are pressed now and display a list of them.</p> <p>I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on the keyboard.</p> <p>How do I do this in python? How do I capture keyboard events?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/365110/cross-platform-keylogger">Cross platform keylogger</a></li> <li><a href="http://stackoverflow.com/questions/676713/is-there-a-cross-platform-python-low-level-api-to-capture-or-generate-keyboard-ev">Is there a cross-platform python low-level API to capture or generate keyboard events?</a></li> </ul> <p><strong>EDIT</strong></p> <p>Just so you know I'm not trying to make a keylogger. I'm trying to make a diagnoses tool (I split water on my laptop and the keyboard is starting to get crazy sometime!!)</p>
18
2009-03-29T08:11:26Z
694,342
<p>I found the answer using a link in a <a href="http://stackoverflow.com/questions/365110/cross-platform-keylogger">related question</a> to <a href="http://pyhook.wiki.sourceforge.net/" rel="nofollow">pyHook</a>:</p> <p><a href="http://pyhook.wiki.sourceforge.net/pyHook%5FTutorial#tocpyHook%5FTutorial4" rel="nofollow">pyHook tutorial: capturing keypress events</a></p>
2
2009-03-29T08:58:30Z
[ "python", "events", "keyboard" ]
Detect in python which keys are pressed
694,296
<p>I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, </p> <p>I want to know which keys are pressed now and display a list of them.</p> <p>I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on the keyboard.</p> <p>How do I do this in python? How do I capture keyboard events?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/365110/cross-platform-keylogger">Cross platform keylogger</a></li> <li><a href="http://stackoverflow.com/questions/676713/is-there-a-cross-platform-python-low-level-api-to-capture-or-generate-keyboard-ev">Is there a cross-platform python low-level API to capture or generate keyboard events?</a></li> </ul> <p><strong>EDIT</strong></p> <p>Just so you know I'm not trying to make a keylogger. I'm trying to make a diagnoses tool (I split water on my laptop and the keyboard is starting to get crazy sometime!!)</p>
18
2009-03-29T08:11:26Z
695,439
<p>The easiest way to do something like this, if you're not too fussy, is to bring in a GUI toolkit such as pygame or wxPython. For example, run the wxPython Demo, then go to the demo for KeyEvents.</p>
3
2009-03-29T21:43:02Z
[ "python", "events", "keyboard" ]
How can I make this recursive crawl function iterative?
694,366
<p>For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in a shared environment.</p> <pre><code> def crawl(self, url): "Get all URLS from which to scrape categories." try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) self.crawl(attr[1]) </code></pre>
4
2009-03-29T09:13:29Z
694,369
<p>Use a BFS instead of crawling recursively (DFS): <a href="http://en.wikipedia.org/wiki/Breadth_first_search" rel="nofollow">http://en.wikipedia.org/wiki/Breadth_first_search</a></p> <p>You can use an external storage solution (such as a database) for BFS queue to free up RAM.</p> <p>The algorithm is:</p> <pre><code>//pseudocode: var urlsToVisit = new Queue(); // Could be a queue (BFS) or stack(DFS). (probably with a database backing or something). var visitedUrls = new Set(); // List of visited URLs. // initialization: urlsToVisit.Add( rootUrl ); while(urlsToVisit.Count &gt; 0) { var nextUrl = urlsToVisit.FetchAndRemoveNextUrl(); var page = FetchPage(nextUrl); ProcessPage(page); visitedUrls.Add(nextUrl); var links = ParseLinks(page); foreach (var link in links) if (!visitedUrls.Contains(link)) urlsToVisit.Add(link); } </code></pre>
11
2009-03-29T09:16:53Z
[ "python", "recursion", "web-crawler" ]
How can I make this recursive crawl function iterative?
694,366
<p>For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in a shared environment.</p> <pre><code> def crawl(self, url): "Get all URLS from which to scrape categories." try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) self.crawl(attr[1]) </code></pre>
4
2009-03-29T09:13:29Z
694,398
<p>Instead of recursing, you could put the new URLs to crawl into a queue. Then run until the queue is empty without recursing. If you put the queue into a file this uses almost no memory at all.</p>
5
2009-03-29T09:54:17Z
[ "python", "recursion", "web-crawler" ]
How can I make this recursive crawl function iterative?
694,366
<p>For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in a shared environment.</p> <pre><code> def crawl(self, url): "Get all URLS from which to scrape categories." try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) self.crawl(attr[1]) </code></pre>
4
2009-03-29T09:13:29Z
695,187
<p>You can do it pretty easily just by using <code>links</code> as a queue:</p> <pre><code>def get_links(url): "Extract all matching links from a url" try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return [] def crawl(self, url): "Get all URLS from which to scrape categories." links = get_links(url) while len(links) &gt; 0: link = links.pop() for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) # prepend the new links to the queue links = get_links(attr[1]) + links </code></pre> <p>Of course, this doesn't solve the memory problem...</p>
0
2009-03-29T19:26:10Z
[ "python", "recursion", "web-crawler" ]
How can I make this recursive crawl function iterative?
694,366
<p>For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in a shared environment.</p> <pre><code> def crawl(self, url): "Get all URLS from which to scrape categories." try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) self.crawl(attr[1]) </code></pre>
4
2009-03-29T09:13:29Z
697,001
<p>@Mehrdad - Thank you for your reply, the example you provided was concise and easy to understand.</p> <p>The solution:</p> <pre><code> def crawl(self, url): urls = Queue(-1) _crawled = [] urls.put(url) while not urls.empty(): url = urls.get() try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: continue for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): continue else: Crawler._visit(attr[1]) if attr[1] not in _crawled: urls.put(attr[1]) </code></pre>
2
2009-03-30T12:33:44Z
[ "python", "recursion", "web-crawler" ]
how to hook to events / messages in windows using python
694,475
<h2>in short:</h2> <p>i want to intercept <strong>suspend/standby messages</strong> on my laptop, but my program doesn't receives all relevant messages.</p> <h2>background:</h2> <p>there's a bug in ms-excel on windows xp/2k, which prevents system suspend if a file is opened on a network/usb drive.</p> <p>i'm trying to work-around it programmatically (my toolbox include python, vb6, or command line tools).</p> <p>i know nothing about windows instrumentation :-)</p> <p>i have a sysinternals utility that suspends the system anyhow. i want to hook it to the close-lid event!</p> <h2>in long:</h2> <p>The notebook lid close (fujitsu u810) initiate the standby procedure [how?]</p> <p>The system then send everybody WM_POWERBROADCAST: PBT_APMQUERYSUSPEND (i can trace them using <code>SPYXX.EXE</code>)</p> <p>Every program answers "True", until excel answers "false", and the whole process stops.</p> <h2>My questions:</h2> <p>1) my python program doesn't catch neither pbm_apmquerysuspend, nor PBT_APMQUERYSTANDBYFAILED, nor PBT_APMQUERYSUSPENDFAILED: ` ...</p> <pre><code>query = "SELECT * FROM Win32_PowerManagementEvent" power_watcher = wmi.ExecNotificationQuery ( query ) power_event = power_watcher.NextEvent () </code></pre> <p>` it receives only PBT_APMSUSPEND, if standby finally occurs.</p> <p>Why not - and how do i intercept it?</p> <p>2) Is there another way to intercept the standby process?</p> <p>in a prefect world, i would set the lid-close event to run a command i choose. in a perfect world, lid-closure is a documented event.</p> <p>thank you all :-)</p>
9
2009-03-29T11:15:10Z
702,555
<p>Is this a learning experience or something that you actually want ? </p> <p>Could your program instead just quit excel when it detects a shut down therefore avoiding the issue of excel reporting back a false?</p>
0
2009-03-31T18:58:02Z
[ "python", "windows", "wmi", "power-management" ]
how to hook to events / messages in windows using python
694,475
<h2>in short:</h2> <p>i want to intercept <strong>suspend/standby messages</strong> on my laptop, but my program doesn't receives all relevant messages.</p> <h2>background:</h2> <p>there's a bug in ms-excel on windows xp/2k, which prevents system suspend if a file is opened on a network/usb drive.</p> <p>i'm trying to work-around it programmatically (my toolbox include python, vb6, or command line tools).</p> <p>i know nothing about windows instrumentation :-)</p> <p>i have a sysinternals utility that suspends the system anyhow. i want to hook it to the close-lid event!</p> <h2>in long:</h2> <p>The notebook lid close (fujitsu u810) initiate the standby procedure [how?]</p> <p>The system then send everybody WM_POWERBROADCAST: PBT_APMQUERYSUSPEND (i can trace them using <code>SPYXX.EXE</code>)</p> <p>Every program answers "True", until excel answers "false", and the whole process stops.</p> <h2>My questions:</h2> <p>1) my python program doesn't catch neither pbm_apmquerysuspend, nor PBT_APMQUERYSTANDBYFAILED, nor PBT_APMQUERYSUSPENDFAILED: ` ...</p> <pre><code>query = "SELECT * FROM Win32_PowerManagementEvent" power_watcher = wmi.ExecNotificationQuery ( query ) power_event = power_watcher.NextEvent () </code></pre> <p>` it receives only PBT_APMSUSPEND, if standby finally occurs.</p> <p>Why not - and how do i intercept it?</p> <p>2) Is there another way to intercept the standby process?</p> <p>in a prefect world, i would set the lid-close event to run a command i choose. in a perfect world, lid-closure is a documented event.</p> <p>thank you all :-)</p>
9
2009-03-29T11:15:10Z
707,898
<p>I've found an ugly workaround: I wrote an <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> script which detects the Excel's error MessageBox, closes it, and runs a sysinternals' utility which forces the computer to standby.</p> <pre> Opt("WinWaitDelay",400) ; -- exact text match, to save LOTS of cup cycles! Opt("WinTitleMatchMode",3) Opt("WinDetectHiddenText",1) Opt("MouseCoordMode",0) ; Opt("WinSearchChildren",1) dim $title = "Microsoft Excel" dim $text = "Windows cannot go on standby because Microsoft Office documents or application components are being accessed from the network. You must close the open documents or exit the applications before you can put the computer on standby." While True ; wait for excel's error msg WinWait($title, $text) Run("psshutdown.exe -c -d -accepteula -m mooshmoosh -t 5") ; the annoying msgbox doesn't close without the 'sleep' Sleep(1000) ; close the annoying modal msgbox! WinClose($title) ;1 minute delay, save cpu (?) Sleep(1*60*1000) WEnd </pre> <p>(this is an optimized version - the first trials were CPU intensive).<br> now it sits in the system-tray and just works.</p> <p>the lost messages question is still open. though i realized it has nothing to do with python in the first place.</p>
2
2009-04-02T00:47:07Z
[ "python", "windows", "wmi", "power-management" ]
What is the best way to internationalize a Python app with multiple i18n domains?
694,768
<p>I'm internationalizing a Python application, with two goals in mind:</p> <ol> <li><p>The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using domain B, etc.</p></li> <li><p>The locale can be changed while the application is running.</p></li> </ol> <p>Python's <code>gettext</code> module makes internationalizing a single-domain single-language application very easy; you just set the locale, then call <code>gettext.install()</code>, which finds the right <code>Translation</code> and installs its <code>ugettext</code> method in the global namespace as <code>_</code>. But obviously a global value only works for a single domain, and since it loads a single <code>Translation</code>, it only works for that locale.</p> <p>I could instead load the <code>Translation</code> at the top of each module, and bind its ugettext method as <code>_</code>. Then each module would be using the <code>_</code> for its own domain. But this still breaks when the locale is changed, because <code>_</code> is for the wrong locale.</p> <p>So I guess I could load the correct <code>ugettext</code> at the top of every function, but that seems awfully cumbersome. An alternative would be to still do it per-module, but instead of binding <code>ugettext</code>, I would substitute my own function, which would check the current locale, get its <code>Translation</code>, and forward the string to it. Does anyone have a cleaner solution?</p>
2
2009-03-29T15:08:06Z
694,953
<p>how about you bind _ to a function roughly like this (for each module):</p> <pre><code>def _(message): return my_gettext(__name__, message) </code></pre> <p>This allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.</p>
2
2009-03-29T16:55:49Z
[ "python", "localization", "internationalization" ]
Shortening a oft-used code segment for testing a return value in Python
694,775
<p>Consider this Python segment:</p> <pre><code>def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution continues </code></pre> <p>Now, the question: the three-line segment in the beginning of SomeCallingFunction to get the value of the test function and bail out if it's not None, is repeated very often in many other functions. Three lines is too long. I want to shorten it to one. How do I do that?</p> <p>I can freely restructure this code and the contents of someTestFunction however needed. I thought of using exceptions, but those don't seem to help in cutting down the calling code length.</p> <p>(I've read a bit about Python decorators, but haven't used them. Would this be the place? How would it work?)</p>
1
2009-03-29T15:10:51Z
694,786
<p>I often use a hash table in place of a series of elifs:</p> <pre><code>def someTestFunction(decorated_test): options = { 'val1': return_val_1, 'val2': return_val_2 } return options[decorated_test] </code></pre> <p>You can set up options as a defaultdict(None) to default to None if a key isn't found.</p> <p>If you can't get your tests in that form, then a series of if statements might actually be the best thing to do.</p> <p>One small thing you can do to shorten your code is to use this:</p> <pre><code>if a: return a </code></pre> <p>There may be other ways to shorten your code, but these are the ones I can come up with on the spot.</p>
4
2009-03-29T15:17:44Z
[ "python", "optimization" ]
Shortening a oft-used code segment for testing a return value in Python
694,775
<p>Consider this Python segment:</p> <pre><code>def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution continues </code></pre> <p>Now, the question: the three-line segment in the beginning of SomeCallingFunction to get the value of the test function and bail out if it's not None, is repeated very often in many other functions. Three lines is too long. I want to shorten it to one. How do I do that?</p> <p>I can freely restructure this code and the contents of someTestFunction however needed. I thought of using exceptions, but those don't seem to help in cutting down the calling code length.</p> <p>(I've read a bit about Python decorators, but haven't used them. Would this be the place? How would it work?)</p>
1
2009-03-29T15:10:51Z
694,803
<p>If you want to use a decorator, it would look like this:</p> <pre><code>def testDecorator(f): def _testDecorator(): a = someTestFunction() if a is None: return f() else: return a return _testDecorator @testDecorator def SomeCallingFunction(): ... normal execution </code></pre> <p>When the module is first imported, it runs <code>testDecorator</code>, passing it your original <code>SomeCallingFunction</code> as a parameter. A new function is returned, and that gets bound to the <code>SomeCallingFunction</code> name. Now, whenever you call <code>SomeCallingFunction</code>, it runs that other function, which does the check, and returns either <code>a</code>, or the result of the original <code>SomeCallingFunction</code>.</p>
9
2009-03-29T15:27:43Z
[ "python", "optimization" ]
Shortening a oft-used code segment for testing a return value in Python
694,775
<p>Consider this Python segment:</p> <pre><code>def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution continues </code></pre> <p>Now, the question: the three-line segment in the beginning of SomeCallingFunction to get the value of the test function and bail out if it's not None, is repeated very often in many other functions. Three lines is too long. I want to shorten it to one. How do I do that?</p> <p>I can freely restructure this code and the contents of someTestFunction however needed. I thought of using exceptions, but those don't seem to help in cutting down the calling code length.</p> <p>(I've read a bit about Python decorators, but haven't used them. Would this be the place? How would it work?)</p>
1
2009-03-29T15:10:51Z
694,811
<p>I think this would do it:</p> <p><strong>UPDATE</strong> Fixed!<br /> Sorry for yesterday, I rushed and didn't test the code!</p> <pre><code>def test_decorator( test_func ): def tester( normal_function ): def tester_inner(): a = test_func() if a is not None: return a return normal_function() return tester_inner return tester #usage: @test_decorator( my_test_function ) def my_normal_function(): #.... normal execution continue ... </code></pre> <p>It's similar to DNS's answer but allows you to specify which test function you want to use </p>
2
2009-03-29T15:34:09Z
[ "python", "optimization" ]
Help with Python loop weirdness?
695,040
<p>I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. </p> <p>Anyways, here's the code I'm having trouble with:</p> <pre><code>db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # &lt;== what it says else: # they do want an alert during the current hour, send an email # send mail code here </code></pre> <p>The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.</p>
1
2009-03-29T17:54:24Z
695,077
<p>I would check the logic in your conditionals. You looping construct should work. </p>
0
2009-03-29T18:19:52Z
[ "python", "csv", "loops" ]
Help with Python loop weirdness?
695,040
<p>I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. </p> <p>Anyways, here's the code I'm having trouble with:</p> <pre><code>db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # &lt;== what it says else: # they do want an alert during the current hour, send an email # send mail code here </code></pre> <p>The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.</p>
1
2009-03-29T17:54:24Z
695,113
<p>Be explicit with what's in a row. Using 0, 1, 2...n is actually your bug, and it makes code very hard to read in the future for yourself or others. So let's use the handy tuple to show what we're expecting from a row. This sort of works like code as documentation</p> <pre><code>db = open("db.csv") for line in db.readlines(): recipient, start_hour, end_hour = line.split(",") nrt = [] etc... </code></pre> <p>This shows the reader of your code what you're expecting a line to contain, and it would have shown your bug to you the first time you ran it :)</p>
0
2009-03-29T18:37:01Z
[ "python", "csv", "loops" ]
Help with Python loop weirdness?
695,040
<p>I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. </p> <p>Anyways, here's the code I'm having trouble with:</p> <pre><code>db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # &lt;== what it says else: # they do want an alert during the current hour, send an email # send mail code here </code></pre> <p>The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.</p>
1
2009-03-29T17:54:24Z
695,125
<p>Have you tried something more simple? Just to see how your file is actually read by Python:</p> <pre><code>db = open("db.csv") for line in db: print line </code></pre> <p>There can be problem with format of your csv-file. That happens, for instance, when you open Unix file in Windows environment. In that case the whole file looks like single string as Windows and Unix have different line separators. So, I don't know certain cause of your problem, but offer to think in that direction.</p> <p><strong>Update:</strong> Your have multiple ways through the body of your loop: </p> <ol> <li>when <code>s</code> is <code>"no"</code>: <code>"They always want alerts, sending email"</code> will be printed.</li> <li>when <code>s</code> is not <code>"no"</code> and <code>curtime in nrt</code>: <code>"They don't want an alert during the current hour, not sending"</code> will be printed.</li> <li>when <code>s</code> is not <code>"no"</code> and <code>curtime in nrt</code> is false (the last <code>else</code>): <strong>nothing</strong> will be printed and no other action undertaken.</li> </ol> <p>Shouldn't you place some <code>print</code> statement in the last <code>else</code> branch?</p> <p>Also, what is exact output of your snippet? Is it <code>"They always want alerts, sending email"</code>?</p>
5
2009-03-29T18:44:43Z
[ "python", "csv", "loops" ]
Help with Python loop weirdness?
695,040
<p>I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. </p> <p>Anyways, here's the code I'm having trouble with:</p> <pre><code>db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # &lt;== what it says else: # they do want an alert during the current hour, send an email # send mail code here </code></pre> <p>The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.</p>
1
2009-03-29T17:54:24Z
695,148
<p>If this is a regular CSV file you should not try to parse it yourself. Use the standard library <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a>.</p> <p>Here is a short example from the docs:</p> <pre><code>import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: print row </code></pre>
9
2009-03-29T19:00:33Z
[ "python", "csv", "loops" ]
Help with Python loop weirdness?
695,040
<p>I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. </p> <p>Anyways, here's the code I'm having trouble with:</p> <pre><code>db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # &lt;== what it says else: # they do want an alert during the current hour, send an email # send mail code here </code></pre> <p>The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.</p>
1
2009-03-29T17:54:24Z
695,152
<p>There are at least two bugs in your program:</p> <pre><code>curtime = time.strftime("%H") ... for hour in range(int(s), int(f)): nrt.append(hour) # this is an inefficient synonym for # nrt = range(int(s), int(f)) if curtime in nrt: ... </code></pre> <p>First, curtime is a string, whereas nrt is a list of integers. Python is strongly typed, so the two are not interchangeable, and won't compare equal:</p> <pre><code>'4' == 4 # False '4' in [3, 4, 5] # False </code></pre> <p>This revised code addresses that issue, and is also more efficient than generating a list and searching for the current hour in it:</p> <pre><code>cur_hour = time.localtime().tm_hour if int(s) &lt;= cur_hour &lt; int(f): # You can "chain" comparison operators in Python # so that a op1 b op2 c is equivalent to a op1 b and b op2c ... </code></pre> <p>A second issue that the above does not address is that your program will not behave properly if the hours wrap around midnight (e.g. s = 22 and f = 8).</p> <p>Neither of these problems are necessarily related to "the script only ends up looping through one of the lines", but you haven't given us enough information to figure out why that might be. A more useful way to ask questions is to post a <strong>brief</strong> but <strong>complete</strong> code snippet that shows the behavior you are observing, along with sample input and the resulting error messages, if any (along with traceback).</p>
7
2009-03-29T19:02:11Z
[ "python", "csv", "loops" ]
Help with Python loop weirdness?
695,040
<p>I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. </p> <p>Anyways, here's the code I'm having trouble with:</p> <pre><code>db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # &lt;== what it says else: # they do want an alert during the current hour, send an email # send mail code here </code></pre> <p>The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.</p>
1
2009-03-29T17:54:24Z
695,531
<p>You could go thro an existing well written IRC bot in Python <a href="http://susam.in/downloads/pibby/pibby-0.0.3-alpha.tar.gz" rel="nofollow">Download</a></p>
0
2009-03-29T22:40:40Z
[ "python", "csv", "loops" ]
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
695,370
<p>Google is sponsoring an Open Source project to increase the speed of Python by 5x.</p> <p><a href="http://code.google.com/p/unladen-swallow/">Unladen-Swallow</a> seems to have a <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">good project plan</a></p> <p>Why is concurrency such a hard problem? <br /> Is LLVM going to solve the concurrency problem? <br /> Are there solutions other than Multi-core for Hardware advancement?</p>
26
2009-03-29T21:01:56Z
695,428
<p><a href="http://llvm.org/">LLVM</a> is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate a standalone executable. </p> <p>The problem with concurrency is that, although it was used for a long time in scientific computing, it has just recently has become common in consumer apps. So while it's widely known how to program a scientific calculation program to achieve great performance, it is completely different thing to write a mail user agent/word processor that can be good at concurrency. Also, most of the current OS's were being designed with a single processor in mind, and they may not be fully prepared for multicore processors.</p> <p>The benefit of LLVM with respect to concurrency is that you have an intermediate output, and if in the future there are advances in concurrency, then by updating your interpreter you instantly gain those benefits in all LLVM-compiled programs. This is not so easy if you had compiled to a standalone executable. So LLVM doesn't solve the concurrency problem per se but it leaves an open door for future enhancements.</p> <p>Sure there are more possible advances for the hardware like quantum computers, genetics computers, etc. But we have to wait for them to become a reality.</p>
32
2009-03-29T21:37:41Z
[ "python", "multicore", "llvm", "unladen-swallow" ]
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
695,370
<p>Google is sponsoring an Open Source project to increase the speed of Python by 5x.</p> <p><a href="http://code.google.com/p/unladen-swallow/">Unladen-Swallow</a> seems to have a <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">good project plan</a></p> <p>Why is concurrency such a hard problem? <br /> Is LLVM going to solve the concurrency problem? <br /> Are there solutions other than Multi-core for Hardware advancement?</p>
26
2009-03-29T21:01:56Z
695,433
<p>The switch to LLVM itself isn't solving the concurrency problem. That's being solved separately, by getting rid of the <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock">Global Interpreter Lock</a>.</p> <p>I'm not sure how I feel about that; I use threads mainly to deal with blocking I/O, not to take advantage of multicore processors (for that, I would use the <code>multiprocessing</code> module to spawn separate processes).</p> <p>So I kind of like the GIL; it makes my life a lot easier not having to think about tricky synchronization issues.</p>
17
2009-03-29T21:39:59Z
[ "python", "multicore", "llvm", "unladen-swallow" ]
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
695,370
<p>Google is sponsoring an Open Source project to increase the speed of Python by 5x.</p> <p><a href="http://code.google.com/p/unladen-swallow/">Unladen-Swallow</a> seems to have a <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">good project plan</a></p> <p>Why is concurrency such a hard problem? <br /> Is LLVM going to solve the concurrency problem? <br /> Are there solutions other than Multi-core for Hardware advancement?</p>
26
2009-03-29T21:01:56Z
695,479
<p>LLVM takes care of the nitty-gritty of code generation, so it lets them rewrite Psyco in a way that's more general, portable, maintainable. That in turn allows them to rewrite the CPython core, which lets them experiment with alternate GCs and other things needed to improve python's support for concurrency.</p> <p>In other words, LLVM doesn't solve the concurrency problem, it just frees up your hands so YOU can solve it.</p>
15
2009-03-29T22:07:58Z
[ "python", "multicore", "llvm", "unladen-swallow" ]