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 |
|---|---|---|---|---|---|---|---|---|---|
App Engine: 13 StringPropertys vs. 1 StringListProperty (w.r.t. indexing/storage and query performance) | 1,220,794 | <p>A bit of background first: <a href="http://code.google.com/p/geomodel" rel="nofollow">GeoModel</a> is a library I wrote that adds very basic geospatial indexing and querying functionality to App Engine apps. It is similar in approach to geohashing. The equivalent location hash in GeoModel is called a 'geocell.'</p>
<p>Currently, the GeoModel library adds 13 properties (location_geocell__n_, <em>n</em>=1..13) to each location-aware entity. For example, an entity can have property values such as:</p>
<pre><code>location_geocell_1 = 'a'
location_geocell_2 = 'a3'
location_geocell_3 = 'a3f'
...
</code></pre>
<p>This is required in order to not use up an inequality filter during spatial queries.</p>
<p>The problem with the 13-properties approach is that, for any geo query an app would like to run, 13 new indexes must be defined and built. This is definitely a maintenance hassle, as I've just painfully realized while rewriting the demo app for the project. This leads to my first question:</p>
<p><strong><em>QUESTION 1:</strong> Is there any significant storage overhead per index? i.e. if I have 13 indexes with n entities in each, versus 1 index with 13n entities in it, is the former much worse than the latter in terms of storage?</em></p>
<p>It seems like the answer to (1) is no, per <a href="http://code.google.com/appengine/articles/index_building.html" rel="nofollow">this article</a>, but I'd just like to see if anyone has had a different experience.</p>
<p>Now, I'm considering adjusting the GeoModel library so that instead of 13 string properties, there'd only be one StringListProperty called location_geocells, i.e.:</p>
<pre><code>location_geocells = ['a', 'a3', 'a3f']
</code></pre>
<p>This results in a much cleaner <code>index.yaml</code>. But, I do question the performance implications:</p>
<p><strong><em>QUESTION 2:</strong> If I switch from 13 string properties to 1 StringListProperty, will query performance be adversely affected; my current filter looks like:</em></p>
<pre><code>query.filter('location_geocell_%d =' % len(search_cell), search_cell)
</code></pre>
<p><em>and the new filter would look like:</em></p>
<pre><code>query.filter('location_geocells =', search_cell)
</code></pre>
<p><em>Note that the first query has a search space of _n_ entities, whereas the second query has a search space of _13n_ entities.</em></p>
<p>It seems like the answer to (2) is that both result in equal query performance, per tip #6 in <a href="http://googleappengine.blogspot.com/2009/06/10-things-you-probably-didnt-know-about.html" rel="nofollow">this blog post</a>, but again, I'd like to see if anyone has any differing real-world experiences with this.</p>
<p>Lastly, if anyone has any other suggestions or tips that can help improve storage utilization, query performance and/or ease of use (specifically w.r.t. index.yaml), please do let me know! The source can be found here <a href="http://code.google.com/p/geomodel" rel="nofollow">geomodel</a> & <a href="http://code.google.com/p/geomodel/source/browse/trunk/geo/geomodel.py" rel="nofollow">geomodel.py</a></p>
| 3 | 2009-08-03T05:36:06Z | 1,222,133 | <p>You're correct that there's no significant overhead per-index - 13n entries in one index is more or less equivalent to n entries in 13 indexes. There's a total index count limit of 100, though, so this eats up a fair chunk of your available indexes.</p>
<p>That said, using a ListProperty is definitely a far superior approach from usability and index consumption perspectives. There is, as you supposed, no performance difference between querying a small index and a much larger index, supposing both queries return the same number of rows.</p>
<p>The only reason I can think of for using separate properties is if you knew you only needed to index on certain levels of detail - but that could be accomplished better at insert-time by specifying the levels of detail you want added to the list in the first place.</p>
<p>Note that in either case you only need the indexes if you intend to query the geocell properties in conjunction with a sort order or inequality filter, though - in all other cases, the automatic indexing will suffice.</p>
| 5 | 2009-08-03T12:40:46Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
App Engine: 13 StringPropertys vs. 1 StringListProperty (w.r.t. indexing/storage and query performance) | 1,220,794 | <p>A bit of background first: <a href="http://code.google.com/p/geomodel" rel="nofollow">GeoModel</a> is a library I wrote that adds very basic geospatial indexing and querying functionality to App Engine apps. It is similar in approach to geohashing. The equivalent location hash in GeoModel is called a 'geocell.'</p>
<p>Currently, the GeoModel library adds 13 properties (location_geocell__n_, <em>n</em>=1..13) to each location-aware entity. For example, an entity can have property values such as:</p>
<pre><code>location_geocell_1 = 'a'
location_geocell_2 = 'a3'
location_geocell_3 = 'a3f'
...
</code></pre>
<p>This is required in order to not use up an inequality filter during spatial queries.</p>
<p>The problem with the 13-properties approach is that, for any geo query an app would like to run, 13 new indexes must be defined and built. This is definitely a maintenance hassle, as I've just painfully realized while rewriting the demo app for the project. This leads to my first question:</p>
<p><strong><em>QUESTION 1:</strong> Is there any significant storage overhead per index? i.e. if I have 13 indexes with n entities in each, versus 1 index with 13n entities in it, is the former much worse than the latter in terms of storage?</em></p>
<p>It seems like the answer to (1) is no, per <a href="http://code.google.com/appengine/articles/index_building.html" rel="nofollow">this article</a>, but I'd just like to see if anyone has had a different experience.</p>
<p>Now, I'm considering adjusting the GeoModel library so that instead of 13 string properties, there'd only be one StringListProperty called location_geocells, i.e.:</p>
<pre><code>location_geocells = ['a', 'a3', 'a3f']
</code></pre>
<p>This results in a much cleaner <code>index.yaml</code>. But, I do question the performance implications:</p>
<p><strong><em>QUESTION 2:</strong> If I switch from 13 string properties to 1 StringListProperty, will query performance be adversely affected; my current filter looks like:</em></p>
<pre><code>query.filter('location_geocell_%d =' % len(search_cell), search_cell)
</code></pre>
<p><em>and the new filter would look like:</em></p>
<pre><code>query.filter('location_geocells =', search_cell)
</code></pre>
<p><em>Note that the first query has a search space of _n_ entities, whereas the second query has a search space of _13n_ entities.</em></p>
<p>It seems like the answer to (2) is that both result in equal query performance, per tip #6 in <a href="http://googleappengine.blogspot.com/2009/06/10-things-you-probably-didnt-know-about.html" rel="nofollow">this blog post</a>, but again, I'd like to see if anyone has any differing real-world experiences with this.</p>
<p>Lastly, if anyone has any other suggestions or tips that can help improve storage utilization, query performance and/or ease of use (specifically w.r.t. index.yaml), please do let me know! The source can be found here <a href="http://code.google.com/p/geomodel" rel="nofollow">geomodel</a> & <a href="http://code.google.com/p/geomodel/source/browse/trunk/geo/geomodel.py" rel="nofollow">geomodel.py</a></p>
| 3 | 2009-08-03T05:36:06Z | 1,223,095 | <blockquote>
<blockquote>
<p>Lastly, if anyone has any other suggestions or tips that can help improve storage utilization, query performance and/or ease of use </p>
</blockquote>
</blockquote>
<p>The StringListproperty is the way to go for the reasons mentioned above, but in actual usage one might want to add the geocells to ones own previously existing StringList so one could query against multiple properties.</p>
<p>So, if you were to provide a lower level api it could work with full text search implementations like <a href="http://www.billkatz.com/2009/6/Simple-Full-Text-Search-for-App-Engine" rel="nofollow">bill katz's</a></p>
<pre><code>def point2StringList(Point, stub="blah"):
.....
return ["blah_1:a", "blah_2":"a3", "blah_3":"a3f" ....]
def boundingbox2Wheresnippet(Box, stringlist="words", stub="blah"):
.....
return "words='%s_3:a3f' AND words='%s_3:b4g' ..." %(stub)
etc.
</code></pre>
| 1 | 2009-08-03T15:47:37Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
App Engine: 13 StringPropertys vs. 1 StringListProperty (w.r.t. indexing/storage and query performance) | 1,220,794 | <p>A bit of background first: <a href="http://code.google.com/p/geomodel" rel="nofollow">GeoModel</a> is a library I wrote that adds very basic geospatial indexing and querying functionality to App Engine apps. It is similar in approach to geohashing. The equivalent location hash in GeoModel is called a 'geocell.'</p>
<p>Currently, the GeoModel library adds 13 properties (location_geocell__n_, <em>n</em>=1..13) to each location-aware entity. For example, an entity can have property values such as:</p>
<pre><code>location_geocell_1 = 'a'
location_geocell_2 = 'a3'
location_geocell_3 = 'a3f'
...
</code></pre>
<p>This is required in order to not use up an inequality filter during spatial queries.</p>
<p>The problem with the 13-properties approach is that, for any geo query an app would like to run, 13 new indexes must be defined and built. This is definitely a maintenance hassle, as I've just painfully realized while rewriting the demo app for the project. This leads to my first question:</p>
<p><strong><em>QUESTION 1:</strong> Is there any significant storage overhead per index? i.e. if I have 13 indexes with n entities in each, versus 1 index with 13n entities in it, is the former much worse than the latter in terms of storage?</em></p>
<p>It seems like the answer to (1) is no, per <a href="http://code.google.com/appengine/articles/index_building.html" rel="nofollow">this article</a>, but I'd just like to see if anyone has had a different experience.</p>
<p>Now, I'm considering adjusting the GeoModel library so that instead of 13 string properties, there'd only be one StringListProperty called location_geocells, i.e.:</p>
<pre><code>location_geocells = ['a', 'a3', 'a3f']
</code></pre>
<p>This results in a much cleaner <code>index.yaml</code>. But, I do question the performance implications:</p>
<p><strong><em>QUESTION 2:</strong> If I switch from 13 string properties to 1 StringListProperty, will query performance be adversely affected; my current filter looks like:</em></p>
<pre><code>query.filter('location_geocell_%d =' % len(search_cell), search_cell)
</code></pre>
<p><em>and the new filter would look like:</em></p>
<pre><code>query.filter('location_geocells =', search_cell)
</code></pre>
<p><em>Note that the first query has a search space of _n_ entities, whereas the second query has a search space of _13n_ entities.</em></p>
<p>It seems like the answer to (2) is that both result in equal query performance, per tip #6 in <a href="http://googleappengine.blogspot.com/2009/06/10-things-you-probably-didnt-know-about.html" rel="nofollow">this blog post</a>, but again, I'd like to see if anyone has any differing real-world experiences with this.</p>
<p>Lastly, if anyone has any other suggestions or tips that can help improve storage utilization, query performance and/or ease of use (specifically w.r.t. index.yaml), please do let me know! The source can be found here <a href="http://code.google.com/p/geomodel" rel="nofollow">geomodel</a> & <a href="http://code.google.com/p/geomodel/source/browse/trunk/geo/geomodel.py" rel="nofollow">geomodel.py</a></p>
| 3 | 2009-08-03T05:36:06Z | 7,483,965 | <p>Looks like you ended up with 13 indices because you encoded in hex (for human readability / map levels?).
If you had utilized full potential of a byte (ByteString), you'd have had 256 cells instead of 16 cells per character (byte). There by reducing to far fewer number of indices for the same precision. </p>
<blockquote>
<p><a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ByteString" rel="nofollow">ByteString</a> is just a subclass of a str and is indexed similarly if less than 500bytes in length.</p>
</blockquote>
<p>However number of levels might be lower; to me 4 or 5 levels is practically good enough for most situations on 'the Earth'. For a larger planet or when cataloging each sand particle, more divisions might anyway need to be introduced irrespective of encoding used. In either case ByteString is better than hex encoding. And helps reduce indexing <strong>substantially</strong>. </p>
<ul>
<li>For representing 4 billion low(est) level cells, all we need is 4 bytes or just <strong>4 indices</strong>. (From basic computer arch or memory addressing). </li>
<li>For representing the same, we'd need <strong>16</strong> hex digits or <strong>16 indices</strong>. </li>
</ul>
<p>I could be wrong. May be the number of index levels matching map zoom levels are more important. Please correct me. Am planning to try this instead of hex if just one (other) person here finds this meaningful :)</p>
<p>Or a solution that has fewer large cells (16) but more (128,256) as we go down the hierarchy.
Any thoughts?</p>
<p>eg:</p>
<ul>
<li>[0-15][0-31][0-63][0-127][0-255] gives 1G low level cells with 5 indices with log2 decrement in size.</li>
<li>[0-15][0-63][0-255][0-255][0-255] gives 16G low level cells with 5 indices. </li>
</ul>
| 0 | 2011-09-20T10:50:15Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
Creating Date Intervals in Python | 1,220,872 | <p>I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output.</p>
<p>So, how can I change this:</p>
<pre><code>sum = 0
for i in range(1,11):
print sum
sum += i
</code></pre>
<p>To this?</p>
<pre><code>InputDate = '2009-01-01'
for i in range('2009-01-01','2009-07-01'):
print InputDate
InputDate += i
</code></pre>
<p>I realize there is something in rrule that does this exact function:</p>
<pre><code>a = date(2009, 1, 1)
b = date(2009, 7, 1)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
</code></pre>
<p>But, I am restricted to older version of python.</p>
<p>This is the shell script version of what I am trying to do, if this helps clarify:</p>
<pre><code>while [InputDate <= EndDate]
do
sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date"
name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db)
echo "$name"
InputDate=$(( InputDate + 1 ))
done
</code></pre>
<p>So how can I do this in Python?</p>
<p>Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line.</p>
<p>while day <= b:
print "Running extract for :" day</p>
<p>sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"</p>
<p>os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db')</p>
<p>day += one_day</p>
| 2 | 2009-08-03T06:19:56Z | 1,220,895 | <p>This will work:</p>
<pre><code>import datetime
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
# do important stuff
day += one_day
</code></pre>
| 7 | 2009-08-03T06:33:27Z | [
"python",
"mysql"
] |
Creating Date Intervals in Python | 1,220,872 | <p>I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output.</p>
<p>So, how can I change this:</p>
<pre><code>sum = 0
for i in range(1,11):
print sum
sum += i
</code></pre>
<p>To this?</p>
<pre><code>InputDate = '2009-01-01'
for i in range('2009-01-01','2009-07-01'):
print InputDate
InputDate += i
</code></pre>
<p>I realize there is something in rrule that does this exact function:</p>
<pre><code>a = date(2009, 1, 1)
b = date(2009, 7, 1)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
</code></pre>
<p>But, I am restricted to older version of python.</p>
<p>This is the shell script version of what I am trying to do, if this helps clarify:</p>
<pre><code>while [InputDate <= EndDate]
do
sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date"
name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db)
echo "$name"
InputDate=$(( InputDate + 1 ))
done
</code></pre>
<p>So how can I do this in Python?</p>
<p>Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line.</p>
<p>while day <= b:
print "Running extract for :" day</p>
<p>sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"</p>
<p>os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db')</p>
<p>day += one_day</p>
| 2 | 2009-08-03T06:19:56Z | 1,220,903 | <p>Try this:</p>
<pre><code>import datetime
dt1 = datetime.date(2009, 1, 1)
dt2 = datetime.date(2009, 7, 1)
dt = dt1
while dt <= dt2:
print dt.strftime("%Y-%m-%d")
dt += datetime.timedelta(days=1)
</code></pre>
<p>You say you are restricted to an older version of Python. If you don't have the datetime module (Python < 2.3), then you can also do:</p>
<pre><code>import time
dt1 = time.mktime(time.strptime('2009-01-01', '%Y-%m-%d'))
dt2 = time.mktime(time.strptime('2009-07-01', '%Y-%m-%d'))
ONE_DAY = 86400
dt = dt1
while dt <= dt2:
print time.strftime('%Y-%m-%d', time.gmtime(dt))
dt += ONE_DAY
</code></pre>
| 2 | 2009-08-03T06:35:42Z | [
"python",
"mysql"
] |
Creating Date Intervals in Python | 1,220,872 | <p>I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output.</p>
<p>So, how can I change this:</p>
<pre><code>sum = 0
for i in range(1,11):
print sum
sum += i
</code></pre>
<p>To this?</p>
<pre><code>InputDate = '2009-01-01'
for i in range('2009-01-01','2009-07-01'):
print InputDate
InputDate += i
</code></pre>
<p>I realize there is something in rrule that does this exact function:</p>
<pre><code>a = date(2009, 1, 1)
b = date(2009, 7, 1)
for dt in rrule(DAILY, dtstart=a, until=b):
print dt.strftime("%Y-%m-%d")
</code></pre>
<p>But, I am restricted to older version of python.</p>
<p>This is the shell script version of what I am trying to do, if this helps clarify:</p>
<pre><code>while [InputDate <= EndDate]
do
sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date"
name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db)
echo "$name"
InputDate=$(( InputDate + 1 ))
done
</code></pre>
<p>So how can I do this in Python?</p>
<p>Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line.</p>
<p>while day <= b:
print "Running extract for :" day</p>
<p>sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"</p>
<p>os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db')</p>
<p>day += one_day</p>
| 2 | 2009-08-03T06:19:56Z | 1,220,990 | <pre><code>In [1]: from dateutil.relativedelta import *
In [2]: from datetime import *
In [3]: aday = datetime.today()
In [4]: nextweek = aday+relativedelta(weeks=1)
In [5]: while aday<nextweek:
...: print datetime.strftime(aday,format='%Y-%b-%d')
...: aday+=relativedelta(days=1)
...:
...:
#Output
2009-Aug-03
2009-Aug-04
2009-Aug-05
2009-Aug-06
2009-Aug-07
2009-Aug-08
2009-Aug-09
</code></pre>
<p>While you can do, most of the stuff about <code>datetime</code> using the stdlib, (IMO) <code>dateutil</code> lets you do it faster and better.</p>
| 2 | 2009-08-03T07:06:02Z | [
"python",
"mysql"
] |
Barchart with vertical labels in python/matplotlib | 1,221,108 | <p>I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?</p>
| 29 | 2009-08-03T07:46:13Z | 1,221,218 | <p>Do you mean something like this:</p>
<pre><code>>>> from matplotlib import *
>>> plot(xrange(10))
>>> yticks(xrange(10), rotation='vertical')
</code></pre>
<p>?</p>
<p>In general, to show any text in matplotlib with a vertical orientation, you can add the keyword <code>rotation='vertical'</code>.</p>
<p>For further options, you can look at help(matplotlib.pyplot.text) </p>
<p>The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical'</p>
<p>Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.</p>
| 40 | 2009-08-03T08:32:27Z | [
"python",
"charts",
"matplotlib",
"bar-chart"
] |
Barchart with vertical labels in python/matplotlib | 1,221,108 | <p>I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?</p>
| 29 | 2009-08-03T07:46:13Z | 1,241,078 | <p>I would suggest looking at <a href="http://matplotlib.sourceforge.net/gallery.html" rel="nofollow">the matplotlib gallery</a>. At least two of the examples seem to be relevant:</p>
<ul>
<li><a href="http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/text%5Frotation.html" rel="nofollow">text_rotation.py</a> for understanding how text layout works</li>
<li><a href="http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/barchart%5Fdemo2.html" rel="nofollow">barchart_demo2.py</a>, an example of a bar chart with somewhat more complicated layout than the most basic example.</li>
</ul>
| 3 | 2009-08-06T20:03:58Z | [
"python",
"charts",
"matplotlib",
"bar-chart"
] |
returning a value to a c# program through python script | 1,221,135 | <p>I have a C# program which executes a python scrip</p>
<p>How can I retrieve the python returning value in my C# program ?</p>
<p>thanks!</p>
| 1 | 2009-08-03T07:59:41Z | 1,221,152 | <p>As far as I know, you should use ScriptScope object which you create from the ScriptEngine object using CreateScope method</p>
<pre><code>ScriptEngine engine = ScriptRuntime.Create().GetEngine("py");
ScriptScope scope = engine.CreateScope();
</code></pre>
<p>Then you can share variables between the C# program and the python script by doing this</p>
<pre><code>scope.SetVariable("x", x);
</code></pre>
| 2 | 2009-08-03T08:04:15Z | [
"c#",
"python"
] |
returning a value to a c# program through python script | 1,221,135 | <p>I have a C# program which executes a python scrip</p>
<p>How can I retrieve the python returning value in my C# program ?</p>
<p>thanks!</p>
| 1 | 2009-08-03T07:59:41Z | 1,221,155 | <p>if your using System.Diagnostics.Process to launch your python script, then you can get the return code after process exit</p>
<p>using </p>
<pre><code>process.ExitCode
</code></pre>
| 1 | 2009-08-03T08:06:46Z | [
"c#",
"python"
] |
need to put a nested Dict into a text file | 1,221,202 | <p>I have a nested dict like this</p>
<pre><code>d={ time1 : column1 : {data1,data2,data3}
column2 : {data1,data2,data3}
column3 : {data1,data2,data3} #So on.
time2 : {column1: } #Same as Above
}
</code></pre>
<p>data1,data2,data3 represent the type of data and not the data itself
I need to put this dict into a file like this.</p>
<p>Timestamp col1/data1 Col1/data2 col1/data3 col2/data1 col2/data2 col2/data3 (So on...)</p>
<p>My problem is How do I ensure that the text goes under the corresponding column?<br />
i.e Say I have put some text under time1 column14 and I again come across column14 in another timestamp. How do I keep track of the location of these columns in the text file?</p>
<p>The columns are just numbers (in string form)</p>
| 0 | 2009-08-03T08:25:44Z | 1,221,359 | <p>I would do it like this:</p>
<pre><code>#get the row with maximum number of columns
maxrowlen = 0
maxrowkey = ""
for timesid in d.keys():
if len(timesid.keys()) > maxrowlen:
maxrowlen = len(timesid.keys())
maxrowkey = timesid
maxrowcols = sorted(d[maxrowkey].keys())
# prepare the writing
cell_format = "%10r" # or whatever suits your data
# create the output string
lines = []
for timesid in d.keys(): # go through all times
line = ""
for col in maxrowcols: # go through the standard columns
colstr = ""
if col in d[timesid].keys(): # create an entry for each standard column
colstr += cell_format % d[timesid][col] # either from actual data
else:
colstr += cell_format % "" # or blanks
line += colstr
lines.append(line)
text = "\n".join(lines)
</code></pre>
| 1 | 2009-08-03T09:14:20Z | [
"python",
"file",
"dictionary"
] |
need to put a nested Dict into a text file | 1,221,202 | <p>I have a nested dict like this</p>
<pre><code>d={ time1 : column1 : {data1,data2,data3}
column2 : {data1,data2,data3}
column3 : {data1,data2,data3} #So on.
time2 : {column1: } #Same as Above
}
</code></pre>
<p>data1,data2,data3 represent the type of data and not the data itself
I need to put this dict into a file like this.</p>
<p>Timestamp col1/data1 Col1/data2 col1/data3 col2/data1 col2/data2 col2/data3 (So on...)</p>
<p>My problem is How do I ensure that the text goes under the corresponding column?<br />
i.e Say I have put some text under time1 column14 and I again come across column14 in another timestamp. How do I keep track of the location of these columns in the text file?</p>
<p>The columns are just numbers (in string form)</p>
| 0 | 2009-08-03T08:25:44Z | 1,221,545 | <p>I would use JSON.</p>
<p>In Python 2.6 it's directly available, in earlier Python's you have to download and install it.</p>
<pre><code>try:
import json
exception ImportError:
import simplejson as json
out= open( "myFile.json", "w" )
json.dump( { 'timestamp': time.time(), 'data': d }, indent=2 )
out.close()
</code></pre>
<p>Works nicely. Easy to edit manually. Easy to parse.</p>
| 2 | 2009-08-03T10:08:33Z | [
"python",
"file",
"dictionary"
] |
Executing a MySQL query on command line via os.system in Python | 1,221,232 | <p>I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e</p>
<p>I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. It also looks like I might need to convert the day to a string before concatenating to sql? </p>
<pre><code>#!/usr/bin/python
import datetime
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print day
sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
print "SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
os.system('mysql -h -sN -u -p -e " + sql + " > /home/output/DateLoop-" + day + ".txt db')
day += one_day
</code></pre>
<p>Would it be possible to set this up to have the SQL as an input file and pass the day as a string to that? The query might become more complex or even require several queries and that might become a problem trying to pass as a string.</p>
<p>I am open to any ideas as long as the query can take the date as input, name the output file with the same date and do it from the command line MySQL client</p>
| 1 | 2009-08-03T08:36:15Z | 1,221,261 | <p>Try explicit formatting and quoting resulting string:</p>
<pre><code>sql = "....WHERE d.Date = '" + date.isoformat() + "' GROUP BY ..."
</code></pre>
<p>Quotes at os.system call are messy and redirection look weird (if it's not a typo)</p>
<pre><code>os.system("mysql db -h -sN -u -p -e '" + sql + "' > /home/output/DateLoop-" + day + ".txt")
</code></pre>
| 1 | 2009-08-03T08:45:11Z | [
"python",
"mysql",
"shell"
] |
Executing a MySQL query on command line via os.system in Python | 1,221,232 | <p>I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e</p>
<p>I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. It also looks like I might need to convert the day to a string before concatenating to sql? </p>
<pre><code>#!/usr/bin/python
import datetime
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print day
sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
print "SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
os.system('mysql -h -sN -u -p -e " + sql + " > /home/output/DateLoop-" + day + ".txt db')
day += one_day
</code></pre>
<p>Would it be possible to set this up to have the SQL as an input file and pass the day as a string to that? The query might become more complex or even require several queries and that might become a problem trying to pass as a string.</p>
<p>I am open to any ideas as long as the query can take the date as input, name the output file with the same date and do it from the command line MySQL client</p>
| 1 | 2009-08-03T08:36:15Z | 1,221,273 | <p>Well, you can save the mysql template query in a config file and parse it with <a href="http://docs.python.org/library/configparser.html" rel="nofollow">ConfigParser</a>:</p>
<p>The config file will look like that:</p>
<pre><code>[mysql query configuration]
dbhost =
db =
username = guest
password =
[query template]
template = SELECT Date, SUM(CostUsd).......
</code></pre>
<p>or you can just store it to a separate file and then read it with the standard open(filename).read, etc.
If you think that the query will become more complex in the future, the config file approach may be simpler to manage and understand, but it is not a big difference.</p>
<p>To get the date as a parameter, you can use sys.argv, or a library like <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> </p>
| 0 | 2009-08-03T08:47:20Z | [
"python",
"mysql",
"shell"
] |
Executing a MySQL query on command line via os.system in Python | 1,221,232 | <p>I am trying to pass the 'day' from the while loop into a sql statement that then gets passed into a MySQL command line to be executed with -e</p>
<p>I can not use the DB module or other python libraries to access MySQL, it needs to be done via command line. It also looks like I might need to convert the day to a string before concatenating to sql? </p>
<pre><code>#!/usr/bin/python
import datetime
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print day
sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
print "SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"
os.system('mysql -h -sN -u -p -e " + sql + " > /home/output/DateLoop-" + day + ".txt db')
day += one_day
</code></pre>
<p>Would it be possible to set this up to have the SQL as an input file and pass the day as a string to that? The query might become more complex or even require several queries and that might become a problem trying to pass as a string.</p>
<p>I am open to any ideas as long as the query can take the date as input, name the output file with the same date and do it from the command line MySQL client</p>
| 1 | 2009-08-03T08:36:15Z | 1,557,007 | <p>Code below might help you out. It isn't particularly exciting and is deliberately simple. This is not the way many programmers would tackle this problem, but without more info it seems to fulfil your requirements.</p>
<p>I have also made an assumption that you are new to python; If I'm wrong, feel free to ignore this post.</p>
<ul>
<li>Allows the passing of database credentials, output directory and dates (start and end) on the command line.</li>
<li>Uses subprocess in place of os.system. Subprocess provides the preferred mechanisms to call external executables from python. This code uses the simplest of them; call() as it is similar to os.system()</li>
<li>Uses optparse to process the command line arguments. Whilst the code is certainly longer and more verbose, it will be easier for you to make additions and modifications to the arg processing in the future. It is also pretty clear what is going on (and code is always read far more often than it is written).</li>
<li>The command line setup only runs when the script is executed as it is within the <code>__main__</code> block. As the "logic" of the script is within the main() method, you can also import it and provide the options object (and arg list) from another source.</li>
</ul>
<p>If you can remove the need to output each date in a separate file, you can have the database engine calculate the SUM() and group them by date. You would get all sums back in one db call which would be quicker and could yield simpler code.</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import os
import subprocess
from optparse import OptionParser
SQL = """SELECT d.Date, SUM(d.CostUsd) FROM Stats d WHERE d.Date = '%s' GROUP BY d.Date"""
def get_stats(options, dateobj):
"""Return statistics for the date of `dateobj`"""
_datestr = dateobj.strftime('%Y-%m-%d')
sql = SQL % _datestr
filepath = os.path.join(options.outdir, 'DateLoop-%s.txt' % _datestr)
return subprocess.call('mysql -h %s -u %s -p -sN -e "%s" db > %s' % (options.dbhost, options.dbuser, sql, filepath), shell=True)
def main(options, args):
""""""
_date = options.startdate
while _date <= options.enddate:
rs = get_stats(options, _date)
_date += datetime.timedelta(days=1)
if __name__ == '__main__':
parser = OptionParser(version="%prog 1.0")
parser.add_option('-s', '--startdate', type='string', dest='startdate',
help='the start date (format: yyyymmdd)')
parser.add_option('-e', '--enddate', type='string', dest='enddate',
help='the end date (format: yyyymmdd)')
parser.add_option('--output', type='string', dest='outdir', default='/home/output/',
help='target directory for output files')
parser.add_option('--dbhost', type='string', dest='dbhost', default='myhost',
help='SQL server address')
parser.add_option('--dbuser', type='string', dest='dbuser', default='dbuser',
help='SQL server user')
options, args = parser.parse_args()
## Process the date args
if not options.startdate:
options.startdate = datetime.datetime.today()
else:
try:
options.startdate = datetime.datetime.strptime('%Y%m%d', options.startdate)
except ValueError:
parser.error("Invalid value for startdate (%s)" % options.startdate)
if not options.enddate:
options.enddate = options.startdate + datetime.timedelta(days=7)
else:
try:
options.enddate = datetime.datetime.strptime('%Y%m%d', options.enddate)
except ValueError:
parser.error("Invalid value for enddate (%s)" % options.enddate)
main(options, args)
</code></pre>
| 3 | 2009-10-12T21:16:58Z | [
"python",
"mysql",
"shell"
] |
Find unique elements in tuples in a python list | 1,221,775 | <p>Is there a better way to do this in python, or rather: Is this a good way to do it?</p>
<pre><code>x = ('a', 'b', 'c')
y = ('d', 'e', 'f')
z = ('g', 'e', 'i')
l = [x, y, z]
s = set([e for (_, e, _) in l])
</code></pre>
<p>I looks somewhat ugly but does what i need without writing a complex "get_unique_elements_from_tuple_list" function... ;)</p>
<p>edit: expected value of s is set(['b','e'])</p>
| 3 | 2009-08-03T11:15:37Z | 1,221,802 | <p>That's fine, that's what sets are for. One thing I would change is this:</p>
<pre><code>s = set(e[1] for e in l)
</code></pre>
<p>as it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.</p>
| 22 | 2009-08-03T11:24:26Z | [
"python",
"list",
"set",
"tuples"
] |
Why does Django post_save signal give me pre_save data? | 1,221,878 | <p>Im trying to connect a "Information" object to many "Customers" (see code below)</p>
<p>When one Information object is updated, I want to send email to each Customer that is connected to the Information.</p>
<p>However, when I log the sold_to field that the signal recieves I always get what the data is like BEFORE the save.</p>
<p>I'm guessing this is because its ManyToManyField and the data is stored in a separate table, but shouldn't the post_save signal be called after all relations have been updated?</p>
<p>Anyone got a suggestion for a solution?</p>
<pre><code>class Customer
name = models.CharField(max_length=200)
category = models.ManyToManyField('Category',symmetrical=False)
contact = models.EmailField()
class Information
name = models.CharField(max_length=200)
email = models.EmailField(max_length=200)
mod_date = models.DateTimeField(auto_now=True)
sold_to = models.ManyToManyField(Customer, null=True, blank=True)
def send_admin_email(sender, instance, signal, *args, **kwargs):
from myapp import settings
for cust in instance.sold_to.all():
settings.debug(cust.name)
post_save.connect(send_admin_email, sender=Information)
</code></pre>
<p>Edit: apollo13 in #django alerted me to this:
"Related items (the things being saved into the many-to-many relation)
are not saved as part of a model's save method, as you have discovered." - <a href="http://groups.google.com/group/django-users/msg/2b734c153537f970">http://groups.google.com/group/django-users/msg/2b734c153537f970</a></p>
<p>But since its from Jul 9 2006 I really really hope there is a solution for this.</p>
| 9 | 2009-08-03T11:42:41Z | 1,222,282 | <p>There's an open ticket for the issue you are facing <a href="http://code.djangoproject.com/ticket/5390">here</a>. You could either keep an eye on that for when it makes it into a release, or you could try applying the patch that it provides and see if that helps.</p>
| 5 | 2009-08-03T13:12:06Z | [
"python",
"django",
"django-signals"
] |
Why does Django post_save signal give me pre_save data? | 1,221,878 | <p>Im trying to connect a "Information" object to many "Customers" (see code below)</p>
<p>When one Information object is updated, I want to send email to each Customer that is connected to the Information.</p>
<p>However, when I log the sold_to field that the signal recieves I always get what the data is like BEFORE the save.</p>
<p>I'm guessing this is because its ManyToManyField and the data is stored in a separate table, but shouldn't the post_save signal be called after all relations have been updated?</p>
<p>Anyone got a suggestion for a solution?</p>
<pre><code>class Customer
name = models.CharField(max_length=200)
category = models.ManyToManyField('Category',symmetrical=False)
contact = models.EmailField()
class Information
name = models.CharField(max_length=200)
email = models.EmailField(max_length=200)
mod_date = models.DateTimeField(auto_now=True)
sold_to = models.ManyToManyField(Customer, null=True, blank=True)
def send_admin_email(sender, instance, signal, *args, **kwargs):
from myapp import settings
for cust in instance.sold_to.all():
settings.debug(cust.name)
post_save.connect(send_admin_email, sender=Information)
</code></pre>
<p>Edit: apollo13 in #django alerted me to this:
"Related items (the things being saved into the many-to-many relation)
are not saved as part of a model's save method, as you have discovered." - <a href="http://groups.google.com/group/django-users/msg/2b734c153537f970">http://groups.google.com/group/django-users/msg/2b734c153537f970</a></p>
<p>But since its from Jul 9 2006 I really really hope there is a solution for this.</p>
| 9 | 2009-08-03T11:42:41Z | 1,251,607 | <p>This is my solution, after applying the patch from code.djangoproject.com mentioned above.</p>
<p>Added this in models.py:</p>
<pre><code>from django.db.models.signals import m2m_changed
m2m_changed.connect(send_admin_email, sender=Information)
</code></pre>
<p>And the send_admin_email function:</p>
<pre><code>def send_customer_email(sender, instance, action, model, field_name, reverse, objects, **kwargs):
if ("add" == action):
# do stuff
</code></pre>
| 1 | 2009-08-09T15:43:04Z | [
"python",
"django",
"django-signals"
] |
Why does Django post_save signal give me pre_save data? | 1,221,878 | <p>Im trying to connect a "Information" object to many "Customers" (see code below)</p>
<p>When one Information object is updated, I want to send email to each Customer that is connected to the Information.</p>
<p>However, when I log the sold_to field that the signal recieves I always get what the data is like BEFORE the save.</p>
<p>I'm guessing this is because its ManyToManyField and the data is stored in a separate table, but shouldn't the post_save signal be called after all relations have been updated?</p>
<p>Anyone got a suggestion for a solution?</p>
<pre><code>class Customer
name = models.CharField(max_length=200)
category = models.ManyToManyField('Category',symmetrical=False)
contact = models.EmailField()
class Information
name = models.CharField(max_length=200)
email = models.EmailField(max_length=200)
mod_date = models.DateTimeField(auto_now=True)
sold_to = models.ManyToManyField(Customer, null=True, blank=True)
def send_admin_email(sender, instance, signal, *args, **kwargs):
from myapp import settings
for cust in instance.sold_to.all():
settings.debug(cust.name)
post_save.connect(send_admin_email, sender=Information)
</code></pre>
<p>Edit: apollo13 in #django alerted me to this:
"Related items (the things being saved into the many-to-many relation)
are not saved as part of a model's save method, as you have discovered." - <a href="http://groups.google.com/group/django-users/msg/2b734c153537f970">http://groups.google.com/group/django-users/msg/2b734c153537f970</a></p>
<p>But since its from Jul 9 2006 I really really hope there is a solution for this.</p>
| 9 | 2009-08-03T11:42:41Z | 9,172,783 | <p>I run across the same issue since I have M2M fields in my model I also got the pre_save like data. </p>
<p>In the situation, the problem is that in M2M fields both related models should be saved in order to get the auto generated IDs. </p>
<p>In my solution, neither I used the post_save signal nor m2m_changed signal, instead of that signals I used log_addition and log_change methods in ModelAdmin class definition. </p>
<p>In your custom ModelAdmin class:</p>
<pre><code> class CustomModelAdmin(admin.ModelAdmin):
def log_addition(self, request, object):
"""
Log that an object has been successfully added.
"""
super(CustomModelAdmin, self).log_addition(request, object)
#call post_save callback here object created
def log_change(self, request, object):
"""
Log that an object has been successfully changed.
"""
super(CustomModelAdmin, self).log_change(request, object)
#call post_save callback here object changed
</code></pre>
<p>If you want, you may also override log_deletion() method.</p>
<p>Happy overriding...</p>
| 1 | 2012-02-07T08:01:11Z | [
"python",
"django",
"django-signals"
] |
Convolution of two functions in Python | 1,222,147 | <p>I will have to implement a convolution of two functions in Python, but SciPy/Numpy appear to have functions only for the convolution of two arrays.</p>
<p>Before I try to implement this by using the the regular integration expression of convolution, I would like to ask if someone knows of an already available module that performs these operations.</p>
<p>Failing that, which of the several kinds of integration that SciPy provides is the best suited for this?</p>
<p>Thanks!</p>
| 2 | 2009-08-03T12:42:53Z | 1,224,347 | <p>You could try to implement the <a href="http://en.wikipedia.org/wiki/Convolution#Discrete%5Fconvolution" rel="nofollow">Discrete Convolution</a> if you need it point by point.</p>
| 1 | 2009-08-03T20:07:25Z | [
"python",
"convolution"
] |
Convolution of two functions in Python | 1,222,147 | <p>I will have to implement a convolution of two functions in Python, but SciPy/Numpy appear to have functions only for the convolution of two arrays.</p>
<p>Before I try to implement this by using the the regular integration expression of convolution, I would like to ask if someone knows of an already available module that performs these operations.</p>
<p>Failing that, which of the several kinds of integration that SciPy provides is the best suited for this?</p>
<p>Thanks!</p>
| 2 | 2009-08-03T12:42:53Z | 1,226,509 | <p>Yes, SciPy/Numpy is mostly concerned about arrays.</p>
<p>If you can tolerate an approximate solution, and your functions only operate over a range of value (not infinite) you can fill an array with the values and convolve the arrays.</p>
<p>If you want something more "correct" calculus-wise you would probably need a powerful solver (mathmatica, maple...)</p>
| 1 | 2009-08-04T09:29:38Z | [
"python",
"convolution"
] |
signals or triggers in SQLAlchemy | 1,222,208 | <p>does SQLAlchemy have something similar to Django's signal concept? Basically, I'd like to trigger a few functions when I pre-save or post-save some entity objects. Thanks.</p>
<p>Edit: I JUST want equivalent of django-signals in SQLAlchemy.</p>
| 11 | 2009-08-03T12:54:48Z | 1,222,267 | <p>You didn't make clear, whether you are integrating SQLAlchemy and Django, or you JUST want equivalent of django-signals in SQLAlchemy.</p>
<p>If you want equivalent of Django signals like post_save, pre_save, pre_delete etc, i would refer you the page,</p>
<p><a href="http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.MapperExtension">sqlalchemy.orm.interfaces.MapperExtension</a></p>
| 5 | 2009-08-03T13:09:43Z | [
"python",
"django",
"sqlalchemy"
] |
signals or triggers in SQLAlchemy | 1,222,208 | <p>does SQLAlchemy have something similar to Django's signal concept? Basically, I'd like to trigger a few functions when I pre-save or post-save some entity objects. Thanks.</p>
<p>Edit: I JUST want equivalent of django-signals in SQLAlchemy.</p>
| 11 | 2009-08-03T12:54:48Z | 1,222,946 | <p>You may want to consider the <a href="http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.SessionExtension" rel="nofollow">sqlalchemy.orm.SessionExtension</a> as well</p>
<p>Here's some code I threw together to set an owner id on an instance and set an update_date that get's the job done in a pylons app. the OrmExt class is where all the magic happens. And init_model is where you wire it up. </p>
<pre><code>import logging
import sqlalchemy as sa
from sqlalchemy import orm
from pylons import session
import datetime
log = logging.getLogger(__name__)
class ORMSecurityException(Exception):
'''
thrown for security violations in orm layer
'''
pass
def _get_current_user():
log.debug('getting current user from session...')
log.debug(session)
return session['user']
def _is_admin(user):
return False
def set_update_date(instance):
if hasattr(instance,'update_date'):
instance.update_date = datetime.datetime.now()
def set_owner(instance):
'''
if owner_id, run it through the rules
'''
log.info('set_owner')
if hasattr(instance, 'owner_id'):
log.info('instance.owner_id=%s' % instance.owner_id)
u = _get_current_user()
log.debug('user: %s' % u.email)
if not u:
#anonymous users can't save owned objects
raise ORMSecurityException()
if instance.owner_id==None:
#must be new object thus, owned by current user
log.info('setting owner on object %s for user: %s' % (instance.__class__.__name__,u.email))
instance.owner_id = u.id
elif instance.owner_id!=u.id and not _is_admin(u):
#if owner_id does not match user_id and user is not admin VIOLATION
raise ORMSecurityException()
else:
log.info('object is already owned by this user')
return #good to go
else:
log.info('%s is not an owned object' % instance.__class__.__name__)
return
def instance_policy(instance):
log.info('setting owner for %s' % instance.__class__.__name__)
set_owner(instance)
log.info('setting update_date for %s' % instance.__class__.__name__)
set_update_date(instance)
class ORMExt(orm.SessionExtension):
'''
attempt at managing ownership logic on objects
'''
def __init__(self,policy):
self._policy = policy
def before_flush(self,sqlsess,flush_context,instances):
'''
check all instances for owner_id==user.id
'''
try:
for instance in sqlsess.deleted:
try:
log.info('running policy for deleted %s' % instance.__class__.__name__)
self._policy(instance)
except Exception,ex:
log.error(ex)
raise ex
for instance in sqlsess.new:
try:
log.info('running policy for new %s' % instance.__class__.__name__)
self._policy(instance)
except Exception,ex:
log.error(ex)
raise ex
for instance in sqlsess.dirty:
try:
if sqlsess.is_modified(instance,include_collections=False,passive=True):
log.info('running policy for updated %s' % instance.__class__.__name__)
self._policy(instance)
except Exception, ex:
log.error(ex)
raise ex
except Exception,ex:
sqlsess.expunge_all()
raise ex
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
sm = orm.sessionmaker(autoflush=True, autocommit=True, bind=engine,extension=ORMExt(instance_policy))
meta.engine = engine
meta.Session = orm.scoped_session(sm)
</code></pre>
| 2 | 2009-08-03T15:22:57Z | [
"python",
"django",
"sqlalchemy"
] |
signals or triggers in SQLAlchemy | 1,222,208 | <p>does SQLAlchemy have something similar to Django's signal concept? Basically, I'd like to trigger a few functions when I pre-save or post-save some entity objects. Thanks.</p>
<p>Edit: I JUST want equivalent of django-signals in SQLAlchemy.</p>
| 11 | 2009-08-03T12:54:48Z | 4,539,784 | <p>Here's my take at this problem, it uses <a href="http://pypi.python.org/pypi/Louie" rel="nofollow">Louie</a> to dispatch signals:</p>
<p><strong><code>dispatch.py</code></strong></p>
<pre><code>"""
Signals dispatching for SQLAlchemy mappers.
"""
import louie
from sqlalchemy.orm.interfaces import MapperExtension
import signals
class LouieDispatcherExtension(MapperExtension):
"""
Dispatch signals using louie on insert, update and delete actions.
"""
def after_insert(self, mapper, connection, instance):
louie.send(signals.after_insert, instance.__class__,
instance=instance)
return super(LouieDispatcherExtension, self).after_insert(mapper,
connection, instance)
def after_delete(self, mapper, connection, instance):
louie.send(signals.after_delete, instance.__class__,
instance=instance)
return super(LouieDispatcherExtension, self).after_delete(mapper,
connection, instance)
def after_update(self, mapper, connection, instance):
louie.send(signals.after_update, instance.__class__,
instance=instance)
return super(LouieDispatcherExtension, self).after_update(mapper,
connection, instance)
def before_delete(self, mapper, connection, instance):
louie.send(signals.before_delete, instance.__class__,
instance=instance)
return super(LouieDispatcherExtension, self).before_delete(mapper,
connection, instance)
def before_insert(self, mapper, connection, instance):
louie.send(signals.before_insert, instance.__class__,
instance=instance)
return super(LouieDispatcherExtension, self).before_insert(mapper,
connection, instance)
def before_update(self, mapper, connection, instance):
louie.send(signals.before_update, instance.__class__,
instance=instance)
return super(LouieDispatcherExtension, self).before_update(mapper,
connection, instance)
</code></pre>
<p><strong><code>signals.py</code></strong></p>
<pre><code>from louie import Signal
class after_delete(Signal): pass
class after_insert(Signal): pass
class after_update(Signal): pass
class before_delete(Signal): pass
class before_insert(Signal): pass
class before_update(Signal): pass
</code></pre>
<p>Sample usage:</p>
<pre><code>class MyModel(DeclarativeBase):
__mapper_args__ = {"extension": LouieDispatcherExtension()}
ID = Column(Integer, primary_key=True)
name = Column(String(255))
def on_insert(instance):
print "inserted %s" % instance
louie.connect(on_insert, signals.after_insert, MyModel)
</code></pre>
| 2 | 2010-12-27T15:38:22Z | [
"python",
"django",
"sqlalchemy"
] |
signals or triggers in SQLAlchemy | 1,222,208 | <p>does SQLAlchemy have something similar to Django's signal concept? Basically, I'd like to trigger a few functions when I pre-save or post-save some entity objects. Thanks.</p>
<p>Edit: I JUST want equivalent of django-signals in SQLAlchemy.</p>
| 11 | 2009-08-03T12:54:48Z | 12,663,837 | <p>I think you are looking for `ORM Events'.
You can find documentation here: </p>
<p><a href="http://docs.sqlalchemy.org/en/latest/orm/events.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/events.html</a></p>
| 6 | 2012-09-30T18:28:50Z | [
"python",
"django",
"sqlalchemy"
] |
signals or triggers in SQLAlchemy | 1,222,208 | <p>does SQLAlchemy have something similar to Django's signal concept? Basically, I'd like to trigger a few functions when I pre-save or post-save some entity objects. Thanks.</p>
<p>Edit: I JUST want equivalent of django-signals in SQLAlchemy.</p>
| 11 | 2009-08-03T12:54:48Z | 20,677,966 | <p>You can use inner <code>MapperExtension</code> class:</p>
<pre><code>class YourModel(db.Model):
class BaseExtension(MapperExtension):
def before_insert(self, mapper, connection, instance):
# do something here
def before_update(self, mapper, connection, instance):
# do something here
__mapper_args__ = { 'extension': BaseExtension() }
# ....
</code></pre>
| 0 | 2013-12-19T09:37:36Z | [
"python",
"django",
"sqlalchemy"
] |
Is there a good html parser like HtmlAgilityPack (.NET) for Python? | 1,222,222 | <p>I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">http://www.codeplex.com/htmlagilitypack</a>), but for using with Python.</p>
<p>Anyone knows?</p>
| 2 | 2009-08-03T12:58:05Z | 1,222,233 | <p>Use <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> like everyone does.</p>
| 8 | 2009-08-03T13:00:12Z | [
"python",
"html",
"parsing"
] |
Is there a good html parser like HtmlAgilityPack (.NET) for Python? | 1,222,222 | <p>I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">http://www.codeplex.com/htmlagilitypack</a>), but for using with Python.</p>
<p>Anyone knows?</p>
| 2 | 2009-08-03T12:58:05Z | 1,222,240 | <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> should be something you search for. It is a html/xml parser that can deal with invalid pages and allows e.g. to iterate over specific tags.</p>
| 0 | 2009-08-03T13:02:05Z | [
"python",
"html",
"parsing"
] |
Is there a good html parser like HtmlAgilityPack (.NET) for Python? | 1,222,222 | <p>I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">http://www.codeplex.com/htmlagilitypack</a>), but for using with Python.</p>
<p>Anyone knows?</p>
| 2 | 2009-08-03T12:58:05Z | 1,222,991 | <p>Others have recommended BeautifulSoup, but it's much better to use <a href="http://codespeak.net/lxml/">lxml</a>. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p>
<p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/">Ian Blicking agrees</a>.</p>
<p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p>
| 8 | 2009-08-03T15:31:44Z | [
"python",
"html",
"parsing"
] |
Is there a way to modify a class in a class method in Python? | 1,222,311 | <p>I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get:</p>
<pre><code>NameError: global name 'ClassName' is not defined
</code></pre>
<p>Is there a way for a class method to modify the class? Something like this but that actually works:</p>
<pre><code>class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, name)
HocusPocus("blah")
HocusPocus("bleh")
</code></pre>
| 0 | 2009-08-03T13:18:05Z | 1,222,327 | <p>Class methods get the class passed as the first argument:</p>
<pre><code>class Bla(object):
@classmethod
def cm(cls,value):
cls.storedValue = value
Bla.cm("Hello")
print Bla.storedValue # prints "Hello"
</code></pre>
<p><hr></p>
<p><strong>Edit</strong>: I think I understand your problem now. If I get it correctly, all you want to do is this:</p>
<pre><code>class Bla(object):
storedValue = "Hello again"
print Bla.storedValue # prints "Hello again"
</code></pre>
<p>Class creation in Python (pretty much) simply means:</p>
<ol>
<li>Create a fresh namespace.</li>
<li>Run the code that you find inside the class body using this namespace</li>
<li>Put everything that's left in the namespace into the class as class attributes.</li>
</ol>
<p>Since <code>storedValue</code> <em>is</em> in the namespace after step 2, it's turned into a class attribute in step 3.</p>
| 5 | 2009-08-03T13:22:30Z | [
"python"
] |
Is there a way to modify a class in a class method in Python? | 1,222,311 | <p>I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get:</p>
<pre><code>NameError: global name 'ClassName' is not defined
</code></pre>
<p>Is there a way for a class method to modify the class? Something like this but that actually works:</p>
<pre><code>class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, name)
HocusPocus("blah")
HocusPocus("bleh")
</code></pre>
| 0 | 2009-08-03T13:18:05Z | 1,222,634 | <p>Another way you could do this would be to use a <a href="http://www.python.org/dev/peps/pep-3129/" rel="nofollow">class decorator</a>, though these are only available from Python 2.6 onwards IIRC.</p>
<p>Something like this:</p>
<pre><code>def addattributes(cls):
cls.foobar = 10
return cls
@addattributes
class MyClass(object):
pass
print MyClass.foobar
</code></pre>
<p>This kind of this most useful when you want to "decorate" a number of classes with some specific functionality / properties. In your case, if you only want to do this once, you might just want to use class methods as previously shown.</p>
| 0 | 2009-08-03T14:22:54Z | [
"python"
] |
Is there a way to modify a class in a class method in Python? | 1,222,311 | <p>I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get:</p>
<pre><code>NameError: global name 'ClassName' is not defined
</code></pre>
<p>Is there a way for a class method to modify the class? Something like this but that actually works:</p>
<pre><code>class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, name)
HocusPocus("blah")
HocusPocus("bleh")
</code></pre>
| 0 | 2009-08-03T13:18:05Z | 1,223,035 | <p>While many good suggestions have been advanced, the closest one can get to the originally requested code, that is:</p>
<pre><code>class ClassName(object):
def HocusPocus(name):
setattr(ClassName, name, property(fget=..., fset=...))
HocusPocus("blah")
HocusPocus("bleh")
</code></pre>
<p>is this:</p>
<pre><code>class ClassName(object):
def HocusPocus(name):
return property(fget=..., fset=...)
blah = HocusPocus("blah")
bleh = HocusPocus("bleh")
</code></pre>
<p>I'm assuming the mysterious <code>...</code> redacted parts need access to <code>name</code> too (otherwise it's not necessary to pass it as an argument).</p>
<p>The point is that, within the class body, HocusPocus is still just a function (since the class object doesn't exist yet until the class body finishes executing, the body is essentially like a function body that's running in its local dict [without the namespace optimizations typically performed by the Python compiler on locals of a real function, but that only makes the semantics simpler!]) and in particular it can be called within that body, can return a value, that value can be assigned (to a local variable of the class body, which will become a class attribute at the end of the body's execution), etc.</p>
<p>If you don't want ClassName.HocusPocus hanging around later, when you're done executing it within the class body just add a <code>del</code> statement (e.g. as the last statement in the class body):</p>
<pre><code> del HocusPocus
</code></pre>
| 0 | 2009-08-03T15:39:14Z | [
"python"
] |
Screen Scrape Form Results | 1,222,373 | <p>I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.</p>
<p>My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.</p>
<p>As an aside, I would prefer to do any processing in python.</p>
<p>Thanks</p>
| 3 | 2009-08-03T13:30:22Z | 1,222,427 | <p>You can pass a <code>data</code> parameter to <a href="http://docs.python.org/library/urllib.html#urllib.urlopen" rel="nofollow"><code>urllib.urlopen</code></a> to send POST data with the request just like you had filled out the form. You'll obviously have to take a look at what data exactly the form contains.</p>
<p>Also, if the form has <code>method="GET"</code>, the request data is just part of the url given to <code>urlopen</code>.</p>
<p>Pretty much standard for scraping the returned HTML data is <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>.</p>
| 2 | 2009-08-03T13:41:36Z | [
"python",
"forms",
"screen-scraping"
] |
Screen Scrape Form Results | 1,222,373 | <p>I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.</p>
<p>My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.</p>
<p>As an aside, I would prefer to do any processing in python.</p>
<p>Thanks</p>
| 3 | 2009-08-03T13:30:22Z | 1,222,613 | <p>A really nice library for screen-scraping is <a href="http://wwwsearch.sourceforge.net/mechanize/">mechanize</a>, which I believe is a clone of an original library written in Perl. Anyway, that in combination with the <a href="http://wwwsearch.sourceforge.net/ClientForm/">ClientForm</a> module, and some additional help from either BeautifulSoup and you should be away.</p>
<p>I've written loads of screen-scraping code in Python and these modules turned out to be the most useful. Most of the stuff that <a href="http://wwwsearch.sourceforge.net/mechanize/">mechanize</a> does could in theory be done by simply using the <a href="http://docs.python.org/library/urllib2.html">urllib2</a> or <a href="http://docs.python.org/library/httplib.html">httplib</a> modules from the standard library, but <a href="http://wwwsearch.sourceforge.net/mechanize/">mechanize</a> makes this stuff a breeze: essentially it gives you a programmatic browser (note, it does not require a browser to work, but mearly provides you with an API that behaves like a completely customisable browser).</p>
<p>For post-processing, I've had a lot of success with BeautifulSoup, but <a href="http://codespeak.net/lxml/lxmlhtml.html">lxml.html</a> is a good choice too.</p>
<p>Basically, you will be able to do this in Python for sure, and your results should be really good with the range of tools out there.</p>
| 5 | 2009-08-03T14:17:43Z | [
"python",
"forms",
"screen-scraping"
] |
Screen Scrape Form Results | 1,222,373 | <p>I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.</p>
<p>My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.</p>
<p>As an aside, I would prefer to do any processing in python.</p>
<p>Thanks</p>
| 3 | 2009-08-03T13:30:22Z | 1,222,906 | <p>I see the other two answers already mention all the major libraries of choice for the purpose... as long as the site being scraped does not make extensive use of Javascript, that is. If it IS a Javascript-heavy site and dependent on JS for the data it fetches and display (e.g. via AJAX) your problem is an order of magnitude harder; in that case, I might suggest starting with <a href="http://grep.codeconsult.ch/2007/02/24/crowbar-scrape-javascript-generated-pages-via-gecko-and-rest/" rel="nofollow">crowbar</a>, some customization of <a href="http://code.google.com/p/diggstripper/" rel="nofollow">diggstripper</a>, or <a href="http://www.jroller.com/bjornmartensson/entry/web%5Fscraping%5Fin%5Fearly%5F2007" rel="nofollow">selenium</a>, etc.</p>
<p>You'll have to do substantial work in Javascript and probably dedicated work to deal with the specifics of the (hypothetically JS-heavy) site in question, depending on the JS frameworks it uses, etc; that's why the job is so much harder if that is the case. But in any case you might end up with (at least in part) local HTML copies of the site's pages as displayed, and end by scraping <em>those</em> copies with the other tools already recommended. Good luck: may the sites you scrape always be Javascript-light!-)</p>
| 0 | 2009-08-03T15:13:32Z | [
"python",
"forms",
"screen-scraping"
] |
Screen Scrape Form Results | 1,222,373 | <p>I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.</p>
<p>My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.</p>
<p>As an aside, I would prefer to do any processing in python.</p>
<p>Thanks</p>
| 3 | 2009-08-03T13:30:22Z | 1,222,959 | <p>Others have recommended BeautifulSoup, but it's much better to use <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p>
<p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/" rel="nofollow">Ian Blicking agrees</a>.</p>
<p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p>
| 0 | 2009-08-03T15:25:27Z | [
"python",
"forms",
"screen-scraping"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,222,524 | <p>In Python:</p>
<pre><code>'[%s]' % ', '.join(pythonlistwithemails)
</code></pre>
<p>In bare HTML it is impossible... you'd have to use javascript.</p>
| 4 | 2009-08-03T14:00:33Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,222,595 | <p>It all depends how the HTML generation is treating your <em>values</em> array. Here is what you usually do to serialize a unicode string:</p>
<pre><code>In [550]: ss=u'one@example.com'
In [551]: print ss # uses str() implicitly
Out[552]: one@example.com
In [552]: str(ss)
Out[552]: 'one@example.com'
In [553]: repr(ss)
Out[553]: "u'one@example.com'"
</code></pre>
<p>If you are confident <em>values</em> only contains ASCII character strings, just use <em>str()</em> on the values. If you are unsure, use an explicit encoding like</p>
<pre><code>ss.encode('ascii', error='replace')
</code></pre>
| 1 | 2009-08-03T14:14:53Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,222,604 | <p>I don't know any Python, but if those <code>u</code>-markers and the single quotes show, doesn't that actually indicate that you're accessing the list members in the wrong way? </p>
<p>You're printing the whole list rather than each item, and the output looks like debug information to me. Such debug information could very well look different in another version or configuration of Python. So, though I don't know Python, I'd say: you should NOT try to parse that.</p>
<p>Using <a href="http://stackoverflow.com/questions/1222508/dropping-the-unicode-markers/1222524#1222524">liori's answer</a> does not actually <em>drop</em> the <code>u</code>-markers, but ensures the items from the list are accessed individually, which gives you the true value rather than some debug information. You could also use some loop to achieve the same (though the <code>join</code> makes the code a lot easier).</p>
| 2 | 2009-08-03T14:15:52Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,223,618 | <p>Option 1:</p>
<pre><code>myStr = str('[ ' + ', '.join(ss) + ' ]')
</code></pre>
<p>Option 2:</p>
<pre><code>myStr = '[ ' + ', '.join(ss) + ' ]'
myStr = myStr.encode(<whatever encoding you want>, <whatever way of handling errors you wish to use>)
</code></pre>
<p>I'm not used to Python pre-version 3, so I'm not really sure whether the additional strings need a <code>u</code> prefix or if it's an implicit conversion.</p>
| 0 | 2009-08-03T17:37:54Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,223,862 | <pre><code>"[{0}]".format(", ".join(python_email_list))
</code></pre>
<p>From Python 2.6 format() method is the preferred way of string formatting.
Docs <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">here</a>.</p>
| 2 | 2009-08-03T18:24:24Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,226,523 | <p>The easiest way for you to do it would be to iterate over your email list. e.g. </p>
<pre><code>{% for email in Emails %}
email,
{% endfor %}
</code></pre>
<p>This way you (or a designer) will have a lot more control of the layout.</p>
<p>Have a look at the <a href="http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates" rel="nofollow">template documentation</a> for more details.</p>
| -1 | 2009-08-04T09:33:02Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,228,904 | <p>In the template</p>
<pre><code>[ {{ email_list|join:", " }} ]
</code></pre>
<p>note: the [, and ] are literal square brackets, not code :)</p>
| 1 | 2009-08-04T17:37:12Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
Dropping the Unicode markers in Html output | 1,222,508 | <p>I have a python list which holds a few email ids accepted as unicode strings:</p>
<pre><code>[u'one@example.com',u'two@example.com',u'three@example.com']
</code></pre>
<p>This is assigned to <code>values['Emails']</code> and <code>values</code> is passed to render as html.
The Html renders as this:</p>
<blockquote>
<p>Emails: [u'one@example.com',u'two@example.com',u'three@example.com']</p>
</blockquote>
<p>I would like it to look like this:</p>
<blockquote>
<p>Emails: [ one@example.com, two@example.com, three@example.com ]</p>
</blockquote>
<p>How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?</p>
| 1 | 2009-08-03T13:58:29Z | 1,248,797 | <p>This is actually a long and formatted comment on <a href="http://stackoverflow.com/questions/1222508/dropping-the-unicode-markers-in-html-output/1237495#1237495">the last answer</a>. Still not knowing any Python, I am a bit disappointed by not using <code>join</code> to get commas between each address (like <a href="http://stackoverflow.com/questions/1222508/dropping-the-unicode-markers-in-html-output/1222524#1222524">suggested</a> by liori). Replacing the comma with some space feels like walking away from the problem, and is not going to learn anyone anything. We don't sacrifice quality here at Stack Overflow! ;-)</p>
<p>I just typed the following on my Mac:</p>
<pre>$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = [ u'one@example.com', u'two@example.com', u'three@example.com' ]
>>> print lst
[u'one@example.com', u'two@example.com', u'three@example.com']
>>> print ', '.join(lst)
one@example.com, two@example.com, three@example.com
>>> print 'Emails: [%s]' % ', '.join(lst)
Emails: [one@example.com, two@example.com, three@example.com]
>>> lst = [ u'one@example.com' ]
>>> print lst
[u'one@example.com']
>>> print ', '.join(lst)
one@example.com
>>> print 'Emails: [%s]' % ', '.join(lst)
Emails: [one@example.com]
>>> s = u'one@example.com'
>>> print s
one@example.com
>>> print ', '.join(s)
o, n, e, @, e, x, a, m, p, l, e, ., c, o, m</pre>
<p>Makes perfect sense to me... Now, using a different separator for the last item (<a href="http://mail.python.org/pipermail/python-list/2008-July/670406.html" rel="nofollow">like</a> <em>one@example.com, two@example.com <strong>and</strong> three@example.com</em>) will need some more work, but printing the very same separator between each item should not be complicated at all.</p>
| 0 | 2009-08-08T12:45:39Z | [
"python",
"html",
"django",
"unicode",
"html-lists"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,222,717 | <p>Sure, the difference between the following two:</p>
<pre><code>[f(x) for x in list]
</code></pre>
<p>and this:</p>
<pre><code>(f(x) for x in list)
</code></pre>
<p>is that the first will generate the list in memory, whereas the second is a new generator, with lazy evaluation.</p>
<p>So, simply write the "unfiltered" list as a generator instead. Here's your code, with the generator inline:</p>
<pre><code>def myFunction(x):
print("called for: " + str(x))
return x * x
originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
limit = 10
result = [C2 for C2 in ((myFunction(C), C) for C in originalList) if C2[0] < limit]
# result = [C2 for C2 in [(myFunction(C), C) for C in originalList] if C2[0] < limit]
</code></pre>
<p>Note that you will not see a difference in the printout from the two, but if you were to look at memory usage, the second statement which is commented out, will use more memory.</p>
<p>To do a simple change to your code in your question, rewrite unfiltered as this:</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
^ ^
+---------- change these to (..) ---------+
|
v
unfiltered = ( (myFunction(C),C) for C in originalList )
</code></pre>
| 8 | 2009-08-03T14:38:39Z | [
"python",
"list-comprehension"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,222,720 | <p>Don't use a list comprehension; a normal for loop is fine here.</p>
| 3 | 2009-08-03T14:39:03Z | [
"python",
"list-comprehension"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,222,729 | <p>Just compute the distances beforehand and then filter the results:</p>
<pre><code>with_distances = ((myFunction(C), C) for C in originalList)
result = [C for C in with_distances if C[0] < limit]
</code></pre>
<p>Note: instead of building a new list, I use a generator expression to build the distance/element pairs.</p>
| 3 | 2009-08-03T14:42:03Z | [
"python",
"list-comprehension"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,222,730 | <p>Rather than using a global variable as in your option 2, you could rely on the fact that in Python parameters are passed by object - that is, the object that is passed into your <code>myFunction</code> function is the <em>same</em> object as the one in the list (this isn't exactly the same thing as call by reference, but it's close enough).</p>
<p>So, if your myFunction set an attribute on the object - say, <code>_result</code> - you could filter by that attribute:</p>
<pre><code>result = [(_result, C) for C in originalList if myFunction(C) < limit]
</code></pre>
<p>and your myFunction might look like this:</p>
<pre><code>def myFunction(obj):
obj._result = ... calculation ....
return obj._result
</code></pre>
| 0 | 2009-08-03T14:42:05Z | [
"python",
"list-comprehension"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,222,732 | <p>What's wrong with option 1?</p>
<p>"duplicate my originalList and waste some memory (the list could be quite big - more than 10,000 elements)"</p>
<p>10,000 elements is only 10,000 pointers to tuples that point to existing objects. Think 160K or so of memory. Hardly worth talking about.</p>
| 0 | 2009-08-03T14:42:59Z | [
"python",
"list-comprehension"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,222,784 | <p>Some options:</p>
<ul>
<li>Use <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoization</a></li>
<li>Use a normal for loop</li>
<li>Create an unfiltered list, then filter it (your option 1). The 'wasted' memory will be reclaimed by the GC very quickly - it's not something you need to worry about.</li>
</ul>
| 0 | 2009-08-03T14:52:33Z | [
"python",
"list-comprehension"
] |
List Comprehensions in Python : efficient selection in a list | 1,222,677 | <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p>
<p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p>
<pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ]
</code></pre>
<p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p>
<p>So, is there a way to avoid this ??</p>
<p>I have two other possibilities, but they are not so good:</p>
<ol>
<li><p>the first one, is to create the
unfiltered list</p>
<pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ]
</code></pre>
<p>and then sort it</p>
<pre><code>result = [ (dist,C) for dist,C in unfiltered if dist < limit ]
</code></pre>
<p>but in that case, I duplicate my
<code>originalList</code> and waste some memory
(the list could be quite big - more
than 10,000 elements)</p></li>
<li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br />
result in a global variable (<code>lastResult</code> for example), and this value is re-used in the
List comprehension </p>
<pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ]
</code></pre></li>
</ol>
<p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p>
<p>Thanks for your answers.</p>
| 7 | 2009-08-03T14:30:18Z | 1,226,540 | <p>Lasse V. Karlsen has an excellent reply to your question.</p>
<p>If your distance computation is slow, I guess your elements are polylines, or something like that, right ?</p>
<p>There are lots of ways to make it faster :</p>
<ul>
<li><p>If the distance between bounding boxes of objects is > X, then it follows that the distance between those objects is > X. So you only need to compute distance between bounding boxes.</p></li>
<li><p>If you want all objects that are at a distance less than X from object A, only objects whose bounding box intersect A's bounding box enlarged by X are potential matches.</p></li>
</ul>
<p>Using the second point you can probably drop lots of candidate matches and only do the slow computation when needed.</p>
<p>Bounding boxes must be cached beforehand.</p>
<p>If you really have a lot of objects you could also use space partitioning...</p>
<p>Or convex enclosing polys if you are in 3D</p>
| 1 | 2009-08-04T09:37:38Z | [
"python",
"list-comprehension"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,222,804 | <p>I think that you will be better served going straight into 3.0. Unless you have a legacy codebase to contend with, there are very few advantages to learning the 2.xx ways of doing things.</p>
<p>In the Python world (as in most others, really), releases do tend to take a while to migrate down to all of the subprojects, but if you ever find the need to transition back to 2.xx, I don't think you'll find relearning things to be particularly painful.</p>
| 3 | 2009-08-03T14:55:43Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,222,832 | <p>Use python 3.1, Luke.</p>
| 1 | 2009-08-03T14:58:45Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,222,843 | <p>Absolutely not 3.0 - 3.1 is out and is stabler, better, faster in every respect; it makes absolutely no sense to start with 3.0 at this time, if you want to take up the 3 series it should on all accounts be 3.1.</p>
<p>As for 2.6 vs 3.1, 3.1 is a better language (especially because some cruft was removed that had accumulated over the years but has to stay in 2.* for backwards compatibility) but all the rest of the ecosystem (from extensions to tools, from books to collective knowledge) is still very much in favor of 2.6 -- if you don't care about being able to use (e.g.) certain GUIs or scientific extensions, deploy on App Engine, script Windows with COM, have a spiffy third party IDE, and so on, 3.1 is advisable, but if you care about such things, still 2.* for now.</p>
| 18 | 2009-08-03T15:00:58Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,222,856 | <p>You should go with the latest release of any programming language you learn unless you have a specific reason <strong>not</strong> to. Since you don't have an existing project that won't work with Python 3.0, you should feel free to use the newest version.</p>
| 2 | 2009-08-03T15:03:20Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,222,924 | <p>Python 3.1 should not be used until other libraries have caught up with support for it.</p>
<p>You should use 2.6 now. It has several 3.x features back-ported to it, so that migrating to 3.x won't be difficult later on, and you won't learn obsolete practices.</p>
| 3 | 2009-08-03T15:18:03Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,223,029 | <p>The good news is that it's not really that tough to learn both Python 2.x and 3.x. You can install the latest 2.x version as the version registered with the system to run Python scripts by default, but also install the latest 3.x version to explicitly kick off when you want to. That's what I have on my Windows Vista system.</p>
<p>Then, the key document for learning the differences between the 2.x and 3.x versions is:</p>
<p><a href="http://docs.python.org/3.1/whatsnew/3.0.html" rel="nofollow">http://docs.python.org/3.1/whatsnew/3.0.html</a></p>
<p>If you read Python learning materials out there which are based on 2.x and also refer to that "Whatâs New In Python 3.0" link above, you'll get an understanding of how things changed. Also see the other whats new docs, like for the differences between 3.0 and 3.1, but the link above is the main one to understand the 2.x vs. 3.x changes.</p>
| 2 | 2009-08-03T15:38:08Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,225,173 | <p>Short answer: Start with Python 2.6.</p>
<p>Why: Programming is more fun and useful when you can leverage the work of others. This means using 3rd party libraries often. Many of the popular libraries for Python don't have 3.x support yet. PIL and NumPy/SciPy come to mind. My favorite interpreter, ipython, also doesn't work with 3.0 yet. Many unit testing frameworks and web frameworks are also not on 3.0 yet.</p>
<p>So if you start out in 3.x many doors will be closed to you, at least until 3.x porting takes on steam. There are admittedly a lot of nice features in Python 3.x, but some of them have been backported to 2.6 and some more will make it into 2.7. So stick with 2.6 for now, and re-evaluate 3.x in a year's time or so.</p>
| 8 | 2009-08-03T23:53:05Z | [
"python",
"python-3.x"
] |
Should I Start With Python 3.0? | 1,222,782 | <p>Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.</p>
| 11 | 2009-08-03T14:52:17Z | 1,540,468 | <p>Use 3.1</p>
<p>Why?</p>
<p>1) Because as long as everyone is still using 2.6, the libraries will have less reasons to migrate to 3.1. As long as those libraries are not ported to 3.1, you are stuck with the choice of either not using the strengths of 3.1, or only doing the jobs half way by using the hackish solution of using a back-ported feature set. <strong>Be a forward thinker and help push Python forward.</strong></p>
<p>2) If you learn and use 3.1 now, you wont have to relearn it later when the mass port is complete. I know some people say you wont have to learn much, but why learn the old crap at all? <strong>Python itself is moving towards 3.1</strong>, the libraries will move toward 3.1, and it sucks to have to play catch-up and relearn a language you are already using.</p>
<p>3) <strong>3.1 is all around a better language</strong>, more stable and more consistent than 2.6... this is normal. The lessons learned from 2.6 were all poured into 3.1 to make it better. <strong>It is a process called PROGRESS</strong>. This is why nobody still uses Windows 3.1. It is the way things move FORWARD. Why else do you think they went to the trouble of back porting a feature set in the first place?</p>
<p>4) If you are learning Python, and learn 2.6, then by the time you are really comfortable with the language, the ports will be out, and you will have to learn the libraries, and the language all over again. If you start with 3.1, then by the time you are comfortable with the language, the ports will be out, and then you can learn the libraries that you are interested in. <strong>It is a smoother process</strong>.</p>
<p>5) <strong>To be a better developer.</strong> If you have to learn and relearn the same things, your understanding will not be very deep. By learning this language, and its libraries only once, you will have more time to work with them rather than relearning syntax. This allows you to understand them better. If you are really missing some pieces by forgoing on the libraries? WRITE THEM. You will probably not need an entire library, and can usually write only those pieces that you need, and develop tools for yourself. This, again, helps you understand the language better, and more deeply.</p>
| 7 | 2009-10-08T21:02:30Z | [
"python",
"python-3.x"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 1,222,957 | <p>GIL is still there in CPython 3.1; the <a href="http://code.google.com/p/unladen-swallow/">Unladen Swallow</a> projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2.6 first with the intent of eventually porting to 3.x for whatever x will be current by the time the 2.y version is considered to be done. For now, multiprocessing (instead of threading) remains the way of choice for using multiple cores in CPython (IronPython and Jython are fine too, but they don't support Python 3 currently, nor do they make C++ integration all that easy either;-).</p>
| 22 | 2009-08-03T15:25:03Z | [
"python",
"multithreading",
"gil"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 1,224,503 | <p>The GIL is a good thing.</p>
<p>Just make your C++ application release the GIL while it is doing its multithreaded work. Python code will continue to run in the other threads, unspoiled. Only acquire the GIL when you have to touch python objects.</p>
| 4 | 2009-08-03T20:39:39Z | [
"python",
"multithreading",
"gil"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 1,225,350 | <p>The GIL will not affect your code which does not use python objects. In Numpy, we release the GIL for computational code (linear algebra calls, etc...), and the underlying code can use multithreading freely (in fact, those are generally 3rd party libraries which do not know anything about python)</p>
| 9 | 2009-08-04T01:17:51Z | [
"python",
"multithreading",
"gil"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 1,457,021 | <p>I guess there will always be a GIL.
The reason is performance. Making all the low level access thread safe - means putting a mutex around each hash operation etc. is heavy. Remember that a simple statement like</p>
<pre><code>self.foo(self.bar, 3, val)
</code></pre>
<p>Might already have at least 3 (if val is a global) hashtable lookups at the moment and maybe even much more if the method cache is not hot (depending on the inheritance depth of the class)</p>
<p>It's expensive - that's why Java dropped the idea and introduced hashtables which do not use a monitor call to get rid of its "Java Is Slow" trademark.</p>
| 0 | 2009-09-21T21:36:43Z | [
"python",
"multithreading",
"gil"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 2,137,581 | <p>Significant changes will occur in the GIL for Python 3.2. Take a look at the <a href="http://docs.python.org/dev/py3k/whatsnew/3.2.html#multi-threading">What's New for Python 3.2</a>, and <a href="http://mail.python.org/pipermail/python-dev/2009-October/093359.html">the thread that initiated it in the mailing list</a>.</p>
<p>While the changes don't signify the end of the GIL, they herald potentially enormous performance gains.</p>
<h2>Update0</h2>
<ul>
<li>The general performance gains with the new GIL in 3.2 by Antoine Pitrou were negligible, and instead focused on <a href="http://bugs.python.org/issue7316">improving contention issues</a> that arise in certain corner cases.</li>
<li>An <a href="http://bugs.python.org/issue7946">admirable effort</a> by David Beazley was made to implement a scheduler to significantly improve performance when CPU and IO bound threads are mixed, which was unfortunately shot down.</li>
<li>The Unladen Swallow work was <a href="http://www.python.org/dev/peps/pep-3146/">proposed for merging</a> in Python 3.3, but this has been withdrawn due to lack of results in that project. <a href="http://pypy.org/">PyPy</a> is now the preferred project and is currently <a href="http://pypy.org/py3donate.html">requesting funding</a> to add Python3k support. There's very little chance that PyPy will become the default at present.</li>
</ul>
<p>Efforts have been made for the last 15 years to remove the GIL from CPython but for the foreseeable future it is here to stay.</p>
| 12 | 2010-01-26T04:51:43Z | [
"python",
"multithreading",
"gil"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 4,965,477 | <p>As I understand it the "brainfuck" scheduler will replace the GIL from python 3.2</p>
<p><a href="http://bugs.python.org/issue7946" rel="nofollow">BFS bainfuck scheduler</a></p>
| 1 | 2011-02-11T03:54:50Z | [
"python",
"multithreading",
"gil"
] |
GIL in Python 3.1 | 1,222,929 | <p>Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration</p>
| 14 | 2009-08-03T15:18:55Z | 4,965,523 | <p>If the GIL is getting in the way, just use the <a href="http://docs.python.org/dev/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module. It spawns new processes but uses the threading model and (most of the) api. In other words, you can do process-based parallelism in a thread-like way.</p>
| 1 | 2011-02-11T04:05:27Z | [
"python",
"multithreading",
"gil"
] |
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? | 1,223,007 | <p>I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition. </p>
<p>For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers. </p>
<p>Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters. </p>
<p>Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now. </p>
<p>In response to some comments here is some more information:<br />
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.<br />
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').</p>
| 3 | 2009-08-03T15:33:54Z | 1,223,046 | <p>First, profile to find the bottleneck.</p>
<p>If the bottleneck is simply the massive number of possible partitions, I recommend parallelization, possibly via <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code></a>. If that's still not enough, you might look into a <a href="http://www.beowulf.org/" rel="nofollow">Beowulf</a> cluster.</p>
<p>If the bottleneck is just that the calculation is slow, try shelling out to C. It's pretty easy to do via <a href="http://docs.python.org/library/ctypes.html" rel="nofollow"><code>ctypes</code></a>.</p>
<p>Also, I'm not really sure how you're storing the partitions, but you could probably squash memory consumption a pretty good bit by using one string and a <a href="http://en.wikipedia.org/wiki/Suffix%5Farray" rel="nofollow">suffix array</a>. If your bottleneck is swapping and/or cache misses, that might be a big win.</p>
| 3 | 2009-08-03T15:40:49Z | [
"python",
"string",
"partitioning"
] |
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? | 1,223,007 | <p>I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition. </p>
<p>For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers. </p>
<p>Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters. </p>
<p>Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now. </p>
<p>In response to some comments here is some more information:<br />
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.<br />
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').</p>
| 3 | 2009-08-03T15:33:54Z | 1,223,140 | <p>A <a href="http://en.wikipedia.org/wiki/Dynamic%5Fprogramming" rel="nofollow">Dynamic Programming</a> solution (if I understood the question right):</p>
<pre><code>def dynProgSolution(text, probs):
probUpTo = [1]
for i in range(1, len(text)+1):
cur = sum(v*probs[text[k:i]] for k, v in enumerate(probUpTo))
probUpTo.append(cur)
return probUpTo[-1]
print dynProgSolution(
'abc',
{'a': 0.1, 'b': 0.2, 'c': 0.3,
'ab': 0.4, 'bc': 0.5, 'abc': 0.6}
)
</code></pre>
<p>The complexity is O(N<sup>2</sup>) so it will easily solve the problem for N=20.</p>
<p>How why does this work:</p>
<ul>
<li>Everything you will multiply by <code>probs['a']*probs['b']</code> you will also multiply by <code>probs['ab']</code></li>
<li>Thanks to the <a href="http://en.wikipedia.org/wiki/Multiplication#Properties" rel="nofollow">Distributive Property</a> of multiplication and addition, you can sum those two together and multiply this single sum by all of its continuations.</li>
<li>For every possible last substring, it adds the sum of all splits ending with that by adding its probability multiplied by the sum of all probabilities of previous paths. (alternative phrasing would be appreciated. my python is better than my english..)</li>
</ul>
| 5 | 2009-08-03T15:57:35Z | [
"python",
"string",
"partitioning"
] |
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? | 1,223,007 | <p>I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition. </p>
<p>For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers. </p>
<p>Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters. </p>
<p>Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now. </p>
<p>In response to some comments here is some more information:<br />
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.<br />
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').</p>
| 3 | 2009-08-03T15:33:54Z | 1,223,144 | <p>Your substrings are going to be reused over and over again by the longer strings, so caching the values using a <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoizing</a> technique seems like an obvious thing to try. This is just a time-space trade off. The simplest implementation is to use a dictionary to cache values as you calculate them. Do a dictionary lookup for every string calculation; if it's not in the dictionary, calculate and add it. Subsequent calls will make use of the pre-computed value. If the dictionary lookup is faster than the calculation, you're in luck.</p>
<p>I realise you are using Python, but... as a side note that may be of interest, if you do this in Perl, you don't even have to write any code; the built in <a href="http://search.cpan.org/~mjd/Memoize-1.01/Memoize.pm" rel="nofollow">Memoize module</a> will do the caching for you!</p>
| 1 | 2009-08-03T15:58:10Z | [
"python",
"string",
"partitioning"
] |
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? | 1,223,007 | <p>I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition. </p>
<p>For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers. </p>
<p>Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters. </p>
<p>Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now. </p>
<p>In response to some comments here is some more information:<br />
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.<br />
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').</p>
| 3 | 2009-08-03T15:33:54Z | 1,223,148 | <p>You may get a minor reduction of the amount of computation by a small refactoring based on associative properties of arithmetic (and string concatenation) though I'm not sure it will be a life-changer. The core idea would be as follows:</p>
<p>consider a longish string e.g. 'abcdefghik', 10-long, for definiteness w/o loss of generality. In a naive approach you'd be multiplying p(a) by the many partitions of the 9-tail, p(ab) by the many partitions of the 8-tail, etc; in particular p(a) and p(b) will be multiplying exactly the same partitions of the 8-tail (all of them) as p(ab) will -- 3 multiplications and two sums among them. So factor that out:</p>
<pre><code>(p(ab) + p(a) * p(b)) * (partitions of the 8-tail)
</code></pre>
<p>and we're down to 2 multiplications and 1 sum for this part, having saved 1 product and 1 sum. to cover all partitions with a split point just right of 'b'. When it comes to partitions with a split just right of 'c',</p>
<pre><code>(p(abc) + p(ab) * p(c) + p(a) * (p(b)*p(c)+p(bc)) * (partitions of the 7-tail)
</code></pre>
<p>the savings mount, partly thanks to the internal refactoring -- though of course one must be careful about double-counting. I'm thinking that this approach may be generalized -- start with the midpoint and consider all partitions that have a split there, separately (and recursively) for the left and right part, multiplying and summing; then add all partitions that DON'T have a split there, e.g. in the example, the halves being 'abcde' on the left and 'fghik' on the right, the second part is about all partitions where 'ef' are together rather than apart -- so "collapse" all probabilities by considering that 'ef' as a new 'superletter' X, and you're left with a string one shorter, 'abcdXghik' (of course the probabilities for the substrings of THAT map directly to the originals, e.g. the p(cdXg) in the new string is just exactly the p(cdefg) in the original).</p>
| 1 | 2009-08-03T15:58:36Z | [
"python",
"string",
"partitioning"
] |
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? | 1,223,007 | <p>I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition. </p>
<p>For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers. </p>
<p>Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters. </p>
<p>Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now. </p>
<p>In response to some comments here is some more information:<br />
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.<br />
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc').</p>
| 3 | 2009-08-03T15:33:54Z | 1,223,236 | <p>You should look into the <code>itertools</code> module. It can create a generator for you that is very fast. Given your input string, it will provide you with all possible permutations. Depending on what you need, there is also a <code>combinations()</code> generator. I'm not quite sure if you're looking at "b|ca" when you're looking at "abc," but either way, this module may prove useful to you.</p>
| 0 | 2009-08-03T16:16:28Z | [
"python",
"string",
"partitioning"
] |
How to write native newline character to a file descriptor in Python? | 1,223,289 | <p>The <code>os.write</code> function can be used to writes bytes into a <em>file descriptor</em> (not file object). If I execute <em><code>os.write(fd, '\n')</code></em>, only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux.<br>
What is the best way to achieve this?</p>
<p>I'm using Python 2.6, but I'm also wondering if Python 3 has a different solution.</p>
| 18 | 2009-08-03T16:30:43Z | 1,223,303 | <p>Use this</p>
<pre><code>import os
os.write(fd, os.linesep)
</code></pre>
| 37 | 2009-08-03T16:33:16Z | [
"python"
] |
How to write native newline character to a file descriptor in Python? | 1,223,289 | <p>The <code>os.write</code> function can be used to writes bytes into a <em>file descriptor</em> (not file object). If I execute <em><code>os.write(fd, '\n')</code></em>, only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux.<br>
What is the best way to achieve this?</p>
<p>I'm using Python 2.6, but I'm also wondering if Python 3 has a different solution.</p>
| 18 | 2009-08-03T16:30:43Z | 1,223,313 | <p>How about <code>os.write(<file descriptor>, os.linesep)</code>? (<code>import os</code> is unnecessary because you seem to have already imported it, otherwise you'd be getting errors using <code>os.write</code> to begin with.)</p>
| 8 | 2009-08-03T16:36:00Z | [
"python"
] |
Error starting Django with Pinax | 1,223,513 | <p>Upon trying to start a Pinax app, I receive the following error:</p>
<pre><code>Error: No module named notification
</code></pre>
<p>Below are the steps I took</p>
<pre><code>svn co http://svn.pinaxproject.com/pinax/trunk/ pinax
cd pinax/pinax/projects/basic_project
./manage.py syncdb
</code></pre>
<p>Any suggestions?</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>Turns out there are some bugs in the SVN version. Downloading the latest release solved my problem. If any one has any other suggestions on getting the trunk working, they would still be appreciated.</p>
| 1 | 2009-08-03T17:18:38Z | 1,223,664 | <p>Two thoughts:
1. Check all of your imports to make sure that notification is getting into the namespace.
2. You may be missing quotes around an import path (eg. in your urls.py: (r'^test', 'mysite.notification') -- sometimes I forget the quotes around the view)</p>
| 0 | 2009-08-03T17:48:05Z | [
"python",
"django",
"pinax"
] |
Error starting Django with Pinax | 1,223,513 | <p>Upon trying to start a Pinax app, I receive the following error:</p>
<pre><code>Error: No module named notification
</code></pre>
<p>Below are the steps I took</p>
<pre><code>svn co http://svn.pinaxproject.com/pinax/trunk/ pinax
cd pinax/pinax/projects/basic_project
./manage.py syncdb
</code></pre>
<p>Any suggestions?</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>Turns out there are some bugs in the SVN version. Downloading the latest release solved my problem. If any one has any other suggestions on getting the trunk working, they would still be appreciated.</p>
| 1 | 2009-08-03T17:18:38Z | 1,225,094 | <p>Try following the latest install instructions here:</p>
<p><a href="http://github.com/pinax/pinax/blob/600d6c5ca0b45814bdc73b1264d28bb66c661ac8/INSTALL" rel="nofollow">http://github.com/pinax/pinax/blob/600d6c5ca0b45814bdc73b1264d28bb66c661ac8/INSTALL</a></p>
<p>Don't think this will work on Windows (maybe if you are using cygwin) as they are using virtualenv and pip.</p>
<p>Note the version has recently been upgraded to 0.7rc1</p>
<p>IIRC I had to add a directory or two to the Python path last time I did a fresh install of Pinax. I'm doing a fresh checkout now into a new virtualenv, I'll edit this answer if I hit any snags.</p>
| 0 | 2009-08-03T23:22:29Z | [
"python",
"django",
"pinax"
] |
Error starting Django with Pinax | 1,223,513 | <p>Upon trying to start a Pinax app, I receive the following error:</p>
<pre><code>Error: No module named notification
</code></pre>
<p>Below are the steps I took</p>
<pre><code>svn co http://svn.pinaxproject.com/pinax/trunk/ pinax
cd pinax/pinax/projects/basic_project
./manage.py syncdb
</code></pre>
<p>Any suggestions?</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>Turns out there are some bugs in the SVN version. Downloading the latest release solved my problem. If any one has any other suggestions on getting the trunk working, they would still be appreciated.</p>
| 1 | 2009-08-03T17:18:38Z | 1,225,786 | <p>I'd avoid the svn version all together. It's unmaintained and out of date. Instead, use the git version at <a href="http://github.com/pinax/pinax" rel="nofollow">http://github.com/pinax/pinax</a> or (even better) the recently release 0.7b3 downloadable from <a href="http://pinaxproject.com" rel="nofollow">http://pinaxproject.com</a></p>
| 5 | 2009-08-04T05:22:18Z | [
"python",
"django",
"pinax"
] |
Python TypeError unsupported operand type(s) for %: 'file' and 'unicode' | 1,223,563 | <p>I'm working on a django field validation and I can't figure out why I'm getting a type error for this section:</p>
<pre><code>def clean_tid(self):
data = self.cleaned_data['tid']
stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data
result = stdout_handel.read()
</code></pre>
<p>Do I have to convert data somehow before I can pass it in as a string variable?</p>
| 0 | 2009-08-03T17:29:17Z | 1,223,568 | <p>Check your parenthesis.</p>
<p>Wrong</p>
<pre><code>stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data
</code></pre>
<p>Might be right.</p>
<pre><code>stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN" % data )
</code></pre>
| 1 | 2009-08-03T17:30:52Z | [
"python",
"django",
"unicode",
"typeerror"
] |
Python TypeError unsupported operand type(s) for %: 'file' and 'unicode' | 1,223,563 | <p>I'm working on a django field validation and I can't figure out why I'm getting a type error for this section:</p>
<pre><code>def clean_tid(self):
data = self.cleaned_data['tid']
stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data
result = stdout_handel.read()
</code></pre>
<p>Do I have to convert data somehow before I can pass it in as a string variable?</p>
| 0 | 2009-08-03T17:29:17Z | 1,223,939 | <p>Just a small tip - it's better to use <code>subprocess</code> module and <code>Popen</code> class instead of <code>os.popen</code> function. More details <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">here (docs)</a>.</p>
| 1 | 2009-08-03T18:40:41Z | [
"python",
"django",
"unicode",
"typeerror"
] |
Lightweight markup language for Python | 1,223,741 | <p>Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text:</p>
<pre><code>my_text = cgidata.getvalue('my_text', 'default_text')
ftable.AddRow([Label(_('Enter your text')),
TextArea('my_text', my_text, rows=8, cols=60).Format()])
</code></pre>
<p>How can I change this so that only some (safe, eventually lightweight) markup is allowed? All suggestions including sanitizers are welcome, as long as it easily integrates with Python.</p>
| 4 | 2009-08-03T18:02:54Z | 1,223,778 | <p>You could use <a href="http://docutils.sourceforge.net/rst.html" rel="nofollow">restructured text</a> . I'm not sure if it has a sanitizing option, but it's well supported by Python, and it generates all sorts of formats.</p>
| 2 | 2009-08-03T18:08:18Z | [
"python",
"html",
"markup"
] |
Lightweight markup language for Python | 1,223,741 | <p>Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text:</p>
<pre><code>my_text = cgidata.getvalue('my_text', 'default_text')
ftable.AddRow([Label(_('Enter your text')),
TextArea('my_text', my_text, rows=8, cols=60).Format()])
</code></pre>
<p>How can I change this so that only some (safe, eventually lightweight) markup is allowed? All suggestions including sanitizers are welcome, as long as it easily integrates with Python.</p>
| 4 | 2009-08-03T18:02:54Z | 1,223,981 | <p>Use the python <a href="http://www.freewisdom.org/projects/python-markdown/Using%5Fas%5Fa%5FModule" rel="nofollow">markdown</a> implementation</p>
<pre><code>import markdown
mode = "remove" # or "replace" or "escape"
md = markdown.Markdown(safe_mode=mode)
html = md.convert(text)
</code></pre>
<p>It is very flexible, you can use various extensions, create your own etc.</p>
| 8 | 2009-08-03T18:49:43Z | [
"python",
"html",
"markup"
] |
Lightweight markup language for Python | 1,223,741 | <p>Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text:</p>
<pre><code>my_text = cgidata.getvalue('my_text', 'default_text')
ftable.AddRow([Label(_('Enter your text')),
TextArea('my_text', my_text, rows=8, cols=60).Format()])
</code></pre>
<p>How can I change this so that only some (safe, eventually lightweight) markup is allowed? All suggestions including sanitizers are welcome, as long as it easily integrates with Python.</p>
| 4 | 2009-08-03T18:02:54Z | 1,224,521 | <p>This simple sanitizing function uses a whitelist and is roughly the same as the solution of <a href="http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter">python-html-sanitizer-scrubber-filter</a>, but also allows to limit the use of attributes (since you probably don't want someone to use, among others, the <code>style</code> attribute):</p>
<pre><code>from BeautifulSoup import BeautifulSoup
def sanitize_html(value):
valid_tags = 'p i b strong a pre br'.split()
valid_attrs = 'href src'.split()
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in valid_tags:
tag.hidden = True
tag.attrs = [(attr, val) for attr, val in tag.attrs if attr in valid_attrs]
return soup.renderContents().decode('utf8').replace('javascript:', '')
</code></pre>
| 1 | 2009-08-03T20:42:23Z | [
"python",
"html",
"markup"
] |
How do I associate input to a Form with a Model in Django? | 1,223,763 | <p>In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?</p>
<p>For example:</p>
<pre><code>class PhoneNumber(models.Model):
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=30)
PhoneNumber = models.CharField(max_length=20)
class PhoneNumber(forms.Form):
FirstName = forms.CharField(max_length=30)
LastName = forms.CharField(max_length=30)
PhoneNumber = forms.CharField(max_length=20)
</code></pre>
<p>I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.</p>
<p>Thanks.</p>
<p>UPDATED:
To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.</p>
<p>ANSWERED:</p>
<p>With the help of the anwers, I arrived at this solution:</p>
<p>Form definition:</p>
<pre><code>class ThisForm(forms.Form)
[various Field assignments]
model = ThisModel()
</code></pre>
<p>Code in views to save entered data to database:</p>
<pre><code>if request_method == 'POST':
form = ThisForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
setattr(form.model, key, value)
form.model.save(form.model)
</code></pre>
<p>After this the data entered in the browser form was in the database table.</p>
<p>Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.</p>
<p>CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.</p>
| 2 | 2009-08-03T18:06:07Z | 1,223,907 | <p>I'm not sure which class do you mean. I know that there were a helper, something like <code>form_for_model</code> (don't really remember the exact name; that was way before 1.0 version was released). Right now I'd it that way:</p>
<pre><code>import myproject.myapp.models as models
class PhoneNumberForm(forms.ModelForm):
class Meta:
model = models.PhoneNumber
</code></pre>
<p>To see the metaclass magic behind, you'd have to look into the code as there is a lot to explain :]. The constructor of the form can take <code>instance</code> argument. Passing it will make the form operate on an existing record rather than creating a new one. More info <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms" rel="nofollow">here</a>.</p>
| 2 | 2009-08-03T18:32:10Z | [
"python",
"django"
] |
How do I associate input to a Form with a Model in Django? | 1,223,763 | <p>In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?</p>
<p>For example:</p>
<pre><code>class PhoneNumber(models.Model):
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=30)
PhoneNumber = models.CharField(max_length=20)
class PhoneNumber(forms.Form):
FirstName = forms.CharField(max_length=30)
LastName = forms.CharField(max_length=30)
PhoneNumber = forms.CharField(max_length=20)
</code></pre>
<p>I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.</p>
<p>Thanks.</p>
<p>UPDATED:
To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.</p>
<p>ANSWERED:</p>
<p>With the help of the anwers, I arrived at this solution:</p>
<p>Form definition:</p>
<pre><code>class ThisForm(forms.Form)
[various Field assignments]
model = ThisModel()
</code></pre>
<p>Code in views to save entered data to database:</p>
<pre><code>if request_method == 'POST':
form = ThisForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
setattr(form.model, key, value)
form.model.save(form.model)
</code></pre>
<p>After this the data entered in the browser form was in the database table.</p>
<p>Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.</p>
<p>CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.</p>
| 2 | 2009-08-03T18:06:07Z | 1,223,909 | <p>I think <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method" rel="nofollow">ModelForm.save</a> documentation should explain it. With its base class (Form) you would need to use the Form.cleaned_data() to get the field values and set them to appropriate Model fields "by hand". ModelForm does all that for you.</p>
| 1 | 2009-08-03T18:32:44Z | [
"python",
"django"
] |
How do I associate input to a Form with a Model in Django? | 1,223,763 | <p>In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?</p>
<p>For example:</p>
<pre><code>class PhoneNumber(models.Model):
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=30)
PhoneNumber = models.CharField(max_length=20)
class PhoneNumber(forms.Form):
FirstName = forms.CharField(max_length=30)
LastName = forms.CharField(max_length=30)
PhoneNumber = forms.CharField(max_length=20)
</code></pre>
<p>I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.</p>
<p>Thanks.</p>
<p>UPDATED:
To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.</p>
<p>ANSWERED:</p>
<p>With the help of the anwers, I arrived at this solution:</p>
<p>Form definition:</p>
<pre><code>class ThisForm(forms.Form)
[various Field assignments]
model = ThisModel()
</code></pre>
<p>Code in views to save entered data to database:</p>
<pre><code>if request_method == 'POST':
form = ThisForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
setattr(form.model, key, value)
form.model.save(form.model)
</code></pre>
<p>After this the data entered in the browser form was in the database table.</p>
<p>Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.</p>
<p>CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.</p>
| 2 | 2009-08-03T18:06:07Z | 1,224,656 | <p>The Django documentation is pretty clear on this subject. However, here is a rough guide for you to get started: You can either override the form's save method or implement that functionality in the view.</p>
<pre><code>if form.is_valid() # validation - first the fields, then the form itself is validated
form.save()
</code></pre>
<p>inside the form:</p>
<pre><code>def save(self, *args, **kwargs):
foo = Foo()
foo.somefield = self.cleaned_data['somefield']
foo.otherfield = self.cleaned_data['otherfield']
...
return foo.save()
</code></pre>
| 0 | 2009-08-03T21:09:12Z | [
"python",
"django"
] |
How do I associate input to a Form with a Model in Django? | 1,223,763 | <p>In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?</p>
<p>For example:</p>
<pre><code>class PhoneNumber(models.Model):
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=30)
PhoneNumber = models.CharField(max_length=20)
class PhoneNumber(forms.Form):
FirstName = forms.CharField(max_length=30)
LastName = forms.CharField(max_length=30)
PhoneNumber = forms.CharField(max_length=20)
</code></pre>
<p>I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.</p>
<p>Thanks.</p>
<p>UPDATED:
To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.</p>
<p>ANSWERED:</p>
<p>With the help of the anwers, I arrived at this solution:</p>
<p>Form definition:</p>
<pre><code>class ThisForm(forms.Form)
[various Field assignments]
model = ThisModel()
</code></pre>
<p>Code in views to save entered data to database:</p>
<pre><code>if request_method == 'POST':
form = ThisForm(request.POST)
if form.is_valid():
for key, value in form.cleaned_data.items():
setattr(form.model, key, value)
form.model.save(form.model)
</code></pre>
<p>After this the data entered in the browser form was in the database table.</p>
<p>Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.</p>
<p>CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.</p>
| 2 | 2009-08-03T18:06:07Z | 1,224,807 | <p>Back when I first used Forms and Models (without using ModelForm), what I remember doing was checking if the form was valid, which would set your cleaned data, manually moving the data from the form to the model (or whatever other processing you want to do), and then saving the model. As you can tell, this was extremely tedious when your form exactly (or even closely) matches your model. By using the ModelForm (since you said you weren't quite sure how it worked), when you save the ModelForm, it instantiates an object with the form data according to the model spec and then saves that model for you. So all-in-all, the flow of data goes from the HTML form, to the Django Form, to the Django Model, to the DB.</p>
<p>Some actual code for your questions:</p>
<p>To get the browser form data into the form object:</p>
<pre><code>if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
model.attr = form.cleaned_data['attr']
model.attr2 = form.cleaned_data['attr2']
model.save()
else:
form = SomeForm()
return render_to_response('page.html', {'form': form, })
</code></pre>
<p>In the template page you can do things like this with the form:</p>
<pre><code><form method="POST">
{{ form.as_p }}
<input type="submit"/>
</form>
</code></pre>
<p>That's just one example that I pulled from <a href="http://docs.djangoproject.com/en/dev/topics/forms/" rel="nofollow">here</a>.</p>
| 3 | 2009-08-03T21:51:22Z | [
"python",
"django"
] |
How to stop WSGI from hanging apache | 1,223,927 | <p>I have django running through WSGI like this :</p>
<pre><code><VirtualHost *:80>
WSGIScriptAlias / /home/ptarjan/django/django.wsgi
WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup ptarjan
Alias /media /home/ptarjan/django/mysite/media/
</VirtualHost>
</code></pre>
<p>But if in python I do :</p>
<pre><code>def handler(request) :
data = urllib2.urlopen("http://example.com/really/unresponsive/url").read()
</code></pre>
<p>the whole apache server hangs and is unresponsive with this backtrace</p>
<pre><code>#0 0x00007ffe3602a570 in __read_nocancel () from /lib/libpthread.so.0
#1 0x00007ffe36251d1c in apr_file_read () from /usr/lib/libapr-1.so.0
#2 0x00007ffe364778b5 in ?? () from /usr/lib/libaprutil-1.so.0
#3 0x0000000000440ec2 in ?? ()
#4 0x00000000004412ae in ap_scan_script_header_err_core ()
#5 0x00007ffe2a2fe512 in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#6 0x00007ffe2a2f9bdd in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#7 0x000000000043b623 in ap_run_handler ()
#8 0x000000000043eb4f in ap_invoke_handler ()
#9 0x000000000044bbd8 in ap_process_request ()
#10 0x0000000000448cd8 in ?? ()
#11 0x0000000000442a13 in ap_run_process_connection ()
#12 0x000000000045017d in ?? ()
#13 0x00000000004504d4 in ?? ()
#14 0x00000000004510f6 in ap_mpm_run ()
#15 0x0000000000428425 in main ()
</code></pre>
<p>on Debian Apache 2.2.11-7.</p>
<p>Similarly, can we be protected against :</p>
<pre><code>def handler(request) :
while (1) :
pass
</code></pre>
<p>In PHP, I would set time and memory limits.</p>
| 8 | 2009-08-03T18:38:40Z | 1,224,066 | <p>If I understand well the question, you want to protect apache from locking up when running some random scripts from people. Well, if you're running untrusted code, I think you have other things to worry about that are worst than apache.</p>
<p>That said, you can use some configuration directives to adjust a <em>safer</em> environment. These two below are very useful:</p>
<ul>
<li><p><strong>WSGIApplicationGroup</strong> - Sets which application group WSGI application belongs to. It allows to separate settings for each user - All WSGI applications within the same application group will execute within the context of the same Python sub interpreter of the process handling the request.</p></li>
<li><p><strong>WSGIDaemonProcess</strong> - Configures a distinct daemon process for running applications. The daemon processes can be run as a user different to that which the Apache child processes would normally be run as. This directive accepts a lot of useful options, I'll list some of them:</p>
<ul>
<li><p><code>user=name | user=#uid</code>, <code>group=name | group=#gid</code>:</p>
<p>Defines the UNIX user and groupname name or numeric user uid or group gid of the user/group that the daemon processes should be run as.</p></li>
<li><p><code>stack-size=nnn</code></p>
<p>The amount of virtual memory in bytes to be allocated for the stack corresponding to each thread created by mod_wsgi in a daemon process. </p></li>
<li><p><code>deadlock-timeout=sss</code></p>
<p>Defines the maximum number of seconds allowed to pass before the daemon process is shutdown and restarted after a potential deadlock on the Python GIL has been detected. The default is 300 seconds. </p></li>
</ul></li>
</ul>
<p>You can read more about the configuration directives <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives" rel="nofollow">here</a>.</p>
| 3 | 2009-08-03T19:03:55Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
How to stop WSGI from hanging apache | 1,223,927 | <p>I have django running through WSGI like this :</p>
<pre><code><VirtualHost *:80>
WSGIScriptAlias / /home/ptarjan/django/django.wsgi
WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup ptarjan
Alias /media /home/ptarjan/django/mysite/media/
</VirtualHost>
</code></pre>
<p>But if in python I do :</p>
<pre><code>def handler(request) :
data = urllib2.urlopen("http://example.com/really/unresponsive/url").read()
</code></pre>
<p>the whole apache server hangs and is unresponsive with this backtrace</p>
<pre><code>#0 0x00007ffe3602a570 in __read_nocancel () from /lib/libpthread.so.0
#1 0x00007ffe36251d1c in apr_file_read () from /usr/lib/libapr-1.so.0
#2 0x00007ffe364778b5 in ?? () from /usr/lib/libaprutil-1.so.0
#3 0x0000000000440ec2 in ?? ()
#4 0x00000000004412ae in ap_scan_script_header_err_core ()
#5 0x00007ffe2a2fe512 in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#6 0x00007ffe2a2f9bdd in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#7 0x000000000043b623 in ap_run_handler ()
#8 0x000000000043eb4f in ap_invoke_handler ()
#9 0x000000000044bbd8 in ap_process_request ()
#10 0x0000000000448cd8 in ?? ()
#11 0x0000000000442a13 in ap_run_process_connection ()
#12 0x000000000045017d in ?? ()
#13 0x00000000004504d4 in ?? ()
#14 0x00000000004510f6 in ap_mpm_run ()
#15 0x0000000000428425 in main ()
</code></pre>
<p>on Debian Apache 2.2.11-7.</p>
<p>Similarly, can we be protected against :</p>
<pre><code>def handler(request) :
while (1) :
pass
</code></pre>
<p>In PHP, I would set time and memory limits.</p>
| 8 | 2009-08-03T18:38:40Z | 1,224,993 | <p>It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case.</p>
<p>As far as trying to use mod_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive.</p>
<p>Even then, this is not a complete solution. This is because the 'inactivity-timeout' option is specifically to detect whether all request processing by a daemon process has ceased, it is not a per request timeout. It only equates to a per request timeout if daemon processes are single threaded. As well as help to unstick a process, the option will also have side effect of restarting daemon process if no requests arrive at all in that time.</p>
<p>In short, there is no way at mod_wsgi level to have per request timeouts, this is because there is no real way of interrupting a request, or thread, in Python.</p>
<p>What you really need to implement is a timeout on the HTTP request in your application code. Am not sure where it is up to and whether available already, but do a Google search for 'urllib2 socket timeout'.</p>
| 12 | 2009-08-03T22:49:06Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
How can I merge fields in a CSV string using Python? | 1,223,967 | <p>I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:</p>
<pre><code>,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
</code></pre>
<p>Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.</p>
<p>Thanks.</p>
| 2 | 2009-08-03T18:47:30Z | 1,223,982 | <p>Something like this?</p>
<pre><code>import csv
source= csv.reader( open("some file","rb") )
dest= csv.writer( open("another file","wb") )
for row in source:
result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
dest.writerow( result )
</code></pre>
<p><hr /></p>
<p><strong>Example</strong></p>
<pre><code>>>> data=''',,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
... '''.splitlines()
>>> rdr= csv.reader( data )
>>> row= rdr.next()
>>> row
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CT', '', 'goo', '' ]
>>> row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CTgoo', '']
</code></pre>
| 10 | 2009-08-03T18:49:56Z | [
"python",
"database",
"string",
"csv"
] |
How can I merge fields in a CSV string using Python? | 1,223,967 | <p>I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:</p>
<pre><code>,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
</code></pre>
<p>Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.</p>
<p>Thanks.</p>
| 2 | 2009-08-03T18:47:30Z | 1,224,027 | <p>There's a builtin module in Python for parsing CSV files:</p>
<p><a href="http://docs.python.org/library/csv.html" rel="nofollow">http://docs.python.org/library/csv.html</a></p>
| 1 | 2009-08-03T18:57:23Z | [
"python",
"database",
"string",
"csv"
] |
How can I merge fields in a CSV string using Python? | 1,223,967 | <p>I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:</p>
<pre><code>,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
</code></pre>
<p>Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.</p>
<p>Thanks.</p>
| 2 | 2009-08-03T18:47:30Z | 1,224,104 | <p>You have tagged this question as 'database'. In fact, maybe it would be easier to upload the two files to separate tables of the db (you can use sqllite or any python sql library, like sqlalchemy) and then join them.</p>
<p>That would give you some advantage after, you would be able to use a sql syntax to query the tables and you can store it on the disk instead of keeping it on memory, so think about it.. :)</p>
| 1 | 2009-08-03T19:12:35Z | [
"python",
"database",
"string",
"csv"
] |
How can I merge fields in a CSV string using Python? | 1,223,967 | <p>I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:</p>
<pre><code>,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
</code></pre>
<p>Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.</p>
<p>Thanks.</p>
| 2 | 2009-08-03T18:47:30Z | 1,225,253 | <p>You can use the csv module to do the heavy lifting: <a href="http://docs.python.org/library/csv.html" rel="nofollow">http://docs.python.org/library/csv.html</a></p>
<p>You didn't say exactly how you wanted to merge the columns; presumably you don't want your merged field to be "Moved from Portland, CTgoo". The code below allows you to specify a separator string (maybe <code>", "</code>) and handles empty/blank fields.</p>
<pre><code>[transcript of session]
prompt>type merge.py
import csv
def merge_csv_cols(infile, outfile, startcol, numcols, sep=", "):
reader = csv.reader(open(infile, "rb"))
writer = csv.writer(open(outfile, "wb"))
endcol = startcol + numcols
for row in reader:
merged = sep.join(x for x in row[startcol:endcol] if x.strip())
row[startcol:endcol] = [merged]
writer.writerow(row)
if __name__ == "__main__":
import sys
args = sys.argv[1:6]
args[2:4] = map(int, args[2:4])
merge_csv_cols(*args)
prompt>type input.csv
1,2,3,4,5,6,7,8,9,a,b,c
1,2,3,4,5,6,,,,a,b,c
1,2,3,4,5,6,7,8,,a,b,c
1,2,3,4,5,6,7,,9,a,b,c
prompt>\python26\python merge.py input.csv output.csv 6 3 ", "
prompt>type output.csv
1,2,3,4,5,6,"7, 8, 9",a,b,c
1,2,3,4,5,6,,a,b,c
1,2,3,4,5,6,"7, 8",a,b,c
1,2,3,4,5,6,"7, 9",a,b,c
</code></pre>
| 2 | 2009-08-04T00:24:52Z | [
"python",
"database",
"string",
"csv"
] |
Reading files in python | 1,224,391 | <p>Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly:</p>
<pre><code>import os.path
filename = "A 180 mb large file.data"
size = os.path.getsize(filename)
f = open(filename, "r")
contents = f.read()
f.close()
print "The real filesize is", size
print "The read filesize is", len(contents)
f = open(filename, "r")
size = 0
while True:
contents = f.read(4)
if not contents: break
size += len(contents)
f.close()
print "this time it's", size
</code></pre>
<p>Outputs:</p>
<pre><code>The real filesize is 183574528
The read filesize is 10322
this time it's 13440
</code></pre>
<p>Somebody knows whats going on here? :)</p>
| 1 | 2009-08-03T20:18:08Z | 1,224,421 | <p>If your file confuses the C libraries, then your results are expected.</p>
<p>The OS thinks it's 180Mb.</p>
<p>However, there are null bytes scattered around, which can confuse the C stdio libraries.</p>
<p>Try opening the file with "rb" and see if you get different results.</p>
| 5 | 2009-08-03T20:24:53Z | [
"python",
"file"
] |
Reading files in python | 1,224,391 | <p>Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly:</p>
<pre><code>import os.path
filename = "A 180 mb large file.data"
size = os.path.getsize(filename)
f = open(filename, "r")
contents = f.read()
f.close()
print "The real filesize is", size
print "The read filesize is", len(contents)
f = open(filename, "r")
size = 0
while True:
contents = f.read(4)
if not contents: break
size += len(contents)
f.close()
print "this time it's", size
</code></pre>
<p>Outputs:</p>
<pre><code>The real filesize is 183574528
The read filesize is 10322
this time it's 13440
</code></pre>
<p>Somebody knows whats going on here? :)</p>
| 1 | 2009-08-03T20:18:08Z | 1,224,437 | <p>The first is the filesize in bytes, the other times you read the file <em>as text</em> and count <em>characters</em>. Change all <code>open(filename, "r")</code> to <code>open(filename, "rb")</code> and it works.</p>
| 3 | 2009-08-03T20:27:24Z | [
"python",
"file"
] |
Reading files in python | 1,224,391 | <p>Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly:</p>
<pre><code>import os.path
filename = "A 180 mb large file.data"
size = os.path.getsize(filename)
f = open(filename, "r")
contents = f.read()
f.close()
print "The real filesize is", size
print "The read filesize is", len(contents)
f = open(filename, "r")
size = 0
while True:
contents = f.read(4)
if not contents: break
size += len(contents)
f.close()
print "this time it's", size
</code></pre>
<p>Outputs:</p>
<pre><code>The real filesize is 183574528
The read filesize is 10322
this time it's 13440
</code></pre>
<p>Somebody knows whats going on here? :)</p>
| 1 | 2009-08-03T20:18:08Z | 1,226,467 | <p>This is not about strings : Python is perfectly happy with null bytes in strings.</p>
<p>This is because you are on Windows and you open the file in text mode, so it converts all "\n" into "\r\n", thus destroying all your binary data.</p>
<p>Open your file in binary mode with mode "rb"</p>
| 0 | 2009-08-04T09:19:43Z | [
"python",
"file"
] |
Check for a module in Python without using exceptions | 1,224,585 | <p>I can check for a module in Python doing something like:</p>
<pre><code>try:
import some_module
except ImportError:
print "No some_module!"
</code></pre>
<p>But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)</p>
<p><strong>Note:</strong> The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.</p>
| 3 | 2009-08-03T20:55:47Z | 1,224,607 | <p>All methods of importing modules raise exceptions when called. You could try searching the filesystem yourself first for the file, but there are many things to consider.</p>
<p>Not sure why you don't want to use <code>try</code>/<code>except</code> though. It is the best solution, far better than the one I provided. Maybe you should clarify that first, because you probably have an invalid reason for not using <code>try</code>/<code>except</code>.</p>
| 0 | 2009-08-03T20:59:56Z | [
"python",
"module",
"python-module"
] |
Check for a module in Python without using exceptions | 1,224,585 | <p>I can check for a module in Python doing something like:</p>
<pre><code>try:
import some_module
except ImportError:
print "No some_module!"
</code></pre>
<p>But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)</p>
<p><strong>Note:</strong> The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.</p>
| 3 | 2009-08-03T20:55:47Z | 1,224,621 | <p>sys.modules dictionary seems to contain the info you need.</p>
| -1 | 2009-08-03T21:02:49Z | [
"python",
"module",
"python-module"
] |
Check for a module in Python without using exceptions | 1,224,585 | <p>I can check for a module in Python doing something like:</p>
<pre><code>try:
import some_module
except ImportError:
print "No some_module!"
</code></pre>
<p>But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)</p>
<p><strong>Note:</strong> The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.</p>
| 3 | 2009-08-03T20:55:47Z | 1,224,626 | <p>You can read <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-import-statement" rel="nofollow">here</a> about how Python locates and imports modules. If you wanted to, you could replicate this logic in python, searching through sys.modules, sys.meta_path & sys.path to look for the required module.</p>
<p>However, predicting whether it would parse successfully (taking into account compiled binary modules) without using exception handling would be very difficult, I imagine!</p>
| 1 | 2009-08-03T21:03:27Z | [
"python",
"module",
"python-module"
] |
Check for a module in Python without using exceptions | 1,224,585 | <p>I can check for a module in Python doing something like:</p>
<pre><code>try:
import some_module
except ImportError:
print "No some_module!"
</code></pre>
<p>But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.)</p>
<p><strong>Note:</strong> The reason for no using try/except is arbitrary, it is just because I want to know if there is a way to test this without using exceptions.</p>
| 3 | 2009-08-03T20:55:47Z | 1,224,911 | <p>It takes trickery to perform the request (and one <code>raise</code> statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say "I don't deal with this path item"!), but the following would avoid any <code>try</code>/<code>except</code>:</p>
<pre><code>import sys
sentinel = object()
class FakeLoader(object):
def find_module(self, fullname, path=None):
return self
def load_module(*_):
return sentinel
def fakeHook(apath):
if apath == 'GIVINGUP!!!':
return FakeLoader()
raise ImportError
sys.path.append('GIVINGUP!!!')
sys.path_hooks.append(fakeHook)
def isModuleOK(modulename):
result = __import__(modulename)
return result is not sentinel
print 'sys', isModuleOK('sys')
print 'Cookie', isModuleOK('Cookie')
print 'nonexistent', isModuleOK('nonexistent')
</code></pre>
<p>This prints:</p>
<pre><code>sys True
Cookie True
nonexistent False
</code></pre>
<p>Of course, these would be absurd lengths to go to in real life for the pointless purpose of avoiding a perfectly normal <code>try</code>/<code>except</code>, but they seem to satisfy the request as posed (and can hopefully prompt Python-wizards wannabes to start their own research -- finding out exactly how and why all of this code does work as required is in fact instructive, which is why for once I'm not offering detailed explanations and URLs;-).</p>
| 7 | 2009-08-03T22:20:54Z | [
"python",
"module",
"python-module"
] |
is it possible to get python purple running either in cygwin or on a linux that isn't debian? | 1,224,726 | <p>python purple says it needs dbms and debhelper in order to run, but I don't run debian. Is there a way to get this running on a different linux? or in cygwin?</p>
| 0 | 2009-08-03T21:30:15Z | 1,250,118 | <p>Both cdbs and debhelper are only needed if you are trying to build a debian package. Just do a regular <code>python setup.py build</code>, and it should work fine (assuming you have the other prerequisites available).</p>
| 5 | 2009-08-08T23:19:29Z | [
"python",
"linux",
"cygwin",
"debhelper"
] |
Trying to import module with the same name as a built-in module causes an import error | 1,224,741 | <p>I have a module that conflicts with a built-in module. For example, a <code>myapp.email</code> module defined in <code>myapp/email.py</code>.</p>
<p>I can reference <code>myapp.email</code> anywhere in my code without issue. However, I need to reference the built-in email module from my email module.</p>
<pre><code># myapp/email.py
from email import message_from_string
</code></pre>
<p>It only finds itself, and therefore raises an <code>ImportError</code>, since <code>myapp.email</code> doesn't have a <code>message_from_string</code> method. <code>import email</code> causes the same issue when I try <code>email.message_from_string</code>.</p>
<p>Is there any native support to do this in Python, or am I stuck with renaming my "email" module to something more specific?</p>
| 48 | 2009-08-03T21:34:46Z | 1,224,760 | <p>You will want to read about <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports">Absolute and Relative Imports</a> which addresses this very problem. Use:</p>
<pre><code>from __future__ import absolute_import
</code></pre>
<p>Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (<code>from .email import ...</code>) to access your own package.</p>
| 66 | 2009-08-03T21:38:47Z | [
"python",
"python-import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.