title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
print vs stderr
939,866
<p>Are there any specific advantages or disadvantages to either <code>print</code> or <code>stderr</code>?</p>
23
2009-06-02T14:25:54Z
16,592,589
<p>It is useful to separate stderr and stdout when running your script by redirecting them to different files. I usually use stderr for log messages and to keep track of the flow of the program, but use stdout for more useful messages that I am going to use them later.</p> <p>One another way to write to stderr is as the following example:</p> <pre><code>import sys sys.stderr.write("Error has occurred opening a file!") </code></pre>
2
2013-05-16T16:16:23Z
[ "python", "printing", "stderr" ]
How do I update an object's members using a dict?
940,089
<p>I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL.</p> <p>So some internal application sends off a request to <code>/import/?a=1&amp;b=2&amp;c=3</code>, for example. In the view, I want to create a new object, <code>foo = Foo()</code> and have the members of <code>foo</code> set to the data in the request.GET dictionary.</p> <p>Here is what I'm doing now:</p> <ol> <li>Request sent to <code>/import/?a=1&amp;b=2&amp;c=3</code></li> <li>View creates new object: <code>foo = Foo()</code></li> <li>Object is updated with data.</li> </ol> <p>Here is what I got thus far:</p> <pre><code>foo.a = request['a'] foo.b = request['b'] foo.c = request['c'] </code></pre> <p>Obviously this is tedious and error prone. The data in the URL has the exact same name as the object's members so it is a simple 1-to-1 mapping. </p> <p>Ideally, I would like to do able to do something like this:</p> <pre><code>foo = Foo() foo.update(request.GET) </code></pre> <p>or something to that effect.</p> <p>Thanks!</p>
9
2009-06-02T15:07:29Z
940,101
<p>You can use the setattr function to dynamically set attributes:</p> <pre><code>for key,value in request.GET.items(): setattr(foo, key, value) </code></pre>
17
2009-06-02T15:09:14Z
[ "python", "django" ]
How do I update an object's members using a dict?
940,089
<p>I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL.</p> <p>So some internal application sends off a request to <code>/import/?a=1&amp;b=2&amp;c=3</code>, for example. In the view, I want to create a new object, <code>foo = Foo()</code> and have the members of <code>foo</code> set to the data in the request.GET dictionary.</p> <p>Here is what I'm doing now:</p> <ol> <li>Request sent to <code>/import/?a=1&amp;b=2&amp;c=3</code></li> <li>View creates new object: <code>foo = Foo()</code></li> <li>Object is updated with data.</li> </ol> <p>Here is what I got thus far:</p> <pre><code>foo.a = request['a'] foo.b = request['b'] foo.c = request['c'] </code></pre> <p>Obviously this is tedious and error prone. The data in the URL has the exact same name as the object's members so it is a simple 1-to-1 mapping. </p> <p>Ideally, I would like to do able to do something like this:</p> <pre><code>foo = Foo() foo.update(request.GET) </code></pre> <p>or something to that effect.</p> <p>Thanks!</p>
9
2009-06-02T15:07:29Z
940,131
<p>You've almost got it.</p> <pre><code>foo = Foo(**request.GET) </code></pre> <p>should do the trick.</p>
1
2009-06-02T15:13:08Z
[ "python", "django" ]
How do I update an object's members using a dict?
940,089
<p>I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL.</p> <p>So some internal application sends off a request to <code>/import/?a=1&amp;b=2&amp;c=3</code>, for example. In the view, I want to create a new object, <code>foo = Foo()</code> and have the members of <code>foo</code> set to the data in the request.GET dictionary.</p> <p>Here is what I'm doing now:</p> <ol> <li>Request sent to <code>/import/?a=1&amp;b=2&amp;c=3</code></li> <li>View creates new object: <code>foo = Foo()</code></li> <li>Object is updated with data.</li> </ol> <p>Here is what I got thus far:</p> <pre><code>foo.a = request['a'] foo.b = request['b'] foo.c = request['c'] </code></pre> <p>Obviously this is tedious and error prone. The data in the URL has the exact same name as the object's members so it is a simple 1-to-1 mapping. </p> <p>Ideally, I would like to do able to do something like this:</p> <pre><code>foo = Foo() foo.update(request.GET) </code></pre> <p>or something to that effect.</p> <p>Thanks!</p>
9
2009-06-02T15:07:29Z
940,203
<p>If you are using this to create a model object that then gets persisted, I'd strongly recommend using a <a href="http://docs.djangoproject.com/en/1.0/topics/forms/modelforms/" rel="nofollow">ModelForm</a>. This would do what you described, in the canonical way for Django, with the addition of validation.</p> <p>To expand -- I didn't mean to use it for form output, just form input. As follows:</p> <pre><code>class Foo(models.Model): a = models.CharField(max_length=255), b = models.PositiveIntegerField() class FooForm(forms.ModelForm): class Meta: model = Foo def insert_foo(request): form = FooForm(request.GET) if not form.is_valid(): # Handle error conditions here pass else: form.save() return HttpResponse('Your response') </code></pre> <p>Then, assuming it's bound to /import/, a GET to /import/?a=Test&amp;b=1 would insert a new Foo with a = "Test" and b="1".</p>
1
2009-06-02T15:24:36Z
[ "python", "django" ]
How do I update an object's members using a dict?
940,089
<p>I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL.</p> <p>So some internal application sends off a request to <code>/import/?a=1&amp;b=2&amp;c=3</code>, for example. In the view, I want to create a new object, <code>foo = Foo()</code> and have the members of <code>foo</code> set to the data in the request.GET dictionary.</p> <p>Here is what I'm doing now:</p> <ol> <li>Request sent to <code>/import/?a=1&amp;b=2&amp;c=3</code></li> <li>View creates new object: <code>foo = Foo()</code></li> <li>Object is updated with data.</li> </ol> <p>Here is what I got thus far:</p> <pre><code>foo.a = request['a'] foo.b = request['b'] foo.c = request['c'] </code></pre> <p>Obviously this is tedious and error prone. The data in the URL has the exact same name as the object's members so it is a simple 1-to-1 mapping. </p> <p>Ideally, I would like to do able to do something like this:</p> <pre><code>foo = Foo() foo.update(request.GET) </code></pre> <p>or something to that effect.</p> <p>Thanks!</p>
9
2009-06-02T15:07:29Z
953,807
<p>If <code>request.GET</code> is a dictionary and <code>class Foo</code> does not use <code>__slots__</code>, then this should also work:</p> <pre><code># foo is a Foo instance foo.__dict__.update(request.GET) </code></pre>
3
2009-06-05T00:51:04Z
[ "python", "django" ]
How to pass pointer to an array in Python for a wrapped C++ function
940,132
<p>I am new to C++/Python mixed language programming and do not have much idea about Python/C API. I just started using Boost.Python to wrap a C++ library for Python. I am stuck at wrapping a function that takes pointer to an array as an argument. Following (2nd ctor) is its prototype in C++.</p> <pre><code>class AAF{ AAF(AAF_TYPE t); AAF(double v0, const double * t1, const unsigned * t2, unsigned T); ~AAF(); } </code></pre> <p>Am I doing right by wrapping it like this in boost::python?</p> <pre><code>class_&lt;AAF&gt;("AAF", init&lt;AAF_TYPE&gt;()) .def(init&lt;double, const double*, const unsigned*, unsigned&gt;()); </code></pre> <p>Note that it compiled and linked successfully, but I couldn't figure out how to call it in Python. My naive tries like the following failed.</p> <pre><code>&gt;&gt;&gt; z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3); Traceback (most recent call last): File "./test_interval.py", line 40, in &lt;module&gt; z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3); Boost.Python.ArgumentError: Python argument types in AAF.__init__(AAF, int, list, list, int) did not match C++ signature: __init__(_object*, AAF_TYPE) __init__(_object*, double, double const*, unsigned int const*, unsigned int) &gt;&gt;&gt; t1 = array.array('d', [4, 5.5, 10]) &gt;&gt;&gt; t2 = array.array('I', [1, 1, 2]) &gt;&gt;&gt; z = AAF(10, t1, t2, 3); Traceback (most recent call last): File "./test_interval.py", line 40, in &lt;module&gt; z = AAF(10, t1, t2, 3); Boost.Python.ArgumentError: Python argument types in AAF.__init__(AAF, int, array.array, array.array, int) did not match C++ signature: __init__(_object*, AAF_TYPE) __init__(_object*, double, double const*, unsigned int const*, unsigned int) </code></pre> <p>My second question is that do I also need to wrap the destructor? Please specify if this might be necessary in some cases but not always.</p>
4
2009-06-02T15:13:49Z
940,782
<p>The wrapping is right (in principle) but in</p> <pre><code>AAF(10, [4, 5.5, 10], [1, 1, 2], 3); </code></pre> <p>(as the interpreter points out) you're passing to your function python's list objects, not pointers.</p> <p>In short, if your function needs only to work on python's lists you need to change your code to use that interface (instead of using pointers). If you need to keep that interface, you have to write a wrapper function that takes a list from python, does the proper conversion and calls your orginal c++ function. The same applies to numpy arrays.</p> <p>Please note that boost::python offers some built-in mechanism to convert python containers to stl compatible containers.</p> <p>An example wrapping code for your case could be</p> <pre><code>void f(list o) { std::size_t n = len(o); double* tmp = new double[n]; for (int i = 0; i &lt; n; i++) { tmp[i] = extract&lt;double&gt;(o[i]); } std::cout &lt;&lt; std::endl; // use tmp delete tmp; } </code></pre> <p>Please give a look at the boost.python tutorial at <a href="http://www.boost.org/doc/libs/1_39_0/libs/python/doc/tutorial/doc/html/index.html" rel="nofollow">http://www.boost.org/doc/libs/1_39_0/libs/python/doc/tutorial/doc/html/index.html</a>.</p>
4
2009-06-02T17:22:33Z
[ "python", "arrays", "pointers", "wrapping", "boost-python" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
940,214
<p>The state of affairs is pretty bad. The most reliable method at present is probably to use JRuby. I know that's probably not the answer you want to hear, but, as you say, ruby2exe is unreliable, and Shoes is a long way off (and isn't even intended to be a full-scale application). Personally, I dislike forcing users to install GTK or Qt or wxWidgets, but the JVM is fairly ubiquitous.</p>
2
2009-06-02T15:26:15Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
940,241
<p>I don't know about ruby2exe, but py2exe works perfeclty fine. Even with librairies like wxWidgets. <strong>Edit</strong>: you don't even have to ask the user to install wxWidgets, it's bundled with the app (same goes for py2app)</p> <p>I use it for my very small project <a href="http://github.com/loicwolff/notagapp/">here</a>.</p> <p>For the Mac crowd, py2app works fine too with wxWidgets.</p>
11
2009-06-02T15:31:46Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
940,261
<p>I don't know about Ruby, but the standard for Python is <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> to create Windows binaries. For me, the cross-plattform <a href="http://www.pyinstaller.org/" rel="nofollow">pyinstaller</a> has worked well, once. For your GUI, <a href="http://wiki.python.org/moin/TkInter" rel="nofollow">TkInter</a> is the standard. A lot of people like <a href="http://www.wxpython.org/" rel="nofollow">wxPython</a>. All those are fairly actively developed. I suggest playing a little bit around with these options to decide whether Python is the better choice.</p>
6
2009-06-02T15:37:18Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
940,509
<p>Depending on how far you development is, <a href="http://shoesrb.com/" rel="nofollow">Shoes</a> is pretty good. Its basically it's own Ruby Distribution. It may be a bit hidden (in the files menu), but it allows you to package your application for all 3 platforms without having that Shoes startup screen.</p> <p>The rendering engine behind it is Cairo.</p>
1
2009-06-02T16:30:05Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
941,539
<p>For Ruby, the <a href="http://rubyforge.org/projects/ocra/">One-Click Ruby Application Builder</a> (OCRA) is emerging as the successor to <a href="http://www.erikveen.dds.nl/rubyscript2exe/">RubyScript2Exe</a>. </p> <p>Ocra works with both Ruby 1.8.6 and 1.9.1, and with wxRuby. Supports LZMA compression for relatively compact executables.</p>
8
2009-06-02T19:48:28Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
942,712
<p>I've read about (but not used) Seattlerb's Wilson, which describes itself as a pure x86 assembler, but it doesn't sound like it'd be cross-platform or GUI.</p>
-2
2009-06-03T01:32:42Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Distributing Ruby/Python desktop apps
940,149
<p>Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?</p> <p>I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.</p> <p>RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.</p> <p>Generally — what is the current fad?</p> <p>BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.</p>
10
2009-06-02T15:15:46Z
976,069
<p>I don't think anyone really answered his question.</p> <p>As for me, I use VB to do Shell() calls to Ocra compiled Ruby scripts. It works pretty well and allows me to create apps that run in all modern OS.</p> <p>Linux testing is done by using Wine to run and ensuring that I use a pre .NET version of VB for the .exe compilation.</p>
0
2009-06-10T14:50:17Z
[ "python", "ruby", "user-interface", "desktop", "software-distribution" ]
Getting a list of specific index items from a list of dictionaries in python (list comprehension)
940,442
<p>I have a list of dictionaries like so:</p> <pre><code>listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] </code></pre> <p>I want a list of all the ids from the dictionaries. So, from the given list I would get the list:</p> <pre><code>[1,3,5] </code></pre> <p>It should be one line. I know I've done this before, I've just forgotten the syntax...Thanks</p>
1
2009-06-02T16:18:43Z
940,450
<pre><code>[i['id'] for i in listDict] </code></pre>
2
2009-06-02T16:20:59Z
[ "python" ]
Getting a list of specific index items from a list of dictionaries in python (list comprehension)
940,442
<p>I have a list of dictionaries like so:</p> <pre><code>listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] </code></pre> <p>I want a list of all the ids from the dictionaries. So, from the given list I would get the list:</p> <pre><code>[1,3,5] </code></pre> <p>It should be one line. I know I've done this before, I've just forgotten the syntax...Thanks</p>
1
2009-06-02T16:18:43Z
940,455
<p>[elem['id'] for elem in listDict]</p>
0
2009-06-02T16:21:57Z
[ "python" ]
Getting a list of specific index items from a list of dictionaries in python (list comprehension)
940,442
<p>I have a list of dictionaries like so:</p> <pre><code>listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] </code></pre> <p>I want a list of all the ids from the dictionaries. So, from the given list I would get the list:</p> <pre><code>[1,3,5] </code></pre> <p>It should be one line. I know I've done this before, I've just forgotten the syntax...Thanks</p>
1
2009-06-02T16:18:43Z
940,457
<pre><code>&gt;&gt;&gt; listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] &gt;&gt;&gt; [item["id"] for item in listDict] [1, 3, 5] </code></pre>
10
2009-06-02T16:22:07Z
[ "python" ]
Getting a list of specific index items from a list of dictionaries in python (list comprehension)
940,442
<p>I have a list of dictionaries like so:</p> <pre><code>listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] </code></pre> <p>I want a list of all the ids from the dictionaries. So, from the given list I would get the list:</p> <pre><code>[1,3,5] </code></pre> <p>It should be one line. I know I've done this before, I've just forgotten the syntax...Thanks</p>
1
2009-06-02T16:18:43Z
940,969
<p>For the python geeks:</p> <pre><code>import operator map(operator.itemgetter('id'), listDict) </code></pre>
1
2009-06-02T17:51:56Z
[ "python" ]
Getting a list of specific index items from a list of dictionaries in python (list comprehension)
940,442
<p>I have a list of dictionaries like so:</p> <pre><code>listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] </code></pre> <p>I want a list of all the ids from the dictionaries. So, from the given list I would get the list:</p> <pre><code>[1,3,5] </code></pre> <p>It should be one line. I know I've done this before, I've just forgotten the syntax...Thanks</p>
1
2009-06-02T16:18:43Z
39,280,827
<p>More conceptually pleasing and potentially faster method depending on how big your data is.</p> <p>Using pandas package to simply refer to keys as column headers and group values using the same key:</p> <pre><code>import pandas as pd listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] df = pd.DataFrame(listDict) # Then just reference the 'id' column to get a numpy array of it df['id'] # or just get a list df['id'].tolist() </code></pre> <p>Some benchmarking below, pandas clearly outperforms on large data. The small case uses the given 3 entries, the large case has 150k entries:</p> <pre><code>setup_large = "listDict = [];\ [listDict.extend(({'id':1,'other':2},{'id':3,'other':4},\ {'id':5,'other':6})) for _ in range(50000)];\ from operator import itemgetter;import pandas as pd;\ df = pd.DataFrame(listDict);" setup_small = "listDict = [];\ listDict.extend(({'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}));\ from operator import itemgetter;import pandas as pd;\ df = pd.DataFrame(listDict);" method1 = '[item["id"] for item in listDict]' method2 = "df['id'].tolist()" import timeit t = timeit.Timer(method1, setup_small) print('Small Method LC: ' + str(t.timeit(100))) t = timeit.Timer(method2, setup_small) print('Small Method Pandas: ' + str(t.timeit(100))) t = timeit.Timer(method1, setup_large) print('Large Method LC: ' + str(t.timeit(100))) t = timeit.Timer(method2, setup_large) print('Large Method Pandas: ' + str(t.timeit(100))) #Small Method LC: 8.79764556885e-05 #Small Method Pandas: 0.00153517723083 #Large Method LC: 2.34853601456 #Large Method Pandas: 0.605192184448 </code></pre>
2
2016-09-01T21:03:00Z
[ "python" ]
Python 2.6 subprocess.call() appears to be invoking setgid behavior triggering Perl's taint checks. How can I resolve?
940,552
<p>I've got some strange behavioral differences between Python's subprocess.call() and os.system() that appears to be related to setgid. The difference is causing Perl's taint checks to be invoked when subprocess.call() is used, which creates problems because I do not have the ability to modify all the Perl scripts that would need untaint code added to them.</p> <p>Example, "process.py"</p> <pre><code>#!/usr/bin/python import os, subprocess print "Python calling os.system" os.system('perl subprocess.pl true') print "Python done calling os.system" print "Python calling subprocess.call" subprocess.call(['perl', 'subprocess.pl', 'true']) print "Python done calling subprocess.call" </code></pre> <p>"subprocess.pl"</p> <pre><code>#!/usr/bin/perl print "perl subprocess\n"; `$ARGV[0]`; print "perl subprocess done\n"; </code></pre> <p>The output - both runs of subprocess.pl should be the same, but the one run with subprocess.call() gets a taint error:</p> <pre><code>mybox&gt; process.py Python calling os.system perl subprocess perl subprocess done Python done calling os.system Python calling subprocess.call perl subprocess Insecure dependency in `` while running setgid at subprocess.pl line 4. Python done calling subprocess.call mybox&gt; </code></pre> <p>While using os.system() works, I would really rather be using subprocess.check_call() as it's more forward-compatible and has nice checking behaviors.</p> <p>Any suggestions or documentation that might explain why these two are different? Is it possible this is some strange setting in my local unix environment that is invoking these behaviors?</p>
2
2009-06-02T16:36:22Z
940,740
<p>Doesn't happen for me:</p> <pre><code>$ python proc.py Python calling os.system perl subprocess perl subprocess done Python done calling os.system Python calling subprocess.call perl subprocess perl subprocess done Python done calling subprocess.call $ python --version Python 2.5.2 $ perl --version This is perl, v5.8.8 built for i486-linux-gnu-thread-multi </code></pre> <p>What are your version numbers?</p> <p>Under what sort of account are you running?</p> <p>EDIT:</p> <p>Sorry missed the title - I don't have python 2.6 anywhere easy to access, so I'll have to leave this problem.</p> <p>EDIT:</p> <p>So it looks like we worked out the problem - sgid on the python 2.6 binary.</p> <p>It would also be interesting to see if subprocess with the shell also avoids the problem.</p>
0
2009-06-02T17:13:47Z
[ "python", "perl", "subprocess" ]
Python 2.6 subprocess.call() appears to be invoking setgid behavior triggering Perl's taint checks. How can I resolve?
940,552
<p>I've got some strange behavioral differences between Python's subprocess.call() and os.system() that appears to be related to setgid. The difference is causing Perl's taint checks to be invoked when subprocess.call() is used, which creates problems because I do not have the ability to modify all the Perl scripts that would need untaint code added to them.</p> <p>Example, "process.py"</p> <pre><code>#!/usr/bin/python import os, subprocess print "Python calling os.system" os.system('perl subprocess.pl true') print "Python done calling os.system" print "Python calling subprocess.call" subprocess.call(['perl', 'subprocess.pl', 'true']) print "Python done calling subprocess.call" </code></pre> <p>"subprocess.pl"</p> <pre><code>#!/usr/bin/perl print "perl subprocess\n"; `$ARGV[0]`; print "perl subprocess done\n"; </code></pre> <p>The output - both runs of subprocess.pl should be the same, but the one run with subprocess.call() gets a taint error:</p> <pre><code>mybox&gt; process.py Python calling os.system perl subprocess perl subprocess done Python done calling os.system Python calling subprocess.call perl subprocess Insecure dependency in `` while running setgid at subprocess.pl line 4. Python done calling subprocess.call mybox&gt; </code></pre> <p>While using os.system() works, I would really rather be using subprocess.check_call() as it's more forward-compatible and has nice checking behaviors.</p> <p>Any suggestions or documentation that might explain why these two are different? Is it possible this is some strange setting in my local unix environment that is invoking these behaviors?</p>
2
2009-06-02T16:36:22Z
941,219
<p>I think your error is with perl, or the way it's interacting with your environment. Your backtick process is calling setgid for some reason. The only way I can replicate this, is to setgid on /usr/bin/perl (-rwxr-sr-x). [EDIT] Having python setgid does this too!</p> <p>[EDIT] I forgot that os.system <em>is</em> working for you. I think the only relevant difference here, is that with os.system the environment is <em>not</em> inherited by the subprocess. Look through the environment of each subprocess, and you may find your culprit.</p>
2
2009-06-02T18:45:03Z
[ "python", "perl", "subprocess" ]
PyQt sending parameter to slot when connecting to a signal
940,555
<p>I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don't know how to send that information to the function connected to. Here is the used to connect the action to the function:</p> <pre><code>QtCore.QObject.connect(menuAction, 'triggered()', menuClickedFunc) </code></pre> <p>I know that some events return a value, but triggered() doesn't. So how do I make this happen? Do I have to make my own signal?</p>
21
2009-06-02T16:38:00Z
940,655
<p>Use a <code>lambda</code></p> <p>Here's an example from the <a href="http://www.qtrac.eu/pyqtbook.html">PyQt book</a>:</p> <pre><code>self.connect(button3, SIGNAL("clicked()"), lambda who="Three": self.anyButton(who)) </code></pre> <p>By the way, you can also use <code>functools.partial</code>, but I find the <code>lambda</code> method simpler and clearer.</p>
33
2009-06-02T16:52:11Z
[ "python", "qt4", "pyqt" ]
PyQt sending parameter to slot when connecting to a signal
940,555
<p>I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don't know how to send that information to the function connected to. Here is the used to connect the action to the function:</p> <pre><code>QtCore.QObject.connect(menuAction, 'triggered()', menuClickedFunc) </code></pre> <p>I know that some events return a value, but triggered() doesn't. So how do I make this happen? Do I have to make my own signal?</p>
21
2009-06-02T16:38:00Z
940,658
<p>In general, you should have each menu item connected to a different slot, and have each slot handle the functionality only for it's own menu item. For example, if you have menu items like "save", "close", "open", you ought to make a separate slot for each, not try to have a single slot with a case statement in it.</p> <p>If you don't want to do it that way, you could use the <a href="http://doc.trolltech.com/4.5/signalsandslots.html#advanced-signals-and-slots-usage" rel="nofollow">QObject::sender()</a> function to get a pointer to the sender (ie: the object that emitted the signal). I'd like to hear a bit more about what you're trying to accomplish, though.</p>
0
2009-06-02T16:52:40Z
[ "python", "qt4", "pyqt" ]
PyQt sending parameter to slot when connecting to a signal
940,555
<p>I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don't know how to send that information to the function connected to. Here is the used to connect the action to the function:</p> <pre><code>QtCore.QObject.connect(menuAction, 'triggered()', menuClickedFunc) </code></pre> <p>I know that some events return a value, but triggered() doesn't. So how do I make this happen? Do I have to make my own signal?</p>
21
2009-06-02T16:38:00Z
19,752,158
<p>As already mentioned <a href="http://stackoverflow.com/questions/8824311">here</a> you can use the lambda function to pass extra arguments to the method you want to execute.</p> <p>In this example you can pass a string obj to the function AddControl() invoked when the button is pressed.</p> <pre><code># Create the build button with its caption self.build_button = QPushButton('&amp;Build Greeting', self) # Connect the button's clicked signal to AddControl self.build_button.clicked.connect(lambda: self.AddControl('fooData')) def AddControl(self, name): print name </code></pre> <p>Source: <a href="http://www.snip2code.com/Snippet/12165/">snip2code - Using Lambda Function To Pass Extra Argument in PyQt4</a> </p>
6
2013-11-03T10:56:42Z
[ "python", "qt4", "pyqt" ]
PyQt sending parameter to slot when connecting to a signal
940,555
<p>I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don't know how to send that information to the function connected to. Here is the used to connect the action to the function:</p> <pre><code>QtCore.QObject.connect(menuAction, 'triggered()', menuClickedFunc) </code></pre> <p>I know that some events return a value, but triggered() doesn't. So how do I make this happen? Do I have to make my own signal?</p>
21
2009-06-02T16:38:00Z
34,001,792
<p>use functools.partial</p> <p>otherwise you will find you cannot pass arguments dynamically when script is running, if you use lambda.</p>
3
2015-11-30T15:13:04Z
[ "python", "qt4", "pyqt" ]
Python Extension Returned Object Etiquette
940,563
<p>I am writing a python extension to provide access to Solaris kstat data ( in the same spirit as the shipping perl library Sun::Solaris::Kstat ) and I have a question about conditionally returning a list or a single object. The python use case would look something like:</p> <pre> cpu_stats = cKstats.lookup(module='cpu_stat') cpu_stat0 = cKstats.lookup('cpu_stat',0,'cpu_stat0') </pre> <p>As it's currently implemented, lookup() returns a list of all kstat objects which match. The first case would result in a list of objects ( as many as there are CPUs ) and the second call specifies a single kstat completely and would return a list containing one kstat.</p> <p>My question is it poor form to return a single object when there is only one match, and a list when there are many?</p> <p>Thank you for the thoughtful answer! My python-fu is weak but growing stronger due to folks like you. </p>
1
2009-06-02T16:39:04Z
940,741
<p>"My question is it poor form to return a single object when there is only one match, and a list when there are many?"</p> <p>It's poor form to return inconsistent types.</p> <p>Return a consistent type: List of kstat.</p> <p>Most Pythonistas don't like using <code>type(result)</code> to determine if it's a kstat or a list of kstats.</p> <p>We'd rather check the length of the list in a simple, consistent way. </p> <p>Also, if the length depends on a piece of system information, perhaps an API method could provide this metadata.</p> <p>Look at <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">DB-API PEP</a> for advice and ideas on how to handle query-like things.</p>
7
2009-06-02T17:13:49Z
[ "python", "python-c-api" ]
How does Spring for Python compare with Spring for Java
940,564
<p>I am an avid fan of the Spring framework for Java (by Rod Johnson). I am learning Python and was excited to find about Spring for Python. I would be interested in hearing the community's views on the comparison of these two flavours of Spring. How well does it fit Python's paradigms etc.</p>
6
2009-06-02T16:39:13Z
940,804
<p>Dependency injection frameworks are not nearly as useful in a dynamically typed language. See for example the presentation <a href="http://onestepback.org/articles/depinj/index.html">Dependency Injection: Vitally important or totally irrelevant?</a> In Java the flexibility provided by a dependency injection framework is vital, while in Python it usually results in unneeded complexity.</p> <p>This doesn't mean that the principles are wrong. See this example how to achieve loose coupling between classes by using simple idioms:</p> <pre><code># A concrete class implementing the greeting provider interface class EnglishGreetingProvider(object): def get_greeting(self, who): return "Hello %s!" % who # A class that takes a greeting provider factory as a parameter class ConsoleGreeter(object): def __init__(self, who, provider=EnglishGreetingProvider): self.who = who self.provider = provider() def greet(self): print(self.provider.get_greeting(self.who)) # Default wiring greeter = ConsoleGreeter(who="World") greeter.greet() # Alternative implementation class FrenchGreetingProvider(object): def get_greeting(self, who): return "Bonjour %s!" % who greeter = ConsoleGreeter(who="World", provider=FrenchGreetingProvider) greeter.greet() </code></pre>
20
2009-06-02T17:26:25Z
[ "java", "python", "spring" ]
How does Spring for Python compare with Spring for Java
940,564
<p>I am an avid fan of the Spring framework for Java (by Rod Johnson). I am learning Python and was excited to find about Spring for Python. I would be interested in hearing the community's views on the comparison of these two flavours of Spring. How well does it fit Python's paradigms etc.</p>
6
2009-06-02T16:39:13Z
945,831
<p>DISCLOSURE: I am the project lead for Spring Python, so you can consider my opinion biased.</p> <p>I find that several of the options provided by Spring Python are useful including: <a href="http://blog.springpython.webfactional.com/2009/03/23/the-case-for-aop-in-python/">aspect oriented programming</a>, <a href="http://blog.springpython.webfactional.com/2009/02/01/why-use-spring-python-and-not-just-plain/">dependency injection, remoting, security, and easy database access</a>.</p> <p>Aspect oriented programming is, as they say, easier to implement off the cuff with python than java. But Spring Python makes it easy enough to add to existing python modules without editing their source code. The other solutions require meta-programming or modifying the original source code. I've already had one person visit our forums asking how to add an interceptor to a PyGame application, so he could unobtrusively "tap" some code.</p> <p>Many people quickly <a href="http://wiki.springpython.webfactional.com/index.php/Purpose%5Fof%5FSpring%5FPython">assume "dependency injection" or "IoC" instantly means "XML configuration files"</a>. Not the case. While we support an XML configuration, just leap directly into using python decorators.</p> <p>I already know about one company that is using Spring Python as a key piece of their system. They are interested in making improvements, adding new features, and generally using it as a piece of their solution. They have also experimented with running it inside jython, in case that piques your interest.</p> <p>At the end of the day, my suggestion is to examine all the features, and see if any of them suit your needs. Whether this is adding needless complexity or succint value can only be determined by you. You don't have to use everything; only what you need. To get some more info on what is available, I invite you to view <a href="http://blog.springpython.webfactional.com/downloads/intro%5Fto%5Fspring%5Fpython%5Fturnquist.pdf">Introduction to Spring Python</a>, that I presented at SpringOne Americas 2008 conference.</p>
11
2009-06-03T16:54:44Z
[ "java", "python", "spring" ]
How does Spring for Python compare with Spring for Java
940,564
<p>I am an avid fan of the Spring framework for Java (by Rod Johnson). I am learning Python and was excited to find about Spring for Python. I would be interested in hearing the community's views on the comparison of these two flavours of Spring. How well does it fit Python's paradigms etc.</p>
6
2009-06-02T16:39:13Z
10,500,205
<p>Good stuff. I have used Spring Java, Spring Dot Net and now starting with Spring Python. Python has always been pretty easy to use for programmers; I think, especially since it's easy to write. I found Spring Dot Net to be a bit confusing, but both Spring Java and Python seem to be similar. I'm sure they have their differences, but so far at least I'm not all so confused with the Python implementation of Spring.</p>
0
2012-05-08T14:04:41Z
[ "java", "python", "spring" ]
Using list comprehensions and exceptions?
940,783
<p>Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this:</p> <pre><code>all(value in some_map for value in required_values) </code></pre> <p>Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension? </p> <p>I'm more or less curious, all signs seem to point to no.</p> <p><em>EDIT</em> Argh I meant this:</p> <pre><code>for value in required_values: if value not in some_map: raise somecustomException(value) </code></pre> <p>Looking at those I cant see how I can find the value where the error occurred</p>
3
2009-06-02T17:22:34Z
940,793
<p>If you don't want to consider duplicates and the values are hashable, use sets. They're easier, faster, and can extract "all" elements missing in a single operation:</p> <pre><code>required_values = set('abc') # store this as a set from the beginning values = set('ab') missing = required_values - values if missing: raise SomeException('The values %r are not in %r' % (missing, required_values)) </code></pre>
2
2009-06-02T17:24:05Z
[ "python", "list", "list-comprehension" ]
Using list comprehensions and exceptions?
940,783
<p>Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this:</p> <pre><code>all(value in some_map for value in required_values) </code></pre> <p>Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension? </p> <p>I'm more or less curious, all signs seem to point to no.</p> <p><em>EDIT</em> Argh I meant this:</p> <pre><code>for value in required_values: if value not in some_map: raise somecustomException(value) </code></pre> <p>Looking at those I cant see how I can find the value where the error occurred</p>
3
2009-06-02T17:22:34Z
940,809
<p>You can't use raise in a list comprehension. You can check for yourself by looking at <a href="http://docs.python.org/3.0/reference/expressions.html#comprehensions" rel="nofollow">the grammar in the Python Language Reference</a>.</p> <p>You can however, invoke a function which raises an exception for you.</p>
2
2009-06-02T17:27:55Z
[ "python", "list", "list-comprehension" ]
Using list comprehensions and exceptions?
940,783
<p>Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this:</p> <pre><code>all(value in some_map for value in required_values) </code></pre> <p>Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension? </p> <p>I'm more or less curious, all signs seem to point to no.</p> <p><em>EDIT</em> Argh I meant this:</p> <pre><code>for value in required_values: if value not in some_map: raise somecustomException(value) </code></pre> <p>Looking at those I cant see how I can find the value where the error occurred</p>
3
2009-06-02T17:22:34Z
940,834
<blockquote> <p>lets say i want to the raise an exception when a required value is missing, with the value that it is missing. How can i do that using list comprehension?</p> </blockquote> <p>List comprehensions are a syntactically concise way to create a list based on some existing list—they're <em>not</em> a general-purpose way of writing any <code>for</code>-loop in a single line. In this example, you're not actually creating a list, so it doesn't make any sense to use a list comprehension.</p>
13
2009-06-02T17:33:13Z
[ "python", "list", "list-comprehension" ]
Using list comprehensions and exceptions?
940,783
<p>Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this:</p> <pre><code>all(value in some_map for value in required_values) </code></pre> <p>Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension? </p> <p>I'm more or less curious, all signs seem to point to no.</p> <p><em>EDIT</em> Argh I meant this:</p> <pre><code>for value in required_values: if value not in some_map: raise somecustomException(value) </code></pre> <p>Looking at those I cant see how I can find the value where the error occurred</p>
3
2009-06-02T17:22:34Z
940,979
<p>While I think using sets (like nosklo's example) is better, you could do something simple like this:</p> <pre><code>def has_required(some_map, value): if not value in some_map: raise RequiredException('Missing required value: %s' % value) all(has_required(some_map, value) for value in required_values) </code></pre>
-2
2009-06-02T17:54:05Z
[ "python", "list", "list-comprehension" ]
Using list comprehensions and exceptions?
940,783
<p>Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this:</p> <pre><code>all(value in some_map for value in required_values) </code></pre> <p>Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension? </p> <p>I'm more or less curious, all signs seem to point to no.</p> <p><em>EDIT</em> Argh I meant this:</p> <pre><code>for value in required_values: if value not in some_map: raise somecustomException(value) </code></pre> <p>Looking at those I cant see how I can find the value where the error occurred</p>
3
2009-06-02T17:22:34Z
941,057
<p>Another (ugly) possibility would be the <code>error_on_false</code> function:</p> <pre><code>def error_on_false(value) if value: return value else: raise Exception('Wrong value: %r' % value) if all(error_on_false(value in some_map) for value in required_values): continue_code() do_something('...') </code></pre> <p>That's ugly. I'd use the <code>set</code> instead.</p>
0
2009-06-02T18:11:28Z
[ "python", "list", "list-comprehension" ]
Passing data to mod_wsgi
940,816
<p>In mod_wsgi I send the headers by running the function start_response(), but all the page content is passed by yield/return. Is there a way to pass the page content in a similar fashion as start_response()? Using the return.yield statement is very restrictive when it comes to working with chunked data.</p> <p>E.g.</p> <pre><code>def Application(): b = buffer() [... page code ...] while True: out = b.flush() if out: yield out class buffer: def __init__(self): b = [''] l = 0 def add(self, s): s = str(s) l += len(s) b.append(s) def flush(self): if self.l &gt; 1000: out = ''.join(b) self.__init__() return out </code></pre> <p>I want to have the buffer outputting the content as the page loads, but only outputs the content once enough of it has piled up (in this eg. 1000 bytes).</p>
0
2009-06-02T17:29:07Z
940,827
<p>No; But I don't think it is restrictive. Maybe you want to paste an example code where you describe your restriction and we can help.</p> <p>To work with chunk data you just <code>yield</code> the chunks:</p> <pre><code>def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')] yield 'Chunk 1\n' yield 'Chunk 2\n' yield 'Chunk 3\n' for chunk in chunk_data_generator(): yield chunk def chunk_data_generator() yield 'Chunk 4\n' yield 'Chunk 5\n' </code></pre> <p><hr /></p> <p><strong>EDIT</strong>: Based in the comments you gave, an example of piling data up to a certain length before sending forward:</p> <pre><code>BUFFER_SIZE = 10 # 10 bytes for testing. Use something bigger def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')] buffer = [] size = 0 for chunk in chunk_generator(): buffer.append(chunk) size += len(chunk) if size &gt; BUFFER_SIZE: for buf in buffer: yield buf buffer = [] size = 0 def chunk_data_generator() yield 'Chunk 1\n' yield 'Chunk 2\n' yield 'Chunk 3\n' yield 'Chunk 4\n' yield 'Chunk 5\n' </code></pre>
2
2009-06-02T17:31:52Z
[ "python", "mod-wsgi", "wsgi" ]
Passing data to mod_wsgi
940,816
<p>In mod_wsgi I send the headers by running the function start_response(), but all the page content is passed by yield/return. Is there a way to pass the page content in a similar fashion as start_response()? Using the return.yield statement is very restrictive when it comes to working with chunked data.</p> <p>E.g.</p> <pre><code>def Application(): b = buffer() [... page code ...] while True: out = b.flush() if out: yield out class buffer: def __init__(self): b = [''] l = 0 def add(self, s): s = str(s) l += len(s) b.append(s) def flush(self): if self.l &gt; 1000: out = ''.join(b) self.__init__() return out </code></pre> <p>I want to have the buffer outputting the content as the page loads, but only outputs the content once enough of it has piled up (in this eg. 1000 bytes).</p>
0
2009-06-02T17:29:07Z
941,090
<p>It is <em>possible</em> for your application to "push" data to the WSGI server:</p> <blockquote> <p>Some existing application framework APIs support unbuffered output in a different manner than WSGI. Specifically, they provide a "write" function or method of some kind to write an unbuffered block of data, or else they provide a buffered "write" function and a "flush" mechanism to flush the buffer.</p> <p>Unfortunately, such APIs cannot be implemented in terms of WSGI's "iterable" application return value, unless threads or other special mechanisms are used.</p> <p>Therefore, to allow these frameworks to continue using an imperative API, WSGI includes a special <code>write()</code> callable, returned by the <code>start_response</code> callable.</p> <p>New WSGI applications and frameworks <strong>should not</strong> use the <code>write()</code> callable if it is possible to avoid doing so.</p> <p><a href="http://www.python.org/dev/peps/pep-0333/#the-write-callable" rel="nofollow">http://www.python.org/dev/peps/pep-0333/#the-write-callable</a></p> </blockquote> <p>But it isn't recommended.</p> <blockquote> <p>Generally speaking, applications will achieve the best throughput by buffering their (modestly-sized) output and sending it all at once. This is a common approach in existing frameworks such as Zope: the output is buffered in a StringIO or similar object, then transmitted all at once, along with the response headers.</p> <p>The corresponding approach in WSGI is for the application to simply return a single-element iterable (such as a list) containing the response body as a single string. This is the recommended approach for the vast majority of application functions, that render HTML pages whose text easily fits in memory.</p> <p><a href="http://www.python.org/dev/peps/pep-0333/#buffering-and-streaming" rel="nofollow">http://www.python.org/dev/peps/pep-0333/#buffering-and-streaming</a></p> </blockquote>
1
2009-06-02T18:19:46Z
[ "python", "mod-wsgi", "wsgi" ]
Passing data to mod_wsgi
940,816
<p>In mod_wsgi I send the headers by running the function start_response(), but all the page content is passed by yield/return. Is there a way to pass the page content in a similar fashion as start_response()? Using the return.yield statement is very restrictive when it comes to working with chunked data.</p> <p>E.g.</p> <pre><code>def Application(): b = buffer() [... page code ...] while True: out = b.flush() if out: yield out class buffer: def __init__(self): b = [''] l = 0 def add(self, s): s = str(s) l += len(s) b.append(s) def flush(self): if self.l &gt; 1000: out = ''.join(b) self.__init__() return out </code></pre> <p>I want to have the buffer outputting the content as the page loads, but only outputs the content once enough of it has piled up (in this eg. 1000 bytes).</p>
0
2009-06-02T17:29:07Z
1,041,588
<p>If you don't want to change your WSGI application itself to partially buffer response data before sending it, then implement a WSGI middleware that wraps your WSGI application and which performs that task.</p>
1
2009-06-25T00:13:09Z
[ "python", "mod-wsgi", "wsgi" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
940,840
<p>This shouldn't match anything:</p> <pre><code>re.compile('$^') </code></pre> <p>So if you replace regexp1, regexp2 and regexp3 with '$^' it will be impossible to find a match. Unless you are using the multi line mode.</p> <p><hr /></p> <p>After some tests I found a better solution</p> <pre><code>re.compile('a^') </code></pre> <p>It is impossible to match and will fail earlier than the previous solution. You can replace a with any other character and it will always be impossible to match</p>
59
2009-06-02T17:34:15Z
[ "python", "regex" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
940,846
<p>Maybe <code>'.{0}'</code>?</p>
2
2009-06-02T17:34:58Z
[ "python", "regex" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
940,856
<pre><code>"()" </code></pre> <p>matches nothing and nothing only.</p>
2
2009-06-02T17:36:07Z
[ "python", "regex" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
940,934
<p>To match an empty string - even in multiline mode - you can use <code>\A\Z</code>, so:</p> <pre><code>re.compile('\A\Z|\A\Z*|\A\Z+') </code></pre> <p>The difference is that <code>\A</code> and <code>\Z</code> are start and end of <em>string</em>, whilst <code>^</code> and <code>$</code> these can match start/end of <em>lines</em>, so <code>$^|$^*|$^+</code> could potentially match a string containing newlines (if the flag is enabled).</p> <p>And to fail to match anything (even an empty string), simply attempt to find content before the start of the string, e.g:</p> <pre><code>re.compile('.\A|.\A*|.\A+') </code></pre> <p>Since no characters can come before \A (by definition), this will always fail to match.</p>
14
2009-06-02T17:45:58Z
[ "python", "regex" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
941,007
<p>You could use<br /> <code>\z..</code><br /> This is the absolute end of string, followed by two of anything</p> <p>If <code>+</code> or <code>*</code> is tacked on the end this still works refusing to match anything </p>
1
2009-06-02T17:58:27Z
[ "python", "regex" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
942,104
<p>Or, use some list comprehension to remove the useless regexp entries and join to put them all together. Something like:</p> <pre><code>re.compile('|'.join([x for x in [regexp1, regexp2, ...] if x != None])) </code></pre> <p>Be sure to add some comments next to that line of code though :-)</p>
0
2009-06-02T21:56:16Z
[ "python", "regex" ]
Regular expression syntax for "match nothing"?
940,822
<p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p> <pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" ) </code></pre> <p>I can modify individual substrings (regexp1, regexp2 etc).</p> <p>Is there any small and light expression that matches nothing, which I can use inside a template where I don't want any matches? Unfortunately, sometimes '+' or '*' is appended to the regexp atom so I can't use empty string - a "nothing to repeat" error will rise.</p>
42
2009-06-02T17:30:50Z
942,122
<p><code>(?!)</code> should always fail to match. It is the zero-width negative look-ahead. If what is in the parentheses matches then the whole match fails. Given that it has nothing in it, it will fail the match for anything (including nothing).</p>
18
2009-06-02T22:02:15Z
[ "python", "regex" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
940,997
<blockquote> <p>* Optimising inner loops in code</p> </blockquote> <p>Isn't that about performance ?</p>
8
2009-06-02T17:57:11Z
[ "python", "c", "performance" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
941,020
<p>Performance is a broad topic so you should be more specific. If the bottleneck in your program involves a lot of networking then rewriting it in C/C++ probably won't make a difference since it's the network calls taking up time, not your code. You would be better off rewriting the slow section of your program to use fewer network calls thus reducing the time your program spends waiting on entwork IO. If your doing math intensive stuff such as solving differential equations and you know there are C librarys that can offer better performance then the way you are currently doing it in Python you may want to rewrite the section of your program to use those librarys to increase it's performance.</p>
6
2009-06-02T18:02:36Z
[ "python", "c", "performance" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
941,036
<p>In my experience it is rarely necessary to optimize using C. I prefer to identify bottlenecks and improve algorithms in those areas completely in Python. Using hash tables, caching, and generally re-organizing your data structures to suit future needs has amazing potential for speeding up your program. As your program develops you'll get a better sense of what kind of material can be precalculated, so don't be afraid to go back and redo your storage and algorithms. Additionally, look for chances to kill "two birds with one stone", such as sorting objects as you render them instead of doing huge sorts.</p> <p>When everything is worked to the best of your knowledge, I'd consider using an optimizer like <a href="http://psyco.sourceforge.net/">Psyco</a>. I've experienced literally 10x performance improvements just by using Psyco and adding one line to my program.</p> <p>If all else fails, use C in the proper places and you'll get what you want.</p>
9
2009-06-02T18:06:23Z
[ "python", "c", "performance" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
941,041
<p>You will gain a large performance boost using C from Python (assuming your code is well written, etc) because Python is interpreted at run time, whereas C is compiled beforehand. This will speed up things quite a bit because with C, your code is simply running, whereas with Python, the Python interpreter must figure out what you are doing and interpret it into machine instructions.</p>
0
2009-06-02T18:07:35Z
[ "python", "c", "performance" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
941,079
<p>C can definitely speed up processor bound tasks. Integrating is even easier now, with the ctypes library, or you could go for any of the other methods you mention.</p> <p>I feel mercurial has done a good job with the integration if you want to look at their code as an example. The compute intensive tasks are in C, and everything else is python.</p>
2
2009-06-02T18:17:51Z
[ "python", "c", "performance" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
941,373
<p>I've been told for the calculating portion use C for the scripting use python. So yes you can integrate both. C is capable of faster calculations than that of python</p>
0
2009-06-02T19:12:54Z
[ "python", "c", "performance" ]
Is it reasonable to integrate python with c for performance?
940,982
<p>I like to use python for almost everything and always had clear in my mind that if for some reason I was to find a bottleneck in my python code(due to python's limitations), I could always use a C script integrated to my code.</p> <p>But, as I started to read a <a href="http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html" rel="nofollow">guide</a> on how to integrate python. In the article the author says:</p> <p>There are several reasons why one might wish to extend Python in C or C++, such as:</p> <blockquote> <ul> <li>Calling functions in an existing library.</li> <li>Adding a new builtin type to Python</li> <li>Optimising inner loops in code</li> <li>Exposing a C++ class library to Python</li> <li>Embedding Python inside a C/C++ application</li> </ul> </blockquote> <p>Nothing about performance. So I ask again, is it reasonable to integrate python with c for performance?</p>
2
2009-06-02T17:54:54Z
941,727
<p>The C extensions API is notoriously hard to work with, but there are a number of other ways to integrate C code. </p> <p>For some more usable alternatives see <a href="http://www.scipy.org/PerformancePython" rel="nofollow">http://www.scipy.org/PerformancePython</a>, in particular the section about using Weave for easy inlining of C code. </p> <p>Also of interest is <a href="http://www.cython.org/" rel="nofollow">Cython</a>, which provides a nice system for integrating with C code. Cython is used for optimization by some well-respected high-performance Python projects such as <a href="http://numpy.org" rel="nofollow">NumPy</a> and <a href="http://sagemath.org" rel="nofollow">Sage</a>.</p> <p>As mentioned above, <a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> is another attractive option for optimization, and one which <a href="http://psyco.sourceforge.net/psycoguide/node8.html" rel="nofollow">requires</a> nothing more than</p> <pre><code>import psyco psyco.bind(myfunction) </code></pre> <p>Psyco will identify your inner loops and automatically substitute optimized versions of the routines.</p>
3
2009-06-02T20:28:29Z
[ "python", "c", "performance" ]
Save an html page + change all links to point to the right place
941,235
<p>You probably know that IE has this thing where you can save a web page, and it will automatically download the html file and all he image/css/js files that the html file uses. </p> <p>Now there is one problem with this- the links in the html file are not changed. So if I download the html page of example.com, which has an &lt; a href=/hi.html> the page that I downloaded with IE will have a link to C:\Documents and Settings...(path to the folder that the html file is in).</p> <p>Is there a python library that will download an html page for me, with all the contents of it (images/js/css) too? If yes, is there a library that will also change the links for me?</p> <p>Thanks!!</p>
0
2009-06-02T18:47:55Z
941,424
<p>Since you're mentioning IE specifically, I'm not sure if this is gonna be of any use to you, but on linux the easiest way to completely mirror a website is with the wget command.</p> <pre><code>wget --mirror --convert-links -w 1 http://www.example.com </code></pre> <p>Run man wget if you need more options.</p>
8
2009-06-02T19:22:33Z
[ "javascript", "python", "html", "css", "screen-scraping" ]
Save an html page + change all links to point to the right place
941,235
<p>You probably know that IE has this thing where you can save a web page, and it will automatically download the html file and all he image/css/js files that the html file uses. </p> <p>Now there is one problem with this- the links in the html file are not changed. So if I download the html page of example.com, which has an &lt; a href=/hi.html> the page that I downloaded with IE will have a link to C:\Documents and Settings...(path to the folder that the html file is in).</p> <p>Is there a python library that will download an html page for me, with all the contents of it (images/js/css) too? If yes, is there a library that will also change the links for me?</p> <p>Thanks!!</p>
0
2009-06-02T18:47:55Z
34,292,231
<p>I've written a tool to save web pages into a single standalone html file, and the links are pointed to the same place as it should be.</p> <p><a href="https://github.com/zTrix/webpage2html" rel="nofollow">https://github.com/zTrix/webpage2html</a></p>
0
2015-12-15T14:50:43Z
[ "javascript", "python", "html", "css", "screen-scraping" ]
Validating a slug in Django
941,270
<p>I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to <code>£$(*£$(£@$&amp;£($</code> in the title field, which is converted into a slug using Django <code>slugify</code>.</p> <p>Because none of these characters can be converted, Django returns an error. My question is, what should I put in the form validation method to raise a <code>forms.ValidationError</code> when the user uses a title like this?</p> <p>Thanks.</p>
6
2009-06-02T18:54:25Z
941,297
<p>This question is half a decade old so in updating my question I should explain that I'm at least nodding to the past where some features might not have existed.</p> <p>The easiest way to handle slugs in forms these days is to just use <code>django.models.SlugField</code>. It will validate itself for you and imply that this field is an index.</p> <p>If you're not using this on a model, you can still hook in the same validator that SlugField uses:</p> <pre><code>from django.core.validators import validate_slug slug = forms.CharField(..., validators=[validate_slug]) </code></pre> <p>If you just want to do behind-the-scenes checking or write your own validator, you can use a similar technique to pull in Django's definition of a valid slug. It's just the compiled regex that validate_slug above uses:</p> <pre><code>from django.core.validators import slug_re if slug_re.match(...): ... </code></pre> <p>I can't imagine it will change, but by locking yourself to Django's idea of a slug, you'll ensure consistency if Django does change one day.</p>
10
2009-06-02T18:59:15Z
[ "python", "django", "validation", "slug" ]
Validating a slug in Django
941,270
<p>I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to <code>£$(*£$(£@$&amp;£($</code> in the title field, which is converted into a slug using Django <code>slugify</code>.</p> <p>Because none of these characters can be converted, Django returns an error. My question is, what should I put in the form validation method to raise a <code>forms.ValidationError</code> when the user uses a title like this?</p> <p>Thanks.</p>
6
2009-06-02T18:54:25Z
6,466,286
<p>SLUG_REGEX = re.compile('^[-\w]+$')</p>
12
2011-06-24T10:03:14Z
[ "python", "django", "validation", "slug" ]
using "range" in a google app engine template for - loop
941,282
<p>i've got an appengine project and in my template i want to do something like </p> <pre><code>{% for i in range(0, len(somelist)) %} {{ somelist[i] }} {{ otherlist[i] }} {% endfor %} </code></pre> <p>i've tried using 'forloop.counter' to access list items too, but that didn't work out either. any suggestions?</p> <p>regards, mux </p>
0
2009-06-02T18:57:17Z
941,367
<p>What you might want to do instead is change the data that you're passing in to the template so that somelist and otherlist are zipped together into a single list:</p> <pre><code>combined_list = zip(somelist, otherlist) ... {% for item in combined_list %} {{ item.0 }} {{ item.1 }} {% endfor %} </code></pre>
6
2009-06-02T19:12:02Z
[ "python", "django-templates" ]
Any python OpenID server available?
941,296
<p>I'd like to host my own OpenID provider. Is there anything available in Python?</p>
12
2009-06-02T18:59:07Z
941,311
<p><a href="http://openidenabled.com/python-openid/">You are weak with the Google.</a></p> <p>(Edit: That's a link to <a href="http://openidenabled.com/">OpenID-Enabled.com</a>. There are also PHP and Ruby versions available there.)</p>
14
2009-06-02T19:01:47Z
[ "python", "openid" ]
Any python OpenID server available?
941,296
<p>I'd like to host my own OpenID provider. Is there anything available in Python?</p>
12
2009-06-02T18:59:07Z
1,513,138
<p><a href="http://yangman.ca/poit/">poit</a> is a standalone, single-user OpenID server implemented in Python, using python-openid. (It's a project I started)</p>
7
2009-10-03T07:57:29Z
[ "python", "openid" ]
wxPython won't close Frame with a parent who is a window handle
941,470
<p>I have a program in Python that gets a window handle via COM from another program (think of the Python program as an addin) I set this window to be the main Python frame's parent so that if the other program minimizes, the python frame will too. The problem is when I go to exit, and try to close or destroy the main frame, the frame.close never completes it's execution (although it does disappear) and the other program refuses to close unless killed with TaskManager.</p> <p>Here are roughly the steps we take:</p> <pre><code>if we are started directly, launch other program if not, we are called from the other program, do nothing enter main function: create new wx.App set other program as frame parent: Get handle via COM create a parent using wx.Window_FromHWND create new frame with handle as parent show frame enter main loop App.onexit: close frame frame = None handle as parent = None handle = None </code></pre> <p>Anybody have any thoughts on this or experience with this sort of thing?</p> <p>I appreciate any help with this!</p> <p>[Edit] This is only the case when I use the handle as a parent, if I just get the handle and close the python program, the other program closes fine</p>
1
2009-06-02T19:33:30Z
941,655
<p>I wonder if your <code>Close</code> call may be hanging in the close-handler. Have you tried calling <code>Destroy</code> instead? If that doesn't help, then the only solution would seem to be "reparenting" or "detaching" your frame -- I don't see a way to do that in <code>wx</code>, but maybe you could drop down to win32 API for that one task...?</p>
1
2009-06-02T20:15:58Z
[ "python", "windows", "wxpython", "handle" ]
wxPython won't close Frame with a parent who is a window handle
941,470
<p>I have a program in Python that gets a window handle via COM from another program (think of the Python program as an addin) I set this window to be the main Python frame's parent so that if the other program minimizes, the python frame will too. The problem is when I go to exit, and try to close or destroy the main frame, the frame.close never completes it's execution (although it does disappear) and the other program refuses to close unless killed with TaskManager.</p> <p>Here are roughly the steps we take:</p> <pre><code>if we are started directly, launch other program if not, we are called from the other program, do nothing enter main function: create new wx.App set other program as frame parent: Get handle via COM create a parent using wx.Window_FromHWND create new frame with handle as parent show frame enter main loop App.onexit: close frame frame = None handle as parent = None handle = None </code></pre> <p>Anybody have any thoughts on this or experience with this sort of thing?</p> <p>I appreciate any help with this!</p> <p>[Edit] This is only the case when I use the handle as a parent, if I just get the handle and close the python program, the other program closes fine</p>
1
2009-06-02T19:33:30Z
952,990
<p>If reparenting is all you need, you can try <code>frame.Reparent(None)</code> before <code>frame.Close()</code></p>
0
2009-06-04T20:46:21Z
[ "python", "windows", "wxpython", "handle" ]
wxPython won't close Frame with a parent who is a window handle
941,470
<p>I have a program in Python that gets a window handle via COM from another program (think of the Python program as an addin) I set this window to be the main Python frame's parent so that if the other program minimizes, the python frame will too. The problem is when I go to exit, and try to close or destroy the main frame, the frame.close never completes it's execution (although it does disappear) and the other program refuses to close unless killed with TaskManager.</p> <p>Here are roughly the steps we take:</p> <pre><code>if we are started directly, launch other program if not, we are called from the other program, do nothing enter main function: create new wx.App set other program as frame parent: Get handle via COM create a parent using wx.Window_FromHWND create new frame with handle as parent show frame enter main loop App.onexit: close frame frame = None handle as parent = None handle = None </code></pre> <p>Anybody have any thoughts on this or experience with this sort of thing?</p> <p>I appreciate any help with this!</p> <p>[Edit] This is only the case when I use the handle as a parent, if I just get the handle and close the python program, the other program closes fine</p>
1
2009-06-02T19:33:30Z
1,711,471
<p>My resolution to this is a little bit hacked, and admittedly not the most elegant solution that I've ever come up with - but it works rather effectively...</p> <p>Basically my steps are to start a thread that polls to see whether the window handle is existent or not. While it's still existent, do nothing. If it no longer exists, kill the python application, allowing the handle (and main application) to be released.</p> <pre><code>class CheckingThread(threading.Thread): ''' This class runs a check on Parent Window to see if it still is running If Parent Window closes, this class kills the Python Window application in memory ''' def run(self): ''' Checks Parent Window in 5 seconds intervals to make sure it is still alive. If not alive, exit application ''' self.needKill = False while not self.needKill: if self.handle is not None: if not win32gui.IsWindow(self.handle): os._exit(0) break time.sleep(5) def Kill(self): ''' Call from Python Window main application that causes application to exit ''' self.needKill = True def SetHandle(self, handle): ''' Sets Handle so thread can check if handle exists. This must be called before thread is started. ''' self.handle = handle </code></pre> <p>Again, it feels a little hackish, but I don't really see another way around it. If anybody else has better resolutions, please post. </p>
0
2009-11-10T21:48:13Z
[ "python", "windows", "wxpython", "handle" ]
How to construct a web file browser?
941,638
<p>Goal: simple browser app, for navigating files on a web server, in a tree view.</p> <p>Background: Building a web site as a learning experience, w/ Apache, mod_python, Python code. (No mod_wsgi yet.)</p> <p>What tools should I learn to write the browser tree? I see JavaScript, Ajax, neither of which I know. Learn them? Grab a JS example from the web and rework? Can such a thing be built in raw HTML? Python I'm advanced beginner but I realize that's server side.</p> <p>If you were going to build such a toy from scratch, what would you use? What would be the totally easy, cheesy way, the intermediate way, the fully professional way?</p> <p>No Django yet please -- This is an exercise in learning web programming nuts and bolts.</p>
2
2009-06-02T20:11:52Z
941,652
<p>First, switch to mod_wsgi.</p> <p>Second, write a hello world in Python using mod_wsgi.</p> <p>Third, change your hello world to show the results of <code>os.listdir()</code>.</p> <p>I think you're approximately done.</p> <p>As you mess with this, you'll realize that transforming the content you have (information from <code>os.listdir</code>) into presentation in HTML is a pain in the neck.</p> <p>You can add <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja templates</a> to this to separate content from presentation. </p> <p>Finally, you'll notice that you've started to build Django the hard way. Stop. Learn Django. You'll see that it's still "programming nuts and bolts". It doesn't "conceal" or "abstract" much away from the web server development experience. It just saves you from reinventing the wheel.</p>
10
2009-06-02T20:14:50Z
[ "javascript", "python", "html", "web-applications" ]
How to construct a web file browser?
941,638
<p>Goal: simple browser app, for navigating files on a web server, in a tree view.</p> <p>Background: Building a web site as a learning experience, w/ Apache, mod_python, Python code. (No mod_wsgi yet.)</p> <p>What tools should I learn to write the browser tree? I see JavaScript, Ajax, neither of which I know. Learn them? Grab a JS example from the web and rework? Can such a thing be built in raw HTML? Python I'm advanced beginner but I realize that's server side.</p> <p>If you were going to build such a toy from scratch, what would you use? What would be the totally easy, cheesy way, the intermediate way, the fully professional way?</p> <p>No Django yet please -- This is an exercise in learning web programming nuts and bolts.</p>
2
2009-06-02T20:11:52Z
941,664
<p>If you want to make interactive browser, you have to learn JS and ajax. </p> <p>If you want to build only browser based on links, python would be enough.</p>
1
2009-06-02T20:17:50Z
[ "javascript", "python", "html", "web-applications" ]
How to construct a web file browser?
941,638
<p>Goal: simple browser app, for navigating files on a web server, in a tree view.</p> <p>Background: Building a web site as a learning experience, w/ Apache, mod_python, Python code. (No mod_wsgi yet.)</p> <p>What tools should I learn to write the browser tree? I see JavaScript, Ajax, neither of which I know. Learn them? Grab a JS example from the web and rework? Can such a thing be built in raw HTML? Python I'm advanced beginner but I realize that's server side.</p> <p>If you were going to build such a toy from scratch, what would you use? What would be the totally easy, cheesy way, the intermediate way, the fully professional way?</p> <p>No Django yet please -- This is an exercise in learning web programming nuts and bolts.</p>
2
2009-06-02T20:11:52Z
942,293
<p>The "totally cheesy" way:</p> <pre><code>python -m SimpleHTTPServer </code></pre> <p>This will serve up the files in the current directory at <a href="http://localhost:8000/" rel="nofollow">http://localhost:8000/</a></p>
1
2009-06-02T22:43:50Z
[ "javascript", "python", "html", "web-applications" ]
How to construct a web file browser?
941,638
<p>Goal: simple browser app, for navigating files on a web server, in a tree view.</p> <p>Background: Building a web site as a learning experience, w/ Apache, mod_python, Python code. (No mod_wsgi yet.)</p> <p>What tools should I learn to write the browser tree? I see JavaScript, Ajax, neither of which I know. Learn them? Grab a JS example from the web and rework? Can such a thing be built in raw HTML? Python I'm advanced beginner but I realize that's server side.</p> <p>If you were going to build such a toy from scratch, what would you use? What would be the totally easy, cheesy way, the intermediate way, the fully professional way?</p> <p>No Django yet please -- This is an exercise in learning web programming nuts and bolts.</p>
2
2009-06-02T20:11:52Z
943,612
<p>set "Indexes" option to the directory in the apache config.</p> <p>To learn how to build webapps in python, learn django.</p>
0
2009-06-03T08:18:36Z
[ "javascript", "python", "html", "web-applications" ]
Django 1.0, using default password reset
942,148
<p>I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error:</p> <pre><code>Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments ... </code></pre> <p>in my urlconf I have something like this:</p> <pre><code>#django.contrib.auth.views urlpatterns = patterns('django.contrib.auth.views', (r'^password_reset/$', 'password_reset', {'template_name': 'accounts/registration/password_reset_form.html', 'email_template_name':'accounts/registration/password_reset_email.html', 'post_reset_redirect':'accounts/login/'}), (r'^password_reset/done/$', 'password_reset_done', {'template_name': 'accounts/registration/password_reset_done.html'}), (r'^reset/(?P&lt;uidb36&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', 'password_reset_confirm', {'template_name': 'accounts/registration/password_reset_confirm.html', 'post_reset_redirect':'accounts/login/', 'post_reset_redirect':'accounts/reset/done/'}), (r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/registration/password_reset_complete.html'}), ) </code></pre> <p>The problem seems to be in this file: </p> <pre><code>password_reset_email.html </code></pre> <p>on line 7</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} </code></pre> <p>I'm at loss as to what's going on, so any help would be appreciated.</p> <p>Thanks</p>
6
2009-06-02T22:09:28Z
942,169
<p>This is a problem I figured out myself not 10 minutes ago. The solution is to add the post_change_redirect value to the dictionary of arguments you are passing to the password_reset view.</p> <p>So this is what mine now look like:</p> <pre><code>(r'^/password/$', password_change, {'template_name': 'testing/password.html', 'post_change_redirect': '/account/'}) </code></pre> <p>I hope that does it for you! I agree that the documentation for this particular feature is lacking somewhat, but this solved the exact same issue for my project.</p> <p>Edit: I really should have scrolled across - you've included that already. Apologies for that, but I hope you get it sorted :)</p>
0
2009-06-02T22:15:04Z
[ "python", "django" ]
Django 1.0, using default password reset
942,148
<p>I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error:</p> <pre><code>Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments ... </code></pre> <p>in my urlconf I have something like this:</p> <pre><code>#django.contrib.auth.views urlpatterns = patterns('django.contrib.auth.views', (r'^password_reset/$', 'password_reset', {'template_name': 'accounts/registration/password_reset_form.html', 'email_template_name':'accounts/registration/password_reset_email.html', 'post_reset_redirect':'accounts/login/'}), (r'^password_reset/done/$', 'password_reset_done', {'template_name': 'accounts/registration/password_reset_done.html'}), (r'^reset/(?P&lt;uidb36&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', 'password_reset_confirm', {'template_name': 'accounts/registration/password_reset_confirm.html', 'post_reset_redirect':'accounts/login/', 'post_reset_redirect':'accounts/reset/done/'}), (r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/registration/password_reset_complete.html'}), ) </code></pre> <p>The problem seems to be in this file: </p> <pre><code>password_reset_email.html </code></pre> <p>on line 7</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} </code></pre> <p>I'm at loss as to what's going on, so any help would be appreciated.</p> <p>Thanks</p>
6
2009-06-02T22:09:28Z
944,440
<p><strong>Edit</strong>: I used your example, and had to change to not use keyword parameters.</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uid, token %} </code></pre> <p>Named parameters do work, as long as both uid and token are defined. If either are not defined or blank I get the same error you do:</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} </code></pre>
3
2009-06-03T12:26:55Z
[ "python", "django" ]
Django 1.0, using default password reset
942,148
<p>I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error:</p> <pre><code>Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments ... </code></pre> <p>in my urlconf I have something like this:</p> <pre><code>#django.contrib.auth.views urlpatterns = patterns('django.contrib.auth.views', (r'^password_reset/$', 'password_reset', {'template_name': 'accounts/registration/password_reset_form.html', 'email_template_name':'accounts/registration/password_reset_email.html', 'post_reset_redirect':'accounts/login/'}), (r'^password_reset/done/$', 'password_reset_done', {'template_name': 'accounts/registration/password_reset_done.html'}), (r'^reset/(?P&lt;uidb36&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', 'password_reset_confirm', {'template_name': 'accounts/registration/password_reset_confirm.html', 'post_reset_redirect':'accounts/login/', 'post_reset_redirect':'accounts/reset/done/'}), (r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/registration/password_reset_complete.html'}), ) </code></pre> <p>The problem seems to be in this file: </p> <pre><code>password_reset_email.html </code></pre> <p>on line 7</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} </code></pre> <p>I'm at loss as to what's going on, so any help would be appreciated.</p> <p>Thanks</p>
6
2009-06-02T22:09:28Z
945,160
<p>Just wanted to post the solution I came up with. The problem was in this line:</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} </code></pre> <p>I'm not really a 100% why either, so I just hard coded the url like this:</p> <pre><code>http://mysite.com/accounts/reset/{{uid}}-{{token}}/ </code></pre>
2
2009-06-03T14:38:23Z
[ "python", "django" ]
Django 1.0, using default password reset
942,148
<p>I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error:</p> <pre><code>Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments ... </code></pre> <p>in my urlconf I have something like this:</p> <pre><code>#django.contrib.auth.views urlpatterns = patterns('django.contrib.auth.views', (r'^password_reset/$', 'password_reset', {'template_name': 'accounts/registration/password_reset_form.html', 'email_template_name':'accounts/registration/password_reset_email.html', 'post_reset_redirect':'accounts/login/'}), (r'^password_reset/done/$', 'password_reset_done', {'template_name': 'accounts/registration/password_reset_done.html'}), (r'^reset/(?P&lt;uidb36&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', 'password_reset_confirm', {'template_name': 'accounts/registration/password_reset_confirm.html', 'post_reset_redirect':'accounts/login/', 'post_reset_redirect':'accounts/reset/done/'}), (r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/registration/password_reset_complete.html'}), ) </code></pre> <p>The problem seems to be in this file: </p> <pre><code>password_reset_email.html </code></pre> <p>on line 7</p> <pre><code>{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %} </code></pre> <p>I'm at loss as to what's going on, so any help would be appreciated.</p> <p>Thanks</p>
6
2009-06-02T22:09:28Z
6,640,223
<p>I've struggled with this for over an hour trying everything on this page and every other page on the internet. Finally to solve the problem in my case i had to delete </p> <pre><code>{% load url from future %} </code></pre> <p>from the top of my password_reset_email.html template.</p> <p>Also note, "uidb36=uid" in the url script. Here's my full password_reset_email.html template, I hope it saves someone some time:</p> <pre><code>{% autoescape off %} You're receiving this e-mail because you requested a password reset for your user account at {{ site_name }}. Please go to the following page and choose a new password: {% block reset_link %} {{ protocol }}://{{ domain }}{% url django.contrib.auth.views.password_reset_confirm uidb36=uid token=token %} {% endblock %} Your username, in case you've forgotten:" %} {{ user.username }} Thanks for using our site! The {{ site_name }} team {% endautoescape %} </code></pre>
2
2011-07-10T09:13:00Z
[ "python", "django" ]
Efficient python code for printing the product of divisors of a number
942,198
<p>I am trying to solve a problem involving printing the product of all divisors of a given number. The number of test cases is a number 1 &lt;= t &lt;= 300000 , and the number itself can range from 1 &lt;= n &lt;= 500000</p> <p>I wrote the following code, but it always exceeds the time limit of 2 seconds. Are there any ways to speed up the code ?</p> <pre><code>from math import sqrt def divisorsProduct(n): ProductOfDivisors=1 for i in range(2,int(round(sqrt(n)))+1): if n%i==0: ProductOfDivisors*=i if n/i != i: ProductOfDivisors*=(n/i) if ProductOfDivisors &lt;= 9999: print ProductOfDivisors else: result = str(ProductOfDivisors) print result[len(result)-4:] T = int(raw_input()) for i in range(1,T+1): num = int(raw_input()) divisorsProduct(num) </code></pre> <p>Thank You.</p>
3
2009-06-02T22:20:03Z
942,306
<p>You could eliminate the if statement in the loop by only looping to less than the square root, and check for square root integer-ness outside the loop. <p> It is a rather strange question you pose. I have a hard time imagine a use for it, other than it possibly being an assignment in a course. My first thought was to pre-compute a list of primes and only test against those, but I assume you are quite deliberately counting non-prime factors? I.e., if the number has factors 2 and 3, you are also counting 6. <p> If you do use a table of pre-computed primes, you would then have to also subsequently include all possible combinations of primes in your result, which gets more complex. <p> C is really a great language for that sort of thing, because even suboptimal algorithms run really fast.</p>
1
2009-06-02T22:48:32Z
[ "python", "math" ]
Efficient python code for printing the product of divisors of a number
942,198
<p>I am trying to solve a problem involving printing the product of all divisors of a given number. The number of test cases is a number 1 &lt;= t &lt;= 300000 , and the number itself can range from 1 &lt;= n &lt;= 500000</p> <p>I wrote the following code, but it always exceeds the time limit of 2 seconds. Are there any ways to speed up the code ?</p> <pre><code>from math import sqrt def divisorsProduct(n): ProductOfDivisors=1 for i in range(2,int(round(sqrt(n)))+1): if n%i==0: ProductOfDivisors*=i if n/i != i: ProductOfDivisors*=(n/i) if ProductOfDivisors &lt;= 9999: print ProductOfDivisors else: result = str(ProductOfDivisors) print result[len(result)-4:] T = int(raw_input()) for i in range(1,T+1): num = int(raw_input()) divisorsProduct(num) </code></pre> <p>Thank You.</p>
3
2009-06-02T22:20:03Z
942,784
<p>You need to clarify by what you mean by "product of divisors." The code posted in the question doesn't work for any definition yet. This sounds like a homework question. If it is, then perhaps your instructor was expecting you to think outside the code to meet the time goals.</p> <p>If you mean the product of unique prime divisors, e.g., 72 gives 2*3 = 6, then having a list of primes is the way to go. Just run through the list up to the square root of the number, multiplying present primes into the result. There are not that many, so you could even hard code them into your program.</p> <p>If you mean the product of all the divisors, prime or not, then it is helpful to think of what the divisors are. You can make serious speed gains over the brute force method suggested in the other answers and yours. I suspect this is what your instructor intended.</p> <p>If the divisors are ordered in a list, then they occur in pairs that multiply to n -- 1 and n, 2 and n/2, etc. -- except for the case where n is a perfect square, where the square root is a divisor that is not paired with any other.</p> <p>So the result will be n to the power of half the number of divisors, (regardless of whether or not n is a square). </p> <p>To compute this, find the prime factorization using your list of primes. That is, find the power of 2 that divides n, then the power of 3, etc. To do this, take out all the 2s, then the 3s, etc. </p> <p>The number you are taking the factors out of will be getting smaller, so you can do the square root test on the smaller intermediate numbers to see if you need to continue up the list of primes. To gain some speed, test p*p &lt;= m, rather than p &lt;= sqrt(m) </p> <p>Once you have the prime factorization, it is easy to find the number of divisors. For example, suppose the factorization is 2^i * 3^j * 7^k. Then, since each divisor uses the same prime factors, with exponents less than or equal to those in n including the possibility of 0, the number of divisors is (i+1)(j+1)(k+1).</p> <p>E.g., 72 = 2^3 * 3^2, so the number of divisors is 4*3 = 12, and their product is 72^6 = 139,314,069,504.</p> <p>By using math, the algorithm can become much better than O(n). But it is hard to estimate your speed gains ahead of time because of the relatively small size of the n in the input.</p>
6
2009-06-03T02:19:42Z
[ "python", "math" ]
Efficient python code for printing the product of divisors of a number
942,198
<p>I am trying to solve a problem involving printing the product of all divisors of a given number. The number of test cases is a number 1 &lt;= t &lt;= 300000 , and the number itself can range from 1 &lt;= n &lt;= 500000</p> <p>I wrote the following code, but it always exceeds the time limit of 2 seconds. Are there any ways to speed up the code ?</p> <pre><code>from math import sqrt def divisorsProduct(n): ProductOfDivisors=1 for i in range(2,int(round(sqrt(n)))+1): if n%i==0: ProductOfDivisors*=i if n/i != i: ProductOfDivisors*=(n/i) if ProductOfDivisors &lt;= 9999: print ProductOfDivisors else: result = str(ProductOfDivisors) print result[len(result)-4:] T = int(raw_input()) for i in range(1,T+1): num = int(raw_input()) divisorsProduct(num) </code></pre> <p>Thank You.</p>
3
2009-06-02T22:20:03Z
951,395
<p>Okay, I think this is close to the optimal algorithm. It produces the product_of_divisors for each number in range(500000).</p> <pre><code>import math def number_of_divisors(maxval=500001): """ Example: the number of divisors of 12 is 6: 1, 2, 3, 4, 6, 12. Given a prime factoring of n, the number of divisors of n is the product of each factor's multiplicity plus one (mpo in my variables). This function works like the Sieve of Eratosthenes, but marks each composite n with the multiplicity (plus one) of each prime factor. """ numdivs = [1] * maxval # multiplicative identity currmpo = [0] * maxval # standard logic for 2 &lt; p &lt; sqrt(maxval) for p in range(2, int(math.sqrt(maxval))): if numdivs[p] == 1: # if p is prime for exp in range(2,50): # assume maxval &lt; 2^50 pexp = p ** exp if pexp &gt; maxval: break exppo = exp + 1 for comp in range(pexp, maxval, pexp): currmpo[comp] = exppo for comp in range(p, maxval, p): thismpo = currmpo[comp] or 2 numdivs[comp] *= thismpo currmpo[comp] = 0 # reset currmpo array in place # abbreviated logic for p &gt; sqrt(maxval) for p in range(int(math.sqrt(maxval)), maxval): if numdivs[p] == 1: # if p is prime for comp in range(p, maxval, p): numdivs[comp] *= 2 return numdivs # this initialization times at 7s on my machine NUMDIV = number_of_divisors() def product_of_divisors(n): if NUMDIV[n] % 2 == 0: # each pair of divisors has product equal to n, for example # 1*12 * 2*6 * 3*4 = 12**3 return n ** (NUMDIV[n] / 2) else: # perfect squares have their square root as an unmatched divisor return n ** (NUMDIV[n] / 2) * int(math.sqrt(n)) # this loop times at 13s on my machine for n in range(500000): a = product_of_divisors(n) </code></pre> <p>On my very slow machine, it takes 7s to compute the numberofdivisors for each number, then 13s to compute the productofdivisors for each. Of course it can be sped up by translating it into C. (@someone with a fast machine: how long does it take on your machine?)</p>
1
2009-06-04T15:47:39Z
[ "python", "math" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
942,456
<p><strong>Edit:</strong> Turns out both of the "problems" I spotted here were based on a misunderstanding of the <code>tm</code> struct. I'll leave the answer intact for the sake of the discussion in the comments, but save your votes for someone who might actually be correct. ;-)</p> <p><hr /></p> <p>Caveat: I'm not terribly familiar with C time constructs; I'm mostly going off the field documentation supplied for <code>strftime</code>.</p> <p>I see two "bugs" in your port. First, I believe <code>tm_year</code> is intended to be the year without century, not the year minus 1900, so, <code>goldn</code> should be <code>((lt.year % 100) % 19) + 1</code>. Secondly, your calculation for <code>diy</code> is zero-based, whereas <code>tm_yday</code> appears (again, from the docs) to be one-based. However, I'm not certain about the latter, as fixing just the <code>goldn</code> line gives a correct result (at least for today), where as fixing both gives the wrong answer:</p> <pre><code>&gt;&gt;&gt; def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year % 100) % 19) + 1 epact = (11 * goldn + 18) % 30 if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) &gt;&gt;&gt; phase_of_the_moon(): 3 </code></pre> <p>Again, this is mostly guesswork. Please be kind. :-)</p>
3
2009-06-02T23:44:57Z
[ "python", "c", "time", "porting", "nethack" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
942,559
<p>Curiously, when I compile and run the nethack example I get "2" as the answer ("First Quarter" which is the same as your port)</p> <pre><code>#include &lt;time.h&gt; static struct tm * getlt() { time_t date; (void) time(&amp;date); return(localtime(&amp;date)); } /* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } int main(int argc, char * argv[]) { printf ("phase of the moon %d\n\n", phase_of_the_moon()); } </code></pre> <p>output:</p> <pre><code>&gt; a.out phase of the moon 2 </code></pre> <p>But that doesn't seem like the right answer, as today, weatherunderground.com and alt.org reports the phase of the moon as "Waxing Gibbous" (a.k.a 3).</p> <p>I tried remove the "-1900" but that didn't result in the right answer either.</p>
1
2009-06-03T00:27:40Z
[ "python", "c", "time", "porting", "nethack" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
942,628
<p>The code as written is largely untestable - and you need to make it testable. So, you need the C code to be:</p> <pre><code>int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); return testable_potm(lt); } static int testable_potm(const struct tm *lt) { register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Now you can run tests with multiple values of time. The alternative way to do this is to fake <code>getlt()</code> instead.</p> <p>You then need parallel changes in your Python code. Then you create a file of <code>time_t</code> values which can be read by both Python and C, and then converted into an appropriate structure (via <code>localtime()</code> in C). Then you can see where things are deviating.</p>
4
2009-06-03T00:54:48Z
[ "python", "c", "time", "porting", "nethack" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
1,945,192
<p>I like to think I know a thing or two about calendars, so let's see if I can clear a few things up.</p> <p>The Catholic Church defines the date of Easter in terms of lunar phases (this is why the date jumps around from year to year). Because of this, it needs to be able to calculate the approximate moon phase, and its algorithm for doing so is explained <a href="http://en.wikipedia.org/wiki/Computus" rel="nofollow">here</a>.</p> <p>I have not done very detailed checking, but it appears that the NetHack algorithm is based heavily on the Church's algorithm. The NetHack algorithm seems to, like the Church's algorithm, pay attention only to the calendar date, ignoring time zones and the time of day.</p> <p>The NetHack algorithm uses only the year and the day of the year. I can tell from examining the code that, to be Y2K compatible, that tm_year has to be the year minus 1900.</p>
0
2009-12-22T09:30:24Z
[ "python", "c", "time", "porting", "nethack" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
1,945,256
<p>Following code is <a href="http://www.daniweb.com/code/post968407.html" rel="nofollow">borrowed from this site</a>, pasting it here for easy reference (and in case the other site goes down). Seems to do what you want.</p> <pre><code># Determine the moon phase of a date given # Python code by HAB def moon_phase(month, day, year): ages = [18, 0, 11, 22, 3, 14, 25, 6, 17, 28, 9, 20, 1, 12, 23, 4, 15, 26, 7] offsets = [-1, 1, 0, 1, 2, 3, 4, 5, 7, 7, 9, 9] description = ["new (totally dark)", "waxing crescent (increasing to full)", "in its first quarter (increasing to full)", "waxing gibbous (increasing to full)", "full (full light)", "waning gibbous (decreasing from full)", "in its last quarter (decreasing from full)", "waning crescent (decreasing from full)"] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] if day == 31: day = 1 days_into_phase = ((ages[(year + 1) % 19] + ((day + offsets[month-1]) % 30) + (year &lt; 1900)) % 30) index = int((days_into_phase + 2) * 16/59.0) if index &gt; 7: index = 7 status = description[index] # light should be 100% 15 days into phase light = int(2 * days_into_phase * 100/29) if light &gt; 100: light = abs(light - 200); date = "%d%s%d" % (day, months[month-1], year) return date, status, light # put in a date you want ... month = 5 day = 14 year = 2006 # use yyyy format date, status, light = moon_phase(month, day, year) print "moon phase on %s is %s, light = %d%s" % (date, status, light, '%') </code></pre> <p>You can use the <code>time</code> module to get the <strong>current local time</strong>. Heres how I did it (paste below posted code to testrun):</p> <pre><code>import time tm = time.localtime() month = tm.tm_mon day = tm.tm_mday year = tm.tm_year date, status, light = moon_phase(month, day, year) print "moon phase on %s is %s, light = %d%s" % (date, status, light, '%') </code></pre> <p>Output:</p> <pre><code>moon phase on 22Dec2009 is waxing crescent (increasing to full), light = 34% </code></pre> <p>Moon stuff is fun. :) </p>
1
2009-12-22T09:42:18Z
[ "python", "c", "time", "porting", "nethack" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
4,066,395
<p>Here is my conversion of it, and I've tested this against the C code by passing in values from xrange(0, 1288578760, 3601), and they both return the same values. Note that I've changed it so that you can pass the seconds since epoch, so that I could test it against the C version for a third of a million different values. The "seconds" value is optional</p> <pre><code>def phase_of_the_moon(seconds = None): '0-7, with 0: new, 4: full' import time if seconds == None: seconds = time.time() lt = time.localtime(seconds) tm_year = lt.tm_year - 1900 diy = lt.tm_yday - 1 goldn = (tm_year % 19) + 1 epact = (11 * goldn + 18) % 30 if (epact == 25 and goldn > 11) or epact == 24: epact += 1 return (((((diy + epact) * 6) + 11) % 177) / 22) & 7</code></pre>
0
2010-11-01T02:56:56Z
[ "python", "c", "time", "porting", "nethack" ]
Help me to port this NetHack function to Python please!
942,328
<p>I am trying to write a Python function which returns the same moon phase value as in the game NetHack. This is found in <a href="http://nethack.wikia.com/wiki/Source:Hacklib.c#phase%5Fof%5Fthe%5Fmoon" rel="nofollow">hacklib.c</a>.</p> <p>I have tried to simply copy the corresponding function from the NetHack code but I don't believe I am getting the correct results.</p> <p>The function which I have written is <code>phase_of_the_moon()</code>.</p> <p>The functions <code>position()</code> and <code>phase()</code>, I found on the net, and I am using them as an indication of the success of my function. They are very accurate and give results which approximately match the nethack.alt.org server (see <a href="http://alt.org/nethack/moon/pom.txt" rel="nofollow">http://alt.org/nethack/moon/pom.txt</a>). What I am after however is an exact replication of the original NetHack function, idiosyncrasies intact.</p> <p>I would expect my function and the 'control' function to give the same moon phase at least, but currently they do not and I'm not sure why!!</p> <p>Any help would be appreciated,</p> <p>Thanks.</p> <p>Here is the NetHack code:</p> <pre><code>/* * moon period = 29.53058 days ~= 30, year = 365.2422 days * days moon phase advances on first day of year compared to preceding year * = 365.2422 - 12*29.53058 ~= 11 * years in Metonic cycle (time until same phases fall on the same days of * the month) = 18.6 ~= 19 * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30 * (29 as initial condition) * current phase in days = first day phase + days elapsed in year * 6 moons ~= 177 days * 177 ~= 8 reported phases * 22 * + 11/22 for rounding */ int phase_of_the_moon() /* 0-7, with 0: new, 4: full */ { register struct tm *lt = getlt(); register int epact, diy, goldn; diy = lt-&gt;tm_yday; goldn = (lt-&gt;tm_year % 19) + 1; epact = (11 * goldn + 18) % 30; if ((epact == 25 &amp;&amp; goldn &gt; 11) || epact == 24) epact++; return( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ); } </code></pre> <p>Here is the <code>getlt()</code> function (also in hacklib.c):</p> <pre><code>static struct tm * getlt() { time_t date; #if defined(BSD) &amp;&amp; !defined(POSIX_TYPES) (void) time((long *)(&amp;date)); #else (void) time(&amp;date); #endif #if (defined(ULTRIX) &amp;&amp; !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) &amp;&amp; !defined(POSIX_TYPES)) return(localtime((long *)(&amp;date))); #else return(localtime(&amp;date)); #endif } </code></pre> <p>Here is my Python code:</p> <pre><code>from datetime import date def phase_of_the_moon(): lt = date.today() diy = (lt - date(lt.year, 1, 1)).days goldn = ((lt.year - 1900) % 19) + 1 epact = (11 * goldn + 18) % 30; if ((epact == 25 and goldn &gt; 11) or epact == 24): epact += 1 return ( (((((diy + epact) * 6) + 11) % 177) / 22) &amp; 7 ) import math, decimal, datetime dec = decimal.Decimal def position(now=None): if now is None: now = datetime.datetime.now() diff = now - datetime.datetime(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) return lunations % dec(1) def phase(pos): index = (pos * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(index) &amp; 7] def phase2(pos): return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent" }[int(pos)] def main(): ## Correct output pos = position() phasename = phase(pos) roundedpos = round(float(pos), 3) print "%s (%s)" % (phasename, roundedpos) ## My output print "%s (%s)" % (phase2(phase_of_the_moon()), phase_of_the_moon()) if __name__=="__main__": main() </code></pre>
9
2009-06-02T22:53:55Z
5,161,447
<p>I'm long late on this thread but fwiw, the alt.org server's display of pom via the web only updates on cron a couple times per day so if you're off by just a bit from it, that could be the reason. The game itself runs from whatever is in the nethack code itself so doesn't suffer the same caching issue. -drew (alt.org owner)</p>
2
2011-03-01T22:58:43Z
[ "python", "c", "time", "porting", "nethack" ]
Operation on every pair of element in a list
942,543
<p>Using Python, I'd like to compare every possible pair in a list.</p> <p>Suppose I have</p> <pre><code>my_list = [1,2,3,4] </code></pre> <p>I'd like to do an operation (let's call it foo) on every combination of 2 elements from the list.</p> <p>The final result should be the same as</p> <pre><code>foo(1,1) foo(1,2) ... foo(4,3) foo(4,4) </code></pre> <p>My first thought was to iterate twice through the list manually, but that doesn't seem very pythonic.</p>
25
2009-06-03T00:21:23Z
942,551
<p>Check out <a href="http://docs.python.org/library/itertools.html#itertools.product"><code>product()</code></a> in the <code>itertools</code> module. It does exactly what you describe.</p> <pre><code>import itertools my_list = [1,2,3,4] for pair in itertools.product(my_list, repeat=2): foo(*pair) </code></pre> <p>This is equivalent to:</p> <pre><code>my_list = [1,2,3,4] for x in my_list: for y in my_list: foo(x, y) </code></pre> <p><strong>Edit:</strong> There are two very similar functions as well, <a href="http://docs.python.org/library/itertools.html#itertools.permutations"><code>permutations()</code></a> and <a href="http://docs.python.org/library/itertools.html#itertools.combinations"><code>combinations()</code></a>. To illustrate how they differ:</p> <p><code>product()</code> generates every possible pairing of elements, including all duplicates:</p> <pre><code>1,1 1,2 1,3 1,4 2,1 2,2 2,3 2,4 3,1 3,2 3,3 3,4 4,1 4,2 4,3 4,4 </code></pre> <p><code>permutations()</code> generates all unique orderings of each unique pair of elements, eliminating the <code>x,x</code> duplicates:</p> <pre><code> . 1,2 1,3 1,4 2,1 . 2,3 2,4 3,1 3,2 . 3,4 4,1 4,2 4,3 . </code></pre> <p>Finally, <code>combinations()</code> only generates each unique pair of elements, in lexicographic order:</p> <pre><code> . 1,2 1,3 1,4 . . 2,3 2,4 . . . 3,4 . . . . </code></pre> <p>All three of these functions were introduced in Python 2.6.</p>
89
2009-06-03T00:24:43Z
[ "python" ]
Operation on every pair of element in a list
942,543
<p>Using Python, I'd like to compare every possible pair in a list.</p> <p>Suppose I have</p> <pre><code>my_list = [1,2,3,4] </code></pre> <p>I'd like to do an operation (let's call it foo) on every combination of 2 elements from the list.</p> <p>The final result should be the same as</p> <pre><code>foo(1,1) foo(1,2) ... foo(4,3) foo(4,4) </code></pre> <p>My first thought was to iterate twice through the list manually, but that doesn't seem very pythonic.</p>
25
2009-06-03T00:21:23Z
942,565
<p>If you're just calling a function, you can't really do much better than:</p> <pre><code>for i in my_list: for j in my_list: foo(i, j) </code></pre> <p>If you want to collect a list of the results of calling the function, you can do:</p> <pre><code>[foo(i, j) for i my_list for j in my_list] </code></pre> <p>which will return you a list of the result of applying <code>foo(i, j)</code> to each possible pair <code>(i, j)</code>.</p>
1
2009-06-03T00:29:43Z
[ "python" ]
Operation on every pair of element in a list
942,543
<p>Using Python, I'd like to compare every possible pair in a list.</p> <p>Suppose I have</p> <pre><code>my_list = [1,2,3,4] </code></pre> <p>I'd like to do an operation (let's call it foo) on every combination of 2 elements from the list.</p> <p>The final result should be the same as</p> <pre><code>foo(1,1) foo(1,2) ... foo(4,3) foo(4,4) </code></pre> <p>My first thought was to iterate twice through the list manually, but that doesn't seem very pythonic.</p>
25
2009-06-03T00:21:23Z
37,907,649
<p>I had a similar problem and found the solution <a href="http://www.wellho.net/resources/ex.php4?item=y104/tessapy" rel="nofollow">here</a>. It works without having to import any module.</p> <p>Supposing a list like:</p> <pre><code>people = ["Lisa","Pam","Phil","John"] </code></pre> <p>A simplified one-line solution would look like this.</p> <p><strong>All possible pairs</strong>, including duplicates:</p> <pre><code>result = [foo(p1, p2) for p1 in people for p2 in people] </code></pre> <p><strong>All possible pairs, excluding duplicates</strong>:</p> <pre><code>result = [foo(p1, p2) for p1 in people for p2 in people if p1 != p2] </code></pre> <p><strong>Unique pairs</strong>, where order is irrelevant:</p> <pre><code>result = [foo(people[p1], people[p2]) for p1 in range(len(people)) for p2 in range(p1+1,len(people))] </code></pre> <hr> <p>In case you don't want to operate but just to get the pairs, removing the word <code>foo</code> would be enough.</p> <p><strong>All possible pairs</strong>, including duplicates:</p> <pre><code>list_of_pairs = [(p1, p2) for p1 in people for p2 in people] </code></pre> <p>Result:</p> <pre><code>('Lisa', 'Lisa') ('Lisa', 'Pam') ('Lisa', 'Phil') ('Lisa', 'John') ('Pam', 'Lisa') ('Pam', 'Pam') ('Pam', 'Phil') ('Pam', 'John') ('Phil', 'Lisa') ('Phil', 'Pam') ('Phil', 'Phil') ('Phil', 'John') ('John', 'Lisa') ('John', 'Pam') ('John', 'Phil') ('John', 'John') </code></pre> <p><strong>All possible pairs, excluding duplicates</strong>:</p> <pre><code>list_of_pairs = [(p1, p2) for p1 in people for p2 in people if p1 != p2] </code></pre> <p>Result:</p> <pre><code>('Lisa', 'Pam') ('Lisa', 'Phil') ('Lisa', 'John') ('Pam', 'Lisa') ('Pam', 'Phil') ('Pam', 'John') ('Phil', 'Lisa') ('Phil', 'Pam') ('Phil', 'John') ('John', 'Lisa') ('John', 'Pam') ('John', 'Phil') </code></pre> <p><strong>Unique pairs</strong>, where order is irrelevant:</p> <pre><code>list_of_pairs = [(people[p1], people[p2]) for p1 in range(len(people)) for p2 in range(p1+1,len(people))] </code></pre> <p>Result:</p> <pre><code>('Lisa', 'Pam') ('Lisa', 'Phil') ('Lisa', 'John') ('Pam', 'Phil') ('Pam', 'John') ('Phil', 'John') </code></pre> <p><em>Edit: After the rework to simplify this solution, I realised it is the same approach than Adam Rosenfield. I hope the larger explanation helps some to understand it better.</em></p>
1
2016-06-19T13:15:38Z
[ "python" ]
Missing 'Median' Aggregate Function in Django?
942,620
<p>The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance (<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8">link text</a>). Is there a reason Median is missing from the list? </p> <p>Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes?</p>
8
2009-06-03T00:51:25Z
942,633
<p>Well, the <em>reason</em> is probably that you need to track all the numbers to calculate median. Avg, Count, Max, Min, StDev, Sum, and Variance can all be calculated with constant storage needs. That is, once you "record" a number you'll never need it again.</p> <p>FWIW, the variables you need to track are: min, max, count, <code>&lt;n&gt;</code> = avg, <code>&lt;n^2&gt;</code> = avg of the square of the values.</p>
7
2009-06-03T00:57:17Z
[ "python", "django", "aggregate-functions" ]
Missing 'Median' Aggregate Function in Django?
942,620
<p>The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance (<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8">link text</a>). Is there a reason Median is missing from the list? </p> <p>Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes?</p>
8
2009-06-03T00:51:25Z
942,638
<p>A strong possibility is that median is not part of standard SQL. </p> <p>Also, it requires a sort, making it quite expensive to compute.</p>
2
2009-06-03T00:59:05Z
[ "python", "django", "aggregate-functions" ]
Missing 'Median' Aggregate Function in Django?
942,620
<p>The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance (<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8">link text</a>). Is there a reason Median is missing from the list? </p> <p>Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes?</p>
8
2009-06-03T00:51:25Z
942,940
<p>Because median isn't a SQL aggregate. See, for example, the <a href="http://www.postgresql.org/docs/8.3/static/functions-aggregate.html">list of PostgreSQL aggregate functions</a> and <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html">the list of MySQL aggregate functions</a>.</p>
12
2009-06-03T03:27:26Z
[ "python", "django", "aggregate-functions" ]
Missing 'Median' Aggregate Function in Django?
942,620
<p>The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance (<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8">link text</a>). Is there a reason Median is missing from the list? </p> <p>Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes?</p>
8
2009-06-03T00:51:25Z
942,985
<p>I have no idea what db backend you are using, but if your db supports another aggregate, or you can find a clever way of doing it, You can probably access it easily by <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/aggregates.py" rel="nofollow">Aggregate</a>.</p>
2
2009-06-03T03:56:12Z
[ "python", "django", "aggregate-functions" ]
Missing 'Median' Aggregate Function in Django?
942,620
<p>The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance (<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8">link text</a>). Is there a reason Median is missing from the list? </p> <p>Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes?</p>
8
2009-06-03T00:51:25Z
6,595,428
<p>FWIW, you can extend PostgreSQL 8.4 and above to have a median aggregate function with <a href="http://wiki.postgresql.org/wiki/Aggregate_Median" rel="nofollow">these code snippets</a>.</p> <p>Other code snippets (which work for older versions of PostgreSQL) are <a href="http://www.postgresonline.com/journal/archives/67-Build-Median-Aggregate-Function-in-SQL.html" rel="nofollow">shown here</a>. Be sure to read the comments for this resource.</p>
1
2011-07-06T11:09:41Z
[ "python", "django", "aggregate-functions" ]
Missing 'Median' Aggregate Function in Django?
942,620
<p>The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance (<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8">link text</a>). Is there a reason Median is missing from the list? </p> <p>Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes?</p>
8
2009-06-03T00:51:25Z
9,503,282
<p>Here's your missing function. Pass it a queryset and the name of the column that you want to find the median for:</p> <pre><code>def median_value(queryset, term): count = queryset.count() return queryset.values_list(term, flat=True).order_by(term)[int(round(count/2))] </code></pre> <p>That wasn't as hard as some of the other responses seem to indicate. The important thing is to let the db sorting do all of the work, so if you have the column already indexed, this is a super cheap operation.</p> <p><em>(update 1/28/2016)</em> If you want to be more strict about the definition of median for an even number of items, this will average together the value of the two middle values.</p> <pre><code>def median_value(queryset, term): count = queryset.count() values = queryset.values_list(term, flat=True).order_by(term) if count % 2 == 1: return values[int(round(count/2))] else: return sum(values[count/2-1:count/2+1])/2.0 </code></pre>
12
2012-02-29T16:56:05Z
[ "python", "django", "aggregate-functions" ]
How to Change Mouse Cursor in PythonCard
942,730
<p>How do I change the mouse cursor to indicate a waiting state using Python and PythonCard? </p> <p>I didn't see anything in the documentation.</p>
0
2009-06-03T01:46:13Z
942,839
<p>PythonCard builds on top of wx, so if you import wx you should be able to build a suitable cursor (e.g. with <code>wx.CursorFromImage</code>), set it (e.g. with <code>wx.BeginBusyCursor</code>) when your wait begins, and end it (with <code>wx.EndBusyCursor</code>) when your wait ends.</p>
1
2009-06-03T02:42:28Z
[ "python", "user-interface", "mouse", "cursor", "pythoncard" ]
Is a list or dictionary faster in Python?
942,902
<p>How much of a difference are these two as far as performance?</p> <pre><code>tmp = [] tmp.append(True) print tmp[0] </code></pre> <p>And</p> <pre><code>tmp = {} tmp[0] = True print tmp[0] </code></pre>
1
2009-06-03T03:14:39Z
942,924
<p>The <code>timeit</code> module in the standard library is designed just to answer such questions! Forget the <code>print</code> (which would have the nasty side effect of spewing stuff to your terminal;-) and compare:</p> <pre><code>$ python -mtimeit 'tmp=[]; tmp.append(True); x=tmp[0]' 1000000 loops, best of 3: 0.716 usec per loop $ python -mtimeit 'tmp={}; tmp[0]=True; x=tmp[0]' 1000000 loops, best of 3: 0.515 usec per loop </code></pre> <p>So, the dict is the winner -- by 0.2 microseconds...!-)</p>
18
2009-06-03T03:21:04Z
[ "python", "data-structures" ]
Is a list or dictionary faster in Python?
942,902
<p>How much of a difference are these two as far as performance?</p> <pre><code>tmp = [] tmp.append(True) print tmp[0] </code></pre> <p>And</p> <pre><code>tmp = {} tmp[0] = True print tmp[0] </code></pre>
1
2009-06-03T03:14:39Z
942,931
<p>they are equitable in my testing</p>
0
2009-06-03T03:25:26Z
[ "python", "data-structures" ]
Is a list or dictionary faster in Python?
942,902
<p>How much of a difference are these two as far as performance?</p> <pre><code>tmp = [] tmp.append(True) print tmp[0] </code></pre> <p>And</p> <pre><code>tmp = {} tmp[0] = True print tmp[0] </code></pre>
1
2009-06-03T03:14:39Z
942,933
<p>Of course there will be a slight difference, but honestly you shouldn't be worrying about this. What you're doing is <a href="https://web.archive.org/web/20120131020641/http://ajbrown.org/blog/2008/11/05/micro-optimize-your-time-not-your-code.html" rel="nofollow">micro-optimizing</a> your code, which is something you should avoid. In essence, you're wasting time optimizing something that won't make any difference in your application at all, when you could be spending that time doing something worthwhile.</p> <p>So is there a difference in speed between the two examples you posted? Certainly. Is it going to matter? Nope. :)</p>
1
2009-06-03T03:25:35Z
[ "python", "data-structures" ]
Is a list or dictionary faster in Python?
942,902
<p>How much of a difference are these two as far as performance?</p> <pre><code>tmp = [] tmp.append(True) print tmp[0] </code></pre> <p>And</p> <pre><code>tmp = {} tmp[0] = True print tmp[0] </code></pre>
1
2009-06-03T03:14:39Z
943,046
<p>Not only is micro-optimization usually pointless in general, I find it is especially difficult and arcane for Python in particular. It is very easy to actually make your code simultaneously slower and more complicated. See <a href="http://stackoverflow.com/questions/900420/elegant-way-to-compare-sequences">this Stack Overflow question</a> for an example where the simplest, clearest, and shortest Python solutions also turned out to be the fastest.</p> <p>As others have shown with actual tests, the speed difference between your two choices is quite small. What is less small is the semantic difference. Lists and dictionaries are not merely two implementations of the same concept, but are intended for different uses. Pick the one which better fits your use.</p>
6
2009-06-03T04:22:49Z
[ "python", "data-structures" ]
Flash-based file upload (swfupload) fails with Apache/mod-wsgi
943,000
<p><strong>This question has been retitled/retagged so that others may more easily find the solution to this problem.</strong></p> <p><hr /></p> <p>I am in the process of trying to migrate a project from the Django development server to a Apache/mod-wsgi environment. If you had asked me yesterday I would have said the transition was going very smoothly. My site is up, accessible, fast, etc. However, a portion of the site relies on file uploads and with this I am experiencing the strangest and most maddening issue. The particular page in question uses <a href="http://swfupload.org/" rel="nofollow">swfupload</a> to POST a file and associated metadata to a url which catches the file and initiates some server-side processing. This works perfectly on the development server, but whenever I POST to this url on Apache the Django request object comes up empty--<strong>no GET, POST, or FILES data</strong>.</p> <p>I have eliminated client-side issues by snooping with Wireshark. As far as I can discern the root cause stems from some sort of Apache configuration issue, possibly related to the temporary file directory I am trying to access. I am a relative newcomer to Apache configuration and have been banging my head against this for hours.</p> <p>My Apache config:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin user@sitename.com ServerName sitename.com ServerAlias www.sitename.com LogLevel warn WSGIDaemonProcess sitename processes=2 maximum-requests=500 threads=1 WSGIProcessGroup sitename WSGIScriptAlias / /home/user/src/sitename/apache/django.wsgi Alias /static /home/user/src/sitename/static Alias /media /usr/share/python-support/python-django/django/contrib/admin/media &lt;/VirtualHost&gt; </code></pre> <p>My intuition is that this may have something to do with the permissions of the file upload directory I have specified in my Django settings.py (<code>'/home/sk/src/sitename/uploads/'</code>), however my Apache error log doesn't suggest anything of the sort, even with the log level bumped up to debug.</p> <p>Suggestions on how I should go about debugging this?</p>
0
2009-06-03T04:05:37Z
943,117
<p>Normally apache runs as a user "www-data"; and you could have problems if it doesn't have read/write access. However, your setup doesn't seem to use apache to access the '/home/sk/src/sitename/uploads'; my understanding from this config file is unless it hit /static or /media, apache will hand it off WGSI, so it might be good to check out those permissions and logs, rather than the apache ones.</p>
3
2009-06-03T04:54:55Z
[ "python", "flash", "apache", "file-upload", "mod-wsgi" ]
Flash-based file upload (swfupload) fails with Apache/mod-wsgi
943,000
<p><strong>This question has been retitled/retagged so that others may more easily find the solution to this problem.</strong></p> <p><hr /></p> <p>I am in the process of trying to migrate a project from the Django development server to a Apache/mod-wsgi environment. If you had asked me yesterday I would have said the transition was going very smoothly. My site is up, accessible, fast, etc. However, a portion of the site relies on file uploads and with this I am experiencing the strangest and most maddening issue. The particular page in question uses <a href="http://swfupload.org/" rel="nofollow">swfupload</a> to POST a file and associated metadata to a url which catches the file and initiates some server-side processing. This works perfectly on the development server, but whenever I POST to this url on Apache the Django request object comes up empty--<strong>no GET, POST, or FILES data</strong>.</p> <p>I have eliminated client-side issues by snooping with Wireshark. As far as I can discern the root cause stems from some sort of Apache configuration issue, possibly related to the temporary file directory I am trying to access. I am a relative newcomer to Apache configuration and have been banging my head against this for hours.</p> <p>My Apache config:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin user@sitename.com ServerName sitename.com ServerAlias www.sitename.com LogLevel warn WSGIDaemonProcess sitename processes=2 maximum-requests=500 threads=1 WSGIProcessGroup sitename WSGIScriptAlias / /home/user/src/sitename/apache/django.wsgi Alias /static /home/user/src/sitename/static Alias /media /usr/share/python-support/python-django/django/contrib/admin/media &lt;/VirtualHost&gt; </code></pre> <p>My intuition is that this may have something to do with the permissions of the file upload directory I have specified in my Django settings.py (<code>'/home/sk/src/sitename/uploads/'</code>), however my Apache error log doesn't suggest anything of the sort, even with the log level bumped up to debug.</p> <p>Suggestions on how I should go about debugging this?</p>
0
2009-06-03T04:05:37Z
943,476
<p>Another possibility is a bug in "old" releases of mod_wsgi (I got crazy to find, and fix, it). More info in this <a href="http://code.google.com/p/modwsgi/issues/detail?id=121" rel="nofollow">bug report</a>. I fixed it (for curl uploads) thanks to the <a href="http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/" rel="nofollow">following hint</a> (that works on the CLI too, using the -H switch).</p>
2
2009-06-03T07:18:33Z
[ "python", "flash", "apache", "file-upload", "mod-wsgi" ]
Benefit of installing Django from .deb versus .tar.gz?
943,242
<p>I'm starting Django development, and I can either install it from the .deb using</p> <pre><code>$ apt-get install python-django </code></pre> <p>on my Ubuntu machine, or I can download the .tar.gz from <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>, and start with that.</p> <p>What are the benefits and drawbacks of each approach?</p>
4
2009-06-03T05:50:43Z
943,264
<p>Using apt-get you'll get better uninstall support via the package manager and it can also install dependencies for you. If you install with apt-get you might get automatic updates, which is very nice for security patches.</p> <p>With the tar you might get a newer version and you might get the opportunity to tailor the compile flags. A build could be more optimized for your particular processor, but since it's python that doesn't matter in this case.</p>
4
2009-06-03T05:58:57Z
[ "python", "django", "ubuntu", "apt-get" ]
Benefit of installing Django from .deb versus .tar.gz?
943,242
<p>I'm starting Django development, and I can either install it from the .deb using</p> <pre><code>$ apt-get install python-django </code></pre> <p>on my Ubuntu machine, or I can download the .tar.gz from <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>, and start with that.</p> <p>What are the benefits and drawbacks of each approach?</p>
4
2009-06-03T05:50:43Z
943,265
<p>Using <code>apt-get</code> lets your system keep track of the install (e.g. if you want to disinstall, upgrade, or the like, late). Installing from source (<code>.tar.gz</code> or otherwise) puts you in charge of what's what and where -- you can have multiple versions installed at various locations, etc, but there's no easy "uninstall" and the like. Personally I prefer to install by my OS's supported method (<code>apt-get</code> and the like) for packages I think as secondary or auxiliary, directly from svn/hg/&amp;c for ones I'm contributing to or otherwise want to keep the closest control on, and <code>.tar.gz</code> (or better when available <code>.tar.bz2</code>;-) "snapshots" and "source releases" that are s/where in the middle...</p>
8
2009-06-03T05:59:05Z
[ "python", "django", "ubuntu", "apt-get" ]
Benefit of installing Django from .deb versus .tar.gz?
943,242
<p>I'm starting Django development, and I can either install it from the .deb using</p> <pre><code>$ apt-get install python-django </code></pre> <p>on my Ubuntu machine, or I can download the .tar.gz from <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>, and start with that.</p> <p>What are the benefits and drawbacks of each approach?</p>
4
2009-06-03T05:50:43Z
943,313
<p>I've always installed using the dev version. <a href="http://docs.djangoproject.com/en/dev/topics/install/#installing-development-version" rel="nofollow">(Instructions)</a></p> <p>This makes updating really easy and gives you all the fancy features in the /dev/ docs. I would suggest you try going this route if possible (if anything it gives you an idea of how site-packages work).</p> <p>Note: ubuntu 9.04's recent move to dist-packages from site-packages (8.04) made this a bit confusing, had to recreate the link.</p>
0
2009-06-03T06:18:44Z
[ "python", "django", "ubuntu", "apt-get" ]
Benefit of installing Django from .deb versus .tar.gz?
943,242
<p>I'm starting Django development, and I can either install it from the .deb using</p> <pre><code>$ apt-get install python-django </code></pre> <p>on my Ubuntu machine, or I can download the .tar.gz from <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>, and start with that.</p> <p>What are the benefits and drawbacks of each approach?</p>
4
2009-06-03T05:50:43Z
943,415
<p>The best way to install is to check out the code, which ever the changeset (branch/tag) you want, and define a symbolic link to it</p> <p>Checkout the version you want:</p> <pre><code># For trunk svn co http://code.djangoproject.com/svn/django/trunk/ django-trunk # For a tag, 1.02 release svn co http://code.djangoproject.com/svn/django/tag/1.02 django-1.02 # To update the trunk cd django-trunk svn up </code></pre> <p>Then define symbolic link</p> <pre><code>ln -fs /usr/lib/python2.5/site-packages/django/* ~/django-1.02/ </code></pre> <p>If you want to test your code in the latest release, just redefine the symbolic link:</p> <pre><code>ln -fs /usr/lib/python2.5/site-packages/django/* ~/django-trunk/ </code></pre> <p>The package managers aptitude and apt-get are good for auto updating those software you don't really bother about developing with every day, like media players, browsers. For stuff U code with everyday, full control of versions is needed, you get that only by source.</p>
6
2009-06-03T06:51:48Z
[ "python", "django", "ubuntu", "apt-get" ]
Benefit of installing Django from .deb versus .tar.gz?
943,242
<p>I'm starting Django development, and I can either install it from the .deb using</p> <pre><code>$ apt-get install python-django </code></pre> <p>on my Ubuntu machine, or I can download the .tar.gz from <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>, and start with that.</p> <p>What are the benefits and drawbacks of each approach?</p>
4
2009-06-03T05:50:43Z
943,660
<p>I know with debian and probably some other distros, the version of django in the package manager is the 0.9 branch, not the 1.X branch. Definately something you want to avoid.</p>
0
2009-06-03T08:35:01Z
[ "python", "django", "ubuntu", "apt-get" ]
Benefit of installing Django from .deb versus .tar.gz?
943,242
<p>I'm starting Django development, and I can either install it from the .deb using</p> <pre><code>$ apt-get install python-django </code></pre> <p>on my Ubuntu machine, or I can download the .tar.gz from <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>, and start with that.</p> <p>What are the benefits and drawbacks of each approach?</p>
4
2009-06-03T05:50:43Z
944,831
<p>Getting Django from your Ubuntu repository gives you the older "stable" version. This may be fine with you, but I believe most developers prefer sticking with latest code available in the trunk to get more features.</p> <p>IMHO the cleanest solution is not to install .tar.gz/SVN version with straightforward <code>sudo python setup.py install</code> (or use <code>easy-install</code>) but to make a .deb package. This way you should get the maximum benefits: 1) all the bleeding edge features you want 2) proper Debian/Ubuntu package, which you may easily uninstall, upgrade and deploy to any number of Debian machines.</p> <p>Here's a quick and dirty way how to do it:</p> <pre><code># # This is dirty (you have been warned) way to quickly # make new Django .deb package from SVN trunk for personal use. # apt-get source python-django apt-get build-dep python-django svn co http://code.djangoproject.com/svn/django/trunk/ django-trunk DJANGO_SVN_REVISION=`LC_ALL=C svn info django-trunk \ | grep ^Revision: | awk '{ print $2 }'` cp -R python-django-*/debian django-trunk/ cd django-trunk dch --newversion=1.1-1ubuntu1~svn${DJANGO_SVN_REVISION} \ "Non-maintainer quick-and-dirty update to SVN r${DJANGO_SVN_REVISION}" dpkg-buildpackage # Have a good sip of tea, coffee or whatever you prefer. # Because of tests, this is going to take quite a while. # You may consider disabling (this is bad!) tests by commenting out # line mentioning "runtests.py" in debian/rules. cd .. dpkg -i python-django_*.deb </code></pre> <p>This is not even really guarranteed to work (and I'm not really sure even about proper package version naming), but I've tried it myself and it worked for me.</p>
1
2009-06-03T13:43:54Z
[ "python", "django", "ubuntu", "apt-get" ]