title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
what is the correct way to process 4 bits inside an octet in python
1,587,496
<p>I'm writing an application to parse certain network packets. A packet field contains the protocol version number in an octet, so that 4 high bits are the 'major' and low 4 are the 'minor' version. Currently I am parsing them as follows, but am wondering if there is a prettier or more 'pythonic' way of doing it:</p> <pre><code> v = ord(data[17]) major = (v &amp; int('11110000',2) ) &gt;&gt; 4 minor = v &amp; int('00001111',2) </code></pre>
1
2009-10-19T08:18:26Z
1,587,576
<p>Well named functions are always a good way to hide ugliness and irrelevant complexity. This way the bit-fiddling is confined to small and easily proven correct functions while the higher level code can refer to the purpose of the fiddling.</p> <pre><code>def high_nibble(byte): """Get 4 high order bits from a byte.""" return (byte &gt;&gt; 4) &amp; 0xF def low_nibble(byte): """Get 4 low order bits from a byte.""" return byte &amp; 0xF def parse_version(version_byte): """Get the major-minor version tuple from the version byte.""" return high_nibble(version_byte), low_nibble(version_byte) major, minor = parse_version(version_byte) </code></pre>
2
2009-10-19T08:43:32Z
[ "python", "bit-manipulation" ]
Django: How to model a MySQL VARBINARY HEX Field?
1,587,617
<p>I am trying to model a <code>VARBINARY</code> MySQL field in Django v1.1.1. The binary field stores a hexadecimal representation of data (i.e. one would use <code>INSERT INTO test(bin_val) VALUES X'4D7953514C'</code>)</p> <p>Reading the Django documentation[1] I came up with this sollution:</p> <pre><code>class MyTest(models.Model): bin_val = BinValField() class BinValField(models.Field): __metaclass__ = models.SubfieldBase def to_python(self, value): """ DB -&gt; Python """ return ''.join('%X%X' % ((ord(byte)&gt;&gt;4) &amp; 0xF, ord(byte) &amp; 0xF) for byte in value) def get_db_prep_value(self, value): """ Python -&gt; DB """ return a2b_hex(value).decode('latin1') </code></pre> <p>However this doesn't work correctly because:</p> <ul> <li>Django does a Unicode transformation of the binary data from MySQL</li> <li>When saving a new MyTest object, the <code>get_db_prep_value()</code> gets called twice (I think this is a bug in Django?)</li> </ul> <p>The question is how would you model such a field? </p> <p>PS: Related to this problem is this ticket[2] that is still opened after 3 years :(</p> <p>[1] Django: Writing custom model fields</p> <p>[2] <a href="http://code.djangoproject.com/ticket/2417" rel="nofollow"><a href="http://code.djangoproject.com/ticket/2417" rel="nofollow">http://code.djangoproject.com/ticket/2417</a></a></p>
3
2009-10-19T08:57:49Z
1,588,794
<p>The same ticket you referred to also has <a href="http://code.djangoproject.com/attachment/ticket/2417/binaryfield.patch" rel="nofollow">a patch</a> which should give some pointers towards implementing this field.</p> <p>In any case whats your real problem to store it in a CharField?</p> <p>Even if you were to implement a bin field, you could just extend the models.CharField and cast it to hex in the to_python method.</p> <p>Also the same question has also been answered earlier: <a href="http://stackoverflow.com/questions/517349/binaryfields-in-django-models">http://stackoverflow.com/questions/517349/binaryfields-in-django-models</a></p>
0
2009-10-19T13:51:17Z
[ "python", "mysql", "django", "model", "varbinary" ]
Django: How to model a MySQL VARBINARY HEX Field?
1,587,617
<p>I am trying to model a <code>VARBINARY</code> MySQL field in Django v1.1.1. The binary field stores a hexadecimal representation of data (i.e. one would use <code>INSERT INTO test(bin_val) VALUES X'4D7953514C'</code>)</p> <p>Reading the Django documentation[1] I came up with this sollution:</p> <pre><code>class MyTest(models.Model): bin_val = BinValField() class BinValField(models.Field): __metaclass__ = models.SubfieldBase def to_python(self, value): """ DB -&gt; Python """ return ''.join('%X%X' % ((ord(byte)&gt;&gt;4) &amp; 0xF, ord(byte) &amp; 0xF) for byte in value) def get_db_prep_value(self, value): """ Python -&gt; DB """ return a2b_hex(value).decode('latin1') </code></pre> <p>However this doesn't work correctly because:</p> <ul> <li>Django does a Unicode transformation of the binary data from MySQL</li> <li>When saving a new MyTest object, the <code>get_db_prep_value()</code> gets called twice (I think this is a bug in Django?)</li> </ul> <p>The question is how would you model such a field? </p> <p>PS: Related to this problem is this ticket[2] that is still opened after 3 years :(</p> <p>[1] Django: Writing custom model fields</p> <p>[2] <a href="http://code.djangoproject.com/ticket/2417" rel="nofollow"><a href="http://code.djangoproject.com/ticket/2417" rel="nofollow">http://code.djangoproject.com/ticket/2417</a></a></p>
3
2009-10-19T08:57:49Z
1,590,063
<p>MySQL neither store hexadecimal representation for VARBINARY fields nor require it in INSERT statement. The only difference from VARCHAR is that MySQL uses binary collation for it. You can pass any 8-bit string as parameter for it.</p>
0
2009-10-19T17:39:43Z
[ "python", "mysql", "django", "model", "varbinary" ]
Django: How to model a MySQL VARBINARY HEX Field?
1,587,617
<p>I am trying to model a <code>VARBINARY</code> MySQL field in Django v1.1.1. The binary field stores a hexadecimal representation of data (i.e. one would use <code>INSERT INTO test(bin_val) VALUES X'4D7953514C'</code>)</p> <p>Reading the Django documentation[1] I came up with this sollution:</p> <pre><code>class MyTest(models.Model): bin_val = BinValField() class BinValField(models.Field): __metaclass__ = models.SubfieldBase def to_python(self, value): """ DB -&gt; Python """ return ''.join('%X%X' % ((ord(byte)&gt;&gt;4) &amp; 0xF, ord(byte) &amp; 0xF) for byte in value) def get_db_prep_value(self, value): """ Python -&gt; DB """ return a2b_hex(value).decode('latin1') </code></pre> <p>However this doesn't work correctly because:</p> <ul> <li>Django does a Unicode transformation of the binary data from MySQL</li> <li>When saving a new MyTest object, the <code>get_db_prep_value()</code> gets called twice (I think this is a bug in Django?)</li> </ul> <p>The question is how would you model such a field? </p> <p>PS: Related to this problem is this ticket[2] that is still opened after 3 years :(</p> <p>[1] Django: Writing custom model fields</p> <p>[2] <a href="http://code.djangoproject.com/ticket/2417" rel="nofollow"><a href="http://code.djangoproject.com/ticket/2417" rel="nofollow">http://code.djangoproject.com/ticket/2417</a></a></p>
3
2009-10-19T08:57:49Z
26,690,218
<p>The problem was the way Django creates database tables and was also related to database collation.</p> <p>The way I solved it was the following:</p> <ul> <li>changed the table charset to <code>utf8</code> and the collation to <code>utf8_bin</code></li> <li>changed the binary field from <code>VARCHAR</code> to <code>VARBINARY</code> in the MySQL table</li> <li>used in the <code>to_python</code> method <code>return hexlify(value)</code></li> </ul>
1
2014-11-01T14:31:09Z
[ "python", "mysql", "django", "model", "varbinary" ]
Light-weight renderer HTML with CSS in Python
1,587,637
<p>Sorry, perhaps I haven't described the problem well first time. All your answers are interesting, but most of them are almost full-featured web browsers, my task is much simpler.</p> <p>I'm planning to write a GUI application using one of the available on linux GUI frameworks (I haven't yet chosen one). I shall use html in my application to render into one of my application frames text with some attributes — different fonts etc, which are stored in CSS. </p> <p>The HTML shall be generated by my application, so the only task is to render a HTML / CSS string. Is there any widget which can do only that render and nothing more — no history, no bookmarks, no URL-loading etc? If there isn't I shall use one of those you advised — it's ok — but I'm just interested if there is just an html-renderer without any extra features.</p>
7
2009-10-19T09:03:32Z
1,587,703
<p>You should use a UI framework:</p> <ul> <li>Qt: The simplest class to use would be <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwebview.html">QWebView</a></li> <li>Gtk: pywebkitgtk would be the best answer, but you can find <a href="http://faq.pygtk.org/index.py?file=faq19.001.htp&req=show">others in the PyGTK page</a>.</li> <li>In Tk is the TkHtml widget from <a href="http://www.hwaci.com/sw/tkhtml">here</a></li> </ul> <p>An other option is to open the OS default web browser through something like this:</p> <pre><code>import webbrowser url = 'http://www.python.org' # Open URL in a new tab, if a browser window is already open. webbrowser.open_new_tab(url + '/doc') # Open URL in new window, raising the window if possible. webbrowser.open_new(url) </code></pre> <p>You can find more info about the webbrowser module <a href="http://docs.python.org/library/webbrowser.html">here</a>. I think that the simplest way would be to use the os browser if you are looking for something very light-weight since it does not depend on a framework and it would work in all platforms. Using Tk may be an other option that is light and will not require to install a 3rd party framework.</p>
10
2009-10-19T09:21:37Z
[ "python", "html", "browser" ]
Light-weight renderer HTML with CSS in Python
1,587,637
<p>Sorry, perhaps I haven't described the problem well first time. All your answers are interesting, but most of them are almost full-featured web browsers, my task is much simpler.</p> <p>I'm planning to write a GUI application using one of the available on linux GUI frameworks (I haven't yet chosen one). I shall use html in my application to render into one of my application frames text with some attributes — different fonts etc, which are stored in CSS. </p> <p>The HTML shall be generated by my application, so the only task is to render a HTML / CSS string. Is there any widget which can do only that render and nothing more — no history, no bookmarks, no URL-loading etc? If there isn't I shall use one of those you advised — it's ok — but I'm just interested if there is just an html-renderer without any extra features.</p>
7
2009-10-19T09:03:32Z
1,587,951
<p><a href="http://code.google.com/p/flying-saucer//" rel="nofollow">Flying Saucer Project</a> -- an XHTML renderer.</p> <p>No, it's not Python. It's -- however -- trivially called from Python.</p>
0
2009-10-19T10:27:16Z
[ "python", "html", "browser" ]
Light-weight renderer HTML with CSS in Python
1,587,637
<p>Sorry, perhaps I haven't described the problem well first time. All your answers are interesting, but most of them are almost full-featured web browsers, my task is much simpler.</p> <p>I'm planning to write a GUI application using one of the available on linux GUI frameworks (I haven't yet chosen one). I shall use html in my application to render into one of my application frames text with some attributes — different fonts etc, which are stored in CSS. </p> <p>The HTML shall be generated by my application, so the only task is to render a HTML / CSS string. Is there any widget which can do only that render and nothing more — no history, no bookmarks, no URL-loading etc? If there isn't I shall use one of those you advised — it's ok — but I'm just interested if there is just an html-renderer without any extra features.</p>
7
2009-10-19T09:03:32Z
1,588,474
<p>Maybe <a href="http://wiki.laptop.org/go/HulaHop" rel="nofollow">HulaHop</a> could be interesting for you (can also be combined with <a href="http://pyjs.org/" rel="nofollow">Pyjamas</a>). The Mozilla <a href="http://labs.mozilla.com/prism/" rel="nofollow">Prism</a> Project might also be relevant.</p>
0
2009-10-19T12:40:45Z
[ "python", "html", "browser" ]
Using different versions of a python library in the same process
1,587,776
<p>We've got a python library that we're developing. During development, I'd like to use some parts of that library in testing the newer versions of it. That is, use the stable code in order to test the development code. Is there any way of doing this in python?</p> <p><strong>Edit:</strong> To be more specific, we've got a library (LibA) that has many useful things. Also, we've got a testing library that uses LibA in order to provide some testing facilities (LibT). We want to test LibA using LibT, but because LibT depends on LibA, we'd rather it to use a stable version of LibA, while testing LibT (because we will change LibT to work with newer LibA only once tests pass etc.). So, when running unit-tests, LibA-dev tests will use LibT code that depends on LibA-stable. </p> <p>One idea we've come up with is calling the stable code using RPyC on a different process, but it's tricky to implement in an air-tight way (making sure it dies properly etc, and allowing multiple instances to execute at the same time on the same computer etc.).</p> <p>Thanks</p>
5
2009-10-19T09:42:13Z
1,587,801
<p>I am unsure of exactly how you need to set up your tests, but you may be able to use <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">VirtualEnv</a> to get both instances running alongside eachother.</p>
0
2009-10-19T09:46:58Z
[ "python", "testing", "dependencies", "circular-dependency" ]
Using different versions of a python library in the same process
1,587,776
<p>We've got a python library that we're developing. During development, I'd like to use some parts of that library in testing the newer versions of it. That is, use the stable code in order to test the development code. Is there any way of doing this in python?</p> <p><strong>Edit:</strong> To be more specific, we've got a library (LibA) that has many useful things. Also, we've got a testing library that uses LibA in order to provide some testing facilities (LibT). We want to test LibA using LibT, but because LibT depends on LibA, we'd rather it to use a stable version of LibA, while testing LibT (because we will change LibT to work with newer LibA only once tests pass etc.). So, when running unit-tests, LibA-dev tests will use LibT code that depends on LibA-stable. </p> <p>One idea we've come up with is calling the stable code using RPyC on a different process, but it's tricky to implement in an air-tight way (making sure it dies properly etc, and allowing multiple instances to execute at the same time on the same computer etc.).</p> <p>Thanks</p>
5
2009-10-19T09:42:13Z
1,588,164
<p>If you "test" libA-dev using libT which depends on libA (stable), then you are not really testing libA-dev as it would behave in a production environment. The only way to really test libA-dev is to take the full plunge and make libT depend on libA-dev. If this breaks your unit tests then that is a good thing -- it is showing you what needs to be fixed.</p> <p>If you don't have unit tests, then this is the time to start making them (using stable libA and libT first!).</p> <p>I recommend using a "version control system" (e.g. bzr,hg,svn,git). Then you could make branches of your project, "stable" and "devA".</p> <p>To work on branch devA, you would first run</p> <pre><code>export PYTHONPATH=/path/to/devA </code></pre> <p>By making sure the PYTHONPATH environment variable excludes the other branches, you're assured Python is using just the modules you desire.</p> <p>When the time comes to merge code from dev --> stable, the version control software will provide an easy way to do that too. </p> <p>Version control also allows you to be bolder -- trying major changes is not as scary. If things do not work out, reverting is super easy. Between that and the PYTHONPATH trick, you are always able to return to known, working code.</p> <p>If you feel the above just simply is not going to work for you, and you must use libT-which-depends-on-libA to test libA-dev, then you'll need to rename all the modules and modify all the import statements to make a clear separation between libA-dev and libA. For example, if libA has a module called moduleA.py, then rename it moduleA_dev.py. </p> <p>The command</p> <pre><code>rename -n 's/^(.*)\.py/$1_dev.py/' *.py </code></pre> <p>will add "_dev" to all the *.py files. (With the "-n" flag the rename command will only show you the contemplated renaming. Remove the "-n" to actually go through with it.)</p> <p>To revert the renaming, run</p> <pre><code>rename -n 's/^(.*)_dev\.py/$1.py/' *.py </code></pre> <p>Next you'll need to change all references to moduleA to moduleA_dev within the code. The command</p> <pre><code>find /path/to/LibA-dev/ -type f -name '*.py' -exec sed -i 's/moduleA/moduleA_dev/g' {} \; </code></pre> <p>will alter every *.py file in LibA-dev, changing "moduleA" --> "moduleA_dev".</p> <p>Be careful with this command. It is dangerous, because if you have a variable called moduleAB then it will get renamed moduleA_devB, while what you really wanted might be moduleAB_dev.</p> <p>To revert this change (subject to the above caveat),</p> <pre><code>find /path/to/LibA-dev/ -type f -name '*.py' -exec sed -i 's/moduleA_dev/moduleA/g' {} \; </code></pre> <p>Once you separate the namespaces, you've broken the circular dependency. Once you are satisfied your libA-dev is good, you could change moduleA_dev.py --> moduleA.py and changes all references to moduleA_dev --> moduleA in your code.</p>
1
2009-10-19T11:27:37Z
[ "python", "testing", "dependencies", "circular-dependency" ]
Using different versions of a python library in the same process
1,587,776
<p>We've got a python library that we're developing. During development, I'd like to use some parts of that library in testing the newer versions of it. That is, use the stable code in order to test the development code. Is there any way of doing this in python?</p> <p><strong>Edit:</strong> To be more specific, we've got a library (LibA) that has many useful things. Also, we've got a testing library that uses LibA in order to provide some testing facilities (LibT). We want to test LibA using LibT, but because LibT depends on LibA, we'd rather it to use a stable version of LibA, while testing LibT (because we will change LibT to work with newer LibA only once tests pass etc.). So, when running unit-tests, LibA-dev tests will use LibT code that depends on LibA-stable. </p> <p>One idea we've come up with is calling the stable code using RPyC on a different process, but it's tricky to implement in an air-tight way (making sure it dies properly etc, and allowing multiple instances to execute at the same time on the same computer etc.).</p> <p>Thanks</p>
5
2009-10-19T09:42:13Z
1,588,192
<p>"We want to test LibA using LibT, but because LibT depends on LibA, we'd rather it to use a stable version of LibA, while testing LibT "</p> <p>It doesn't make sense to use T + A to test A. What does make sense is the following.</p> <p>LibA is really two things mashed together: A1 and A2.</p> <p>T depends on A1.</p> <p>What's really happening is that you're upgrading and testing A2, using T and A1. </p> <p>If you decompose LibA into the parts that T requires and the other parts, you may be able to break this circular dependency.</p>
1
2009-10-19T11:36:01Z
[ "python", "testing", "dependencies", "circular-dependency" ]
Is it possible to access the GetLongPathName() Win32 API in Python?
1,587,816
<p>I need to convert paths in 8.3 convention to full path. In Perl, I can use <a href="http://search.cpan.org/perldoc/Win32#Win32%3a%3aGetLongPathName%28PATHNAME%29" rel="nofollow"><code>Win32::GetLongPathName()</code></a> as pointed out in <a href="http://stackoverflow.com/questions/770171/how-do-i-get-full-win32-path-from-8-3-dos-path-with-perl">How do I get full Win32 path from 8.3 DOS path with Perl?</a> But, I need to do it in Python.</p>
2
2009-10-19T09:49:38Z
1,587,924
<p>Use <code>ctypes</code> which is available in the Python standard without the need of using the <a href="http://docs.activestate.com/activepython/2.5/pywin32/win32api__GetShortPathName_meth.html" rel="nofollow">pywin32 API</a>. Like this:</p> <pre><code>from ctypes import * buf = create_unicode_buffer(260) GetLongPathName = windll.kernel32.GetLongPathNameW rv = GetLongPathName(path, buf, 260) print buf.value </code></pre> <p>From <a href="http://mail.python.org/pipermail/python-win32/2008-January/006642.html" rel="nofollow">http://mail.python.org/pipermail/python-win32/2008-January/006642.html</a></p>
6
2009-10-19T10:19:42Z
[ "python", "windows" ]
Is it possible to access the GetLongPathName() Win32 API in Python?
1,587,816
<p>I need to convert paths in 8.3 convention to full path. In Perl, I can use <a href="http://search.cpan.org/perldoc/Win32#Win32%3a%3aGetLongPathName%28PATHNAME%29" rel="nofollow"><code>Win32::GetLongPathName()</code></a> as pointed out in <a href="http://stackoverflow.com/questions/770171/how-do-i-get-full-win32-path-from-8-3-dos-path-with-perl">How do I get full Win32 path from 8.3 DOS path with Perl?</a> But, I need to do it in Python.</p>
2
2009-10-19T09:49:38Z
2,161,652
<p>Use the GetLongPathName function from <a href="http://docs.activestate.com/activepython/2.6/pywin32/win32file__GetLongPathName_meth.html" rel="nofollow">win32file</a></p>
2
2010-01-29T11:46:23Z
[ "python", "windows" ]
how to determine if webpage has been modified
1,587,902
<p>I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified? </p> <p>I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.</p> <p>Ideally I am looking for a Python solution, but an intuitive algorithm would also be great.</p> <p>Thanks!</p>
6
2009-10-19T10:13:46Z
1,587,914
<p>Something like <a href="http://en.wikipedia.org/wiki/Levenshtein%5Fdistance" rel="nofollow">Levenshtein Distance</a> could come in handy if you set the threshold of the changes to a distance that ignored the right amount of noise for you.</p>
0
2009-10-19T10:18:06Z
[ "python", "diff", "webpage", "snapshot" ]
how to determine if webpage has been modified
1,587,902
<p>I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified? </p> <p>I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.</p> <p>Ideally I am looking for a Python solution, but an intuitive algorithm would also be great.</p> <p>Thanks!</p>
6
2009-10-19T10:13:46Z
1,587,919
<p>Well, first you need to decide what is noise and what isn't. You can use a HTML parser like <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> to remove the noise, pretty-print the result, and compare it as a string.</p> <p>If you are looking for an automatic solution, you can use <a href="http://docs.python.org/library/difflib.html#sequencematcher-objects"><code>difflib.SequenceMatcher</code></a> to calculate the differences between the pages, calculate the <a href="http://docs.python.org/library/difflib.html#difflib.SequenceMatcher.ratio">similarity</a> and compare it to a threshold.</p>
8
2009-10-19T10:19:21Z
[ "python", "diff", "webpage", "snapshot" ]
how to determine if webpage has been modified
1,587,902
<p>I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified? </p> <p>I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.</p> <p>Ideally I am looking for a Python solution, but an intuitive algorithm would also be great.</p> <p>Thanks!</p>
6
2009-10-19T10:13:46Z
1,588,436
<p>The solution really depends if you are scraping a specific site, or are trying to create a program which will work for any site. </p> <p>You can see which areas change frequently doing something like this:</p> <pre><code> diff &lt;(curl http://stackoverflow.com/questions/) &lt;(sleep 15; curl http://stackoverflow.com/questions/) </code></pre> <p>If your only worried about a single site, you can create some sed expressions to filter out stuff like time stamps. You can repeat until no difference is shown for small fields. </p> <p>The general problem is much harder, and I would suggest comparing the total word count on a page for starters.</p>
3
2009-10-19T12:34:25Z
[ "python", "diff", "webpage", "snapshot" ]
how to determine if webpage has been modified
1,587,902
<p>I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified? </p> <p>I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.</p> <p>Ideally I am looking for a Python solution, but an intuitive algorithm would also be great.</p> <p>Thanks!</p>
6
2009-10-19T10:13:46Z
1,588,461
<p>just take snapshots of the files with MD5 or SHA1...if the values differ the next time you check, then they are modified.</p>
-1
2009-10-19T12:38:28Z
[ "python", "diff", "webpage", "snapshot" ]
Caching system for dynamically created files?
1,587,991
<p>I have a web server that is dynamically creating various reports in several formats (pdf and doc files). The files require a fair amount of CPU to generate, and it is fairly common to have situations where two people are creating the same report with the same input.</p> <p>Inputs:</p> <ul> <li>raw data input as a string (equations, numbers, and lists of words), arbitrary length, almost 99% will be less than about 200 words </li> <li>the version of the report creation tool</li> </ul> <p>When a user attempts to generate a report, I would like to check to see if a file already exists with the given input, and if so return a link to the file. If the file doesn't already exist, then I would like to generate it as needed.</p> <ol> <li><p>What solutions are already out there? I've cached simple http requests before, but the keys were extremely simple (usually database id's)</p></li> <li><p>If I have to do this myself, what is the best way. The input can be several hundred words, and I was wondering how I should go about transforming the strings into keys sent to the cache.</p> <p>//entire input, uses too much memory, one to one mapping cache['one two three four five six seven eight nine ten eleven...'] //short keys cache['one two'] => 5 results, then I must narrow these down even more</p></li> <li><p>Is this something that should be done in a database, or is it better done within the web app code (python in my case)</p></li> </ol> <p>Thanks you everyone.</p>
1
2009-10-19T10:42:57Z
1,588,007
<p>This is what Apache is for.</p> <p>Create a directory that will have the reports.</p> <p>Configure Apache to serve files from that directory.</p> <p>If the report exists, redirect to a URL that Apache will serve.</p> <p>Otherwise, the report doesn't exist, so create it. Then redirect to a URL that Apache will serve.</p> <p><hr /></p> <p>There's no "hashing". You have a key ("a string (equations, numbers, and lists of words), arbitrary length, almost 99% will be less than about 200 words") and a value, which is a file. Don't waste time on a hash. You just have a long key.</p> <p>You can compress this key somewhat by making a "slug" out of it: remove punctuation, replace spaces with _, that kind of thing.</p> <p>You should create an internal surrogate key which is a simple integer.</p> <p>You're simply translating a long key to a "report" which either exists as a file or will be created as a file. </p>
2
2009-10-19T10:45:35Z
[ "python" ]
Caching system for dynamically created files?
1,587,991
<p>I have a web server that is dynamically creating various reports in several formats (pdf and doc files). The files require a fair amount of CPU to generate, and it is fairly common to have situations where two people are creating the same report with the same input.</p> <p>Inputs:</p> <ul> <li>raw data input as a string (equations, numbers, and lists of words), arbitrary length, almost 99% will be less than about 200 words </li> <li>the version of the report creation tool</li> </ul> <p>When a user attempts to generate a report, I would like to check to see if a file already exists with the given input, and if so return a link to the file. If the file doesn't already exist, then I would like to generate it as needed.</p> <ol> <li><p>What solutions are already out there? I've cached simple http requests before, but the keys were extremely simple (usually database id's)</p></li> <li><p>If I have to do this myself, what is the best way. The input can be several hundred words, and I was wondering how I should go about transforming the strings into keys sent to the cache.</p> <p>//entire input, uses too much memory, one to one mapping cache['one two three four five six seven eight nine ten eleven...'] //short keys cache['one two'] => 5 results, then I must narrow these down even more</p></li> <li><p>Is this something that should be done in a database, or is it better done within the web app code (python in my case)</p></li> </ol> <p>Thanks you everyone.</p>
1
2009-10-19T10:42:57Z
1,588,045
<p>The usual thing is to use a reverse proxy like <a href="http://en.wikipedia.org/wiki/Squid%5F%28software%29" rel="nofollow">Squid</a> or <a href="http://en.wikipedia.org/wiki/Varnish%5F%28software%29" rel="nofollow">Varnish</a></p>
1
2009-10-19T10:56:26Z
[ "python" ]
Read two variables in a single line with Python
1,588,058
<p>I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables? </p> <p>I'm looking for the equivalent of:</p> <pre><code>scanf("%d%d", &amp;i, &amp;j); // accepts "10 20\n" </code></pre> <p>One way I am able to achieve this is to use <code>raw_input()</code> and then <code>split</code> what was entered. Is there a more elegant way?</p> <p>This is not for live use. Just for learning..</p>
5
2009-10-19T11:00:21Z
1,588,071
<p>No, the usual way is <code>raw_input().split()</code></p> <p>In your case you might use <code>map(int, raw_input().split())</code> if you want them to be integers rather than strings</p> <p>Don't use <code>input()</code> for that. Consider what happens if the user enters </p> <blockquote> <p><code>import os;os.system('do something bad')</code></p> </blockquote>
21
2009-10-19T11:02:53Z
[ "python", "input" ]
Read two variables in a single line with Python
1,588,058
<p>I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables? </p> <p>I'm looking for the equivalent of:</p> <pre><code>scanf("%d%d", &amp;i, &amp;j); // accepts "10 20\n" </code></pre> <p>One way I am able to achieve this is to use <code>raw_input()</code> and then <code>split</code> what was entered. Is there a more elegant way?</p> <p>This is not for live use. Just for learning..</p>
5
2009-10-19T11:00:21Z
1,590,189
<p>You can also read from sys.stdin</p> <pre><code>import sys a,b = map(int,sys.stdin.readline().split()) </code></pre>
5
2009-10-19T18:04:29Z
[ "python", "input" ]
Read two variables in a single line with Python
1,588,058
<p>I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables? </p> <p>I'm looking for the equivalent of:</p> <pre><code>scanf("%d%d", &amp;i, &amp;j); // accepts "10 20\n" </code></pre> <p>One way I am able to achieve this is to use <code>raw_input()</code> and then <code>split</code> what was entered. Is there a more elegant way?</p> <p>This is not for live use. Just for learning..</p>
5
2009-10-19T11:00:21Z
27,749,093
<p>I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The <strong>raw_input</strong> function is back again, changed from <strong>input</strong>. This is what I came up with:</p> <pre><code>i,j = raw_input("Enter two values: ").split i = int(i) j = int(j) </code></pre> <p>Granted, the code is not as elegant as the one-liners using C's <strong>scanf</strong> or C++'s <strong>cin</strong>. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.</p> <p>In Python, the <strong>raw_input</strong> function gets characters off the console and concatenates them into a single <strong>String</strong> as its output. When just one variable is found on the left-hand-side of the assignment operator, the <strong>split</strong> function breaks this <strong>String</strong> into a <strong>list</strong> of <strong>String</strong> values .</p> <p>In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. <strong>String</strong> values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric <strong>int</strong> (or <strong>float</strong>) data type using Python's built-in <strong>int</strong> or <strong>float</strong> function.</p> <p>I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.</p>
3
2015-01-02T21:58:20Z
[ "python", "input" ]
Read two variables in a single line with Python
1,588,058
<p>I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables? </p> <p>I'm looking for the equivalent of:</p> <pre><code>scanf("%d%d", &amp;i, &amp;j); // accepts "10 20\n" </code></pre> <p>One way I am able to achieve this is to use <code>raw_input()</code> and then <code>split</code> what was entered. Is there a more elegant way?</p> <p>This is not for live use. Just for learning..</p>
5
2009-10-19T11:00:21Z
28,778,397
<p>Firstly read the complete line into a string like </p> <pre><code> string = raw_input() </code></pre> <p>Then use a for loop like this </p> <pre><code> prev = 0 lst = [] index = 0 for letter in string : if item == ' ' or item == '\n' : lst.append(int(string[prev:index]) prev = index + 1 </code></pre> <p>This loop takes a full line as input to the string and processes the parts in it individually and then appends the numbers to the list - lst after converting them to integers .</p>
1
2015-02-28T05:18:13Z
[ "python", "input" ]
Read two variables in a single line with Python
1,588,058
<p>I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables? </p> <p>I'm looking for the equivalent of:</p> <pre><code>scanf("%d%d", &amp;i, &amp;j); // accepts "10 20\n" </code></pre> <p>One way I am able to achieve this is to use <code>raw_input()</code> and then <code>split</code> what was entered. Is there a more elegant way?</p> <p>This is not for live use. Just for learning..</p>
5
2009-10-19T11:00:21Z
35,036,763
<p>or you can do this</p> <pre><code>input_user=map(int,raw_input().strip().split(" ")) </code></pre>
0
2016-01-27T11:58:22Z
[ "python", "input" ]
Is there any possibilty to convert recarray to ndarray and change ndim?
1,588,224
<p>I am getting recarray from matplotlib.mlab.csv2rec function. My expectation was it would have 2 dimensions like 'x', but it has 1 dimension like 'y'. Is there any way to get x from y? </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x=np.array([(date(2000,1,1),0,1), ... (date(2000,1,1),1,1), ... (date(2000,1,1),1,0), ... (date(2000,1,1),0,0), ... ]) &gt;&gt;&gt; x array([[2000-01-01, 0, 1], [2000-01-01, 1, 1], [2000-01-01, 1, 0], [2000-01-01, 0, 0]], dtype=object) &gt;&gt;&gt; y = np.rec.fromrecords( x ) &gt;&gt;&gt; y rec.array([(datetime.date(2000, 1, 1), 0, 1), (datetime.date(2000, 1, 1), 1, 1), (datetime.date(2000, 1, 1), 1, 0), (datetime.date(2000, 1, 1), 0, 0)], dtype=[('f0', '|O4'), ('f1', '&lt;i4'), ('f2', '&lt;i4')]) &gt;&gt;&gt; x.ndim 2 &gt;&gt;&gt; y.ndim 1 &gt;&gt;&gt; x.shape (4, 3) &gt;&gt;&gt; y.ndim 1 &gt;&gt;&gt; y.shape (4,) &gt;&gt;&gt; </code></pre>
0
2009-10-19T11:44:08Z
1,588,483
<p>Sounds weird but... I can save to csv by using matplotlib.mlab.rec2csv, and then read to ndarray by using numpy.loadtxt. My case is simpler as I already have csv file. Here is an example how it works. </p> <pre><code>&gt;&gt;&gt; a = np.loadtxt( 'name.csv', skiprows=1, delimiter=',', converters = {0: lambda x: 0} ) &gt;&gt;&gt; a array([[ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0.29, 0.29, 0.43, 0.29, 0. ], [ 0. , 0.71, 0.29, 0.57, 0. , 0. ], [ 0. , 1. , 0.57, 0.71, 0. , 0. ], [ 0. , 0.43, 0.29, 0.14, 0.14, 0. ], [ 0. , 1. , 0.43, 0.71, 0. , 0. ], [ 0. , 0.57, 0.57, 0.29, 0.14, 0. ], [ 0. , 1.43, 0.43, 0.86, 0.43, 0. ], [ 0. , 1. , 0.71, 0.57, 0. , 0. ], [ 0. , 1.14, 0.57, 0.29, 0. , 0. ], [ 0. , 1.43, 0.29, 0.71, 0.29, 0.29], [ 0. , 1.14, 0.43, 1. , 0.29, 0.29], [ 0. , 0.43, 1.14, 0.86, 0.43, 0.14], [ 0. , 1.14, 0.86, 0.86, 0.29, 0.29]]) &gt;&gt;&gt; t = a.any( axis = 1 ) &gt;&gt;&gt; t array([False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True], dtype=bool) &gt;&gt;&gt; a.ndim 2 </code></pre> <p>Also in my case I don't need a first column for making a decision. </p>
0
2009-10-19T12:42:30Z
[ "python", "numpy" ]
Is there any possibilty to convert recarray to ndarray and change ndim?
1,588,224
<p>I am getting recarray from matplotlib.mlab.csv2rec function. My expectation was it would have 2 dimensions like 'x', but it has 1 dimension like 'y'. Is there any way to get x from y? </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x=np.array([(date(2000,1,1),0,1), ... (date(2000,1,1),1,1), ... (date(2000,1,1),1,0), ... (date(2000,1,1),0,0), ... ]) &gt;&gt;&gt; x array([[2000-01-01, 0, 1], [2000-01-01, 1, 1], [2000-01-01, 1, 0], [2000-01-01, 0, 0]], dtype=object) &gt;&gt;&gt; y = np.rec.fromrecords( x ) &gt;&gt;&gt; y rec.array([(datetime.date(2000, 1, 1), 0, 1), (datetime.date(2000, 1, 1), 1, 1), (datetime.date(2000, 1, 1), 1, 0), (datetime.date(2000, 1, 1), 0, 0)], dtype=[('f0', '|O4'), ('f1', '&lt;i4'), ('f2', '&lt;i4')]) &gt;&gt;&gt; x.ndim 2 &gt;&gt;&gt; y.ndim 1 &gt;&gt;&gt; x.shape (4, 3) &gt;&gt;&gt; y.ndim 1 &gt;&gt;&gt; y.shape (4,) &gt;&gt;&gt; </code></pre>
0
2009-10-19T11:44:08Z
1,590,064
<p>Well, there might be a more efficient way than this, but here is one way:</p> <pre><code>#!/usr/bin/env python import numpy as np from datetime import date x=np.array([(date(2000,1,1),0,1), (date(2000,1,1),1,1), (date(2000,1,1),1,0), (date(2000,1,1),0,0), ]) y=np.rec.fromrecords( x ) z=np.empty((len(y),len(y.dtype)),dtype='object') for idx,field in enumerate(y.dtype.names): z[:,idx]=y[field] assert (x==z).all() </code></pre>
0
2009-10-19T17:39:50Z
[ "python", "numpy" ]
Is there any possibilty to convert recarray to ndarray and change ndim?
1,588,224
<p>I am getting recarray from matplotlib.mlab.csv2rec function. My expectation was it would have 2 dimensions like 'x', but it has 1 dimension like 'y'. Is there any way to get x from y? </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x=np.array([(date(2000,1,1),0,1), ... (date(2000,1,1),1,1), ... (date(2000,1,1),1,0), ... (date(2000,1,1),0,0), ... ]) &gt;&gt;&gt; x array([[2000-01-01, 0, 1], [2000-01-01, 1, 1], [2000-01-01, 1, 0], [2000-01-01, 0, 0]], dtype=object) &gt;&gt;&gt; y = np.rec.fromrecords( x ) &gt;&gt;&gt; y rec.array([(datetime.date(2000, 1, 1), 0, 1), (datetime.date(2000, 1, 1), 1, 1), (datetime.date(2000, 1, 1), 1, 0), (datetime.date(2000, 1, 1), 0, 0)], dtype=[('f0', '|O4'), ('f1', '&lt;i4'), ('f2', '&lt;i4')]) &gt;&gt;&gt; x.ndim 2 &gt;&gt;&gt; y.ndim 1 &gt;&gt;&gt; x.shape (4, 3) &gt;&gt;&gt; y.ndim 1 &gt;&gt;&gt; y.shape (4,) &gt;&gt;&gt; </code></pre>
0
2009-10-19T11:44:08Z
19,298,072
<p>You can do it via pandas:</p> <pre><code>import pandas as pd pd.DataFrame(y).values array([[2000-01-01, 0, 1], [2000-01-01, 1, 1], [2000-01-01, 1, 0], [2000-01-01, 0, 0]], dtype=object) </code></pre> <p>But I would consider doing my project in pandas if I were you. Support for named columns is built much more deeply into pandas than into regular numpy.</p> <pre><code>&gt;&gt;&gt; z = pd.DataFrame.from_records(y, index="f0") &gt;&gt;&gt; z f1 f2 f0 2000-01-01 0 1 2000-01-01 1 1 2000-01-01 1 0 2000-01-01 0 0 &gt;&gt;&gt; z["f1"] f0 2000-01-01 0 2000-01-01 1 2000-01-01 1 2000-01-01 0 Name: f1 </code></pre>
2
2013-10-10T14:07:37Z
[ "python", "numpy" ]
How to prepare a django project for future changes
1,588,570
<p>As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new and exiting will come down the pipe and I will want to implement it. </p> <h3>Preparing for the future:</h3> <p>With this in mind, do folks have any suggestions about how I can prepare my code <strong>now</strong> to be as <em>future-ready</em> as possible for these currently unforseen/unknown upgrades/additions to my code base? </p> <h3>Hindsight is 20/20:</h3> <p>What do you wish you had done at the start that would have made your life easier now that your site is up and running ? </p> <h3>Little Things I've Learned (examples):</h3> <ul> <li>use UTC as the default timezone (and use <code>datetime.datetime.utcnow()</code>)</li> <li>use <a href="http://south.aeracode.org/" rel="nofollow">South</a> to aid future database changes (haven't done it yet, but it seems wise)</li> <li>not hard code links in my templates (use <code>get_absolute_url()</code> and reverse lookups)</li> <li>create a separate <code>tools</code> app to contain small re-usable templatetags and utility functions that I may want to use in future projects (no need to decouple them later)</li> </ul> <p>These are small tips, and some straight from the django-docs, but I think they help . </p> <p>How about you? What are your best practices for a new app or project that prepare you for the future?</p>
8
2009-10-19T13:04:09Z
1,588,609
<p>Not sure how relevant this is outside of the wonderful world of Webfaction.</p> <p>Use Django checked out from Django's svn repository, rather than whatever your host installed for you when creating a Django app, so you can update Django to get security fixes by running <code>svn up</code>.</p> <p>I had to do this a few days ago, and whilst it wasn't too painful (remove the Django installation, then run an SVN checkout, then restart Apache), doing it for all my various projects was a bit irritating - would have been much happier to just run <code>svn up</code>.</p>
5
2009-10-19T13:14:53Z
[ "python", "database", "django" ]
How to prepare a django project for future changes
1,588,570
<p>As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new and exiting will come down the pipe and I will want to implement it. </p> <h3>Preparing for the future:</h3> <p>With this in mind, do folks have any suggestions about how I can prepare my code <strong>now</strong> to be as <em>future-ready</em> as possible for these currently unforseen/unknown upgrades/additions to my code base? </p> <h3>Hindsight is 20/20:</h3> <p>What do you wish you had done at the start that would have made your life easier now that your site is up and running ? </p> <h3>Little Things I've Learned (examples):</h3> <ul> <li>use UTC as the default timezone (and use <code>datetime.datetime.utcnow()</code>)</li> <li>use <a href="http://south.aeracode.org/" rel="nofollow">South</a> to aid future database changes (haven't done it yet, but it seems wise)</li> <li>not hard code links in my templates (use <code>get_absolute_url()</code> and reverse lookups)</li> <li>create a separate <code>tools</code> app to contain small re-usable templatetags and utility functions that I may want to use in future projects (no need to decouple them later)</li> </ul> <p>These are small tips, and some straight from the django-docs, but I think they help . </p> <p>How about you? What are your best practices for a new app or project that prepare you for the future?</p>
8
2009-10-19T13:04:09Z
1,588,620
<p><strong>"something will come up and I'll wish I had implemented it earlier"</strong></p> <p>That's the definition of a good site. One that evolves and changes.</p> <p><strong>"future-ready as possible ?"</strong></p> <p>What can this possibly mean? What specific things are you worried about? Technology is always changing. A good site is always evolving. What do you want to prevent? Do you want to prevent technical change? Do you want to prevent your site from evolving?</p> <p>There will always be change. It will always be devastating to previous technology choices you made.</p> <p>You cannot prevent, stop or even reduce the impact of change except by refusing to participate in new technology.</p>
-2
2009-10-19T13:16:27Z
[ "python", "database", "django" ]
How to prepare a django project for future changes
1,588,570
<p>As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new and exiting will come down the pipe and I will want to implement it. </p> <h3>Preparing for the future:</h3> <p>With this in mind, do folks have any suggestions about how I can prepare my code <strong>now</strong> to be as <em>future-ready</em> as possible for these currently unforseen/unknown upgrades/additions to my code base? </p> <h3>Hindsight is 20/20:</h3> <p>What do you wish you had done at the start that would have made your life easier now that your site is up and running ? </p> <h3>Little Things I've Learned (examples):</h3> <ul> <li>use UTC as the default timezone (and use <code>datetime.datetime.utcnow()</code>)</li> <li>use <a href="http://south.aeracode.org/" rel="nofollow">South</a> to aid future database changes (haven't done it yet, but it seems wise)</li> <li>not hard code links in my templates (use <code>get_absolute_url()</code> and reverse lookups)</li> <li>create a separate <code>tools</code> app to contain small re-usable templatetags and utility functions that I may want to use in future projects (no need to decouple them later)</li> </ul> <p>These are small tips, and some straight from the django-docs, but I think they help . </p> <p>How about you? What are your best practices for a new app or project that prepare you for the future?</p>
8
2009-10-19T13:04:09Z
1,588,702
<ul> <li>Deploy into a pure environment using <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>.</li> <li>Document requirements using a <a href="http://pip.openplans.org/" rel="nofollow">pip</a> requirements file.</li> </ul> <p>I'm sure others will suggest their deployment strategies, but making these changes were big positives for me.</p>
8
2009-10-19T13:35:51Z
[ "python", "database", "django" ]
How to prepare a django project for future changes
1,588,570
<p>As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new and exiting will come down the pipe and I will want to implement it. </p> <h3>Preparing for the future:</h3> <p>With this in mind, do folks have any suggestions about how I can prepare my code <strong>now</strong> to be as <em>future-ready</em> as possible for these currently unforseen/unknown upgrades/additions to my code base? </p> <h3>Hindsight is 20/20:</h3> <p>What do you wish you had done at the start that would have made your life easier now that your site is up and running ? </p> <h3>Little Things I've Learned (examples):</h3> <ul> <li>use UTC as the default timezone (and use <code>datetime.datetime.utcnow()</code>)</li> <li>use <a href="http://south.aeracode.org/" rel="nofollow">South</a> to aid future database changes (haven't done it yet, but it seems wise)</li> <li>not hard code links in my templates (use <code>get_absolute_url()</code> and reverse lookups)</li> <li>create a separate <code>tools</code> app to contain small re-usable templatetags and utility functions that I may want to use in future projects (no need to decouple them later)</li> </ul> <p>These are small tips, and some straight from the django-docs, but I think they help . </p> <p>How about you? What are your best practices for a new app or project that prepare you for the future?</p>
8
2009-10-19T13:04:09Z
1,590,806
<p>Learn and use South at the outset, so when you make major DB schema changes, you'll have a migration tool already in place. Otherwise, you'll find you end up running two versions side by side while trying to figure out how to port the data, and it gets very VERY messy.</p> <p><a href="http://south.aeracode.org/" rel="nofollow">http://south.aeracode.org/</a></p>
7
2009-10-19T20:06:32Z
[ "python", "database", "django" ]
How to prepare a django project for future changes
1,588,570
<p>As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new and exiting will come down the pipe and I will want to implement it. </p> <h3>Preparing for the future:</h3> <p>With this in mind, do folks have any suggestions about how I can prepare my code <strong>now</strong> to be as <em>future-ready</em> as possible for these currently unforseen/unknown upgrades/additions to my code base? </p> <h3>Hindsight is 20/20:</h3> <p>What do you wish you had done at the start that would have made your life easier now that your site is up and running ? </p> <h3>Little Things I've Learned (examples):</h3> <ul> <li>use UTC as the default timezone (and use <code>datetime.datetime.utcnow()</code>)</li> <li>use <a href="http://south.aeracode.org/" rel="nofollow">South</a> to aid future database changes (haven't done it yet, but it seems wise)</li> <li>not hard code links in my templates (use <code>get_absolute_url()</code> and reverse lookups)</li> <li>create a separate <code>tools</code> app to contain small re-usable templatetags and utility functions that I may want to use in future projects (no need to decouple them later)</li> </ul> <p>These are small tips, and some straight from the django-docs, but I think they help . </p> <p>How about you? What are your best practices for a new app or project that prepare you for the future?</p>
8
2009-10-19T13:04:09Z
1,591,366
<p>Listen to James Bennett: Read Practical Django Projects, follow <a href="http://b-list.org/" rel="nofollow">http://b-list.org/</a>. Search youtube for his djangocon talk on reusable apps. Read his code (on bitbucket).</p> <p>An example of advice I've gotten from him: Dependency injection on your views will make your apps much more reusable. A concrete example—refactor this situation-specific view:</p> <pre><code>def user_login_view(request): context = { 'login_form': forms.LoginForm } return render_to_response('accounts/login.html', context) </code></pre> <p>with this generic view:</p> <pre><code>def user_login_view(request, form=models.LoginForm, template_name='accounts/login.html'): context = { 'login_form': form, } return render_to_response(template_name, context) </code></pre> <p>Better still, give your view a generic name like "form_view", rename your form 'form' instead of 'login_form', and pass in your parameters explicity. But those changes alter the functionality, and so aren't a pure refactoring. Once you've refactored, then you can start incrementally changing other things.</p>
4
2009-10-19T21:56:42Z
[ "python", "database", "django" ]
AppEngine GeoPt Data Upload
1,588,633
<p>I'm writing a GAE app in Java and only using Python for the data upload. I'm trying to import a CSV file that looks like this:</p> <pre><code>POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Latitude,Longitude 1,A0E2Z0,Monkstown,Newfoundland,NL,D,47.150300000000001,-55.299500000000002 </code></pre> <p>I was able to import this file in my datastore if I import Latitude and Longitude as floats, but I'm having trouble figuring out how to import lat and lng as a GeoPt. Here is my <em>loader.py</em> file:</p> <pre><code>import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() lat = db.FloatProperty() lng = db.FloatProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('lat', float), ('lng', float) ]) loaders = [PostalCodeLoader] </code></pre> <p>I think that the two <em>db.FloatProperty()</em> lines should be replaced with a <em>db.GeoPtProperty()</em>, but that's where my trail ends. I'm very new to Python so any help would be greatly appreciated.</p>
4
2009-10-19T13:21:25Z
1,588,696
<p>I don't know what your loader code but...</p> <pre><code># given this class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() geoLocation = db.GeoPtProperty() # you should be able to do this myPostalCode.geoLocation = db.GeoPt(-44.22, -33.55) </code></pre> <p>more <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#GeoPt" rel="nofollow">here</a></p>
0
2009-10-19T13:34:40Z
[ "python", "google-app-engine", "upload", "csv" ]
AppEngine GeoPt Data Upload
1,588,633
<p>I'm writing a GAE app in Java and only using Python for the data upload. I'm trying to import a CSV file that looks like this:</p> <pre><code>POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Latitude,Longitude 1,A0E2Z0,Monkstown,Newfoundland,NL,D,47.150300000000001,-55.299500000000002 </code></pre> <p>I was able to import this file in my datastore if I import Latitude and Longitude as floats, but I'm having trouble figuring out how to import lat and lng as a GeoPt. Here is my <em>loader.py</em> file:</p> <pre><code>import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() lat = db.FloatProperty() lng = db.FloatProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('lat', float), ('lng', float) ]) loaders = [PostalCodeLoader] </code></pre> <p>I think that the two <em>db.FloatProperty()</em> lines should be replaced with a <em>db.GeoPtProperty()</em>, but that's where my trail ends. I'm very new to Python so any help would be greatly appreciated.</p>
4
2009-10-19T13:21:25Z
1,589,500
<p>Avoid typecasting and instanceof-tests. I use both geopt and geohash http posted, rather similar where deafult values are recommended to get started:</p> <pre><code> geopt=db.GeoPtProperty(verbose_name="geopt") </code></pre> <p>...</p> <pre><code> article.geopt = db.GeoPt(self.request.POST.get('lat'),self.request.POST.get('lng')) article.geohash = Geohash.encode(float(lat),float(lng), precision=2)#evalu8 precision variable </code></pre> <p><a href="http://montao.googlecode.com" rel="nofollow">code disponible</a> </p> <p><a href="http://classifiedsmarket.appspot.com" rel="nofollow">demo app</a></p>
0
2009-10-19T15:49:09Z
[ "python", "google-app-engine", "upload", "csv" ]
AppEngine GeoPt Data Upload
1,588,633
<p>I'm writing a GAE app in Java and only using Python for the data upload. I'm trying to import a CSV file that looks like this:</p> <pre><code>POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Latitude,Longitude 1,A0E2Z0,Monkstown,Newfoundland,NL,D,47.150300000000001,-55.299500000000002 </code></pre> <p>I was able to import this file in my datastore if I import Latitude and Longitude as floats, but I'm having trouble figuring out how to import lat and lng as a GeoPt. Here is my <em>loader.py</em> file:</p> <pre><code>import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() lat = db.FloatProperty() lng = db.FloatProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('lat', float), ('lng', float) ]) loaders = [PostalCodeLoader] </code></pre> <p>I think that the two <em>db.FloatProperty()</em> lines should be replaced with a <em>db.GeoPtProperty()</em>, but that's where my trail ends. I'm very new to Python so any help would be greatly appreciated.</p>
4
2009-10-19T13:21:25Z
1,595,278
<p>Ok, I got my answer from Google Groups (thanks Takashi Matsuo and Mike Armstrong). The solution is to modify my CSV file and combine lat and lng in a double-quoted string. The comma within the double-quoted string will not be counted as a CSV delimiter.</p> <pre><code>POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Point 1,A0E 2Z0,Monkstown,Newfoundland,NL,D,"47.150300000000001,-55.299500000000002" </code></pre> <p>Also, here is my new <em>loader.py</em>. Note that the GeoPtProperty takes a string with "00.0000,00.0000":</p> <pre><code>import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() geo_pt = db.GeoPtProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('geo_pt', str) ]) loaders = [PostalCodeLoader] </code></pre>
3
2009-10-20T15:01:42Z
[ "python", "google-app-engine", "upload", "csv" ]
AppEngine GeoPt Data Upload
1,588,633
<p>I'm writing a GAE app in Java and only using Python for the data upload. I'm trying to import a CSV file that looks like this:</p> <pre><code>POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Latitude,Longitude 1,A0E2Z0,Monkstown,Newfoundland,NL,D,47.150300000000001,-55.299500000000002 </code></pre> <p>I was able to import this file in my datastore if I import Latitude and Longitude as floats, but I'm having trouble figuring out how to import lat and lng as a GeoPt. Here is my <em>loader.py</em> file:</p> <pre><code>import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() lat = db.FloatProperty() lng = db.FloatProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('lat', float), ('lng', float) ]) loaders = [PostalCodeLoader] </code></pre> <p>I think that the two <em>db.FloatProperty()</em> lines should be replaced with a <em>db.GeoPtProperty()</em>, but that's where my trail ends. I'm very new to Python so any help would be greatly appreciated.</p>
4
2009-10-19T13:21:25Z
3,905,888
<p>You can define your own loader which merge two columns from cvs into one value and then write a converter function that parses this value into db.GeoPt. In this solution you don't need to change your csv file. Here is an example (assuming that csv file has only three columns - lat, lng and some name):</p> <pre><code>import csv from google.appengine.ext import db from google.appengine.tools import bulkloader class GeoPoint(db.Model): name = db.StringProperty() location = db.GeoProperty() class GeoFileLoader(bulkloader.Loader): ''' Loader class processing input csv file and merging two columns into one ''' def __init__(self, kind_name, converters): bulkloader.Loader.__init__(self, kind_name, converters) def generate_records(self, filename): csv_reader = csv.reader(open(filename), delimiter=',') for row in csv_reader: if row: lat = row[0] lng = row[1] # Here we yield only one value for geo coordinates and name unchanged yield '%s,%s' % (lat, lng), row[2] def geo_converter(geo_str): ''' Converter function - return db.GeoPt from str ''' if geo_str: lat, lng = geo_str.split(',') return db.GeoPt(lat=float(lat), lon=float(lng)) return None # Loader that uses our GeoFileLoader to load data from csv class PointLoader(GeoFileLoader): def __init__(self): GeoFileLoader.__init__(self, 'GeoPoint', [('location', geo_converter), ('name', str)]) loaders = [PointLoader] </code></pre> <p>More details you can find on <a href="http://blog.notdot.net/2009/9/Advanced-Bulk-Loading-part-3-Alternate-datasources" rel="nofollow">Nick Johnson's blog</a></p>
0
2010-10-11T11:48:56Z
[ "python", "google-app-engine", "upload", "csv" ]
AppEngine GeoPt Data Upload
1,588,633
<p>I'm writing a GAE app in Java and only using Python for the data upload. I'm trying to import a CSV file that looks like this:</p> <pre><code>POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Latitude,Longitude 1,A0E2Z0,Monkstown,Newfoundland,NL,D,47.150300000000001,-55.299500000000002 </code></pre> <p>I was able to import this file in my datastore if I import Latitude and Longitude as floats, but I'm having trouble figuring out how to import lat and lng as a GeoPt. Here is my <em>loader.py</em> file:</p> <pre><code>import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() lat = db.FloatProperty() lng = db.FloatProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('lat', float), ('lng', float) ]) loaders = [PostalCodeLoader] </code></pre> <p>I think that the two <em>db.FloatProperty()</em> lines should be replaced with a <em>db.GeoPtProperty()</em>, but that's where my trail ends. I'm very new to Python so any help would be greatly appreciated.</p>
4
2009-10-19T13:21:25Z
4,505,047
<p>This question should be deleted/deprecated. Python isn't used for the bulkloader anymore. Now only yaml files are used. For the answer to this question using the modern bulkloader, see: <a href="http://stackoverflow.com/questions/3350193/importing-geopt-data-with-the-google-appengine-bulkloader-yaml">Importing GeoPt data with the Google AppEngine BulkLoader YAML</a></p>
0
2010-12-21T23:52:24Z
[ "python", "google-app-engine", "upload", "csv" ]
What are the use cases for non relational datastores?
1,588,708
<p>I'm looking at using CouchDB for one project and the GAE app engine datastore in the other. For relational stuff I tend to use postgres, although I much prefer an ORM. </p> <p>Anyway, what use cases suit non relational datastores best?</p>
3
2009-10-19T13:36:49Z
1,588,748
<p>Consider the situation where you have many entity types but few instances of each entity. In this case you will have many tables each with a few records so a relational approach is not suitable. </p>
2
2009-10-19T13:43:31Z
[ "python", "google-app-engine", "couchdb" ]
What are the use cases for non relational datastores?
1,588,708
<p>I'm looking at using CouchDB for one project and the GAE app engine datastore in the other. For relational stuff I tend to use postgres, although I much prefer an ORM. </p> <p>Anyway, what use cases suit non relational datastores best?</p>
3
2009-10-19T13:36:49Z
1,588,758
<p>Here is a nice little article (spread over three pages) that covers the use-case for non-relational databases.</p> <p><a href="http://www.readwriteweb.com/enterprise/2009/02/is-the-relational-database-doomed.php">http://www.readwriteweb.com/enterprise/2009/02/is-the-relational-database-doomed.php</a></p> <p>In a nutshell, when you need massive scalability then you probably need a non-realtional db. Of course, you may well end up writing a lot more code to do what a relational db does for you, but if you really need that scalability, then the relational db option is usually more expensive, and very tricky to architect properly.</p>
7
2009-10-19T13:44:25Z
[ "python", "google-app-engine", "couchdb" ]
What are the use cases for non relational datastores?
1,588,708
<p>I'm looking at using CouchDB for one project and the GAE app engine datastore in the other. For relational stuff I tend to use postgres, although I much prefer an ORM. </p> <p>Anyway, what use cases suit non relational datastores best?</p>
3
2009-10-19T13:36:49Z
1,589,186
<p>In some cases that are simply nice. ZODB is a Python-only object database, that is so well-integrated with Python that you can simply forget that it's there. You don't have to bother about it, most of the time.</p>
0
2009-10-19T14:59:23Z
[ "python", "google-app-engine", "couchdb" ]
Nested Function in Python
1,589,058
<p>What benefit or implications could we get with Python code like this:</p> <pre><code>class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y) </code></pre> <p>I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found <a href="http://bazaar.launchpad.net/~openerp/openobject-server/trunk/annotate/1861/bin/report/render/rml2pdf/trml2pdf.py#L685">here</a>.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?</p>
46
2009-10-19T14:40:51Z
1,589,162
<p>I can't image any good reason for code like that.</p> <p>Maybe there was a reason for the inner function in older revisions, like other Ops. </p> <p>For example, this makes <em>slightly</em> more sense:</p> <pre><code>class some_class(parent_class): def doOp(self, op, x, y): def add(x, y): return x + y def sub(x,y): return x - y return locals()[op](x,y) some_class().doOp('add', 1,2) </code></pre> <p>but then the inner function should be ("private") class methods instead:</p> <pre><code>class some_class(object): def _add(self, x, y): return x + y def doOp(self, x, y): return self._add(x,y) </code></pre>
7
2009-10-19T14:55:37Z
[ "python", "nested-function" ]
Nested Function in Python
1,589,058
<p>What benefit or implications could we get with Python code like this:</p> <pre><code>class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y) </code></pre> <p>I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found <a href="http://bazaar.launchpad.net/~openerp/openobject-server/trunk/annotate/1861/bin/report/render/rml2pdf/trml2pdf.py#L685">here</a>.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?</p>
46
2009-10-19T14:40:51Z
1,589,173
<p>The idea behind local methods is similar to local variables: don't pollute the larger name space. Obviously the benefits are limited since most languages don't also provide such functionality directly.</p>
4
2009-10-19T14:57:24Z
[ "python", "nested-function" ]
Nested Function in Python
1,589,058
<p>What benefit or implications could we get with Python code like this:</p> <pre><code>class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y) </code></pre> <p>I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found <a href="http://bazaar.launchpad.net/~openerp/openobject-server/trunk/annotate/1861/bin/report/render/rml2pdf/trml2pdf.py#L685">here</a>.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?</p>
46
2009-10-19T14:40:51Z
1,589,188
<p>Are you sure the code was exactly like this? The normal reason for doing something like this is for creating a partial - a function with baked-in parameters. Calling the outer function returns a callable that needs no parameters, and so therefore can be stored and used somewhere it is impossible to pass parameters. However, the code you've posted won't do that - it calls the function immediately and returns the result, rather than the callable. It might be useful to post the actual code you saw.</p>
1
2009-10-19T14:59:37Z
[ "python", "nested-function" ]
Nested Function in Python
1,589,058
<p>What benefit or implications could we get with Python code like this:</p> <pre><code>class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y) </code></pre> <p>I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found <a href="http://bazaar.launchpad.net/~openerp/openobject-server/trunk/annotate/1861/bin/report/render/rml2pdf/trml2pdf.py#L685">here</a>.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?</p>
46
2009-10-19T14:40:51Z
1,589,209
<p>Aside from function generators, where internal function creation is almost the definition of a function generator, the reason I create nested functions is to improve readability. If I have a tiny function that will only be invoked by the outer function, then I inline the definition so you don't have to skip around to determine what that function is doing. I can always move the inner method outside of the encapsulating method if I find a need to reuse the function at a later date.</p> <p>Toy example:</p> <pre><code>import sys def Foo(): def e(s): sys.stderr.write('ERROR: ') sys.stderr.write(s) sys.stderr.write('\n') e('I regret to inform you') e('that a shameful thing has happened.') e('Thus, I must issue this desultory message') e('across numerous lines.') Foo() </code></pre>
35
2009-10-19T15:03:11Z
[ "python", "nested-function" ]
Nested Function in Python
1,589,058
<p>What benefit or implications could we get with Python code like this:</p> <pre><code>class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y) </code></pre> <p>I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found <a href="http://bazaar.launchpad.net/~openerp/openobject-server/trunk/annotate/1861/bin/report/render/rml2pdf/trml2pdf.py#L685">here</a>.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?</p>
46
2009-10-19T14:40:51Z
1,589,606
<p>Normally you do it to make <em><a href="http://en.wikipedia.org/wiki/Closure%5F%28computer%5Fscience%29">closures</a></em>:</p> <pre><code>def make_adder(x): def add(y): return x + y return add plus5 = make_adder(5) print(plus5(12)) # prints 17 </code></pre> <p>Inner functions can access variables from the enclosing scope (in this case, the local variable <code>x</code>). If you're not accessing any variables from the enclosing scope, they're really just ordinary functions with a different scope.</p>
67
2009-10-19T16:05:56Z
[ "python", "nested-function" ]
Nested Function in Python
1,589,058
<p>What benefit or implications could we get with Python code like this:</p> <pre><code>class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y) </code></pre> <p>I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found <a href="http://bazaar.launchpad.net/~openerp/openobject-server/trunk/annotate/1861/bin/report/render/rml2pdf/trml2pdf.py#L685">here</a>.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?</p>
46
2009-10-19T14:40:51Z
13,397,600
<p>One potential benefit of using inner methods is that it allows you to use outer method local variables without passing them as arguments.</p> <pre><code>def helper(feature, resultBuffer): resultBuffer.print(feature) resultBuffer.printLine() resultBuffer.flush() def save(item, resultBuffer): helper(item.description, resultBuffer) helper(item.size, resultBuffer) helper(item.type, resultBuffer) </code></pre> <p>can be written as follows, which arguably reads better</p> <pre><code>def save(item, resultBuffer): def helper(feature): resultBuffer.print(feature) resultBuffer.printLine() resultBuffer.flush() helper(item.description) helper(item.size) helper(item.type) </code></pre>
17
2012-11-15T12:32:05Z
[ "python", "nested-function" ]
Python XMLRPC with concurrent requests
1,589,150
<p>I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is there a way I can block all incoming requests until the single instance has completed?</p>
5
2009-10-19T14:54:08Z
1,589,181
<p>Can you have another communication channel? If yes, then have a "call me back when it is my turn" protocol running between the server and the clients.</p> <p>In other words, each client would register its intention to issue requests to the server and the said server would "callback" the next-up client when it is ready.</p>
0
2009-10-19T14:58:33Z
[ "python", "xml-rpc" ]
Python XMLRPC with concurrent requests
1,589,150
<p>I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is there a way I can block all incoming requests until the single instance has completed?</p>
5
2009-10-19T14:54:08Z
1,589,936
<p>I think python SimpleXMLRPCServer module is what you want. I believe the default behavior of that model is blocking new requests when current request is processing. The default behavior gave me lots of trouble and I changed that behavior by mix in ThreadingMixIn class so that my xmlrpc server could respond multiple requests in the same time.</p> <pre><code>class RPCThreading(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer): pass </code></pre> <p>If I understand your question correctly, SimpleXMLRPCServer is the solution. Just use it directly.</p>
11
2009-10-19T17:12:22Z
[ "python", "xml-rpc" ]
Python XMLRPC with concurrent requests
1,589,150
<p>I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is there a way I can block all incoming requests until the single instance has completed?</p>
5
2009-10-19T14:54:08Z
1,590,010
<p>There are several choices:</p> <ol> <li>Use single-process-single-thread server like <code>SimpleXMLRPCServer</code> to process requests subsequently.</li> <li>Use <code>threading.Lock()</code> in threaded server.</li> <li>You some external locking mechanism (like <code>lockfile</code> module or <code>GET_LOCK()</code> function in mysql) in multiprocess server.</li> </ol>
0
2009-10-19T17:27:52Z
[ "python", "xml-rpc" ]
Why can't I do SHOW PROCESSLIST with QtSql (PyQT)?
1,589,231
<p>I am a Python and QT newbie. I am trying to do a little app with PyQT4 in order to supervise a home MySQL server of mine, so my first idea was to do the classic <code>SHOW PROCESSLIST</code>, parse it, and show in a pretty UI. Nothing big, really.</p> <p>But for some reason, the QtSql module doesn't return anything when doing this query, although it works with other queries like <code>SHOW TABLES</code>, etc</p> <p>I found an old (2002) message in a mailing list talking about this[1], and a reference in the MythTV code[2], but none of them explains it clearly.</p> <p>Here is some code:</p> <pre><code>db = QSqlDatabase.addDatabase('QMYSQL3') # tried with QMYSQL too db.setHostName(host) db.setDatabaseName(dbname) db.setUserName(user) db.setPassword(password) db.open() q = QSqlQuery(db) q.exec_("SHOW PROCESSLIST") print q.size() # returns -1! </code></pre> <p>As I said, it works fine with other queries (SELECT, etc).</p> <p>Am I doing something wrong? Thank you!</p> <blockquote> <p>[1]: lists.trolltech.com/qt-interest/2002-09/thread00104-0.html<br /> [2]: www.google.com/codesearch/p?hl=es&amp;sa=N&amp;cd=1&amp;ct=rc#-zNo3rQOo4A/mythtv/libs/libmyth/dbutil.cpp&amp;l=657</p> </blockquote>
0
2009-10-19T15:07:11Z
1,589,604
<p>I don't know what is wrong, but in recent versions of MySQL you can work it around using <a href="http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html" rel="nofollow">information_schema.processlist</a>:</p> <pre><code>SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST </code></pre>
1
2009-10-19T16:05:43Z
[ "python", "mysql", "qt", "pyqt" ]
Why can't I do SHOW PROCESSLIST with QtSql (PyQT)?
1,589,231
<p>I am a Python and QT newbie. I am trying to do a little app with PyQT4 in order to supervise a home MySQL server of mine, so my first idea was to do the classic <code>SHOW PROCESSLIST</code>, parse it, and show in a pretty UI. Nothing big, really.</p> <p>But for some reason, the QtSql module doesn't return anything when doing this query, although it works with other queries like <code>SHOW TABLES</code>, etc</p> <p>I found an old (2002) message in a mailing list talking about this[1], and a reference in the MythTV code[2], but none of them explains it clearly.</p> <p>Here is some code:</p> <pre><code>db = QSqlDatabase.addDatabase('QMYSQL3') # tried with QMYSQL too db.setHostName(host) db.setDatabaseName(dbname) db.setUserName(user) db.setPassword(password) db.open() q = QSqlQuery(db) q.exec_("SHOW PROCESSLIST") print q.size() # returns -1! </code></pre> <p>As I said, it works fine with other queries (SELECT, etc).</p> <p>Am I doing something wrong? Thank you!</p> <blockquote> <p>[1]: lists.trolltech.com/qt-interest/2002-09/thread00104-0.html<br /> [2]: www.google.com/codesearch/p?hl=es&amp;sa=N&amp;cd=1&amp;ct=rc#-zNo3rQOo4A/mythtv/libs/libmyth/dbutil.cpp&amp;l=657</p> </blockquote>
0
2009-10-19T15:07:11Z
6,200,259
<p>I don't know if you already tried this, but what about adding an ';'?</p> <pre><code>q.exec_("SHOW PROCESSLIST;") </code></pre> <p>I have never worked with QtSQL but some MySQL API's do have quite strange behavior and I've run into that problem before.</p> <p>(sry for bumping an old question, it came up when I was searching for a similar issue)</p>
0
2011-06-01T11:15:09Z
[ "python", "mysql", "qt", "pyqt" ]
Iterating over arbitrary dimension of numpy.array
1,589,706
<p>Is there function to get an iterator over an arbitrary dimension of a numpy array?</p> <p>Iterating over the first dimension is easy...</p> <pre><code>In [63]: c = numpy.arange(24).reshape(2,3,4) In [64]: for r in c : ....: print r ....: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]] </code></pre> <p>But iterating over other dimensions is harder. For example, the last dimension:</p> <pre><code>In [73]: for r in c.swapaxes(2,0).swapaxes(1,2) : ....: print r ....: [[ 0 4 8] [12 16 20]] [[ 1 5 9] [13 17 21]] [[ 2 6 10] [14 18 22]] [[ 3 7 11] [15 19 23]] </code></pre> <p>I'm making a generator to do this myself, but I'm surprised there isn't a function named something like numpy.ndarray.iterdim(axis=0) to do this automatically.</p>
21
2009-10-19T16:27:11Z
1,593,130
<p>What you propose is quite fast, but the legibility can be improved with the clearer forms:</p> <pre><code>for i in range(c.shape[-1]): print c[:,:,i] </code></pre> <p>or, better (faster and more explicit):</p> <pre><code>for i in range(c.shape[-1]): print c[...,i] </code></pre> <p>However, the first approach above appears to be about twice as slow as the <code>swapaxes()</code> approach:</p> <pre><code>python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' 'for r in c.swapaxes(2,0).swapaxes(1,2): u = r' 100000 loops, best of 3: 3.69 usec per loop python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' 'for i in range(c.shape[2]): u = c[:,:,i]' 100000 loops, best of 3: 6.08 usec per loop python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' 'for r in numpy.rollaxis(c, 2): u = r' 100000 loops, best of 3: 6.46 usec per loop </code></pre> <p>I would guess that this is because <code>swapaxes()</code> does not copy any data, and because the handling of <code>c[:,:,i]</code> might be done through general code (that handles the case where <code>:</code> is replaced by a more complicated slice).</p> <p>Note however that the more explicit second solution <code>c[...,i]</code> is both quite legible and quite fast:</p> <pre><code>python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' 'for i in range(c.shape[2]): u = c[...,i]' 100000 loops, best of 3: 4.74 usec per loop </code></pre>
24
2009-10-20T08:13:50Z
[ "python", "numpy", "loops" ]
Iterating over arbitrary dimension of numpy.array
1,589,706
<p>Is there function to get an iterator over an arbitrary dimension of a numpy array?</p> <p>Iterating over the first dimension is easy...</p> <pre><code>In [63]: c = numpy.arange(24).reshape(2,3,4) In [64]: for r in c : ....: print r ....: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]] </code></pre> <p>But iterating over other dimensions is harder. For example, the last dimension:</p> <pre><code>In [73]: for r in c.swapaxes(2,0).swapaxes(1,2) : ....: print r ....: [[ 0 4 8] [12 16 20]] [[ 1 5 9] [13 17 21]] [[ 2 6 10] [14 18 22]] [[ 3 7 11] [15 19 23]] </code></pre> <p>I'm making a generator to do this myself, but I'm surprised there isn't a function named something like numpy.ndarray.iterdim(axis=0) to do this automatically.</p>
21
2009-10-19T16:27:11Z
1,594,884
<p>I guess there is no function. When I wrote my function, I ended up taking the iteration EOL also suggested. For future readers, here it is:</p> <pre><code>def iterdim(a, axis=0) : a = numpy.asarray(a); leading_indices = (slice(None),)*axis for i in xrange(a.shape[axis]) : yield a[leading_indices+(i,)] </code></pre>
1
2009-10-20T14:10:18Z
[ "python", "numpy", "loops" ]
Iterating over arbitrary dimension of numpy.array
1,589,706
<p>Is there function to get an iterator over an arbitrary dimension of a numpy array?</p> <p>Iterating over the first dimension is easy...</p> <pre><code>In [63]: c = numpy.arange(24).reshape(2,3,4) In [64]: for r in c : ....: print r ....: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]] </code></pre> <p>But iterating over other dimensions is harder. For example, the last dimension:</p> <pre><code>In [73]: for r in c.swapaxes(2,0).swapaxes(1,2) : ....: print r ....: [[ 0 4 8] [12 16 20]] [[ 1 5 9] [13 17 21]] [[ 2 6 10] [14 18 22]] [[ 3 7 11] [15 19 23]] </code></pre> <p>I'm making a generator to do this myself, but I'm surprised there isn't a function named something like numpy.ndarray.iterdim(axis=0) to do this automatically.</p>
21
2009-10-19T16:27:11Z
5,923,332
<p>I'd use the following:</p> <pre><code>c = numpy.arange(2 * 3 * 4) c.shape = (2, 3, 4) for r in numpy.rollaxis(c, 2): print(r) </code></pre> <p>The function <strong>rollaxis</strong> creates a new view on the array. In this case it's moving axis 2 to the front, equivalent to the operation <code>c.transpose(2, 0, 1)</code>. </p>
10
2011-05-07T19:05:11Z
[ "python", "numpy", "loops" ]
Iterating over arbitrary dimension of numpy.array
1,589,706
<p>Is there function to get an iterator over an arbitrary dimension of a numpy array?</p> <p>Iterating over the first dimension is easy...</p> <pre><code>In [63]: c = numpy.arange(24).reshape(2,3,4) In [64]: for r in c : ....: print r ....: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]] </code></pre> <p>But iterating over other dimensions is harder. For example, the last dimension:</p> <pre><code>In [73]: for r in c.swapaxes(2,0).swapaxes(1,2) : ....: print r ....: [[ 0 4 8] [12 16 20]] [[ 1 5 9] [13 17 21]] [[ 2 6 10] [14 18 22]] [[ 3 7 11] [15 19 23]] </code></pre> <p>I'm making a generator to do this myself, but I'm surprised there isn't a function named something like numpy.ndarray.iterdim(axis=0) to do this automatically.</p>
21
2009-10-19T16:27:11Z
16,085,248
<p>So, one can iterate over the first dimension easily, as you've shown. Another way to do this for arbitrary dimension is to use numpy.rollaxis() to bring the given dimension to the first (the default behavior), and then use the returned array (which is a view, so this is fast) as an iterator.</p> <pre><code>In [1]: array = numpy.arange(24).reshape(2,3,4) In [2]: for array_slice in np.rollaxis(array, 1): ....: print array_slice.shape ....: (2, 4) (2, 4) (2, 4) </code></pre> <p>EDIT: I'll comment that I submitted a PR to numpy to address this here: <a href="https://github.com/numpy/numpy/pull/3262" rel="nofollow">https://github.com/numpy/numpy/pull/3262</a>. The concensus was that this wasn't enough to add to the numpy codebase. I think using np.rollaxis is the best way to do this, and if you want an interator, wrap it in iter().</p>
1
2013-04-18T14:07:13Z
[ "python", "numpy", "loops" ]
Google App Engine compatibility layer
1,589,743
<p>I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. </p> <p>I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.</p> <p>However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).</p> <p>Regards,</p> <p>Iwan</p>
6
2009-10-19T16:33:42Z
1,589,889
<p>The appscale project is designed to do exactly this. See <a href="https://github.com/AppScale/appscale/wiki" rel="nofollow">https://github.com/AppScale/appscale/wiki</a></p>
6
2009-10-19T17:02:22Z
[ "python", "google-app-engine" ]
Google App Engine compatibility layer
1,589,743
<p>I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. </p> <p>I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.</p> <p>However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).</p> <p>Regards,</p> <p>Iwan</p>
6
2009-10-19T16:33:42Z
1,589,931
<p>Another taken from this <a href="http://serverfault.com/questions/59322/google-app-engine-sdk-is-open-source-would-anyone-from-the-cloud-try-to-catch-it">question:</a></p> <p><a href="http://waxy.org/2008/04/exclusive%5Fgoogle%5Fapp%5Fengine%5Fported%5Fto%5Famazons%5Fec2/" rel="nofollow">Waxy</a></p>
1
2009-10-19T17:11:06Z
[ "python", "google-app-engine" ]
Google App Engine compatibility layer
1,589,743
<p>I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. </p> <p>I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.</p> <p>However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).</p> <p>Regards,</p> <p>Iwan</p>
6
2009-10-19T16:33:42Z
1,590,088
<p><a href="http://code.google.com/p/typhoonae/" rel="nofollow">Typhoonae</a> Might be interesting to you, it is a new project to implement a full production server stack using exisiting technologies, capable of hosting AppEngine instances. It also aims to do this while staying compatable with the AppEngine API, to allow easy portability. I'm not sure what stage they have reached with the integration, but it should definatley be worth a look.</p>
2
2009-10-19T17:46:00Z
[ "python", "google-app-engine" ]
Google App Engine compatibility layer
1,589,743
<p>I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. </p> <p>I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.</p> <p>However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).</p> <p>Regards,</p> <p>Iwan</p>
6
2009-10-19T16:33:42Z
1,590,847
<blockquote> <p>I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility</p> </blockquote> <p>GAE/J uses DataNucleus for persistence. DataNucleus also has plugins for RDBMS, LDAP, XML, Excel, ODF, OODBMS, HBase (HADOOP), and Amazon S3. Consequently the persistence layer (using JDO or JPA) could, in principle, be used across any of those. To write a DataNucleus plugin for Amazon SimpleDB shouldn't be too hard either, or CouchDB.</p> <p>--Andy (<a href="http://www.datanucleus.org" rel="nofollow">DataNucleus</a>)</p>
4
2009-10-19T20:14:34Z
[ "python", "google-app-engine" ]
Google App Engine compatibility layer
1,589,743
<p>I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. </p> <p>I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.</p> <p>However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).</p> <p>Regards,</p> <p>Iwan</p>
6
2009-10-19T16:33:42Z
4,219,064
<p>If you develop with web2py your code will run GAE other architectures wihtout changes using any of the 10 supported relational databases. The compatibility layer covers database api (including blobs and listproperty), email, and fetching). </p>
0
2010-11-18T20:08:40Z
[ "python", "google-app-engine" ]
Must two SQLAlchemy declarative models share the same declarative_base()?
1,589,748
<p>Is it necessary for two SQLAlchemy models to inherit from the same instance of <code>declarative_base()</code> if they must participate in the same Session? This is likely to be the case when importing two or more modules that define SQLAlchemy models.</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String(50)) Base2 = declarative_base() class AnotherClass(Base2): __tablename__ = 'another_table' id = Column(Integer, primary_key=True) name = Column(String(50)) </code></pre>
4
2009-10-19T16:34:41Z
1,589,895
<p>Separate Base classes will work just fine.</p> <p>You'll have to be careful when they are using different database connections, in that case you can't use joins across the two databases - every query needs to go to one database.</p>
2
2009-10-19T17:03:32Z
[ "python", "orm", "sqlalchemy" ]
Must two SQLAlchemy declarative models share the same declarative_base()?
1,589,748
<p>Is it necessary for two SQLAlchemy models to inherit from the same instance of <code>declarative_base()</code> if they must participate in the same Session? This is likely to be the case when importing two or more modules that define SQLAlchemy models.</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String(50)) Base2 = declarative_base() class AnotherClass(Base2): __tablename__ = 'another_table' id = Column(Integer, primary_key=True) name = Column(String(50)) </code></pre>
4
2009-10-19T16:34:41Z
1,590,090
<p>I successfully use different declarative bases in single session. This can be useful when using several databases: each base is created with own metadata and each metadata is bound to separate database. Some of your declarative bases could define additional methods or they could use another metaclass to install extensions.</p>
4
2009-10-19T17:46:12Z
[ "python", "orm", "sqlalchemy" ]
Python: Difference between 'global' & globals().update(var)
1,589,968
<p>What is the difference between initializing a variable as <code>global var</code> or calling <code>globals().update(var)</code>.</p> <p>Thanks</p>
7
2009-10-19T17:19:12Z
1,590,016
<p>When you say</p> <pre><code>global var </code></pre> <p>you are telling Python that var is the same var that was defined in a global context. You would use it in the following way:</p> <pre><code>var=0 def f(): global var var=1 f() print(var) # 1 &lt;---- the var outside the "def f" block is affected by calling f() </code></pre> <p>Without the global statement, the var inside the "def f" block would be a local variable, and setting its value would have no effect on the var outside the "def f" block.</p> <pre><code>var=0 def f(): var=1 f() print(var) # 0 &lt;---- the var outside the "def f" block is unaffected </code></pre> <p>When you say globals.update(var) I am guessing you actually mean globals().update(var). Let's break it apart.</p> <p>globals() returns a dict object. The dict's keys are the names of objects, and the dict's values are the associated object's values.</p> <p>Every dict has a method called "update". So globals().update() is a call to this method. The update method expects at least one argument, and that argument is expected to be a dict. If you tell Python</p> <pre><code>globals().update(var) </code></pre> <p>then var had better be a dict, and you are telling Python to update the globals() dict with the contents of the var dict.</p> <p>For example:</p> <pre><code>#!/usr/bin/env python # Here is the original globals() dict print(globals()) # {'__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None} var={'x':'Howdy'} globals().update(var) # Now the globals() dict contains both var and 'x' print(globals()) # {'var': {'x': 'Howdy'}, 'x': 'Howdy', '__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None} # Lo and behold, you've defined x without saying x='Howdy' ! print(x) Howdy </code></pre>
16
2009-10-19T17:29:41Z
[ "python", "variables", "global" ]
How do I write a unix filter in python?
1,589,994
<p>I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars <code>x</code> from stdin.</p>
9
2009-10-19T17:24:43Z
1,590,013
<p>Read from <code>sys.stdin</code> and write to <code>sys.stdout</code> (or use <code>print</code>). Your example program:</p> <pre><code>import sys for line in sys.stdin: print line.replace("x", ""), </code></pre> <p>There isn't a standard way to make stdin unbuffered, and you don't want that. Let the OS buffer it.</p>
13
2009-10-19T17:28:44Z
[ "python", "unix", "filter" ]
How do I write a unix filter in python?
1,589,994
<p>I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars <code>x</code> from stdin.</p>
9
2009-10-19T17:24:43Z
1,590,058
<p>I don't know exactly what you mean by buffered in this context, but it is pretty simple to do what you are asking...</p> <p>so_gen.py (generating a constant stream that we can watch):</p> <pre><code>import time import sys while True: for char in 'abcdefx': sys.stdout.write(char) sys.stdout.flush() time.sleep(0.1) </code></pre> <p>so_filter.py (doing what you ask):</p> <pre><code>import sys while True: char = sys.stdin.read(1) if not char: break if char != 'x': sys.stdout.write(char) sys.stdout.flush() </code></pre> <p>Try running <code>python so_gen.py | python so_filter.py</code> to see what it does.</p>
7
2009-10-19T17:38:29Z
[ "python", "unix", "filter" ]
How do I write a unix filter in python?
1,589,994
<p>I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars <code>x</code> from stdin.</p>
9
2009-10-19T17:24:43Z
1,590,069
<p>You can use the <a href="http://docs.python.org/library/fileinput.html"><code>fileinput</code> class</a>, which lets you process inputs like the Perl diamond operator would. From the docs:</p> <pre><code>import fileinput for line in fileinput.input(): process(line) </code></pre> <p>where process does something like <code>print line.replace('x','')</code>.</p> <p>You can follow <a href="http://stackoverflow.com/questions/881696/unbuffered-stdout-in-python-as-in-python-u-from-within-the-program">this StackOverflow question</a> for how to unbuffer stdout. Or you can just call <code>sys.stdout.flush()</code> after each <code>print</code>.</p>
8
2009-10-19T17:40:43Z
[ "python", "unix", "filter" ]
How do I write a unix filter in python?
1,589,994
<p>I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars <code>x</code> from stdin.</p>
9
2009-10-19T17:24:43Z
1,590,122
<p>Use the -u switch for the python interpreter to make all reads and writes unbuffered. Similar to setting <code>$| = true;</code> in Perl. Then proceed as you would, reading a line modifying it and then printing it. sys.stdout.flush() not required.</p> <pre><code>#!/path/to/python -u import sys for line in sys.stdin: process_line(line) </code></pre>
2
2009-10-19T17:52:14Z
[ "python", "unix", "filter" ]
url builder for python
1,590,219
<p>I know about <code>urllib</code> and <code>urlparse</code>, but I want to make sure I wouldn't be reinventing the wheel.</p> <p>My problem is that I am going to be fetching a bunch of urls from the same domain via the <code>urllib</code> library. I basically want to be able to generate urls to use (as strings) with different paths and query params. I was hoping that something might have a syntax like:</p> <pre><code>url_builder = UrlBuilder("some.domain.com") # should give me "http://some.domain.com/blah?foo=bar url_i_need_to_hit = url_builder.withPath("blah").withParams("foo=bar") # maybe a ".build()" after this </code></pre> <p>Basically I want to be able to store defaults that get passed to <code>urlparse.urlunsplit</code> instead of constantly clouding up the code by passing in the whole tuple every time.</p> <p>Does something like this exist? Do people agree it's worth throwing together?</p>
10
2009-10-19T18:10:32Z
1,590,317
<p>Are you proposing an extension to <a href="http://docs.python.org/library/urlparse.html#urlparse.urlunparse" rel="nofollow">http://docs.python.org/library/urlparse.html#urlparse.urlunparse</a> that would substitute into the 6-item tuple?</p> <p>Are you talking about something like this?</p> <pre><code>def myUnparse( someTuple, scheme=None, netloc=None, path=None, etc. ): parts = list( someTuple ) if scheme is not None: parts[0] = scheme if netloc is not None: parts[1]= netloc if path is not None: parts[2]= path etc. return urlunparse( parts ) </code></pre> <p>Is that what you're proposing?</p> <p>This?</p> <pre><code>class URLBuilder( object ): def __init__( self, base ): self.parts = list( urlparse(base) ) def __call__( self, scheme=None, netloc=None, path=None, etc. ): if scheme is not None: self.parts[0] = scheme if netloc is not None: self.parts[1]= netloc if path is not None: self.parts[2]= path etc. return urlunparse( self.parts ) bldr= URLBuilder( someURL ) print bldr( scheme="ftp" ) </code></pre> <p>Something like that?</p>
4
2009-10-19T18:31:41Z
[ "python", "url" ]
url builder for python
1,590,219
<p>I know about <code>urllib</code> and <code>urlparse</code>, but I want to make sure I wouldn't be reinventing the wheel.</p> <p>My problem is that I am going to be fetching a bunch of urls from the same domain via the <code>urllib</code> library. I basically want to be able to generate urls to use (as strings) with different paths and query params. I was hoping that something might have a syntax like:</p> <pre><code>url_builder = UrlBuilder("some.domain.com") # should give me "http://some.domain.com/blah?foo=bar url_i_need_to_hit = url_builder.withPath("blah").withParams("foo=bar") # maybe a ".build()" after this </code></pre> <p>Basically I want to be able to store defaults that get passed to <code>urlparse.urlunsplit</code> instead of constantly clouding up the code by passing in the whole tuple every time.</p> <p>Does something like this exist? Do people agree it's worth throwing together?</p>
10
2009-10-19T18:10:32Z
1,590,700
<p>Still not quite sure what you're looking for... But I'll give it a shot. If you're just looking to make a class that will keep your default values and such, it's simple enough to make your own class and use Python magic like <strong>str</strong>. Here's a scratched-out example (suboptimal):</p> <pre><code>class UrlBuilder: def __init__(self,domain,path="blah",params="foo=bar"): self.domain = domain self.path = path self.params = params def withPath(self,path): self.path = path return self def withParams(self,params): self.params = params return self def __str__(self): return 'http://' + self.domain + '/' + self.path + '?' + self.params # or return urlparse.urlunparse( ( "http", self.domain, self.path, self.params, "", "" ) def build(self): return self.__str__() if __name__ == '__main__': u = UrlBuilder('www.example.com') print u.withPath('bobloblaw') print u.withParams('lawyer=yes') print u.withPath('elvis').withParams('theking=true') </code></pre> <p>If you're looking for more of the Builder Design Pattern, the <a href="http://en.wikipedia.org/wiki/Builder%5Fpattern#Python" rel="nofollow">Wikipedia article has a reasonable Python example</a> (as well as <a href="http://en.wikipedia.org/wiki/Builder%5Fpattern#Java" rel="nofollow">Java</a>).</p>
3
2009-10-19T19:44:43Z
[ "python", "url" ]
url builder for python
1,590,219
<p>I know about <code>urllib</code> and <code>urlparse</code>, but I want to make sure I wouldn't be reinventing the wheel.</p> <p>My problem is that I am going to be fetching a bunch of urls from the same domain via the <code>urllib</code> library. I basically want to be able to generate urls to use (as strings) with different paths and query params. I was hoping that something might have a syntax like:</p> <pre><code>url_builder = UrlBuilder("some.domain.com") # should give me "http://some.domain.com/blah?foo=bar url_i_need_to_hit = url_builder.withPath("blah").withParams("foo=bar") # maybe a ".build()" after this </code></pre> <p>Basically I want to be able to store defaults that get passed to <code>urlparse.urlunsplit</code> instead of constantly clouding up the code by passing in the whole tuple every time.</p> <p>Does something like this exist? Do people agree it's worth throwing together?</p>
10
2009-10-19T18:10:32Z
11,576,693
<p>You might want consider having a look at <a href="https://github.com/gruns/furl/" rel="nofollow">furl</a> because it might be an answer to your needs.</p>
4
2012-07-20T09:34:11Z
[ "python", "url" ]
url builder for python
1,590,219
<p>I know about <code>urllib</code> and <code>urlparse</code>, but I want to make sure I wouldn't be reinventing the wheel.</p> <p>My problem is that I am going to be fetching a bunch of urls from the same domain via the <code>urllib</code> library. I basically want to be able to generate urls to use (as strings) with different paths and query params. I was hoping that something might have a syntax like:</p> <pre><code>url_builder = UrlBuilder("some.domain.com") # should give me "http://some.domain.com/blah?foo=bar url_i_need_to_hit = url_builder.withPath("blah").withParams("foo=bar") # maybe a ".build()" after this </code></pre> <p>Basically I want to be able to store defaults that get passed to <code>urlparse.urlunsplit</code> instead of constantly clouding up the code by passing in the whole tuple every time.</p> <p>Does something like this exist? Do people agree it's worth throwing together?</p>
10
2009-10-19T18:10:32Z
35,260,759
<p>I think you want <a href="http://pythonhosted.org/uritools/" rel="nofollow">http://pythonhosted.org/uritools/</a>.</p> <p>Example from the docs:</p> <pre><code>parts = urisplit('foo://user@example.com:8042/over/there?name=ferret#nose') orig_uri = uriunsplit(parts) </code></pre> <p>The split value is a named tuple, not a regular list. It is accessible by name or index:</p> <pre><code>assert(parts[0] == parts.schema) assert(parts[1] == parts.authority) assert(parts[2] == parts.path) assert(parts[3] == parts.query) assert(parts[4] == parts.fragment) </code></pre> <p>Make a copy to make changes:</p> <pre><code>new_parts = [part for part in parts] new_parts[2] = "/some/other/path" new_uri = uriunsplit(new_parts) </code></pre>
1
2016-02-08T00:03:40Z
[ "python", "url" ]
Cache a django view that has URL parameters
1,590,372
<p>I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this?</p> <p>In psuedo code I currently have a URL:</p> <pre><code>http://mysites/ajaxthing/?user=foo&amp;items=10 </code></pre> <p>I would like to cache any this url as long as it has the same get parameters.</p> <p>I'm currently using the cache decorators in my view:</p> <pre><code>myview(stuff) myview = cache_page(myview, 60 * 3) </code></pre> <p>I did read about <a href="http://docs.djangoproject.com/en/dev/topics/cache/#using-vary-headers">django's vary headers</a> but it went a little over my head, and I'm not even sure its the correct solution</p>
9
2009-10-19T18:41:59Z
1,590,735
<p>Right, vary headers is not the correct solution, it's used when you want to cache based on client request headers like user-agent etc. </p> <p>You'll need to use <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">low-level API</a> or <a href="http://docs.djangoproject.com/en/dev/topics/cache/#template-fragment-caching">template fragment caching</a>. It depends on your views really.</p> <p>With low-level API it looks something like this:</p> <pre><code>from django.core.cache import cache def get_user(request): user_id = request.GET.get("user_id") user = cache.get("user_id_%s"%user_id) if user is None: user = User.objects.get(pk=user_id) cache.set("user_id_%s"%user_id, user, 10*60) # 10 minutes ... .. . </code></pre>
12
2009-10-19T19:50:09Z
[ "python", "django", "memcached" ]
Cache a django view that has URL parameters
1,590,372
<p>I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this?</p> <p>In psuedo code I currently have a URL:</p> <pre><code>http://mysites/ajaxthing/?user=foo&amp;items=10 </code></pre> <p>I would like to cache any this url as long as it has the same get parameters.</p> <p>I'm currently using the cache decorators in my view:</p> <pre><code>myview(stuff) myview = cache_page(myview, 60 * 3) </code></pre> <p>I did read about <a href="http://docs.djangoproject.com/en/dev/topics/cache/#using-vary-headers">django's vary headers</a> but it went a little over my head, and I'm not even sure its the correct solution</p>
9
2009-10-19T18:41:59Z
1,609,369
<p>a bit late, but you can use <a href="http://bitbucket.org/kmike/django-view-cache-utils/" rel="nofollow">django-view-cache-utils</a> for that.</p>
0
2009-10-22T19:13:49Z
[ "python", "django", "memcached" ]
Cache a django view that has URL parameters
1,590,372
<p>I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this?</p> <p>In psuedo code I currently have a URL:</p> <pre><code>http://mysites/ajaxthing/?user=foo&amp;items=10 </code></pre> <p>I would like to cache any this url as long as it has the same get parameters.</p> <p>I'm currently using the cache decorators in my view:</p> <pre><code>myview(stuff) myview = cache_page(myview, 60 * 3) </code></pre> <p>I did read about <a href="http://docs.djangoproject.com/en/dev/topics/cache/#using-vary-headers">django's vary headers</a> but it went a little over my head, and I'm not even sure its the correct solution</p>
9
2009-10-19T18:41:59Z
1,640,573
<p>Yes, you can use django-view-cache-utils, here is code for your case:</p> <pre><code>from view_cache_utils import cache_page_with_prefix from django.utils.hashcompat import md5_constructor ... @cache_page_with_prefix(60*15, lambda request: md5_constructor(request.get_full_path()).hexdigest()) def my_view(request): ... </code></pre>
8
2009-10-28T22:34:01Z
[ "python", "django", "memcached" ]
Cache a django view that has URL parameters
1,590,372
<p>I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this?</p> <p>In psuedo code I currently have a URL:</p> <pre><code>http://mysites/ajaxthing/?user=foo&amp;items=10 </code></pre> <p>I would like to cache any this url as long as it has the same get parameters.</p> <p>I'm currently using the cache decorators in my view:</p> <pre><code>myview(stuff) myview = cache_page(myview, 60 * 3) </code></pre> <p>I did read about <a href="http://docs.djangoproject.com/en/dev/topics/cache/#using-vary-headers">django's vary headers</a> but it went a little over my head, and I'm not even sure its the correct solution</p>
9
2009-10-19T18:41:59Z
5,446,363
<p>This should be no longer an issue in Django 1.3+. See: <a href="http://docs.djangoproject.com/en/1.3/topics/cache/#using-vary-headers" rel="nofollow">http://docs.djangoproject.com/en/1.3/topics/cache/#using-vary-headers</a></p>
2
2011-03-27T00:26:49Z
[ "python", "django", "memcached" ]
Cache a django view that has URL parameters
1,590,372
<p>I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this?</p> <p>In psuedo code I currently have a URL:</p> <pre><code>http://mysites/ajaxthing/?user=foo&amp;items=10 </code></pre> <p>I would like to cache any this url as long as it has the same get parameters.</p> <p>I'm currently using the cache decorators in my view:</p> <pre><code>myview(stuff) myview = cache_page(myview, 60 * 3) </code></pre> <p>I did read about <a href="http://docs.djangoproject.com/en/dev/topics/cache/#using-vary-headers">django's vary headers</a> but it went a little over my head, and I'm not even sure its the correct solution</p>
9
2009-10-19T18:41:59Z
29,379,752
<p>It appears that you no longer need to do anything more complicated than placing @cache_page([length of time]) above your View function you are trying to cache, irrespective of whether you have parameters in the URL.</p> <p>For example, if you have a url like:</p> <pre><code>http://example.com/user/some_user_id </code></pre> <p>Your view function in views.py would look something like this:</p> <pre><code>from django.views.decorators.cache import cache_page ... @cache_page(60 * 10) def get_user_detail(request, user_id=None): ... return render(...) </code></pre>
1
2015-03-31T22:34:23Z
[ "python", "django", "memcached" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,590,512
<p>What version of Windows are you running?</p> <p>Did you check the "Settings" tab to make sure all of the options are de-selected?</p> <p>You might also consider a more feature rich scheduler such as <a href="http://www.splinterware.com/products/wincron.htm" rel="nofollow">System Scheduler from Splinterware Software</a></p>
0
2009-10-19T19:11:12Z
[ "python", "windows-xp", "scheduled-tasks" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,590,518
<p>On the first pane (labeled "Task") do you have "Run only if logged on" unchecked and "Enabled (scheduled task runs at specified time" checked?</p> <p>I've run python jobs via Windows scheduled task with settings very similar to what you show.</p>
1
2009-10-19T19:12:16Z
[ "python", "windows-xp", "scheduled-tasks" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,590,546
<p>you can schedule it from another script and kick this off once a day or after each reboot:</p> <pre><code>#!/usr/bin/env python import subprocess interval = 300 # secs while True: p = subprocess.Popen(['pythonw.exe', 'foo.py']) time.sleep(interval) </code></pre> <p>This way you can do sub-minute intervals also.</p>
3
2009-10-19T19:15:42Z
[ "python", "windows-xp", "scheduled-tasks" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,590,558
<p>Also, for the past year or so I've seen a common bug where Scheduled Tasks on Server 2003 or XP do not run if either of the following checkboxes are on:</p> <ul> <li>"Don't start the task if the computer is running on batteries"</li> <li>"Stop the task if battery mode begins"</li> </ul> <p>It seems that Windows gets a little confused if you have a battery (on a laptop) or a UPS (on a server, for example), whether or not your utility power is working.</p> <p>Also, as a rule I would trim down the time or uncheck the option to "Stop the task if it runs for X minutes" when you're running it so often.</p>
1
2009-10-19T19:17:08Z
[ "python", "windows-xp", "scheduled-tasks" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,590,857
<p>From what I know, Scheduled Tasks is horrible. You should use something with better control like </p> <p><a href="http://cronw.sourceforge.net/" rel="nofollow">http://cronw.sourceforge.net/</a> or any other implementation of cron for Windows.</p>
1
2009-10-19T20:16:23Z
[ "python", "windows-xp", "scheduled-tasks" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,590,873
<p>Until: Duration 24 hours</p> <p>That shuts it off at the end of the first day.</p> <p>Remove that, see if it keeps going. It should, and you shouldn't need to install Python in the process. :)</p>
1
2009-10-19T20:19:01Z
[ "python", "windows-xp", "scheduled-tasks" ]
Scheduled tasks in Win32
1,590,474
<p>I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:</p> <p><strong>Daily</strong></p> <p><strong>Start time:</strong> 12:03 AM</p> <p><strong>Schedule task daily:</strong> every 1 day</p> <p><strong>Start date:</strong> some time in the past</p> <p><strong>Repeat task:</strong> every 5 minutes</p> <p><strong>Until</strong>: Duration 24 hours</p> <p>Basically, i want the script to run every five minutes, for ever.<br /> My problem is the task runs sometime after 23:47 every night (presumably after 23:55) and does not run after that. What am I doing wrong? Alternatively, is there a different method you can suggest other than using Windows scheduled tasks?</p>
1
2009-10-19T19:03:48Z
1,591,169
<p>At the risk of not answering your question, can I suggest that if what you have to run is important or even critical then Windows task-Scheduler is not the way to run it. </p> <p>There are so many awful flows when using the task-scheduler. Lets just start with the obvious ones:</p> <p>There is no logging. There is no way to investigate what happens when things go wrong. There's no way to distribute work across PCs. There's no fault-tolerance. It's Windows only and the interface is crappy. </p> <p>If any of the above is a problem for you you need something a bit more sophisticated. My suggestion is that you try Hudson, a.k.a. Sun's continuous integration server. </p> <p>In addition to all of the above it can do cron-style scheduling, with automatic expiry of logs. It can be set to jabber or email on failure and you can even make it auto diagnose what went wrong with your process if you can make it produce some XML output.</p> <p>Please please, do not use Windows Scheduled tasks. There are many better things to use, and I speak from experience when I say that I never regretted dumping the built-in scheduler.</p>
1
2009-10-19T21:09:32Z
[ "python", "windows-xp", "scheduled-tasks" ]
Python Deprecation Warnings with Monostate __new__ -- Can someone explain why?
1,590,477
<p>I have a basic Monostate with Python 2.6.</p> <pre><code>class Borg(object): __shared_state = {} def __new__(cls, *args, **kwargs): self = object.__new__(cls, *args, **kwargs) self.__dict__ = cls.__shared_state return self def __init__(self, *args, **kwargs): noSend = kwargs.get("noSend", False) reportLevel = kwargs.get("reportLevel", 30) reportMethods = kwargs.get("reportMethods", "BaseReport") contacts= kwargs.get("contacts", None) a = Borg(contacts="Foo", noSend="Bar", ) </code></pre> <p>Which happily gives me the following Deprecation warning..</p> <pre><code>untitled:4: DeprecationWarning: object.__new__() takes no parameters self = object.__new__(cls, *args, **kwargs) </code></pre> <p>After a bit of googling I find this is attached to <a href="http://bugs.python.org/issue1683368">Bug #1683368</a>. What I can't figure out is what this means. It's complaining about the following line</p> <pre><code>self = object.__new__(cls, *args, **kwargs) </code></pre> <p>Which appears to be OK. Can someone explain in <em>laymens</em> terms why this is a problem. I understand that "this is inconsistent with other built-ins, like list" but I'm not sure I understand why. Would someone explain this show me the right way to do it?</p> <p>Thanks</p>
5
2009-10-19T19:04:28Z
1,590,517
<p>The warning comes from the fact that <code>__new__()</code> can HAVE args, but since they're ignored everywhere, passing args (other than cls) to it causes the warning. It's not actually (currently) an error to pass the extra args, but they have no effect. </p> <p>In py3k it will become an error to pass the args.</p>
1
2009-10-19T19:12:15Z
[ "python", "deprecated", "monostate" ]
Python Deprecation Warnings with Monostate __new__ -- Can someone explain why?
1,590,477
<p>I have a basic Monostate with Python 2.6.</p> <pre><code>class Borg(object): __shared_state = {} def __new__(cls, *args, **kwargs): self = object.__new__(cls, *args, **kwargs) self.__dict__ = cls.__shared_state return self def __init__(self, *args, **kwargs): noSend = kwargs.get("noSend", False) reportLevel = kwargs.get("reportLevel", 30) reportMethods = kwargs.get("reportMethods", "BaseReport") contacts= kwargs.get("contacts", None) a = Borg(contacts="Foo", noSend="Bar", ) </code></pre> <p>Which happily gives me the following Deprecation warning..</p> <pre><code>untitled:4: DeprecationWarning: object.__new__() takes no parameters self = object.__new__(cls, *args, **kwargs) </code></pre> <p>After a bit of googling I find this is attached to <a href="http://bugs.python.org/issue1683368">Bug #1683368</a>. What I can't figure out is what this means. It's complaining about the following line</p> <pre><code>self = object.__new__(cls, *args, **kwargs) </code></pre> <p>Which appears to be OK. Can someone explain in <em>laymens</em> terms why this is a problem. I understand that "this is inconsistent with other built-ins, like list" but I'm not sure I understand why. Would someone explain this show me the right way to do it?</p> <p>Thanks</p>
5
2009-10-19T19:04:28Z
1,590,586
<p>See <a href="http://stackoverflow.com/questions/1363839/python-singleton-object-instantiation">python-singleton-object-instantiation</a>, and note <a href="http://stackoverflow.com/users/95810/alex-martelli">Alex Martelli's</a> singleton example:</p> <pre><code>class Singleton(object): __instance = None def __new__(cls): if cls.__instance == None: __instance = type.__new__(cls) __instance.name = "The one" return __instance </code></pre> <p>The <code>__new__ deprecation</code> question was <a href="http://mail.python.org/pipermail/python-dev/2008-February/076854.html" rel="nofollow">answered by Guido</a>:</p> <blockquote> <p>The message means just what it says. :-) There's no point in calling object.__new__() with more than a class parameter, and any code that did so was just dumping those args into a black hole.</p> <p>The only time when it makes sense for object.__new__() to ignore extra arguments is when it's not being overridden, but __init__ <em>is</em> being overridden -- then you have a completely default __new__ and the checking of constructor arguments is relegated to __init__.</p> <p>The purpose of all this is to catch the error in a call like object(42) which (again) passes an argument that is not used. This is often a symptom of a bug in your program.</p> <p>--Guido</p> </blockquote>
6
2009-10-19T19:22:52Z
[ "python", "deprecated", "monostate" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,632
<p>"just reorganize my code so that I don't have this problem." Correct. Easy to do. Always works.</p> <p>You can always provide the function prior to it's reference.</p> <p>"However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion"</p> <p>Can't see how that's even remotely possible. Please provide an example of a place where you cannot define the function prior to it's use.</p>
0
2009-10-19T19:33:09Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,640
<p>If you kick-start your script through the following:</p> <pre><code>if __name__=="__main__": main() </code></pre> <p>then you probably do not have to worry about things like "forward declaration". You see, the interpreter would go loading up all your functions and then start your main() function. Of course, make sure you have all the imports correct too ;-)</p> <p>Come to think of it, I've never heard such a thing as "forward declaration" in python... but then again, I might be wrong ;-)</p>
45
2009-10-19T19:33:53Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,655
<p>What you can do is to wrap the invocation into a function of its own.</p> <p>So that</p> <pre><code>foo() def foo(): print "Hi!" </code></pre> <p>will break, but</p> <pre><code>def bar(): foo() def foo(): print "Hi!" bar() </code></pre> <p>will be working properly.</p> <p>General rule in <code>Python</code> is <em>not</em> that function should be defined higher in the code (as in <code>Pascal</code>), but that it should be defined before its usage.</p> <p>Hope that helps. </p>
47
2009-10-19T19:36:32Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,657
<p>If you don't want to define a function <em>before</em> it's used, and defining it <em>afterwards</em> is impossible, what about defining it in some other module?</p> <p>Technically you still define it first, but it's clean.</p> <p>You could create a recursion like the following:</p> <pre><code>def foo(): bar() def bar(): foo() </code></pre> <p>Python's functions are anonymous just like values are anonymous, yet they can be bound to a name.</p> <p>In the above code, <code>foo()</code> does not call a function with the name foo, it calls a function that happens to be bound to the name <code>foo</code> at the point the call is made. It is possible to redefine <code>foo</code> somewhere else, and <code>bar</code> would then call the new function.</p> <p>Your problem cannot be solved because it's like asking to get a variable which has not been declared.</p>
42
2009-10-19T19:36:50Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,660
<p>No, I don't believe there is any way to forward-declare a function in Python.</p> <p>Imagine you are the Python interpreter. When you get to the line </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>either you know what cmp_configs is or you don't. In order to proceed, you have to know cmp_configs. It doesn't matter if there is recursion.</p>
7
2009-10-19T19:37:31Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,664
<p>If the call to cmp_configs is inside its own function definition, you should be fine. I'll give an example.</p> <pre><code>def a(): b() # b() hasn't been defined yet, but that's fine because at this point, we're not # actually calling it. We're just defining what should happen when a() is called. a() # This call fails, because b() hasn't been defined yet, # and thus trying to run a() fails. def b(): print "hi" a() # This call succeeds because everything has been defined. </code></pre> <p>In general, putting your code inside functions (such as main()) will resolve your problem; just call main() at the end of the file.</p>
8
2009-10-19T19:38:52Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,687
<p>There is no such thing in python like forward declaration. You just have to make sure that your function is declared before it is needed. Note that the body of a function isn't interpreted until the function is executed.</p> <p>Consider the following example:</p> <pre><code>def a(): b() # won't be resolved until a is invoked. def b(): print "hello" a() # here b is already defined so this line won't fail. </code></pre> <p>You can think that a body of a function is just another script that will be interpreted once you call the function.</p>
5
2009-10-19T19:42:13Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,590,765
<p>Now wait a minute. When your module reaches the print statement in your example, before <code>cmp_configs</code> has been defined, what exactly is it that you expect it to do?</p> <p>If your posting of a question using print is really trying to represent something like this:</p> <pre><code>fn = lambda mylist:"\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>then there is no requirement to define <code>cmp_configs</code> before executing this statement, just define it later in the code and all will be well.</p> <p>Now if you are trying to reference <code>cmp_configs</code> as a default value of an argument to the lambda, then this is a different story:</p> <pre><code>fn = lambda mylist,cmp_configs=cmp_configs : \ "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>Now you need a <code>cmp_configs</code> variable defined before you reach this line. </p> <p>[EDIT - this next part turns out not to be correct, since the default argument value will get assigned when the function is compiled, and that value will be used even if you change the value of cmp_configs later.]</p> <p>Fortunately, Python being so type-accommodating as it is, does not care <em>what</em> you define as <code>cmp_configs</code>, so you could just preface with this statement:</p> <pre><code>cmp_configs = None </code></pre> <p>And the compiler will be happy. Just be sure to declare the real <code>cmp_configs</code> before you ever invoke <code>fn</code>.</p>
0
2009-10-19T19:56:39Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
1,592,524
<p>You can't forward-declare a function in Python. If you have logic executing before you've defined functions, you've probably got a problem anyways. Put your action in an <code>if __name__ == '__main__'</code> at the end of your script (by executing a function you name "main" if it's non-trivial) and your code will be more modular and you'll be able to use it as a module if you ever need to.</p> <p>Also, replace that list comprehension with a generator express (i.e., print "\n".join(str(bla) for bla in sorted(mylist, cmp=cmp_configs)) )</p> <p>Also, don't use cmp, which is deprecated. Use "key" and provide a less-than function. </p>
2
2009-10-20T04:53:42Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
10,797,465
<p>Sometimes an algorithm is easiest to understand top-down, starting with the overall structure and drilling down into the details.</p> <p>You can do so without forward declarations:</p> <pre><code>def main(): make_omelet() eat() def make_omelet(): break_eggs() whisk() fry() def break_eggs(): for egg in carton: break(egg) # ... main() </code></pre>
5
2012-05-29T10:37:36Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
18,039,692
<p>One way is to create a handler function. Define the handler early on, and put the handler below all the methods you need to call. </p> <p>Then when you invoke the handler method to call your functions, they will always be available.</p> <p>The handler could take an argument <code>nameOfMethodToCall</code>. Then uses a bunch of if statements to call the right method.</p> <p>This would solve your issue.</p> <pre><code>def foo(): print("foo") #take input nextAction=input('What would you like to do next?:') return nextAction def bar(): print("bar") nextAction=input('What would you like to do next?:') return nextAction def handler(action): if(action=="foo"): nextAction = foo() elif(action=="bar"): nextAction = bar() else: print("You entered invalid input, defaulting to bar") nextAction = "bar" return nextAction nextAction=input('What would you like to do next?:') while 1: nextAction = handler(nextAction) </code></pre>
-2
2013-08-04T04:24:25Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
21,949,524
<p>I apologize for reviving this thread, but there was a strategy not discussed here which may be applicable.</p> <p>Using reflection it is possible to do something akin to forward declaration. For instance lets say you have a section of code that looks like this:</p> <pre><code># We want to call a function called 'foo', but it hasn't been defined yet. function_name = 'foo' # Calling at this point would produce an error # Here is the definition def foo(): bar() # Note that at this point the function is defined # Time for some reflection... globals()[function_name]() </code></pre> <p>So in this way we have determined what function we want to call before it is actually defined, effectively a forward declaration. In python the statement <code>globals()[function_name]()</code> is the same as <code>foo()</code> if <code>function_name = 'foo'</code> for the reasons discussed above, since python must lookup each function before calling it. If one were to use the <code>timeit</code> module to see how these two statements compare, they have the exact same computational cost.</p> <p>Of course the example here is very useless, but if one were to have a complex structure which needed to execute a function, but must be declared before (or structurally it makes little sense to have it afterwards), one can just store a string and try to call the function later. </p>
3
2014-02-22T04:08:36Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python?
1,590,608
<p>Is it possible to forward-declare a function in Python? I want to sort a list using my own <code>cmp</code> function before it is declared. </p> <pre><code>print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) </code></pre> <p>I've organized my code to put the definition of <code>cmp_configs</code> method after the invocation. It fails with this error:</p> <pre><code>NameError: name 'cmp_configs' is not defined </code></pre> <p>Is there any way to "declare" <code>cmp_configs</code> method before it's used? It would make my code look cleaner?</p> <p>I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's <em>really</em> necessary to forward declare a function.</p> <p><strong>Consider this case where forward-declaring a function would be necessary in Python:</strong></p> <pre><code>def spam(): if end_condition(): return end_result() else: return eggs() def eggs(): if end_condition(): return end_result() else: return spam() </code></pre> <p>Where <code>end_condition</code> and <code>end_result</code> have been previously defined.</p> <p>Is the only solution to reorganize the code and always put definitions before invocations?</p>
80
2009-10-19T19:29:21Z
28,533,518
<p>Theres a hackish way to do it as follows:</p> <pre><code>bar = None def foo(): print "foo", bar() def bar(): print "bar" foo() </code></pre> <p>By declaring a null value (or really anything) for bar before hand, it now has an entry in the dictionary. Assuming you dont try and call foo before bar is declared , your code will work fine. Generally speaking you should try and refactor around forward declarations, but sometimes its just more practical this way. </p>
2
2015-02-16T02:00:49Z
[ "python", "forward-declaration" ]
How to use twistedweb with django on windows
1,590,651
<p>I'm looking for a super easy way to deploy django application on windows.</p> <p>Basically my plan is to set up any python web server with my app on it and the boundle everything together using py2exe into a single executable.</p> <p>I've tried using cherrypy however the newest (3.1.2) server doesn't work with Windows XP with Nod32 antivirus installed. </p> <p>So I decided to give a try to Twisted. I've only found <a href="http://code.google.com/p/django-on-twisted/" rel="nofollow">Django On Twisted</a> but it seams to be quite old (2008) and it use twistd command which is a bit hard to pack into single executable.</p> <p>Has anyone got a working snipped or good source of info?</p>
0
2009-10-19T19:35:49Z
1,591,690
<p>I would rather suggest <a href="http://en.wlmp-project.net/downloads.php?cat=lighty" rel="nofollow">Portable LightTPD</a> (i.e. the .zip) and <a href="http://www.portablepython.com/wiki/Download" rel="nofollow">Portable Python</a>. It is very easy to set up LightTPD for FastCGI, and very easy to set up sqlite and FastCGI with Django in the Portable Python distro. This is probably your fastest and simplest route to getting an easily-deployable Django app going. If you aren't using it already, you probably want the <a href="http://rads.stackoverflow.com/amzn/click/143021936X" rel="nofollow">Django book</a> to help speed things along.</p> <p><a href="http://www.instantdjango.com/" rel="nofollow">Instant Django</a> has Python 2.6.2 integrated, so perhaps that would serve your needs better.</p>
0
2009-10-19T23:22:41Z
[ "python", "windows", "django", "twisted" ]
How to use twistedweb with django on windows
1,590,651
<p>I'm looking for a super easy way to deploy django application on windows.</p> <p>Basically my plan is to set up any python web server with my app on it and the boundle everything together using py2exe into a single executable.</p> <p>I've tried using cherrypy however the newest (3.1.2) server doesn't work with Windows XP with Nod32 antivirus installed. </p> <p>So I decided to give a try to Twisted. I've only found <a href="http://code.google.com/p/django-on-twisted/" rel="nofollow">Django On Twisted</a> but it seams to be quite old (2008) and it use twistd command which is a bit hard to pack into single executable.</p> <p>Has anyone got a working snipped or good source of info?</p>
0
2009-10-19T19:35:49Z
1,593,040
<p>I've found quite nice <a href="http://blog.dreid.org/2009/03/twisted-django-it-wont-burn-down-your.html" rel="nofollow">blog entry</a> describing how to run django on twisted trunk.</p> <p>Here is an example that merge twisted with django app into one file so it can be used from file created by py2exe:</p> <pre><code># bootstrap your django instance from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() import sys sys.argv += '-no web --wsgi=&lt;module_name&gt;.application --port=8081'.split() from twisted.scripts.twistd import run run() </code></pre>
0
2009-10-20T07:48:14Z
[ "python", "windows", "django", "twisted" ]
Python| How can I make this variable global without initializing it as 'global'
1,590,712
<p>I have this code here. The only part I can add code to is in main_____ AFTER the 'i=1' line. This script will be executing multiple times and will have some variable (might not be 'i', could be 'xy', 'var', anything), incrementing by 1 each time. I have gotten this to work by declaring 'i' as global above the method, but unfortunately, I can't keep it that way.</p> <p>Is there a way in which I can make 'i' function as a global variable within the above-mentioned parameters?</p> <pre><code>def main______(): try: i+=1 except NameError: i=1 main______() </code></pre>
-3
2009-10-19T19:45:51Z
1,591,050
<p>If you want to use a global variable you have to declare it as global. What's wrong with that?</p> <p>If you need to store state between calls, you should be using a class</p> <pre><code>&gt;&gt;&gt; class F(): ... def __init__(self): ... self.i=0 ... def __call__(self): ... print self.i ... self.i+=1 ... &gt;&gt;&gt; f=F() &gt;&gt;&gt; f() 0 &gt;&gt;&gt; f() 1 &gt;&gt;&gt; f() 2 </code></pre>
1
2009-10-19T20:46:13Z
[ "python", "global" ]