title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Passing kwargs from template to view?
1,269,544
<p>As you may be able to tell from my questions, I'm new to both python and django. I would like to allow dynamic filter specifications of query sets from my templates using <code>**kwargs</code>. I'm thinking like a select box of a bunch of kwargs. For example:</p> <pre><code> &lt;select id="filter"&gt; &lt;option value="physician__isnull=True"&gt;Unassigned patients&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Does django provide an elegant solution to this problem that I haven't come across yet?</p> <p>I'm trying to solve this in a generic manner since I need to pass this filter to other views. For example, I need to pass a filter to a paginated patient list view, so the pagination knows what items it's working with. Another example is this filter would have to be passed to a patient detail page so you can iterate through the filtered list of patients with prev/next links.</p> <p>Thanks a bunch, Pete</p> <p><strong>Update:</strong></p> <p>What I came up with was building a <code>FilterSpecification</code> class:</p> <pre><code>class FilterSpec(object): def __init__(self, name, *args): super(FilterSpec, self).__init__() self.name = name self.filters = [] for filter in args: self.add(filter) def pickle(self): return encrypt(pickle.dumps(self)) def add(self, f): self.filters.append(f) def kwargs(self): kwargs = {} for f in self.filters: kwargs = f.kwarg(**kwargs) return kwargs def __unicode__(self): return self.name class Filter(object): def __init__(self, key, value): super(Filter, self).__init__() self.filter_key = key self.filter_value = value def kwarg(self, **kwargs): if self.filter_key != None: kwargs[self.filter_key] = self.filter_value return kwargs </code></pre> <p>I then can filter any type of model like this:</p> <pre><code>filterSpec = FilterSpec('Assigned', Filter('service__isnull', False))) patients = Patient.objects.filter(**filterSpec.kwargs()) </code></pre> <p>I pass these filterSpec objects from the client to server by serializing, compressing, applying some symmetric encryption, and url-safe base-64 encoding. The only downside is that you end up with URLs looking like this:</p> <pre><code>http://127.0.0.1:8000/hospitalists/assign_test/?filter=eJwBHQHi_iDiTrccFpHA4It7zvtNIW5nUdRAxdiT-cZStYhy0PHezZH2Q7zmJB-NGAdYY4Q60Tr_gT_Jjy_bXfB6iR8inrNOVkXKVvLz3SCVrCktGc4thePSNAKoBtJHkcuoaf9YJA5q9f_1i6uh45-6k7ZyXntRu5CVEsm0n1u5T1vdMwMnaNA8QzYk4ecsxJRSy6SMbUHIGhDiwHHj1UnQaOWtCSJEt2zVxaurMuCRFT2bOKlj5nHfXCBTUCh4u3aqZZjmSd2CGMXZ8Pn3QGBppWhZQZFztP_1qKJaqSVeTNnDWpehbMvqabpivtnFTxwszJQw9BMcCBNTpvJf3jUGarw_dJ89VX12LuxALsketkPbYhXzXNxTK1PiZBYqGfBbioaYkjo%3D </code></pre> <p>I would love to get some comments on this approach and hear other solutions.</p>
1
2009-08-13T01:09:18Z
1,270,117
<p>Rather than face the horrible dangers of SQL injection, why not just assign a value to each select option and have your form-handling view run the selected query based on the value.</p> <p>Passing the parameters for a DB query from page to view is just asking for disaster. Django is built to avoid this sort of thing.</p>
1
2009-08-13T05:04:41Z
[ "python", "django" ]
Passing kwargs from template to view?
1,269,544
<p>As you may be able to tell from my questions, I'm new to both python and django. I would like to allow dynamic filter specifications of query sets from my templates using <code>**kwargs</code>. I'm thinking like a select box of a bunch of kwargs. For example:</p> <pre><code> &lt;select id="filter"&gt; &lt;option value="physician__isnull=True"&gt;Unassigned patients&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Does django provide an elegant solution to this problem that I haven't come across yet?</p> <p>I'm trying to solve this in a generic manner since I need to pass this filter to other views. For example, I need to pass a filter to a paginated patient list view, so the pagination knows what items it's working with. Another example is this filter would have to be passed to a patient detail page so you can iterate through the filtered list of patients with prev/next links.</p> <p>Thanks a bunch, Pete</p> <p><strong>Update:</strong></p> <p>What I came up with was building a <code>FilterSpecification</code> class:</p> <pre><code>class FilterSpec(object): def __init__(self, name, *args): super(FilterSpec, self).__init__() self.name = name self.filters = [] for filter in args: self.add(filter) def pickle(self): return encrypt(pickle.dumps(self)) def add(self, f): self.filters.append(f) def kwargs(self): kwargs = {} for f in self.filters: kwargs = f.kwarg(**kwargs) return kwargs def __unicode__(self): return self.name class Filter(object): def __init__(self, key, value): super(Filter, self).__init__() self.filter_key = key self.filter_value = value def kwarg(self, **kwargs): if self.filter_key != None: kwargs[self.filter_key] = self.filter_value return kwargs </code></pre> <p>I then can filter any type of model like this:</p> <pre><code>filterSpec = FilterSpec('Assigned', Filter('service__isnull', False))) patients = Patient.objects.filter(**filterSpec.kwargs()) </code></pre> <p>I pass these filterSpec objects from the client to server by serializing, compressing, applying some symmetric encryption, and url-safe base-64 encoding. The only downside is that you end up with URLs looking like this:</p> <pre><code>http://127.0.0.1:8000/hospitalists/assign_test/?filter=eJwBHQHi_iDiTrccFpHA4It7zvtNIW5nUdRAxdiT-cZStYhy0PHezZH2Q7zmJB-NGAdYY4Q60Tr_gT_Jjy_bXfB6iR8inrNOVkXKVvLz3SCVrCktGc4thePSNAKoBtJHkcuoaf9YJA5q9f_1i6uh45-6k7ZyXntRu5CVEsm0n1u5T1vdMwMnaNA8QzYk4ecsxJRSy6SMbUHIGhDiwHHj1UnQaOWtCSJEt2zVxaurMuCRFT2bOKlj5nHfXCBTUCh4u3aqZZjmSd2CGMXZ8Pn3QGBppWhZQZFztP_1qKJaqSVeTNnDWpehbMvqabpivtnFTxwszJQw9BMcCBNTpvJf3jUGarw_dJ89VX12LuxALsketkPbYhXzXNxTK1PiZBYqGfBbioaYkjo%3D </code></pre> <p>I would love to get some comments on this approach and hear other solutions.</p>
1
2009-08-13T01:09:18Z
1,298,226
<p>Concerning your update: FilterSpecs are unfortunately one of those (rare) pieces of Django that lack public documentation. As such, there is no guarantee that they will keep working as they do.</p> <p>Another approach would be to use Alex Gaynor's <a href="http://lazypython.blogspot.com/2009/02/announcing-django-filter.html" rel="nofollow">django-filter</a> which look really well thought out. I'll be using them for my next project.</p>
0
2009-08-19T07:05:45Z
[ "python", "django" ]
Get information from related object in generic list view
1,269,625
<p>So, I've been noodling about with Django's generic views, specifically the <code>object_list</code> view. I have this in my <code>urls.py</code>:</p> <pre><code>from django.conf.urls.defaults import * from django.views.generic import list_detail from diplomacy.engine.models import Game game_info = { "queryset": Game.objects.filter(state__in=('A', 'P')), "template_object_name": "game", } urlpatterns = patterns('', (r'^$', list_detail.object_list, game_info), ) </code></pre> <p>and this fairly rough template that it is going to:</p> <pre><code>{% block content %} &lt;table&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Turn&lt;/th&gt; &lt;th&gt;Last Generated&lt;/th&gt; &lt;/tr&gt; {% for game in game_list %} &lt;tr&gt; &lt;td&gt;{{ game.name }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; {% endblock %} </code></pre> <p>What I'm looking for is the best idiomatic way of including in this view the unicode representation and <code>generated</code> field (a <code>DateTimeField</code>) from the <em>most recent</em> <code>Turn</code> that points to the current <code>Game</code> in the loop, based on the value of <code>generated</code>. <code>Turn.game</code> is the field that points to the <code>Game</code> the turn belongs to (a <code>ForeignKey</code>).</p> <p><strong>Update:</strong></p> <p>My <code>Turn</code> model is as follows:</p> <pre><code>SEASON_CHOICES = ( ('S', 'Spring'), ('SR', 'Spring Retreat'), ('F', 'Fall'), ('FR', 'Fall Retreat'), ('FB', 'Fall Build') ) class Turn(models.Model): game = models.ForeignKey(Game) year = models.PositiveIntegerField() season = models.CharField(max_length=2, choices=SEASON_CHOICES) generated = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "%s %s" % (self.season, self.year) </code></pre> <p>The <code>Game</code> model has not appreciably changed from the way I specified it in <a href="http://stackoverflow.com/questions/1197674/actions-triggered-by-field-change-in-django">this other question</a>.</p>
0
2009-08-13T01:45:28Z
1,269,733
<p>If <code>Turn.game</code> points to the associated <code>Game</code> object, then <code>{{game.turn_set.all}}</code> should return the set of <code>Turn</code> objects for that game. </p> <p>You may need to add a Meta class to the <code>Turn</code> model to order from newest to oldest.</p> <pre><code>Class Meta: ordering = ['-generated'] </code></pre> <p>Then, <code>{{game.turn_set.all.0}}</code> should return the unicode representation for the newest turn for that game, and <code>{{game.turn_set.all.0.generated}}</code> will return the associated <code>datetime</code> object.</p> <p>Note: This is untested code.</p>
0
2009-08-13T02:32:11Z
[ "python", "django", "django-templates", "django-views" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,269,820
<p>I am not an expert at C++ optimization, but I believe the speed difference may be due to the fact that Python lists have preallocated more space at the beginning while your C++ vectors must reallocate and possibly copy every time it grows.</p> <p>As for GMan's comment about find, I believe that the Python "in" operator is also a linear search and is the same speed.</p> <p><strong>Edit</strong></p> <p>Also I just noticed that you rolled your own pow function. There is no need to do that and the stdlib is likely faster.</p>
1
2009-08-13T03:06:01Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,269,839
<p>It looks like you're passing vectors by value to other functions. This will be a significant slowdown because the program will actually make a full copy of your vector before it passes it to your function. To get around this, pass a constant reference to the vector instead of a copy. So instead of: </p> <pre><code>int sum(vector&lt;int&gt; given)</code></pre> <p>Use:</p> <pre><code>int sum(const vector&lt;int&gt;& given)</code></pre> <p>When you do this, you'll no longer be able to use the vector::iterator because it is not constant. You'll need to replace it with vector::const_iterator.</p> <p>You can also pass in non-constant references, but in this case, you don't need to modify the parameter at all.</p>
16
2009-08-13T03:14:40Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,269,842
<p>I can see that you have quite a few heap allocations that are unnecessary</p> <p>For example:</p> <pre><code>while(!next) { char* buffer = new char[10]; </code></pre> <p>This doesn't look very optimized. So, you probably want to have the array pre-allocated and using it inside your loop. This is a basic optimizing technique which is easy to spot and to do. It might become into a mess too, so be careful with that.</p> <p>You are also using the atoi() function, which I don't really know if it is really optimized. Maybe doing a modulus 10 and getting the digit might be better (you have to measure thou, I didn't test this).</p> <p>The fact that you have a linear search (inVector) might be bad. Replacing the vector data structure with a std::set might speed things up. A hash_set could do the trick too.</p> <p>But I think that the worst problem is the string and this allocation of stuff on the heap inside that loop. That doesn't look good. I would try at those places first.</p>
7
2009-08-13T03:15:41Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,269,845
<p>Here's some food for thought: If given the choice of running a 1979 algorithm for finding prime numbers in a 2009 computer or a 2009 algorithm on a 1979 computer, which would you choose?</p> <p>The new algorithm on ancient hardware would be the better choice by a huge margin. Have a look at your "helper" functions.</p>
0
2009-08-13T03:16:18Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,269,998
<p>For 100000 elements, the Python code took 6.9 seconds while the C++ originally took above 37 seconds.</p> <p>I did some basic optimizations on your code and managed to get the C++ code above 100 times faster than the Python implementation. It now does 100000 elements in 0.06 seconds. That is 617 times faster than the original C++ code. </p> <p>The most important thing is to compile in Release mode, with all optimizations. This code is literally orders of magnitude slower in Debug mode.</p> <p>Next, I will explain the optimizations I did.</p> <ul> <li>Moved all vector declarations outside of the loop; replaced them by a clear() operation, which is much faster than calling the constructor.</li> <li>Replaced the call to pow(value, 2) by a multiplication : value * value.</li> <li>Instead of having a squares vector and calling sum on it, I sum the values in-place using just an integer.</li> <li>Avoided all string operations, which are very slow compared to integer operations. For instance, it is possible to compute the squares of each digit by repeatedly dividing by 10 and fetching the modulus 10 of the resulting value, instead of converting the value to a string and then each character back to int.</li> <li>Avoided all vector copies, first by replacing passing by value with passing by reference, and finally by eliminating the helper functions completely.</li> <li>Eliminated a few temporary variables.</li> <li>And probably many small details I forgot. Compare your code and mine side-by-side to see exactly what I did.</li> </ul> <p>It may be possible to optimize the code even more by using pre-allocated arrays instead of vectors, but this would be a bit more work and I'll leave it as an exercise to the reader. :P</p> <p>Here's the optimized code :</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;algorithm&gt; #include &lt;windows.h&gt; using namespace std; void calcMain(int upperBound, vector&lt;int&gt;&amp; known); int main() { while(true) { vector&lt;int&gt; results; int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound, results); end = GetTickCount(); for (size_t i = 0; i &lt; results.size(); ++i) { cout &lt;&lt; results[i] &lt;&lt; ", "; } cout &lt;&lt; endl; double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound, vector&lt;int&gt;&amp; known) { vector&lt;int&gt; history; for(int i = 0; i &lt;= upperBound; i++) { int current = i; history.clear(); while(true) { int temp = current; int sum = 0; while (temp &gt; 0) { sum += (temp % 10) * (temp % 10); temp /= 10; } current = sum; if(find(history.begin(), history.end(), current) != history.end()) { if(current == 1) { known.push_back(i); } break; } history.push_back(current); } } } </code></pre>
144
2009-08-13T04:14:59Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,270,015
<p>Well, I also gave it a once-over. I didn't test or even compile, though.</p> <p>General rules for numerical programs:</p> <ul> <li><p>Never process numbers as text. That's what makes lesser languages than Python slow, so if you do it in C, the program will be slower than Python.</p></li> <li><p>Don't use data structures if you can avoid them. You were building an array just to add the numbers up. Better keep a running total.</p></li> <li><p>Keep a copy of the STL reference open so you can use it rather than writing your own functions.</p></li> </ul> <p><hr /></p> <pre><code>void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { int current = i; vector&lt;int&gt; history; do { squaresum = 0 for ( ; current; current /= 10 ) { int digit = current % 10; squaresum += digit * digit; } current = squaresum; history.push_back(current); } while ( ! count(history.begin(), history.end() - 1, current) ); if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } //cout &lt;&lt; "\n\n"; } </code></pre>
3
2009-08-13T04:22:10Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,270,032
<p>There are quite a few optimizations possible:</p> <p>(1) Use const references </p> <pre><code>bool inVector(int inQuestion, const vector&lt;int&gt;&amp; known) { for(vector&lt;int&gt;::const_iterator it = known.begin(); it != known.end(); ++it) if(*it == inQuestion) return true; return false; } int sum(const vector&lt;int&gt;&amp; given) { int sum = 0; for(vector&lt;int&gt;::const_iterator it = given.begin(); it != given.end(); ++it) sum += *it; return sum; } </code></pre> <p>(2) Use counting down loops</p> <pre><code>int pow(int given, int power) { int current = 1; while(power--) current *= given; return current; } </code></pre> <p>Or, as others have said, use the standard library code.</p> <p>(3) Don't allocate buffers where not required</p> <pre><code> vector&lt;int&gt; squares; for (int temp = current; temp != 0; temp /= 10) { squares.push_back(pow(temp % 10, 2)); } </code></pre>
0
2009-08-13T04:29:59Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,271,103
<p>With similar optimizations as PotatoSwatter I got time for 10000 numbers down from 1.063 seconds to 0.062 seconds (except I replaced itoa with standard sprintf in the original). </p> <p>With all the memory optimizations (don't pass containers by value - in C++ you have to explicitly decide whether you want a copy or a reference; move operations that allocate memory out of inner loops; if you already have the number in a char buffer, what's the point of copying it to std::string etc) I got it down to 0.532. </p> <p>The rest of the time came from using %10 to access digits, rather than converting numbers to string.</p> <p>I suppose there might be another algorithmic level optimization (numbers that you have encountered while finding a happy number are themselves also happy numbers?) but I don't know how much that gains (there is not that many happy numbers in the first place) and this optimization is not in the Python version either.</p> <p>By the way, by not using string conversion and a list to square digits, I got the Python version from 0.825 seconds down to 0.33 too.</p>
0
2009-08-13T10:02:48Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,271,927
<p><strong>There's a new, radically faster version as <a href="http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1275074#1275074">a separate answer</a>, so this answer is deprecated.</strong></p> <hr> <p>I rewrote your algorithm by making it cache whenever it finds the number to be happy or unhappy. I also tried to make it as pythonic as I could, for example by creating separate functions <code>digits()</code> and <code>happy()</code>. Sorry for using Python 3, but I get to show off a couple a useful things from it as well.</p> <p>This version is <strong>much faster</strong>. It runs at <strong>1.7s</strong> which is <strong>10 times</strong> faster than your original program that takes <strong>18s</strong> (well, my MacBook is quite old and slow :) )</p> <pre><code>#!/usr/bin/env python3 from timeit import Timer from itertools import count print_numbers = False upperBound = 10**5 # Default value, can be overidden by user. def digits(x:'nonnegative number') -&gt; "yields number's digits": if not (x &gt;= 0): raise ValueError('Number should be nonnegative') while x: yield x % 10 x //= 10 def happy(number, known = {1}, happies = {1}) -&gt; 'True/None': '''This function tells if the number is happy or not, caching results. It uses two static variables, parameters known and happies; the first one contains known happy and unhappy numbers; the second contains only happy ones. If you want, you can pass your own known and happies arguments. If you do, you should keep the assumption commented out on the 1 line. ''' # assert 1 in known and happies &lt;= known # &lt;= is expensive if number in known: return number in happies history = set() while True: history.add(number) number = sum(x**2 for x in digits(number)) if number in known or number in history: break known.update(history) if number in happies: happies.update(history) return True def calcMain(): happies = {x for x in range(upperBound) if happy(x) } if print_numbers: print(happies) if __name__ == '__main__': upperBound = eval( input("Pick an upper bound [default {0}]: " .format(upperBound)).strip() or repr(upperBound)) result = Timer(calcMain).timeit(1) print ('This computation took {0} seconds'.format(result)) </code></pre>
19
2009-08-13T13:25:13Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,272,569
<p>Here's a C# version:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; namespace CSharp { class Program { static void Main (string [] args) { while (true) { Console.Write ("Pick an upper bound: "); String input = Console.ReadLine (); uint upper_bound; if (uint.TryParse (input, out upper_bound)) { DateTime start = DateTime.Now; CalcHappyNumbers (upper_bound); DateTime end = DateTime.Now; TimeSpan span = end - start; Console.WriteLine ("Time taken = " + span.TotalSeconds + " seconds."); } else { Console.WriteLine ("Error in input, unable to parse '" + input + "'."); } } } enum State { Happy, Sad, Unknown } static void CalcHappyNumbers (uint upper_bound) { SortedDictionary&lt;uint, State&gt; happy = new SortedDictionary&lt;uint, State&gt; (); SortedDictionary&lt;uint, bool&gt; happy_numbers = new SortedDictionary&lt;uint, bool&gt; (); happy [1] = State.Happy; happy_numbers [1] = true; for (uint current = 2 ; current &lt; upper_bound ; ++current) { FindState (ref happy, ref happy_numbers, current); } //foreach (KeyValuePair&lt;uint, bool&gt; pair in happy_numbers) //{ // Console.Write (pair.Key.ToString () + ", "); //} //Console.WriteLine (""); } static State FindState (ref SortedDictionary&lt;uint, State&gt; happy, ref SortedDictionary&lt;uint,bool&gt; happy_numbers, uint value) { State current_state; if (happy.TryGetValue (value, out current_state)) { if (current_state == State.Unknown) { happy [value] = State.Sad; } } else { happy [value] = current_state = State.Unknown; uint new_value = 0; for (uint i = value ; i != 0 ; i /= 10) { uint lsd = i % 10; new_value += lsd * lsd; } if (new_value == 1) { current_state = State.Happy; } else { current_state = FindState (ref happy, ref happy_numbers, new_value); } if (current_state == State.Happy) { happy_numbers [value] = true; } happy [value] = current_state; } return current_state; } } } </code></pre> <p>I compared it against Dr_Asik's C++ code. For an upper bound of 100000 the C++ version ran in about 2.9 seconds and the C# version in 0.35 seconds. Both were compiled using Dev Studio 2005 using default release build options and both were executed from a command prompt.</p>
0
2009-08-13T15:07:34Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,275,074
<p>This is my second answer; which <strong>caches things like sum of squares</strong> for values <code>&lt;= 10**6</code>:</p> <pre><code> happy_list[sq_list[x%happy_base] + sq_list[x//happy_base]] </code></pre> <p>That is, </p> <ul> <li>the number is split into 3 digits + 3 digits</li> <li>the <strong>precomputed table</strong> is used to get sum of squares for both parts</li> <li>these two results are added</li> <li>the precomputed table is consulted to get the happiness of number:</li> </ul> <p>I don't think Python version can be made much faster than that (ok, if you throw away fallback to old version, that is <code>try:</code> overhead, it's 10% faster). </p> <p>I think this is an <strong>excellent question</strong> which shows that, indeed, </p> <ul> <li>things that have to be fast should be written in C</li> <li>however, usually you don't need things to be fast (even if you needed the program to run for a day, it would be less then the combined time of programmers optimizing it)</li> <li>it's easier and faster to write programs in Python</li> <li>but for some problems, especially computational ones, a C++ solution, like the ones above, are actually more readable and more beautiful than an attempt to optimize Python program.</li> </ul> <p><hr /></p> <p>Ok, here it goes (2nd version now...):</p> <pre><code>#!/usr/bin/env python3 '''Provides slower and faster versions of a function to compute happy numbers. slow_happy() implements the algorithm as in the definition of happy numbers (but also caches the results). happy() uses the precomputed lists of sums of squares and happy numbers to return result in just 3 list lookups and 3 arithmetic operations for numbers less than 10**6; it falls back to slow_happy() for big numbers. Utilities: digits() generator, my_timeit() context manager. ''' from time import time # For my_timeit. from random import randint # For example with random number. upperBound = 10**5 # Default value, can be overridden by user. class my_timeit: '''Very simple timing context manager.''' def __init__(self, message): self.message = message self.start = time() def __enter__(self): return self def __exit__(self, *data): print(self.message.format(time() - self.start)) def digits(x:'nonnegative number') -&gt; "yields number's digits": if not (x &gt;= 0): raise ValueError('Number should be nonnegative') while x: yield x % 10 x //= 10 def slow_happy(number, known = {1}, happies = {1}) -&gt; 'True/None': '''Tell if the number is happy or not, caching results. It uses two static variables, parameters known and happies; the first one contains known happy and unhappy numbers; the second contains only happy ones. If you want, you can pass your own known and happies arguments. If you do, you should keep the assumption commented out on the 1 line. ''' # This is commented out because &lt;= is expensive. # assert {1} &lt;= happies &lt;= known if number in known: return number in happies history = set() while True: history.add(number) number = sum(x**2 for x in digits(number)) if number in known or number in history: break known.update(history) if number in happies: happies.update(history) return True # This will define new happy() to be much faster ------------------------. with my_timeit('Preparation time was {0} seconds.\n'): LogAbsoluteUpperBound = 6 # The maximum possible number is 10**this. happy_list = [slow_happy(x) for x in range(81*LogAbsoluteUpperBound + 1)] happy_base = 10**((LogAbsoluteUpperBound + 1)//2) sq_list = [sum(d**2 for d in digits(x)) for x in range(happy_base + 1)] def happy(x): '''Tell if the number is happy, optimized for smaller numbers. This function works fast for numbers &lt;= 10**LogAbsoluteUpperBound. ''' try: return happy_list[sq_list[x%happy_base] + sq_list[x//happy_base]] except IndexError: return slow_happy(x) # End of happy()'s redefinition -----------------------------------------. def calcMain(print_numbers, upper_bound): happies = [x for x in range(upper_bound + 1) if happy(x)] if print_numbers: print(happies) if __name__ == '__main__': while True: upperBound = eval(input( "Pick an upper bound [{0} default, 0 ends, negative number prints]: " .format(upperBound)).strip() or repr(upperBound)) if not upperBound: break with my_timeit('This computation took {0} seconds.'): calcMain(upperBound &lt; 0, abs(upperBound)) single = 0 while not happy(single): single = randint(1, 10**12) print('FYI, {0} is {1}.\n'.format(single, 'happy' if happy(single) else 'unhappy')) print('Nice to see you, goodbye!') </code></pre>
6
2009-08-13T22:51:01Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,275,866
<p>Here is another way that relies on memorising all the numbers already explored. I obtain a factor x4-5, which is oddly stable against DrAsik's code for 1000 and 1000000, I expected the cache to be more efficient the more numbers we were exploring. Otherwise, the same kind of classic optimizations have been applied. BTW, if the compiler accepts NRVO <em>(/RNVO ? I never remember the exact term)</em> or rvalue references, we wouldn't need to pass the vector as an <em>out</em> parameter.</p> <p>NB: micro-optimizations are still possible IMHO, and moreover the caching is naive as it allocates much more memory than really needed.</p> <pre><code>enum Status { never_seen, being_explored, happy, unhappy }; char const* toString[] = { "never_seen", "being_explored", "happy", "unhappy" }; inline size_t sum_squares(size_t i) { size_t s = 0; while (i) { const size_t digit = i%10; s += digit * digit; i /= 10; } return s ; } struct Cache { Cache(size_t dim) : m_cache(dim, never_seen) {} void set(size_t n, Status status) { if (m_cache.size() &lt;= n) { m_cache.resize(n+1, never_seen); } m_cache[n] = status; // std::cout &lt;&lt; "(c[" &lt;&lt; n &lt;&lt; "]&lt;-"&lt;&lt;toString[status] &lt;&lt; ")"; } Status operator[](size_t n) const { if (m_cache.size() &lt;= n) { return never_seen; } else { return m_cache[n]; } } private: std::vector&lt;Status&gt; m_cache; }; void search_happy_lh(size_t upper_bound, std::vector&lt;size_t&gt; &amp; happy_numbers) { happy_numbers.clear(); happy_numbers.reserve(upper_bound); // it doesn't improve much the performances Cache cache(upper_bound+1); std::vector&lt;size_t&gt; current_stack; cache.set(1,happy); happy_numbers.push_back(1); for (size_t i = 2; i&lt;=upper_bound ; ++i) { // std::cout &lt;&lt; "\r" &lt;&lt; i &lt;&lt; std::flush; current_stack.clear(); size_t s= i; while ( s != 1 &amp;&amp; cache[s]==never_seen) { current_stack.push_back(s); cache.set(s, being_explored); s = sum_squares(s); // std::cout &lt;&lt; " - " &lt;&lt; s &lt;&lt; std::flush; } const Status update_with = (cache[s]==being_explored ||cache[s]==unhappy) ? unhappy : happy; // std::cout &lt;&lt; " =&gt; " &lt;&lt; s &lt;&lt; ":" &lt;&lt; toString[update_with] &lt;&lt; std::endl; for (size_t j=0; j!=current_stack.size(); ++j) { cache.set(current_stack[j], update_with); } if (cache[i] == happy) { happy_numbers.push_back(i); } } } </code></pre>
1
2009-08-14T03:11:06Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,281,089
<p>Just to get a little more closure on this issue by seeing how fast I could truely find these numbers, I wrote a multithreaded C++ implementation of Dr_Asik's algorithm. There are two things that are important to realize about the fact that this implementation is multithreaded.</p> <ol> <li><p>More threads does not necessarily lead to better execution times, there is a happy medium for every situation depending on the volume of numbers you want to calculate.</p></li> <li><p>If you compare the times between this version running with one thread and the original version, the only factors that could cause a difference in time are the overhead from starting the thread and variable system performance issues. Otherwise, the algorithm is the same.</p></li> </ol> <p>The code for this implementation (all credit for the algorithm goes to Dr_Asik) is <a href="http://dawnofdigital.net/script/happy%5Fmultithreaded.cpp.txt" rel="nofollow">here</a>. Also, I wrote some speed tests with a double check for each test to help back up those 3 points.</p> <p><strong>Calculation of the first 100,000,000 happy numbers:</strong></p> <p>Original - 39.061 / 39.000 (Dr_Asik's original implementation)<br/> 1 Thread - 39.000 / 39.079<br /> 2 Threads - 19.750 / 19.890<br /> 10 Threads - 11.872 / 11.888<br /> 30 Threads - 10.764 / 10.827<br /> 50 Threads - 10.624 / 10.561 &lt;--<br /> 100 Threads - 11.060 / 11.216<br /> 500 Threads - 13.385 / 12.527<br /></p> <p>From these results it looks like our happy medium is about 50 threads, plus or minus ten or so.</p>
2
2009-08-15T03:39:31Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,282,449
<p><strong>Other optimizations</strong>: by using arrays and direct access using the loop index rather than searching in a vector, and by caching prior sums, the following code (inspired by Dr Asik's answer but probably not optimized at all) runs <strong><em>2445</em></strong> times faster than the original C++ code, about <strong><em>400</em></strong> times faster than the Python code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;vector&gt; void calcMain(int upperBound, std::vector&lt;int&gt;&amp; known) { int tempDigitCounter = upperBound; int numDigits = 0; while (tempDigitCounter &gt; 0) { numDigits++; tempDigitCounter /= 10; } int maxSlots = numDigits * 9 * 9; int* history = new int[maxSlots + 1]; int* cache = new int[upperBound+1]; for (int jj = 0; jj &lt;= upperBound; jj++) { cache[jj] = 0; } int current, sum, temp; for(int i = 0; i &lt;= upperBound; i++) { current = i; while(true) { sum = 0; temp = current; bool inRange = temp &lt;= upperBound; if (inRange) { int cached = cache[temp]; if (cached) { sum = cached; } } if (sum == 0) { while (temp &gt; 0) { int tempMod = temp % 10; sum += tempMod * tempMod; temp /= 10; } if (inRange) { cache[current] = sum; } } current = sum; if(history[current] == i) { if(current == 1) { known.push_back(i); } break; } history[current] = i; } } } int main() { while(true) { int upperBound; std::vector&lt;int&gt; known; std::cout &lt;&lt; "Pick an upper bound: "; std::cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound, known); end = GetTickCount(); for (size_t i = 0; i &lt; known.size(); ++i) { std::cout &lt;&lt; known[i] &lt;&lt; ", "; } double seconds = (double)(end-start) / 1000.0; std::cout &lt;&lt; std::endl &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; std::endl &lt;&lt; std::endl; } return 0; } </code></pre>
2
2009-08-15T17:49:37Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
1,283,788
<pre><code> #!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = set() for i in xrange(0,upperBound+1): next = False current = i history = set() while not next: squaresum=0 while current &gt; 0: current, digit = divmod(current, 10) squaresum += digit * digit current = squaresum if current in history: next = True if current == 1: known.add(i) history.add(current) while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre> <p>I made a couple of minor changes to your original python code example that make a better than 16x improvement to the performance of the code. The changes I made took the 100,000 case from about 9.64 seconds to about 3.38 seconds.</p> <p>The major change was to make the mod 10 and accumulator changes to run in a while loop. I made a couple of other changes that improved execution time in only fractions of hundredths of seconds. The first minor change was changing the main for loop from a range list comprehension to an xrange iterator. The second minor change was substituting the set class for the list class for both the known and history variables. I also experimented with iterator comprehensions and precalculating the squares but they both had negative effects on the efficiency. I seem to be running a slower version of python or on a slower processor than some of the other contributers. I would be interest in the results of someone else's timing comparison of my python code against one of the optimized C++ versions of the same algorithm. I also tried using the python -O and -OO optimizations but they had the reverse of the intended effect.</p>
0
2009-08-16T08:37:07Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
3,979,841
<p>Why is everyone using a vector in the c++ version? Lookup time is O(N).</p> <p>Even though it's not as efficient as the python set, use std::set. Lookup time is O(log(N)).</p>
0
2010-10-20T15:57:11Z
[ "c++", "python", "algorithm", "performance" ]
Unusual Speed Difference between Python and C++
1,269,795
<p>I recently wrote a short algorithm to calculate <a href="http://en.wikipedia.org/wiki/Happy%5FNumbers">happy numbers</a> in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. </p> <p>Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. </p> <p>I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. </p> <p>Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). </p> <p>The two pieces of code, with speed testing are here: <a href="http://dawnofdigital.net/script/happy.py.txt">Python Version</a>, <a href="http://dawnofdigital.net/script/happy.cpp.txt">C++ Version</a>. Thanks for the help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; bool inVector(int inQuestion, vector&lt;int&gt; known); int sum(vector&lt;int&gt; given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout &lt;&lt; "Pick an upper bound: "; cin &gt;&gt; upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout &lt;&lt; seconds &lt;&lt; " seconds." &lt;&lt; endl &lt;&lt; endl; } return 0; } void calcMain(int upperBound) { vector&lt;int&gt; known; for(int i = 0; i &lt;= upperBound; i++) { bool next = false; int current = i; vector&lt;int&gt; history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector&lt;int&gt; squares; for(int j = 0; j &lt; digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&amp;charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout &lt;&lt; i &lt;&lt; "\t"; } } history.push_back(current); } } //cout &lt;&lt; "\n\n"; } bool inVector(int inQuestion, vector&lt;int&gt; known) { for(vector&lt;int&gt;::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector&lt;int&gt; given) { int sum = 0; for(vector&lt;int&gt;::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i &lt; power-1; i++) current *= original; return current; } </code></pre> <p><hr /></p> <pre><code>#!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n" </code></pre>
35
2009-08-13T02:58:19Z
10,529,801
<p>Stumbled over this page whilst bored and thought I'd golf it in js. The algorithm is my own, and I haven't checked it thoroughly against anything other than my own calculations (so it could be wrong). It calculates the first 1e7 happy numbers and stores them in h. If you want to change it, change both the 7s. </p> <pre><code>m=1e7,C=7*81,h=[1],t=true,U=[,,,,t],n=w=2; while(n&lt;m){ z=w,s=0;while(z)y=z%10,s+=y*y,z=0|z/10;w=s; if(U[w]){if(n&lt;C)U[n]=t;w=++n;}else if(w&lt;n)h.push(n),w=++n;} </code></pre> <p>This will print the first 1000 items for you in console or a browser: </p> <pre><code>o=h.slice(0,m&gt;1e3?1e3:m); (!this.document?print(o):document.load=document.write(o.join('\n'))); </code></pre> <p>155 characters for the functional part and it appears to be as fast* as Dr. Asik's offering on firefox or v8 (350-400 times as fast as the original python program on my system when running time d8 happygolf.js or js -a -j -p happygolf.js in spidermonkey).<br> I shall be in awe of the analytic skills anyone who can figure out why this algorithm is doing so well without referencing the longer, commented, fortran version.</p> <p>I was intrigued by how fast it was, so I learned fortran to get a comparison of the same algorithm, be kind if there are any glaring newbie mistakes, it's my first fortran program. <a href="http://pastebin.com/q9WFaP5C" rel="nofollow">http://pastebin.com/q9WFaP5C</a> It's static memory wise, so to be fair to the others, it's in a self-compiling shell script, if you don't have gcc/bash/etc strip out the preprocessor and bash stuff at the top, set the macros manually and compile it as fortran95.</p> <p>Even if you include compilation time it beats most of the others here. If you don't, it's about ~3000-3500 times as fast as the original python version (and by extension >40,000 times as fast as the C++*, although I didn't run any of the C++ programs).</p> <p>Surprisingly many of the optimizations I tried in the fortran version (incl some like loop unrolling which I left out of the pasted version due to small effect and readability) were detrimental to the js version. This exercise shows that modern trace compilers are extremely good (within a factor of 7-10 of carefully optimized, static memory fortran) if you get out of their way and don't try any tricky stuff. get out of their way, and trying to do tricky stuff Finally, here's a much nicer, more recursive js version.</p> <pre><code>// to s, then integer divides x by 10. // Repeats until x is 0. function sumsq(x) { var y,s=0; while(x) { y = x % 10; s += y * y; x = 0| x / 10; } return s; } // A boolean cache for happy(). // The terminating happy number and an unhappy number in // the terminating sequence. var H=[]; H[1] = true; H[4] = false; // Test if a number is happy. // First check the cache, if that's empty // Perform one round of sumsq, then check the cache // For that. If that's empty, recurse. function happy(x) { // If it already exists. if(H[x] !== undefined) { // Return whatever is already in cache. return H[x]; } else { // Else calc sumsq, set and return cached val, or if undefined, recurse. var w = sumsq(x); return (H[x] = H[w] !== undefined? H[w]: happy(w)); } } //Main program loop. var i, hN = []; for(i = 1; i &lt; 1e7; i++) { if(happy(i)) { hN.push(i); } } </code></pre> <p>Surprisingly, even though it is rather high level, it did almost exactly as well as the imperative algorithm in spidermonkey (with optimizations on), and close (1.2 times as long) in v8.</p> <p>Moral of the story I guess, spend a bit of time thinking about your algorithm if it's important. Also high level languages already have a lot of overhead (and sometimes have tricks of their own to reduce it) so sometimes doing something more straightforwared or utilizing their high level features is just as fast. Also micro-optimization doesn't always help.</p> <p>*Unless my python installation is unusually slow, direct times are somewhat meaningless as this is a first generation eee. Times are:<br> 12s for fortran version, no output, 1e8 happy numbers.<br> 40s for fortran version, pipe output through gzip to disk.<br> 8-12s for both js versions. 1e7 happy numbers, no output with full optimization 10-100s for both js versions 1e7 with less/no optimization (depending on definition of no optimization, the 100s was with eval()) no output</p> <p>I'd be interested to see times for these programs on a real computer.</p>
1
2012-05-10T08:03:55Z
[ "c++", "python", "algorithm", "performance" ]
mechanize (python) click on a javascript type link
1,270,274
<p>is it possible to have mechanize follow an anchor link that is of type javascript?</p> <p>I am trying to login into a website in python using mechanize and beautifulsoup.</p> <p>this is the anchor link</p> <pre><code>&lt;a id="StaticModuleID15_ctl00_SkinLogin1_Login1_Login1_LoginButton" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&amp;quot;StaticModuleID15$ctl00$SkinLogin1$Login1$Login1$LoginButton&amp;quot;, &amp;quot;&amp;quot;, true, &amp;quot;Login1&amp;quot;, &amp;quot;&amp;quot;, false, true))"&gt;&lt;img id="StaticModuleID15_ctl00_SkinLogin1_Login1_Login1_Image2" border="0" src="../../App_Themes/default/images/Member/btn_loginenter.gif" align="absmiddle" style="border-width:0px;" /&gt;&lt;/a&gt; </code></pre> <p>and here is what i have tried</p> <pre><code> links = SoupStrainer('a', id="StaticModuleID15_ctl00_SkinLogin1_Login1_Login1_LoginButton") [anchor for anchor in BeautifulSoup(data, parseOnlyThese=links)] link = mechanize.Link( base_url = self.url, url = str(anchor['href']), text = str(anchor.string), tag = str(anchor.name), attrs = [(str(name), str(value)) for name, value in anchor.attrs]) response2 = br.follow_link(link) </code></pre> <p>Right now I am getting the error message of, </p> <p>urllib2.URLError: </p> <p>any help or suggestion is appreciated </p> <p><strong>Edit</strong></p> <p>After the comment by helpers, I went and looked at the code of the asp page a bit.</p> <p>I found a little bit of useful scripts but I am unsure of what I have to do in python to emulate the JS code with python. In no where did I see any cookies set, am I looking at the wrong places?</p> <pre><code>&lt;form name="form1" method="post" action="BrowseSchedule.aspx?ItemId=75" onsubmit="javascript:return WebForm_OnSubmit();" id="form1"&gt; //&lt;![CDATA[ function WebForm_OnSubmit() { if (typeof(ValidatorOnSubmit) == "function" &amp;&amp; ValidatorOnSubmit() == false) return false; return true; } //]]&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ var theForm = document.forms['form1']; if (!theForm) { theForm = document.form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]&gt; &lt;/script&gt; function WebForm_DoPostBackWithOptions(options) { var validationResult = true; if (options.validation) { if (typeof(Page_ClientValidate) == 'function') { validationResult = Page_ClientValidate(options.validationGroup); } } if (validationResult) { if ((typeof(options.actionUrl) != "undefined") &amp;&amp; (options.actionUrl != null) &amp;&amp; (options.actionUrl.length &gt; 0)) { theForm.action = options.actionUrl; } if (options.trackFocus) { var lastFocus = theForm.elements["__LASTFOCUS"]; if ((typeof(lastFocus) != "undefined") &amp;&amp; (lastFocus != null)) { if (typeof(document.activeElement) == "undefined") { lastFocus.value = options.eventTarget; } else { var active = document.activeElement; if ((typeof(active) != "undefined") &amp;&amp; (active != null)) { if ((typeof(active.id) != "undefined") &amp;&amp; (active.id != null) &amp;&amp; (active.id.length &gt; 0)) { lastFocus.value = active.id; } else if (typeof(active.name) != "undefined") { lastFocus.value = active.name; } } } } } } if (options.clientSubmit) { __doPostBack(options.eventTarget, options.eventArgument); } } </code></pre>
3
2009-08-13T06:01:00Z
1,270,296
<p>I don't think this is possible with the mechanize module: it doesn't have the ability to interact with JavaScript: its purely Python and HTTP based.</p> <p>That said, you may be intested in <a href="http://github.com/davisp/python-spidermonkey/tree/master" rel="nofollow">python-spidermonkey</a> module, which it seems is aimed at letting you do just this kind of thing. According to it's website it's aim is to let you</p> <blockquote> <p>"Execute arbitrary JavaScript code from Python. Allows you to reference arbitrary Python objects and functions in the JavaScript VM"</p> </blockquote> <p>I've not used it yet but it certainly looks like it would do what you are looking for, although it is still in alpha.</p>
4
2009-08-13T06:11:01Z
[ "javascript", "python", "mechanize" ]
mechanize (python) click on a javascript type link
1,270,274
<p>is it possible to have mechanize follow an anchor link that is of type javascript?</p> <p>I am trying to login into a website in python using mechanize and beautifulsoup.</p> <p>this is the anchor link</p> <pre><code>&lt;a id="StaticModuleID15_ctl00_SkinLogin1_Login1_Login1_LoginButton" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&amp;quot;StaticModuleID15$ctl00$SkinLogin1$Login1$Login1$LoginButton&amp;quot;, &amp;quot;&amp;quot;, true, &amp;quot;Login1&amp;quot;, &amp;quot;&amp;quot;, false, true))"&gt;&lt;img id="StaticModuleID15_ctl00_SkinLogin1_Login1_Login1_Image2" border="0" src="../../App_Themes/default/images/Member/btn_loginenter.gif" align="absmiddle" style="border-width:0px;" /&gt;&lt;/a&gt; </code></pre> <p>and here is what i have tried</p> <pre><code> links = SoupStrainer('a', id="StaticModuleID15_ctl00_SkinLogin1_Login1_Login1_LoginButton") [anchor for anchor in BeautifulSoup(data, parseOnlyThese=links)] link = mechanize.Link( base_url = self.url, url = str(anchor['href']), text = str(anchor.string), tag = str(anchor.name), attrs = [(str(name), str(value)) for name, value in anchor.attrs]) response2 = br.follow_link(link) </code></pre> <p>Right now I am getting the error message of, </p> <p>urllib2.URLError: </p> <p>any help or suggestion is appreciated </p> <p><strong>Edit</strong></p> <p>After the comment by helpers, I went and looked at the code of the asp page a bit.</p> <p>I found a little bit of useful scripts but I am unsure of what I have to do in python to emulate the JS code with python. In no where did I see any cookies set, am I looking at the wrong places?</p> <pre><code>&lt;form name="form1" method="post" action="BrowseSchedule.aspx?ItemId=75" onsubmit="javascript:return WebForm_OnSubmit();" id="form1"&gt; //&lt;![CDATA[ function WebForm_OnSubmit() { if (typeof(ValidatorOnSubmit) == "function" &amp;&amp; ValidatorOnSubmit() == false) return false; return true; } //]]&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ var theForm = document.forms['form1']; if (!theForm) { theForm = document.form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]&gt; &lt;/script&gt; function WebForm_DoPostBackWithOptions(options) { var validationResult = true; if (options.validation) { if (typeof(Page_ClientValidate) == 'function') { validationResult = Page_ClientValidate(options.validationGroup); } } if (validationResult) { if ((typeof(options.actionUrl) != "undefined") &amp;&amp; (options.actionUrl != null) &amp;&amp; (options.actionUrl.length &gt; 0)) { theForm.action = options.actionUrl; } if (options.trackFocus) { var lastFocus = theForm.elements["__LASTFOCUS"]; if ((typeof(lastFocus) != "undefined") &amp;&amp; (lastFocus != null)) { if (typeof(document.activeElement) == "undefined") { lastFocus.value = options.eventTarget; } else { var active = document.activeElement; if ((typeof(active) != "undefined") &amp;&amp; (active != null)) { if ((typeof(active.id) != "undefined") &amp;&amp; (active.id != null) &amp;&amp; (active.id.length &gt; 0)) { lastFocus.value = active.id; } else if (typeof(active.name) != "undefined") { lastFocus.value = active.name; } } } } } } if (options.clientSubmit) { __doPostBack(options.eventTarget, options.eventArgument); } } </code></pre>
3
2009-08-13T06:01:00Z
15,416,360
<p>You may set cookies using cookielib</p> <pre><code>import mechanize import cookielib # add headers to your browser also browser = mechanize.Browser() browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] cj = cookielib.LWPCookieJar() browser.set_cookiejar(cj) </code></pre> <p>I doubt this is even relevant now, but oh well :)</p>
0
2013-03-14T17:37:38Z
[ "javascript", "python", "mechanize" ]
About Python's Mixed Numeric Data Types converting results up to the most complicated operand
1,270,403
<p>A little background: I'm in the process of learning Python through O'Reilly's, "Learning Python" book, I've had some experience in Java.</p> <p>Anyway, upon reading Chapter 5 (I'm still in the middle of it, actually) I have come across a question with the way Python treats results of Mixed Numeric expressions. In the book, they use an example of mixing an integer and a floating-point number (40 + 3.14) and proceed to explain that the result of this expression would be a floating-point number because Python converts operands <em>up</em> to the type of the most complicated operand.</p> <p>My question is this: Instead of programmers having to remember which Numeric operand is the highest and remember that the that the result will be "upped" to that format, wouldn't it be simpler to create a special Numeric Literal for result types?</p> <p>My logic is this: If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number. Why should you have to remember the hierarchy of Numeric Literals just to know what your result is going to be treated as? In my opinion, it seems like it would be a much simpler process to assign results to a single, uninformed Literal to know that regardless of whether or not the expression has Mixed Numerics, it will be treated as a specific Data Type.</p> <p>Follow up question: Is there a language where this kind of thing is currently being preformed?</p> <p>Again, my knowledge of Python is limited, so this may be a silly question, but I would like to know why programmers have to put themselves through this process. The only reason why I could imagine that there isn't a system of some kind in place already is that perhaps the specific Numeric Type of a result isn't as important as it is in some other languages (Java).</p>
0
2009-08-13T06:48:45Z
1,270,465
<blockquote> <p>"If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number."</p> </blockquote> <p>That <em>is</em> the "hierarchy of Numeric Literals". I'm not really sure what more you want. Furthermore, the result will always be a subclass of numbers.Number, so you actually do have some guarantee about what type the resulting object will be.</p>
5
2009-08-13T07:08:18Z
[ "python", "numeric" ]
About Python's Mixed Numeric Data Types converting results up to the most complicated operand
1,270,403
<p>A little background: I'm in the process of learning Python through O'Reilly's, "Learning Python" book, I've had some experience in Java.</p> <p>Anyway, upon reading Chapter 5 (I'm still in the middle of it, actually) I have come across a question with the way Python treats results of Mixed Numeric expressions. In the book, they use an example of mixing an integer and a floating-point number (40 + 3.14) and proceed to explain that the result of this expression would be a floating-point number because Python converts operands <em>up</em> to the type of the most complicated operand.</p> <p>My question is this: Instead of programmers having to remember which Numeric operand is the highest and remember that the that the result will be "upped" to that format, wouldn't it be simpler to create a special Numeric Literal for result types?</p> <p>My logic is this: If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number. Why should you have to remember the hierarchy of Numeric Literals just to know what your result is going to be treated as? In my opinion, it seems like it would be a much simpler process to assign results to a single, uninformed Literal to know that regardless of whether or not the expression has Mixed Numerics, it will be treated as a specific Data Type.</p> <p>Follow up question: Is there a language where this kind of thing is currently being preformed?</p> <p>Again, my knowledge of Python is limited, so this may be a silly question, but I would like to know why programmers have to put themselves through this process. The only reason why I could imagine that there isn't a system of some kind in place already is that perhaps the specific Numeric Type of a result isn't as important as it is in some other languages (Java).</p>
0
2009-08-13T06:48:45Z
1,270,494
<p>Suppose you had a unified numeric type and you typed the following statements:</p> <pre><code>a = 42 b = 42.24 c = 4 + 2j </code></pre> <p>How would this be any different from what you get today?</p> <p>This is already valid Python. The only difference is that <code>type(a)</code>, <code>type(b)</code>, <code>type(c)</code> return <code>int</code>, <code>float</code> and <code>complex</code>, and I guess you want them all to return something like <code>number</code>. But you never really deal with that unless you want/have to. </p> <p>There are reasons for having something like a scheme-like <a href="http://en.wikipedia.org/wiki/Numerical%5Ftower" rel="nofollow">numerical tower</a>. You may take advantage of the hardware for integer calculations if you know you're only dealing with itnegers. Or you may derive from the <code>int</code> type when you know you want to restrict some kind of user input to an integer. </p> <p>I'm sure you can find a language with a type system that has some kind of unified number. But I'm not sure I've understood your argument. Perhaps I've missed something in your question?</p>
2
2009-08-13T07:17:27Z
[ "python", "numeric" ]
About Python's Mixed Numeric Data Types converting results up to the most complicated operand
1,270,403
<p>A little background: I'm in the process of learning Python through O'Reilly's, "Learning Python" book, I've had some experience in Java.</p> <p>Anyway, upon reading Chapter 5 (I'm still in the middle of it, actually) I have come across a question with the way Python treats results of Mixed Numeric expressions. In the book, they use an example of mixing an integer and a floating-point number (40 + 3.14) and proceed to explain that the result of this expression would be a floating-point number because Python converts operands <em>up</em> to the type of the most complicated operand.</p> <p>My question is this: Instead of programmers having to remember which Numeric operand is the highest and remember that the that the result will be "upped" to that format, wouldn't it be simpler to create a special Numeric Literal for result types?</p> <p>My logic is this: If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number. Why should you have to remember the hierarchy of Numeric Literals just to know what your result is going to be treated as? In my opinion, it seems like it would be a much simpler process to assign results to a single, uninformed Literal to know that regardless of whether or not the expression has Mixed Numerics, it will be treated as a specific Data Type.</p> <p>Follow up question: Is there a language where this kind of thing is currently being preformed?</p> <p>Again, my knowledge of Python is limited, so this may be a silly question, but I would like to know why programmers have to put themselves through this process. The only reason why I could imagine that there isn't a system of some kind in place already is that perhaps the specific Numeric Type of a result isn't as important as it is in some other languages (Java).</p>
0
2009-08-13T06:48:45Z
1,270,701
<p>Don't think i really understood question:</p> <ol> <li><p>Do you mean that operation result should be explictly specified? you can do it with explict cast</p> <p>float(1+0.5)</p> <p>int(1+0.5)</p> <p>complex(1+0.5)</p></li> <li><p>Do you mean that operators should accept only same type operands?</p> <p>1+2</p> <p>1+0.5 -> raises exception</p> <p>1+int(0.5)</p> <p>float(1)+0.5</p> <p>while having sense, it would introduce too much verbosity and int->float casts are always successful and don't lead to precision loss (except really large numbers)</p></li> <li><p>Separate operands for different return types:</p> <p>1 + 0.5 -> int</p> <p>1 \<code>float_plus\</code> 2 -> float</p> <p>Duplicates explict cast functionality and is plain sick</p></li> </ol>
0
2009-08-13T08:09:22Z
[ "python", "numeric" ]
Python standard library to POST multipart/form-data encoded data
1,270,518
<p>I would like to POST multipart/form-data encoded data. I have found an external module that does it: <a href="http://atlee.ca/software/poster/index.html">http://atlee.ca/software/poster/index.html</a> however I would rather avoid this dependency. Is there a way to do this using the standard libraries?</p> <p>thanks</p>
17
2009-08-13T07:24:00Z
1,270,548
<p>The standard library <a href="http://bugs.python.org/issue3244">does not currently support that</a>. There is <a href="http://code.activestate.com/recipes/146306/">cookbook recipe</a> that includes a fairly short piece of code that you just may want to copy, though, along with long discussions of alternatives.</p>
17
2009-08-13T07:31:14Z
[ "python", "encoding", "post", "urllib", "multipart" ]
Python standard library to POST multipart/form-data encoded data
1,270,518
<p>I would like to POST multipart/form-data encoded data. I have found an external module that does it: <a href="http://atlee.ca/software/poster/index.html">http://atlee.ca/software/poster/index.html</a> however I would rather avoid this dependency. Is there a way to do this using the standard libraries?</p> <p>thanks</p>
17
2009-08-13T07:24:00Z
1,270,574
<p>You can't do this with the stdlib quickly. Howevewr, see the <code>MultiPartForm</code> class in this PyMOTW. You can probably use or modify that to accomplish whatever you need:</p> <ul> <li><a href="http://pymotw.com/2/urllib2/" rel="nofollow">PyMOTW: urllib2 - Library for opening URLs.</a></li> </ul>
5
2009-08-13T07:37:51Z
[ "python", "encoding", "post", "urllib", "multipart" ]
Python standard library to POST multipart/form-data encoded data
1,270,518
<p>I would like to POST multipart/form-data encoded data. I have found an external module that does it: <a href="http://atlee.ca/software/poster/index.html">http://atlee.ca/software/poster/index.html</a> however I would rather avoid this dependency. Is there a way to do this using the standard libraries?</p> <p>thanks</p>
17
2009-08-13T07:24:00Z
18,888,633
<p>It's an old thread but still a popular one, so here is my contribution using only standard modules.</p> <p>The idea is the same than <a href="http://code.activestate.com/recipes/146306/" rel="nofollow">here</a> but support Python 2.x and Python 3.x. It also has a body generator to avoid unnecessarily memory usage.</p> <pre><code>import codecs import mimetypes import sys import uuid try: import io except ImportError: pass # io is requiered in python3 but not available in python2 class MultipartFormdataEncoder(object): def __init__(self): self.boundary = uuid.uuid4().hex self.content_type = 'multipart/form-data; boundary={}'.format(self.boundary) @classmethod def u(cls, s): if sys.hexversion &lt; 0x03000000 and isinstance(s, str): s = s.decode('utf-8') if sys.hexversion &gt;= 0x03000000 and isinstance(s, bytes): s = s.decode('utf-8') return s def iter(self, fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, file-type) elements for data to be uploaded as files Yield body's chunk as bytes """ encoder = codecs.getencoder('utf-8') for (key, value) in fields: key = self.u(key) yield encoder('--{}\r\n'.format(self.boundary)) yield encoder(self.u('Content-Disposition: form-data; name="{}"\r\n').format(key)) yield encoder('\r\n') if isinstance(value, int) or isinstance(value, float): value = str(value) yield encoder(self.u(value)) yield encoder('\r\n') for (key, filename, fd) in files: key = self.u(key) filename = self.u(filename) yield encoder('--{}\r\n'.format(self.boundary)) yield encoder(self.u('Content-Disposition: form-data; name="{}"; filename="{}"\r\n').format(key, filename)) yield encoder('Content-Type: {}\r\n'.format(mimetypes.guess_type(filename)[0] or 'application/octet-stream')) yield encoder('\r\n') with fd: buff = fd.read() yield (buff, len(buff)) yield encoder('\r\n') yield encoder('--{}--\r\n'.format(self.boundary)) def encode(self, fields, files): body = io.BytesIO() for chunk, chunk_len in self.iter(fields, files): body.write(chunk) return self.content_type, body.getvalue() </code></pre> <p><strong>Demo</strong></p> <pre><code># some utf8 key/value pairs fields = [('প্রায়', 42), ('bar', b'23'), ('foo', 'ން:')] files = [('myfile', 'image.jpg', open('image.jpg', 'rb'))] # iterate and write chunk in a socket content_type, body = MultipartFormdataEncoder().encode(fields, files) </code></pre>
7
2013-09-19T07:28:28Z
[ "python", "encoding", "post", "urllib", "multipart" ]
how to print python location(where python is install) in the output
1,270,537
<p>Lets say Python is installed in the location <code>"C:\TOOLS\COMMON\python\python252"</code> .</p> <p>I want to print this location in the output of my program. Please let me know which is the function for doing this.</p>
8
2009-08-13T07:28:44Z
1,270,552
<p>Try:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.prefix </code></pre> <p>See the documentation for the <a href="http://docs.python.org/library/sys.html" rel="nofollow"><code>sys</code> module</a> for more details.</p>
1
2009-08-13T07:32:10Z
[ "python", "path" ]
how to print python location(where python is install) in the output
1,270,537
<p>Lets say Python is installed in the location <code>"C:\TOOLS\COMMON\python\python252"</code> .</p> <p>I want to print this location in the output of my program. Please let me know which is the function for doing this.</p>
8
2009-08-13T07:28:44Z
1,270,554
<p>you can use</p> <pre><code>import sys, os os.path.dirname(sys.executable) </code></pre> <p>but remember than in Unix systems the "installation" of a program is usually distributed along the following folders:</p> <ul> <li>/usr/bin (this is what you'll probably get)</li> <li>/usr/lib</li> <li>/usr/share</li> <li>etc.</li> </ul>
9
2009-08-13T07:33:33Z
[ "python", "path" ]
how to print python location(where python is install) in the output
1,270,537
<p>Lets say Python is installed in the location <code>"C:\TOOLS\COMMON\python\python252"</code> .</p> <p>I want to print this location in the output of my program. Please let me know which is the function for doing this.</p>
8
2009-08-13T07:28:44Z
1,270,558
<p>Maybe either of these will satisfy you:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.prefix /usr &gt;&gt;&gt; print sys.path ['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0'] </code></pre>
4
2009-08-13T07:34:36Z
[ "python", "path" ]
Python Get Docstring Without Going into Interactive Mode
1,270,615
<p>I want to grab the docstring in my commandline application, but every time I call the builtin help() function, Python goes into interactive mode.</p> <p>How do I get the docstring of an object and <strong>not</strong> have Python grab focus?</p>
5
2009-08-13T07:49:52Z
1,270,621
<p>Any docstring is available through the <code>.__doc__</code> property:</p> <pre><code>&gt;&gt;&gt; print str.__doc__ </code></pre> <p>In python 3, you'll need parenthesis for printing:</p> <pre><code>&gt;&gt;&gt; print(str.__doc__) </code></pre>
7
2009-08-13T07:50:59Z
[ "python", "interactive" ]
Python Get Docstring Without Going into Interactive Mode
1,270,615
<p>I want to grab the docstring in my commandline application, but every time I call the builtin help() function, Python goes into interactive mode.</p> <p>How do I get the docstring of an object and <strong>not</strong> have Python grab focus?</p>
5
2009-08-13T07:49:52Z
1,270,639
<p>You can use <code>dir(</code>{insert class name here}<code>)</code> to get the contents of a class and then iterate over it, looking for methods or other stuff. This example looks in a class <code>Task</code>for methods starting with the name <code>cmd</code> and gets their docstring:</p> <pre><code>command_help = dict() for key in dir( Task ): if key.startswith( 'cmd' ): command_help[ key ] = getattr( Task, key ).__doc__ </code></pre>
3
2009-08-13T07:54:18Z
[ "python", "interactive" ]
Python Get Docstring Without Going into Interactive Mode
1,270,615
<p>I want to grab the docstring in my commandline application, but every time I call the builtin help() function, Python goes into interactive mode.</p> <p>How do I get the docstring of an object and <strong>not</strong> have Python grab focus?</p>
5
2009-08-13T07:49:52Z
26,030,930
<p><code>.__doc__</code> is the best choice. However, You can also use <code>inspect.getdoc</code> to get <code>docstring</code>. One advantage of using this is, it removes indentation from docstrings that are indented to line up with blocks of code.</p> <p><strong>Example:</strong></p> <pre><code>In [21]: def foo(): ....: """ ....: This is the most useful docstring. ....: """ ....: pass ....: In [22]: from inspect import getdoc In [23]: print(getdoc(foo)) This is the most useful docstring. In [24]: print(getdoc(str)) str(object='') -&gt; string Return a nice string representation of the object. If the argument is a string, the return value is the same object. </code></pre>
0
2014-09-25T05:06:44Z
[ "python", "interactive" ]
django unit testing and global fixtures
1,270,657
<p>I'm working on a web project in Django, and I'm using the python unittest framework. For every app I have some fixtures. This means, that every app has some identical tables in fixtures. I would like to share fixtures between apps and testcases, because otherwise if I change a model, I will have to change all json fixtures where this concrete table is referenced.</p> <p>Is it sensible to use global fixtures?</p>
3
2009-08-13T08:00:20Z
1,270,709
<p>I would highly recommend looking into Django's <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">Testing architecture</a>. Check out TestCase.fixtures especially; this is far more advanced and Django-specific than unittest.</p>
1
2009-08-13T08:10:30Z
[ "python", "django", "unit-testing" ]
django unit testing and global fixtures
1,270,657
<p>I'm working on a web project in Django, and I'm using the python unittest framework. For every app I have some fixtures. This means, that every app has some identical tables in fixtures. I would like to share fixtures between apps and testcases, because otherwise if I change a model, I will have to change all json fixtures where this concrete table is referenced.</p> <p>Is it sensible to use global fixtures?</p>
3
2009-08-13T08:00:20Z
1,270,976
<p>I can't think of anything wrong with using global fixtures as long as you delete them in your <code>tearDown</code> method (or <code>teardown_test_environment</code> method - see below).</p> <p>I am not sure if you are asking to find out how to do this. If so there are two ways that I can think of. </p> <ol> <li><p>Use a common base class for all your tests. Something like this:</p> <pre><code>class TestBase(django.test.TestCase): fixtures = ['common_fixtures.xml'] class MyTestClass(TestBase): fixtures = TestBase.fixtures + ['fixtures_for_this_test.xml'] def test_foo(self): # test stuff </code></pre></li> <li><p>Use a custom test runner. In your test runner load all the fixtures you need before running the tests and take them down after executing the tests. You should preferably do this by using your own <code>setup_</code> and <code>teardown_test_environment</code> methods.</p></li> </ol>
1
2009-08-13T09:28:56Z
[ "python", "django", "unit-testing" ]
django unit testing and global fixtures
1,270,657
<p>I'm working on a web project in Django, and I'm using the python unittest framework. For every app I have some fixtures. This means, that every app has some identical tables in fixtures. I would like to share fixtures between apps and testcases, because otherwise if I change a model, I will have to change all json fixtures where this concrete table is referenced.</p> <p>Is it sensible to use global fixtures?</p>
3
2009-08-13T08:00:20Z
5,206,157
<p>Do not use static fixtures, it is a bad automated tests pattern. Use dynamic fixtures.</p> <p><a href="https://github.com/paulocheque/django-dynamic-fixture" rel="nofollow">Django Dynamic Fixture</a> has options to create global fixtures. Check its <a href="https://github.com/paulocheque/django-dynamic-fixture/wiki/Documentation#wiki-setup_nose_plugin" rel="nofollow">Nose plugin</a> or the <a href="https://github.com/paulocheque/django-dynamic-fixture/wiki/Documentation#wiki-default_shelve" rel="nofollow">Shelve option</a>.</p>
2
2011-03-05T19:14:49Z
[ "python", "django", "unit-testing" ]
Why does import of ctypes raise ImportError?
1,270,738
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import ctypes Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\ctypes\__init__.py", line 17, in &lt;module&gt; from struct import calcsize as _calcsize ImportError: cannot import name calcsize &gt;&gt;&gt; from ctypes import * Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\ctypes\__init__.py", line 17, in &lt;module&gt; from struct import calcsize as _calcsize ImportError: cannot import name calcsize &gt;&gt;&gt; </code></pre>
3
2009-08-13T08:18:24Z
1,270,756
<p>It seems you have another struct.py in your path somewhere.</p> <p>Try this to see where python finds your struct module:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; import struct &gt;&gt;&gt; inspect.getabsfile(struct) 'c:\\python26\\lib\\struct.py' </code></pre>
8
2009-08-13T08:23:35Z
[ "python", "ctypes", "python-2.6", "importerror" ]
Most concise way to check whether a list is empty or contains only None?
1,270,920
<p>Most concise way to check whether a list is empty or contains only None?</p> <p>I understand that I can test:</p> <pre><code>if MyList: pass </code></pre> <p>and:</p> <pre><code>if not MyList: pass </code></pre> <p>but what if the list has an item (or multiple items), but those item/s are None:</p> <pre><code>MyList = [None, None, None] if ???: pass </code></pre>
6
2009-08-13T09:13:24Z
1,270,937
<p>If you are concerned with elements in the list which evaluate as true:</p> <pre><code>if mylist and filter(None, mylist): print "List is not empty and contains some true values" else: print "Either list is empty, or it contains no true values" </code></pre> <p>If you want to strictly check for <code>None</code>, use <code>filter(lambda x: x is not None, mylist)</code> instead of <code>filter(None, mylist)</code> in the <code>if</code> statement above.</p>
2
2009-08-13T09:19:15Z
[ "python", "list", "types" ]
Most concise way to check whether a list is empty or contains only None?
1,270,920
<p>Most concise way to check whether a list is empty or contains only None?</p> <p>I understand that I can test:</p> <pre><code>if MyList: pass </code></pre> <p>and:</p> <pre><code>if not MyList: pass </code></pre> <p>but what if the list has an item (or multiple items), but those item/s are None:</p> <pre><code>MyList = [None, None, None] if ???: pass </code></pre>
6
2009-08-13T09:13:24Z
1,270,938
<p>One way is to use <a href="http://docs.python.org/3.1/library/functions.html#all"><code>all</code></a> and a list comprehension:</p> <pre><code>if all(e is None for e in myList): print('all empty or None') </code></pre> <p>This works for empty lists as well. More generally, to test whether the list only contains things that evaluate to <code>False</code>, you can use <a href="http://docs.python.org/3.1/library/functions.html#any"><code>any</code></a>:</p> <pre><code>if not any(myList): print('all empty or evaluating to False') </code></pre>
15
2009-08-13T09:19:45Z
[ "python", "list", "types" ]
Most concise way to check whether a list is empty or contains only None?
1,270,920
<p>Most concise way to check whether a list is empty or contains only None?</p> <p>I understand that I can test:</p> <pre><code>if MyList: pass </code></pre> <p>and:</p> <pre><code>if not MyList: pass </code></pre> <p>but what if the list has an item (or multiple items), but those item/s are None:</p> <pre><code>MyList = [None, None, None] if ???: pass </code></pre>
6
2009-08-13T09:13:24Z
1,270,939
<p>You can use the <code>all()</code> function to test is all elements are None:</p> <pre><code>a = [] b = [None, None, None] all(e is None for e in a) # True all(e is None for e in b) # True </code></pre>
9
2009-08-13T09:19:47Z
[ "python", "list", "types" ]
Most concise way to check whether a list is empty or contains only None?
1,270,920
<p>Most concise way to check whether a list is empty or contains only None?</p> <p>I understand that I can test:</p> <pre><code>if MyList: pass </code></pre> <p>and:</p> <pre><code>if not MyList: pass </code></pre> <p>but what if the list has an item (or multiple items), but those item/s are None:</p> <pre><code>MyList = [None, None, None] if ???: pass </code></pre>
6
2009-08-13T09:13:24Z
1,270,962
<p>You can directly compare lists with <code>==</code>:</p> <pre><code>if x == [None,None,None]: if x == [1,2,3] </code></pre>
4
2009-08-13T09:25:10Z
[ "python", "list", "types" ]
Python - how to refer to relative paths of resources when working with code repository
1,270,951
<p>We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like</p> <pre><code>thefile=open('test.csv') </code></pre> <p>or</p> <pre><code>thefile=open('../somedirectory/test.csv') </code></pre> <p>It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like:</p> <pre><code>path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) </code></pre> <p>Is this the right way? Is it possible? Thanks</p>
89
2009-08-13T09:22:30Z
1,270,970
<p>Try to use a filename relative to the current files path. Example for './my_file':</p> <pre><code>fn = os.path.join(os.path.dirname(__file__), 'my_file') </code></pre>
128
2009-08-13T09:27:28Z
[ "python", "path", "repository", "project", "relative" ]
Python - how to refer to relative paths of resources when working with code repository
1,270,951
<p>We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like</p> <pre><code>thefile=open('test.csv') </code></pre> <p>or</p> <pre><code>thefile=open('../somedirectory/test.csv') </code></pre> <p>It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like:</p> <pre><code>path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) </code></pre> <p>Is this the right way? Is it possible? Thanks</p>
89
2009-08-13T09:22:30Z
1,270,975
<p>You can use the build in <code>__file__</code> variable. It contains the path of the current file. I would implement getBaseOfProject in a module in the root of your project. There I would get the path part of <code>__file__</code> and would return that. This method can then be used everywhere in your project.</p>
0
2009-08-13T09:28:40Z
[ "python", "path", "repository", "project", "relative" ]
Python - how to refer to relative paths of resources when working with code repository
1,270,951
<p>We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like</p> <pre><code>thefile=open('test.csv') </code></pre> <p>or</p> <pre><code>thefile=open('../somedirectory/test.csv') </code></pre> <p>It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like:</p> <pre><code>path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) </code></pre> <p>Is this the right way? Is it possible? Thanks</p>
89
2009-08-13T09:22:30Z
1,271,027
<pre><code>import os cwd = os.getcwd() path = os.path.join(cwd, "my_file") f = open(path) </code></pre> <p>You also try to normalize your <code>cwd</code> using <code>os.path.abspath(os.getcwd())</code>. More info <a href="http://docs.python.org/library/os.path.html" rel="nofollow">here</a>.</p>
1
2009-08-13T09:40:27Z
[ "python", "path", "repository", "project", "relative" ]
Python - how to refer to relative paths of resources when working with code repository
1,270,951
<p>We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like</p> <pre><code>thefile=open('test.csv') </code></pre> <p>or</p> <pre><code>thefile=open('../somedirectory/test.csv') </code></pre> <p>It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like:</p> <pre><code>path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) </code></pre> <p>Is this the right way? Is it possible? Thanks</p>
89
2009-08-13T09:22:30Z
1,271,580
<p>I often use something similar to this:</p> <pre><code>import os DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'datadir')) # if you have more paths to set, you might want to shorten this as here = lambda x: os.path.abspath(os.path.join(os.path.dirname(__file__), x)) DATA_DIR = here('datadir') pathjoin = os.path.join # ... # later in script for fn in os.listdir(DATA_DIR): f = open(pathjoin(DATA_DIR, fn)) # ... </code></pre> <p>The variable</p> <pre><code>__file__ </code></pre> <p>holds the file name of the script you write that code in, so you can make paths relative to script, but still written with absolute paths. It works quite well for several reasons:</p> <ul> <li>path is absolute, but still relative</li> <li>the project can still be deployed in a relative container</li> </ul> <p>But you need to watch for platform compatibility - Windows' os.pathsep is different than UNIX.</p>
6
2009-08-13T12:11:19Z
[ "python", "path", "repository", "project", "relative" ]
Python - how to refer to relative paths of resources when working with code repository
1,270,951
<p>We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like</p> <pre><code>thefile=open('test.csv') </code></pre> <p>or</p> <pre><code>thefile=open('../somedirectory/test.csv') </code></pre> <p>It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like:</p> <pre><code>path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) </code></pre> <p>Is this the right way? Is it possible? Thanks</p>
89
2009-08-13T09:22:30Z
4,874,611
<p>I spent a long time figuring out the answer to this, but I finally got it (and it's actually really simple):</p> <pre><code>import sys import os sys.path.append(os.getcwd() + '/your/subfolder/of/choice') # now import whatever other modules you want, both the standard ones, # as the ones supplied in your subfolders </code></pre> <p>This will append the relative path of your subfolder to the directories for python to look in It's pretty quick and dirty, but it works like a charm :)</p>
-2
2011-02-02T12:43:48Z
[ "python", "path", "repository", "project", "relative" ]
Python - how to refer to relative paths of resources when working with code repository
1,270,951
<p>We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like</p> <pre><code>thefile=open('test.csv') </code></pre> <p>or</p> <pre><code>thefile=open('../somedirectory/test.csv') </code></pre> <p>It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like:</p> <pre><code>path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) </code></pre> <p>Is this the right way? Is it possible? Thanks</p>
89
2009-08-13T09:22:30Z
9,177,940
<p>If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package_resources.</p> <p>In your case the example would be</p> <pre><code>import pkg_resources my_data = pkg_resources.resource_string(__name__, "foo.dat") </code></pre> <p>Which of course reads the resource and the read binary data would be the value of my_data</p> <p>If you just need the filename you could also use</p> <pre><code>resource_filename(package_or_requirement, resource_name) </code></pre> <p>Example:</p> <pre><code>resource_filename("MyPackage","foo.dat") </code></pre> <p>The advantage is that its guaranteed to work even if it is an archive distribution like an egg. </p> <p>See <a href="http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api">http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api</a></p>
23
2012-02-07T14:24:07Z
[ "python", "path", "repository", "project", "relative" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,270,999
<pre><code>line = line[2:] </code></pre>
2
2009-08-13T09:34:34Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,271,003
<p><a href="http://docs.python.org/tutorial/introduction.html#strings">String slicing</a> will help you:</p> <pre><code>&gt;&gt;&gt; a="Some very long string" &gt;&gt;&gt; a[2:] 'me very long string' </code></pre>
19
2009-08-13T09:35:00Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,271,005
<p>Just use line[2:]</p>
0
2009-08-13T09:35:46Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,271,007
<p>You were off to a good start. Try this in your loop:</p> <pre><code>for line in lines: line = line[2:] # do something here </code></pre> <p>The [2:] is called "<a href="http://docs.python.org/tutorial/introduction.html#strings">slice</a>" syntax, it essentially says "give me the part of this sequence which begins at index 2 and continues to the end (since no end point was specified after the colon).</p>
42
2009-08-13T09:36:11Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,271,029
<p>Instead of using a for loop, you might be happier with a a list comprehension:</p> <pre><code>[line[2:] for line in lines] </code></pre> <p><hr /></p> <p>Just as a curiosity, do check the <code>cut</code> unix tool.</p> <pre><code>$ cut -c2- filename </code></pre> <p>The slicing syntax for -c is quite similar to python's.</p>
10
2009-08-13T09:41:14Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,271,030
<p>Just as a tip, you can shorten your program to </p> <pre><code>for line in open('M:/file.txt'): line = line[2:] </code></pre> <p>And if you need to carry the line number too, use</p> <pre><code>for i, line in enumerate(open('M:/file.txt.')): line = line[2:] </code></pre>
10
2009-08-13T09:41:37Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,271,045
<pre><code>for line in open("file"): print line[2:] </code></pre>
2
2009-08-13T09:44:27Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,272,548
<p>If you want to modify a file's contents, not just process the string, try <code>fileinput</code>'s <code>inplace</code> parameter:</p> <pre><code># strip_2_chars.py import fileinput for line in fileinput.input(inplace=1): print line[2:] </code></pre> <p>Then, on the command line:</p> <pre><code>python strip_2_chars.py m:\file.txt </code></pre>
3
2009-08-13T15:03:31Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,274,307
<p>You'll find python has some great ways to deal with strings. Some other useful string methods you might want to check out are ones like split(), replace(), and startswith()/endswith().</p>
1
2009-08-13T20:13:42Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,311,668
<p>It may be interesting to know that there is a subtle, yet important difference between:</p> <pre><code>file = open( filename ) lines = file.readlines() for line in lines: do something </code></pre> <p>and</p> <pre><code>file = open( filename ) for line in file: do something </code></pre> <p>The first solution (with <code>readlines</code>) will load the whole contents of the file in memory and return a python list (of strings). On the other hand, the second solution makes use of something that's called a <a href="http://docs.python.org/tutorial/classes.html#iterators" rel="nofollow"><code>iterator</code></a>. This will in fact move the pointer in the file as needed and return a string. This has an important benefit: The file is not loaded into memory. For small files, both approaches are OK. But as long as you only work with the file line-by-line, I suggest to use the iterator behavior directly.</p> <p>So my solution would be:</p> <pre><code>infile = open( filename ) outfile = open( "%s.new" % filename, "w" ) for line in infile: outfile.write( line[2:] ) infile.close() outfile.close() </code></pre> <p>Come to think of it: If it's a non-ascii file (for example latin-1 encoded), consider using <a href="http://docs.python.org/library/codecs.html#codecs.open" rel="nofollow">codecs.open</a>. Otherwise you may have a nasty surprise as you may accidentally cut a multibyte character in half ;)</p> <p>However, if you don't need python, and the only thing you need to do is crop the first two characters from the file, then the most efficient way to do it is kch's suggestion and use <code>cut</code>:</p> <pre><code>cat filename | cut -d2- &gt; newfile </code></pre> <p>For these kinds of quick-and-dirty file operations I always have <a href="http://www.cygwin.com" rel="nofollow">cygwin</a> installed on my non-linux boxen. But I believe there's a set of windows binaries for these tools as well which would perform faster than in cygwin iirc.</p>
3
2009-08-21T12:32:33Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
1,359,481
<p>Since you are learning Python, I would like to add that, given the tools offered by Python (slicing, split, replace and all the other which have been mention), you will find that for many tasks regex are overkill. So the </p> <pre><code>import re </code></pre> <p>at the beginning of your example may or may not be strictly needed. </p>
0
2009-08-31T21:21:23Z
[ "python" ]
How to remove two chars from the beginning of a line
1,270,990
<p>I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this:</p> <pre><code>#!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here </code></pre>
21
2009-08-13T09:31:53Z
38,113,402
<p>Not very efficient but yes it does work. Looks pretty complex.</p> <pre><code>print line[-(len(line)-2):] </code></pre>
-1
2016-06-30T03:16:12Z
[ "python" ]
Resize a figure automatically in matplotlib
1,271,023
<p>Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image? </p> <p>I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.</p> <p>I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way? </p>
20
2009-08-13T09:38:46Z
1,271,192
<p>Do you mean changing the size of the image or the area that is visable within a plot?</p> <p>The size of a figure can be set with <a href="http://matplotlib.sourceforge.net/api/figure%5Fapi.html" rel="nofollow">Figure.set_figsize_inches</a>. Also the <a href="http://www.scipy.org/Cookbook/Matplotlib/AdjustingImageSize" rel="nofollow">SciPy Cookbook</a> has an entry on changing image size which contains a section about multiple images per figure.</p> <p>Also take a look at this <a href="http://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib">question</a>.</p>
3
2009-08-13T10:31:09Z
[ "python", "matplotlib" ]
Resize a figure automatically in matplotlib
1,271,023
<p>Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image? </p> <p>I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.</p> <p>I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way? </p>
20
2009-08-13T09:38:46Z
1,278,685
<p>Use <strong>bbox_inches='tight'</strong></p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm X = 10*np.random.rand(5,3) fig = plt.figure(figsize=(15,5),facecolor='w') ax = fig.add_subplot(111) ax.imshow(X, cmap=cm.jet) plt.savefig("image.png",bbox_inches='tight',dpi=100) </code></pre> <p>...only works when saving images though, not showing them.</p>
26
2009-08-14T15:57:48Z
[ "python", "matplotlib" ]
Resize a figure automatically in matplotlib
1,271,023
<p>Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image? </p> <p>I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.</p> <p>I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way? </p>
20
2009-08-13T09:38:46Z
10,448,306
<p>just use aspect='auto' when you call imshow</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm X = 10*np.random.rand(5,3) plt.imshow(X, aspect='auto') </code></pre> <p>it works even if it is just for showing and not saving</p>
10
2012-05-04T11:51:06Z
[ "python", "matplotlib" ]
How to change the "Event" portlet in Plone 3
1,271,057
<p>I am trying to customize the "Event" portlet in Plone 3 that shows the upcoming events. The "view" link in the footer of that portlet goes to the /events URL. But my site is multi-lingual so that URL is not always correct. For example, the correct URL for Dutch events should be /evenementen.</p> <p>In my setup I use one folder per language. /en holds all English content, /nl holds all Dutch content, etcetera. The plone root has no portlets so I add the "Event" portlet to both the /nl and /en folder separately. I was looking in the ZMI at the events.pt template and it seems that it takes the URL from a property, but where is that property defines and how can I change it? I can't find the portlet configurations in the ZMI. Here is the snippet from plone.app.portlets.portlets/events.pt:</p> <pre><code>&lt;dd class="portletFooter"&gt; &lt;a href="" class="tile" tal:attributes="href view/all_events_link" i18n:translate="box_upcoming_events"&gt; Upcoming events&amp;hellip; &lt;/a&gt; &lt;span class="portletBottomLeft"&gt;&lt;/span&gt; &lt;span class="portletBottomRight"&gt;&lt;/span&gt; &lt;/dd&gt; </code></pre> <p>So, can I somewhere change that all_events_link property in the ZMI? If so, where?</p> <p>As an alternative I have also tried to add a "Collection" portlet with a collection that lists all events. But the problem is that the collection portlet doesn't want to show the start and end dates for the events.</p>
1
2009-08-13T09:47:59Z
1,271,573
<p>The events portlet uses a view to provide it with data, and the expression 'view/all_events_link' calls a <a href="http://dev.plone.org/plone/browser/plone.app.portlets/trunk/plone/app/portlets/portlets/events.py#L75" rel="nofollow" title="events view source code">method on that view</a> to provide it with a link. You have 2 options to replace that link:</p> <ol> <li><p>Register your own event portlet that subclasses the old one, and replaces the all_events_link method. This in the heavy customization option, and requires Python coding. See <a href="http://n2.nabble.com/Creating-a-new-portlet-Plone-3-tp3332583p3342170.html" rel="nofollow" title="Plone Users: Creating a new portlet Plone 3">this mail thread</a> on some general pointers on how to achieve this.</p></li> <li><p>Replace just the template with a portlet renderer. Martin Aspeli has <a href="http://plone.org/documentation/tutorial/customization-for-developers/portlet-renderers" rel="nofollow" title="Portlet Renderers">documented this method on Plone.org</a>; this only requires some ZCML configuration to get working. You can then copy the events.pt template and replace the portlet footer with one that links to the right location.</p></li> </ol>
1
2009-08-13T12:08:18Z
[ "python", "portlet", "plone", "zope" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
1,271,323
<p>I'd go with IronPython and this article : <a href="http://www.blackwasp.co.uk/MapDriveLetter.aspx" rel="nofollow">Mapping a Drive Letter Programmatically</a>. Or you could use the Win32 API directly.</p>
2
2009-08-13T11:12:35Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
1,271,485
<p>Here are a couple links which show use of the win32net module that should provide the functionality you need.</p> <p><a href="http://docs.activestate.com/activepython/2.4/pywin32/html/win32/help/win32net.html" rel="nofollow">http://docs.activestate.com/activepython/2.4/pywin32/html/win32/help/win32net.html</a> <a href="http://www.blog.pythonlibrary.org/?p=20" rel="nofollow">http://www.blog.pythonlibrary.org/?p=20</a></p>
2
2009-08-13T11:46:02Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
1,272,040
<p>I don't have a server to test with here at home, but maybe you could simply use the standard library's subprocess module to execute the appropriate NET USE command?</p> <p>Looking at NET HELP USE from a windows command prompt, looks like you should be able to enter both the password and user id in the net use command to map the drive.</p> <p>A quick test in the interpreter of a bare net use command w/o the mapping stuff:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.check_call(['net', 'use']) New connections will be remembered. There are no entries in the list. 0 &gt;&gt;&gt; </code></pre>
2
2009-08-13T13:42:57Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
1,860,152
<p>Assuming that you import necessary libraries, This was a part of an RPC server where the client requested the server to map a drive locally...</p> <pre><code>#Small function to check the availability of network resource. def isAvailable(path): winCMD = 'IF EXIST ' + path + ' echo YES' cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate() return string.find(str(cmdOutPut), 'YES',) #Small function to check if the mention location is a directory def isDirectory(path): winCMD = 'dir ' + path + ' | FIND ".."' cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate() return string.find(str(cmdOutPut), 'DIR',) </code></pre> <p>================Check the white spaces from here, these were a part of a function============</p> <pre><code>def mapNetworkDrive(self, drive, networkPath, user, password): #Check for drive availability if isAvailable(drive) &gt; -1: #Drive letter is already in use return -1 #Check for network resource availability if isAvailable(networkPath) == -1: print "Path not accessible: ", networkPath #Network path is not reachable return -1 #Prepare 'NET USE' commands winCMD1 = 'NET USE ' + drive + ' ' + networkPath winCMD2 = winCMD1 + ' ' + password + ' /User' + user print "winCMD1 = ", winCMD1 print "winCMD2 = ", winCMD2 #Execute 'NET USE' command with authentication winCMD = winCMD2 cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate() print "Executed: ", winCMD if string.find(str(cmdOutPut), 'successfully',) == -1: print winCMD, " FAILED" winCMD = winCMD1 #Execute 'NET USE' command without authentication, incase session already open cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate() print "Executed: ", winCMD if string.find(str(cmdOutPut), 'successfully',) == -1: print winCMD, " FAILED" return -1 #Mapped on second try return 1 #Mapped with first try return 1 def unmapNetworkDrive(self, drive): #Check if the drive is in use if isAvailable(drive) == -1: #Drive is not in use return -1 #Prepare 'NET USE' command winCMD = 'net use ' + drive + ' /DELETE' cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate() if string.find(str(cmdOutPut), 'successfully',) == -1: #Could not UN-MAP, this might be a physical drive return -1 #UN-MAP successful return 1 </code></pre>
2
2009-12-07T14:00:50Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
2,093,830
<p>Okay, Here's another method...</p> <p>This one was after going through win32wnet. Let me know what you think...</p> <pre><code>def mapDrive(drive, networkPath, user, password, force=0): print networkPath if (os.path.exists(drive)): print drive, " Drive in use, trying to unmap..." if force: try: win32wnet.WNetCancelConnection2(drive, 1, 1) print drive, "successfully unmapped..." except: print drive, "Unmap failed, This might not be a network drive..." return -1 else: print "Non-forcing call. Will not unmap..." return -1 else: print drive, " drive is free..." if (os.path.exists(networkPath)): print networkPath, " is found..." print "Trying to map ", networkPath, " on to ", drive, " ....." try: win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password) except: print "Unexpected error..." return -1 print "Mapping successful" return 1 else: print "Network path unreachable..." return -1 </code></pre> <p>And to unmap, just use....</p> <pre><code>def unmapDrive(drive, force=0): #Check if the drive is in use if (os.path.exists(drive)): print "drive in use, trying to unmap..." if force == 0: print "Executing un-forced call..." try: win32wnet.WNetCancelConnection2(drive, 1, force) print drive, "successfully unmapped..." return 1 except: print "Unmap failed, try again..." return -1 else: print drive, " Drive is already free..." return -1 </code></pre>
4
2010-01-19T13:38:46Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
19,171,820
<p>Building off of @Anon's suggestion:</p> <pre><code># Drive letter: M # Shared drive path: \\shared\folder # Username: user123 # Password: password import subprocess # Disconnect anything on M subprocess.call(r'net use m: /del', shell=True) # Connect to shared drive, use drive letter M subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True) </code></pre> <p>I prefer this simple approach, especially if all the information is static.</p>
9
2013-10-04T01:39:49Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
20,201,066
<p>I had trouble getting this line to work: </p> <p>win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password)</p> <p>But was successful with this:</p> <p>win32wnet.WNetAddConnection2(1, 'Z:', r'\UNCpath\share', None, 'login', 'password') </p>
0
2013-11-25T19:01:44Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map windows drives using Python?
1,271,317
<p>What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.</p>
11
2009-08-13T11:09:36Z
21,732,529
<p>If you want to map the current login user, i think subprocess solve your problem. But is you want to control different mappings for different users, from a single master account. You could do this from the register of windows</p> <p>The idea is to load the profile of a given user.</p> <pre><code>import win32api import win32security import win32profile import win32netcon import win32net import win32netcon import win32con il = 'G' m = '\\\\192.168.1.16\\my_share_folder' usu = 'my_user' cla = 'passwd' #login the user hUser = win32security.LogonUser( usu, None, cla, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) #load the profile hReg = win32profile.LoadUserProfile ( hUser, {"UserName" : usu} ) #alter the regedit entries of usu win32api.RegCreateKey(hReg, "Network") hkey = win32api.RegOpenKey(hReg, "Network\\", 0, win32con.KEY_ALL_ACCESS) win32api.RegCreateKey(hkey, il) hkey = win32api.RegOpenKey(hReg, "Network\\%s" % il, 0, win32con.KEY_ALL_ACCESS) win32api.RegSetValueEx(hkey, "ConnectionType", 0, win32con.REG_DWORD, 1) win32api.RegSetValueEx(hkey, "DeferFlags", 0, win32con.REG_DWORD, 4) win32api.RegSetValueEx(hkey, "ProviderName", 0, win32con.REG_SZ, "Red de Microsoft Windows") win32api.RegSetValueEx(hkey, "ProviderType", 0, win32con.REG_DWORD, 131072) win32api.RegSetValueEx(hkey, "RemotePath", 0, win32con.REG_SZ, m) win32api.RegSetValueEx(hkey, "UserName", 0, win32con.REG_DWORD, 0) </code></pre>
0
2014-02-12T15:41:21Z
[ "python", "windows", "mapping", "drive" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
1,271,349
<p>If GrzegorzOledzki's answer won't suffice, you could probably use <code>send()</code> to accomplish your goal. See <a href="http://www.python.org/dev/peps/pep-0342/" rel="nofollow">PEP-0342</a> for more details on enhanced generators and yield expressions.</p> <p>UPDATE: Also see <a href="http://docs.python.org/library/itertools.html#itertools.tee" rel="nofollow"><code>itertools.tee()</code></a>. It involves some of that memory vs. processing tradeoff mentioned above, but it <em>might</em> save some memory over just storing the generator results in a <code>list</code>; it depends on how you're using the generator.</p>
4
2009-08-13T11:17:40Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
1,271,353
<p>Generators can't be rewound. You have the following options:</p> <ol> <li><p>Run the generator function again, restarting the generation:</p> <pre><code>y = FunctionWithYield() for x in y: print(x) y = FunctionWithYield() for x in y: print(x) </code></pre></li> <li><p>Store the generator results in a data structure on memory or disk which you can iterate over again:</p> <pre><code>y = list(FunctionWithYield()) for x in y: print(x) # can iterate again: for x in y: print(x) </code></pre></li> </ol> <p>The downside of option <strong>1</strong> is that it computes the values again. If that's CPU-intensive you end up calculating twice. On the other hand, the downside of <strong>2</strong> is the storage. The entire list of values will be stored on memory. If there are too many values, that can be unpractical.</p> <p>So you have the classic <em>memory vs. processing tradeoff</em>. I can't imagine a way of rewinding the generator without either storing the values or calculating them again.</p>
71
2009-08-13T11:18:29Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
1,271,459
<p>Probably the most simple solution is to wrap the expensive part in an object and pass that to the generator:</p> <pre><code>data = ExpensiveSetup() for x in FunctionWithYield(data): pass for x in FunctionWithYield(data): pass </code></pre> <p>This way, you can cache the expensive calculations.</p> <p>If you can keep all results in RAM at the same time, then use <code>list()</code> to materialize the results of the generator in a plain list and work with that.</p>
16
2009-08-13T11:39:50Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
1,271,481
<p>Another option is to use the <code>itertools.tee()</code> function to create a second version of your generator:</p> <pre><code>y = FunctionWithYield() y, y_backup = tee(y) for x in y: print(x) for x in y_backup: print(x) </code></pre> <p>This could be beneficial from memory usage point of view if the original iteration might not process all the items.</p>
47
2009-08-13T11:44:17Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
1,271,699
<p>I'm not sure what you meant by expensive preparation, but I guess you actually have</p> <pre><code>data = ... # Expensive computation y = FunctionWithYield(data) for x in y: print(x) #here must be something to reset 'y' # this is expensive - data = ... # Expensive computation # y = FunctionWithYield(data) for x in y: print(x) </code></pre> <p>If that's the case, why not reuse <code>data</code>?</p>
0
2009-08-13T12:38:04Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
18,455,731
<p>It can be done by code object. Here is the example.</p> <pre><code>code_str="y=(a for a in [1,2,3,4])" code1=compile(code_str,'&lt;string&gt;','single') exec(code1) for i in y: print i </code></pre> <p>1 2 3 4</p> <pre><code>for i in y: print i exec(code1) for i in y: print i </code></pre> <p>1 2 3 4</p>
-3
2013-08-27T01:56:15Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
19,403,253
<pre><code>&gt;&gt;&gt; def gen(): ... def init(): ... return 0 ... i = init() ... while True: ... val = (yield i) ... if val=='restart': ... i = init() ... else: ... i += 1 &gt;&gt;&gt; g = gen() &gt;&gt;&gt; g.next() 0 &gt;&gt;&gt; g.next() 1 &gt;&gt;&gt; g.next() 2 &gt;&gt;&gt; g.next() 3 &gt;&gt;&gt; g.send('restart') 0 &gt;&gt;&gt; g.next() 1 &gt;&gt;&gt; g.next() 2 </code></pre>
17
2013-10-16T12:21:14Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
35,840,651
<p>You can define a function that returns your generator</p> <pre><code>def f(): def FunctionWithYield(generator_args): code here... return FunctionWithYield </code></pre> <p>Now you can just do as many times as you like:</p> <pre><code>for x in f()(generator_args): print(x) for x in f()(generator_args): print(x) </code></pre>
0
2016-03-07T09:55:55Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
39,392,965
<p>From <a href="https://docs.python.org/3/library/itertools.html#itertools.tee" rel="nofollow">official documentation of tee</a>:</p> <blockquote> <p>In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().</p> </blockquote> <p>So it's best to use <code>list(iterable)</code> instead in your case.</p>
1
2016-09-08T13:59:22Z
[ "python", "generator", "yield" ]
Reseting generator object in Python
1,271,320
<p>I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times.</p> <pre><code>y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) </code></pre> <p>Of course, I'm taking in mind copying content into simple list. </p>
73
2009-08-13T11:10:48Z
39,564,774
<p>I want to offer a different solution to an old problem</p> <pre><code>class ReusableGenerator: def __init__(self, generator_factory): self.generator_factory = generator_factory def __iter__(self): return self.generator_factory() squares = ReusableGenerator(lambda: (x * x for x in range(5))) for x in squares: print(x) for x in squares: print(x) </code></pre> <p>This is how you would use it</p> <pre><code>y = ReusableGenerator(function_with_yield) for x in y: print(x) for x in y: print(x) </code></pre> <p>The benefit of this when compared to something like <code>list(generator)</code> is that this is <code>O(1)</code> space complexity and <code>list(generator)</code> is <code>O(n)</code>. The disadvantage is that, if you only have access to the generator, but not the function that produced the generator, then you cannot use this method. For example, <strong>it might seem reasonable to do the following, but it will not work.</strong></p> <pre><code>g = (x * x for x in range(5)) squares = ReusableGenerator(lambda: g) for x in squares: print(x) for x in squares: print(x) </code></pre>
0
2016-09-19T03:04:43Z
[ "python", "generator", "yield" ]
ImportError: no module named py2exe
1,271,337
<p>I get this error when I try to use one of the py2exe samples with py2exe.</p> <pre><code>File "setup.py", line 22, in ? import py2exe ImportError: no module named py2exe </code></pre> <p>I've installed py2exe with the installer, and I use python 2.6. I have downloaded the correct installer from the site (The python 2.6 one.)</p> <p>My path is set to C:\Python26 and I can run normal python scripts from within the command prompt.</p> <p>Any idea what to do?</p> <p>Thanks.</p> <p>Edit: I had python 3.1 installed first but removed it afterwards. Could that be the problem?</p>
9
2009-08-13T11:14:34Z
1,271,366
<p>If you have any other versions of Python installed, it may be that another Python version is the default Python. Could this be the case? I believe the default Python installation is determined from a registry setting.</p>
2
2009-08-13T11:20:45Z
[ "python", "py2exe" ]
ImportError: no module named py2exe
1,271,337
<p>I get this error when I try to use one of the py2exe samples with py2exe.</p> <pre><code>File "setup.py", line 22, in ? import py2exe ImportError: no module named py2exe </code></pre> <p>I've installed py2exe with the installer, and I use python 2.6. I have downloaded the correct installer from the site (The python 2.6 one.)</p> <p>My path is set to C:\Python26 and I can run normal python scripts from within the command prompt.</p> <p>Any idea what to do?</p> <p>Thanks.</p> <p>Edit: I had python 3.1 installed first but removed it afterwards. Could that be the problem?</p>
9
2009-08-13T11:14:34Z
1,271,495
<p>Sounds like something has installed Python 2.4.3 behind your back, and set that to be the default.</p> <p>Short term, try running your script explicitly with Python 2.6 like this:</p> <pre><code>c:\Python26\python.exe setup.py ... </code></pre> <p>Long term, you need to check your system PATH (which it sounds like you've already done) and your file associations, like this:</p> <pre><code>C:\Users\rjh&gt;assoc .py .py=Python.File C:\Users\rjh&gt;ftype Python.File Python.File="C:\Python26\python.exe" "%1" %* </code></pre> <p>Simply removing Python 2.4.3 might be a mistake, as presumably something on your system is relying on it. Changing the PATH and file associations to point to Python 2.6 <em>probably</em> won't break whatever thing that is, but I couldn't guarantee it.</p>
7
2009-08-13T11:47:55Z
[ "python", "py2exe" ]
ImportError: no module named py2exe
1,271,337
<p>I get this error when I try to use one of the py2exe samples with py2exe.</p> <pre><code>File "setup.py", line 22, in ? import py2exe ImportError: no module named py2exe </code></pre> <p>I've installed py2exe with the installer, and I use python 2.6. I have downloaded the correct installer from the site (The python 2.6 one.)</p> <p>My path is set to C:\Python26 and I can run normal python scripts from within the command prompt.</p> <p>Any idea what to do?</p> <p>Thanks.</p> <p>Edit: I had python 3.1 installed first but removed it afterwards. Could that be the problem?</p>
9
2009-08-13T11:14:34Z
1,968,540
<p>Seems like you need to download proper <a href="http://sourceforge.net/projects/py2exe/">py2exe</a> distribution. </p> <p>Check out if your <code>c:\Python26\Lib\site-packages\</code> contains <code>py2exe</code> folder.</p>
5
2009-12-28T08:26:58Z
[ "python", "py2exe" ]
ImportError: no module named py2exe
1,271,337
<p>I get this error when I try to use one of the py2exe samples with py2exe.</p> <pre><code>File "setup.py", line 22, in ? import py2exe ImportError: no module named py2exe </code></pre> <p>I've installed py2exe with the installer, and I use python 2.6. I have downloaded the correct installer from the site (The python 2.6 one.)</p> <p>My path is set to C:\Python26 and I can run normal python scripts from within the command prompt.</p> <p>Any idea what to do?</p> <p>Thanks.</p> <p>Edit: I had python 3.1 installed first but removed it afterwards. Could that be the problem?</p>
9
2009-08-13T11:14:34Z
7,202,892
<p>I had the exact same issue and I just managed to get it solved - so I thought I would share my solution.</p> <p>It turned out that my installation of CollabNet SVN contained an old version of Python that interfered with my recent Python2.7 installation.</p> <p>Replacing CollabNet SVN with VisualSVN (including a couple of reboots) did the trick. I know this is not a "pretty" solution, as it caused me to uninstall CollabNet SVN - a prettier solution might have been doing modifications to the PATH env. variable... However, I am now able to use py2exe :)</p>
3
2011-08-26T09:43:59Z
[ "python", "py2exe" ]
ImportError: no module named py2exe
1,271,337
<p>I get this error when I try to use one of the py2exe samples with py2exe.</p> <pre><code>File "setup.py", line 22, in ? import py2exe ImportError: no module named py2exe </code></pre> <p>I've installed py2exe with the installer, and I use python 2.6. I have downloaded the correct installer from the site (The python 2.6 one.)</p> <p>My path is set to C:\Python26 and I can run normal python scripts from within the command prompt.</p> <p>Any idea what to do?</p> <p>Thanks.</p> <p>Edit: I had python 3.1 installed first but removed it afterwards. Could that be the problem?</p>
9
2009-08-13T11:14:34Z
9,928,563
<p>For the record, my very similar problem was caused by using a <em>Cygwin</em> prompt. Using as standard <em>cmd.exe</em> shell instead worked (given all paths and correctly installed versions of python).</p> <p>This was because (stupid me) the Cygwin install had pulled down it's own version of <code>/usr/bin/python</code>. I equally fixed it by adding the Windows installed python location to the head of the Cygwin <code>PATH=/cygdrive/c/Python27:$PATH</code>.</p>
0
2012-03-29T15:28:20Z
[ "python", "py2exe" ]
Is there an equivalent of Pythons range(12) in C#?
1,271,378
<p>This crops up every now and then for me: I have some C# code badly wanting the <code>range()</code> function available in Python.</p> <p>I am aware of using</p> <pre><code>for (int i = 0; i &lt; 12; i++) { // add code here } </code></pre> <p>But this brakes down in functional usages, as when I want to do a Linq <code>Sum()</code> instead of writing the above loop.</p> <p>Is there any builtin? I guess I could always just roll my own with a <code>yield</code> or such, but this would be <em>so</em> handy to just <em>have</em>.</p>
31
2009-08-13T11:22:57Z
1,271,388
<p>You're looking for the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx"><code>Enumerable.Range</code></a> method:</p> <pre><code>var mySequence = Enumerable.Range(0, 12); </code></pre>
60
2009-08-13T11:24:19Z
[ "c#", "python", "range" ]
Is there an equivalent of Pythons range(12) in C#?
1,271,378
<p>This crops up every now and then for me: I have some C# code badly wanting the <code>range()</code> function available in Python.</p> <p>I am aware of using</p> <pre><code>for (int i = 0; i &lt; 12; i++) { // add code here } </code></pre> <p>But this brakes down in functional usages, as when I want to do a Linq <code>Sum()</code> instead of writing the above loop.</p> <p>Is there any builtin? I guess I could always just roll my own with a <code>yield</code> or such, but this would be <em>so</em> handy to just <em>have</em>.</p>
31
2009-08-13T11:22:57Z
1,271,394
<pre><code>Enumerable.Range(start, numElements); </code></pre> <p>Sample <a href="http://www.hookedonlinq.com/RangeOperator.ashx" rel="nofollow">here</a>.</p>
6
2009-08-13T11:24:48Z
[ "c#", "python", "range" ]
Is there an equivalent of Pythons range(12) in C#?
1,271,378
<p>This crops up every now and then for me: I have some C# code badly wanting the <code>range()</code> function available in Python.</p> <p>I am aware of using</p> <pre><code>for (int i = 0; i &lt; 12; i++) { // add code here } </code></pre> <p>But this brakes down in functional usages, as when I want to do a Linq <code>Sum()</code> instead of writing the above loop.</p> <p>Is there any builtin? I guess I could always just roll my own with a <code>yield</code> or such, but this would be <em>so</em> handy to just <em>have</em>.</p>
31
2009-08-13T11:22:57Z
1,271,399
<p>Enumerable.Range(0,12);</p>
4
2009-08-13T11:25:53Z
[ "c#", "python", "range" ]
Is there an equivalent of Pythons range(12) in C#?
1,271,378
<p>This crops up every now and then for me: I have some C# code badly wanting the <code>range()</code> function available in Python.</p> <p>I am aware of using</p> <pre><code>for (int i = 0; i &lt; 12; i++) { // add code here } </code></pre> <p>But this brakes down in functional usages, as when I want to do a Linq <code>Sum()</code> instead of writing the above loop.</p> <p>Is there any builtin? I guess I could always just roll my own with a <code>yield</code> or such, but this would be <em>so</em> handy to just <em>have</em>.</p>
31
2009-08-13T11:22:57Z
23,062,619
<p>Just to complement everyone's answers, I thought I should add that <code>Enumerable.Range(0, 12);</code> is closer to Python's <code>xrange(12)</code> because it's an enumerable.</p> <p>If anyone is looking specifically for a list or an array:</p> <pre><code>Enumerable.Range(0, 12).ToList(); </code></pre> <p>or</p> <pre><code>Enumerable.Range(0, 12).ToArray(); </code></pre> <p>are closer to Python's <code>range(12)</code>.</p>
10
2014-04-14T14:22:09Z
[ "c#", "python", "range" ]
python db insert
1,271,502
<p>I am in facing a performance problem in my code.I am making db connection a making a select query and then inserting in a table.Around 500 rows in one select query ids populated .Before inserting i am running select query around 8-9 times first and then inserting then all using cursor.executemany.But it is taking 2 miuntes to insert which is not qood .Any idea </p> <pre><code>def insert1(id,state,cursor): cursor.execute("select * from qwert where asd_id =%s",[id]) if sometcondition: adding.append(rd[i]) cursor.executemany(indata, adding) </code></pre> <p>where rd[i] is a aray for records making and indata is a insert statement</p> <pre><code>#prog start here cursor.execute("select * from assd") for rows in cursor.fetchall() if rows[1]=='aq': insert1(row[1],row[2],cursor) if rows[1]=='qw': insert2(row[1],row[2],cursor) </code></pre>
0
2009-08-13T11:49:32Z
1,271,815
<p>I don't really understand why you're doing this.</p> <p>It seems that you want to insert a subset of rows from "assd" into one table, and another subset into another table?</p> <p>Why not just do it with two SQL statements, structured like this:</p> <pre><code>insert into tab1 select * from assd where asd_id = 42 and cond1 = 'set'; insert into tab2 select * from assd where asd_id = 42 and cond2 = 'set'; </code></pre> <p>That'd dramatically reduce your number of roundtrips to the database and your client-server traffic. It'd also be an order of magnitude faster.</p> <p>Of course, I'd also strongly recommend that you specify your column names in both the insert and select parts of the code.</p>
3
2009-08-13T12:59:47Z
[ "python" ]
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
<p>Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?</p> <p>I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.</p> <p>For sure, I can add this flag to the context but I would like to know if there is a better way to do that.</p>
43
2009-08-13T12:25:06Z
1,271,873
<p>You will need to add the <code>DEBUG</code> flag to your <code>context_processors</code>.</p> <p>There may not even be an alternative way. At least, none that I know of.</p>
0
2009-08-13T13:12:51Z
[ "python", "django", "templates" ]
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
<p>Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?</p> <p>I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.</p> <p>For sure, I can add this flag to the context but I would like to know if there is a better way to do that.</p>
43
2009-08-13T12:25:06Z
1,271,914
<p>Assuming you haven't set <code>TEMPLATE_CONTEXT_PROCESSORS</code> to some other value in <code>settings.py</code>, Django will automatically load the <code>debug</code> context preprocessor (as noted <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#id1">here</a>). This means that you will have access to a variable called <code>debug</code> in your templates <em>if</em> <code>settings.DEBUG</code> is true <em>and</em> your local machine's IP address (which can simply be 127.0.0.1) is set in the variable <code>settings.INTERNAL_IPS</code> (which is described <a href="http://docs.djangoproject.com/en/dev/ref/settings/#internal-ips">here</a>). <code>settings.INTERNAL_IPS</code> is a tuple or list of IP addresses that Django should recognize as "internal".</p>
51
2009-08-13T13:23:07Z
[ "python", "django", "templates" ]
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
<p>Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?</p> <p>I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.</p> <p>For sure, I can add this flag to the context but I would like to know if there is a better way to do that.</p>
43
2009-08-13T12:25:06Z
1,272,312
<p>If you haven't already, it always helps to see if/how others have dealt with same issue on djangosnippets. The most recent snippet working with analytics tag is 1656: <a href="http://www.djangosnippets.org/snippets/1656/" rel="nofollow">http://www.djangosnippets.org/snippets/1656/</a></p> <p>What is nice about this solution is that it allows you to keep your <code>GOOGLE_ANALYTICS_CODE = xxxxxx</code> in local_settings.py in the case rest of your source is public, your key remains private. In addition it goes an extra step to not use analytics for logged in users.</p> <blockquote> <p>Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users.</p> <p>Use <code>{% googleanalyticsjs %}</code> in your templates.</p> <p>You must set something like</p> <pre><code>GOOGLE_ANALYTICS_CODE = "UA-1234567-1" </code></pre> <p>in your settings file.</p> <p>Assumes 'user' in your template variables is <code>request.user</code>, which it will be if you use:</p> <pre><code>return render_to_response('template.html',{ }, context_instance=RequestContext(request)) </code></pre> <p>(Assuming <code>django.core.context_processors.auth</code> is in <code>TEMPLATE_CONTEXT_PROCESSORS</code>, which it is by default)</p> <hr> <pre><code>from django import template import settings register = template.Library() class ShowGoogleAnalyticsJS(template.Node): def render(self, context): code = getattr(settings, "GOOGLE_ANALYTICS_CODE", False) if not code: return "&lt;!-- Goggle Analytics not included because you haven't set the settings.GOOGLE_ANALYTICS_CODE variable! --&gt;" if 'user' in context and context['user'] and context['user'].is_staff: return "&lt;!-- Goggle Analytics not included because you are a staff user! --&gt;" if settings.DEBUG: return "&lt;!-- Goggle Analytics not included because you are in Debug mode! --&gt;" return """ &lt;script type="text/javascript"&gt; var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); &lt;/script&gt; &lt;script type="text/javascript"&gt; try { var pageTracker = _gat._getTracker('""" + str(code) + """'); pageTracker._trackPageview(); } catch(err) {}&lt;/script&gt; """ def googleanalyticsjs(parser, token): return ShowGoogleAnalyticsJS() show_common_data = register.tag(googleanalyticsjs) </code></pre> </blockquote>
5
2009-08-13T14:28:01Z
[ "python", "django", "templates" ]
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
<p>Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?</p> <p>I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.</p> <p>For sure, I can add this flag to the context but I would like to know if there is a better way to do that.</p>
43
2009-08-13T12:25:06Z
13,609,888
<p>If modifying <code>INTERNAL_IPS</code> is not possible/suitable, you can do this with a context processor:</p> <p>in <code>myapp/context_processors.py</code>:</p> <pre><code>from django.conf import settings def debug(context): return {'DEBUG': settings.DEBUG} </code></pre> <p>in <code>settings.py</code>:</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( ... 'myapp.context_processors.debug', ) </code></pre> <p>Then in my templates, simply:</p> <pre><code> {% if DEBUG %} .header { background:#f00; } {% endif %} </code></pre>
41
2012-11-28T16:32:40Z
[ "python", "django", "templates" ]
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
<p>Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?</p> <p>I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.</p> <p>For sure, I can add this flag to the context but I would like to know if there is a better way to do that.</p>
43
2009-08-13T12:25:06Z
37,531,987
<p><strong>Django 1.9</strong> <code>settings.py</code>:</p> <pre><code>INTERNAL_IPS = ( '127.0.0.1', ) </code></pre> <p>Templates:</p> <pre><code>{% if debug %} </code></pre> <p><a href="https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-INTERNAL_IPS" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-INTERNAL_IPS</a> says:</p> <blockquote> <p>A list of IP addresses, as strings, that:</p> <ul> <li>Allow the debug() context processor to add some variables to the template context.</li> </ul> </blockquote> <p>The <code>debug</code> context processor is in the default <code>settings.py</code>.</p>
4
2016-05-30T18:45:21Z
[ "python", "django", "templates" ]
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
<p>Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?</p> <p>I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.</p> <p>For sure, I can add this flag to the context but I would like to know if there is a better way to do that.</p>
43
2009-08-13T12:25:06Z
39,074,975
<p><code>{% if debug %}</code> can do the trick but only if you pass <code>RequestContext</code> instead of <code>Context</code>. Additionally, <code>debug</code> is not a boolean flag, its a function that when evaluated while <code>DEBUG = True</code> return some debugging information. This can be unnecessary overhead for your template.</p> <p>Personally, I do this trick instead.</p> <pre><code>{% if request.META.HTTP_HOST == "127.0.0.1:8000" %} </code></pre> <p>This will always work but instead of relying on both DEBUG flag and INTERNAL_IP, it just work for the hard coded IP.</p>
0
2016-08-22T08:46:48Z
[ "python", "django", "templates" ]
How to get started with Sessions in Google App Engine / Django?
1,271,892
<p>I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/" rel="nofollow">read</a> that Django sessions <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html" rel="nofollow">can be backed</a> by BigTable or MemCache, but I never got them working. I guess what I'm asking is "Should I..."</p> <ol> <li>Persist with getting Django sessions working?</li> <li>Look at some other webapp framework for sessions in particular, or the site in general?</li> <li>Roll my own?</li> </ol> <p>It seems to me that sessions are not supported out-of-the-box and are somehow not first class citizens. What do you do?!</p> <p>Thanks.</p>
5
2009-08-13T13:17:31Z
1,273,704
<p>The gaeutilities library comes with a session management class that works well:</p> <ul> <li><a href="http://gaeutilities.appspot.com/" rel="nofollow">http://gaeutilities.appspot.com/</a></li> </ul>
1
2009-08-13T18:18:32Z
[ "python", "django", "google-app-engine" ]
How to get started with Sessions in Google App Engine / Django?
1,271,892
<p>I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/" rel="nofollow">read</a> that Django sessions <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html" rel="nofollow">can be backed</a> by BigTable or MemCache, but I never got them working. I guess what I'm asking is "Should I..."</p> <ol> <li>Persist with getting Django sessions working?</li> <li>Look at some other webapp framework for sessions in particular, or the site in general?</li> <li>Roll my own?</li> </ol> <p>It seems to me that sessions are not supported out-of-the-box and are somehow not first class citizens. What do you do?!</p> <p>Thanks.</p>
5
2009-08-13T13:17:31Z
1,273,792
<p>The reason django sessions are not supported by App engine out of the box is because django uses database table (model) based sessions, and the django ORM is not supported on appengine.</p> <p>A solution to this is to make django models work out of the box on appengine. And it has been done by patching django code, in the <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">App Engine Patch</a> project.</p> <p>Using this patch, as django models work, you get to access django admin, django auth along with the latest django release.</p> <p>You may also find this blog post on deploying a django application on App engine, useful: <a href="http://uswaretech.com/blog/2009/04/develop-twitter-api-application-in-django-and-deploy-on-google-app-engine/" rel="nofollow">http://uswaretech.com/blog/2009/04/develop-twitter-api-application-in-django-and-deploy-on-google-app-engine/</a></p>
3
2009-08-13T18:34:59Z
[ "python", "django", "google-app-engine" ]