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
sequence
launching vs2008 build from python
263,820
<p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p> <p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p> <pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86') os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt') </code></pre> <p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
1
2008-11-04T23:08:03Z
1,237,505
<p>I think that the proper way for achieving this would be running this command:</p> <pre><code>%comspec% /C "%VCINSTALLDIR%\vcvarsall.bat" x86 &amp;&amp; vcbuild "project.sln" </code></pre> <p>Below you'll see the Python version of the same command:</p> <pre><code>os.system('%comspec% /C "%VCINSTALLDIR%\\vcvarsall.bat" x86 &amp;&amp; vcbuild "project.sln"') </code></pre> <p>This should work with any Visual Studio so it would be a good idea to edit the question to make it more generic.</p> <p>There is a small problem I found regarding the location of vcvarsall.bat - Because VCINSTALLDIR is not always set, you have to use the registry entries in order to detect the location where it is installer:</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0] "InstallDir"="c:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\" </code></pre> <p>Add <code>..\..\VC\vcvarsall.bat</code> to this path. Also is a good idea to test for other versions of Visual Studio.</p>
3
2009-08-06T08:00:33Z
[ "python", "windows", "visual-studio-2008", "build-automation" ]
Access Ruby objects with Python via XML-RPC?
264,128
<p>I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:</p> <p>I have a test Ruby XML-RPC server as follows:</p> <pre><code>require "xmlrpc/server" class ExampleBar def bar() return "hello world!" end end class ExampleFoo def foo() return ExampleBar.new end def test() return "test!" end end s = XMLRPC::Server.new( 9090 ) s.add_introspection s.add_handler( "example", ExampleFoo.new ) s.serve </code></pre> <p>And I have a test Python XML-RPC Client as follows:</p> <pre><code>import xmlrpclib s = xmlrpclib.Server( "http://127.0.0.1:9090/" ) print s.example.foo().bar() </code></pre> <p>I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code:</p> <pre><code>example = ExampleFoo.new puts example.foo().bar() </code></pre> <p>However it generates an error: "xmlrpclib.ProtocolError: &lt;ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error&gt;".</p> <p>print s.example.test() works fine.</p> <p>I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured.</p> <p>Can XML-RPC support this kind of usage or is it too basic?</p> <p>So I guess my question really is; how can I get this working, if not with XML-RPC what with?</p>
3
2008-11-05T01:33:50Z
264,165
<p>Your client (s in you Python code) is a ServerProxy object. It only accepts return values of type boolean, integers, floats, arrays, structures, dates or binary data.</p> <p>However, without you doing the wiring, there is no way for it to return another ServerProxy, which you would need for accessing another class. You could probably implement an object cache on the Ruby side, but it would involve keeping track of active session and deciding when to remove objects, how to handle missing objects, etc.</p> <p>Instead I would suggest exposing a thin wrapper on the ruby side that does atomic operations like:</p> <pre><code>def foobar() return ExampleFoo.new().foo().bar() end </code></pre>
5
2008-11-05T02:03:03Z
[ "python", "ruby", "xml-rpc", "interop" ]
Access Ruby objects with Python via XML-RPC?
264,128
<p>I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:</p> <p>I have a test Ruby XML-RPC server as follows:</p> <pre><code>require "xmlrpc/server" class ExampleBar def bar() return "hello world!" end end class ExampleFoo def foo() return ExampleBar.new end def test() return "test!" end end s = XMLRPC::Server.new( 9090 ) s.add_introspection s.add_handler( "example", ExampleFoo.new ) s.serve </code></pre> <p>And I have a test Python XML-RPC Client as follows:</p> <pre><code>import xmlrpclib s = xmlrpclib.Server( "http://127.0.0.1:9090/" ) print s.example.foo().bar() </code></pre> <p>I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code:</p> <pre><code>example = ExampleFoo.new puts example.foo().bar() </code></pre> <p>However it generates an error: "xmlrpclib.ProtocolError: &lt;ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error&gt;".</p> <p>print s.example.test() works fine.</p> <p>I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured.</p> <p>Can XML-RPC support this kind of usage or is it too basic?</p> <p>So I guess my question really is; how can I get this working, if not with XML-RPC what with?</p>
3
2008-11-05T01:33:50Z
264,586
<p>XML-RPC can't pass objects. The set of parameter types is limited (as jakber says).</p>
1
2008-11-05T08:07:33Z
[ "python", "ruby", "xml-rpc", "interop" ]
Access Ruby objects with Python via XML-RPC?
264,128
<p>I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:</p> <p>I have a test Ruby XML-RPC server as follows:</p> <pre><code>require "xmlrpc/server" class ExampleBar def bar() return "hello world!" end end class ExampleFoo def foo() return ExampleBar.new end def test() return "test!" end end s = XMLRPC::Server.new( 9090 ) s.add_introspection s.add_handler( "example", ExampleFoo.new ) s.serve </code></pre> <p>And I have a test Python XML-RPC Client as follows:</p> <pre><code>import xmlrpclib s = xmlrpclib.Server( "http://127.0.0.1:9090/" ) print s.example.foo().bar() </code></pre> <p>I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code:</p> <pre><code>example = ExampleFoo.new puts example.foo().bar() </code></pre> <p>However it generates an error: "xmlrpclib.ProtocolError: &lt;ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error&gt;".</p> <p>print s.example.test() works fine.</p> <p>I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured.</p> <p>Can XML-RPC support this kind of usage or is it too basic?</p> <p>So I guess my question really is; how can I get this working, if not with XML-RPC what with?</p>
3
2008-11-05T01:33:50Z
1,257,360
<p>Returning a nil inside of a supported data structure will also cause an Internal Server Error message. The stdlib ruby xmlrpc server does not appear to support the xmlrpc extensions which allow nils, even though the python side does. xmlrpc4r supports nils but I haven't tried it yet.</p>
1
2009-08-10T21:38:59Z
[ "python", "ruby", "xml-rpc", "interop" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
264,171
<p><strong>You can't.</strong></p> <p>Part of the FAQ states that there is no way you can access beyond row 1000 of a query, increasing the "OFFSET" will just result in a shorter result set, </p> <p>ie: OFFSET 999 --> 1 result comes back. </p> <p>From Wikipedia: </p> <blockquote> <p>App Engine limits the maximum rows returned from an entity get to 1000 rows per Datastore call. Most web database applications use paging and caching, and hence do not require this much data at once, so this is a non-issue in most scenarios.[citation needed] If an application needs more than 1,000 records per operation, it can use its own client-side software or an Ajax page to perform an operation on an unlimited number of rows.</p> </blockquote> <p>From <a href="http://code.google.com/appengine/docs/whatisgoogleappengine.html" rel="nofollow">http://code.google.com/appengine/docs/whatisgoogleappengine.html</a></p> <blockquote> <p>Another example of a service limit is the number of results returned by a query. A query can return at most 1,000 results. Queries that would return more results only return the maximum. In this case, a request that performs such a query isn't likely to return a request before the timeout, but the limit is in place to conserve resources on the datastore.</p> </blockquote> <p>From <a href="http://code.google.com/appengine/docs/datastore/gqlreference.html" rel="nofollow">http://code.google.com/appengine/docs/datastore/gqlreference.html</a></p> <blockquote> <p>Note: A LIMIT clause has a maximum of 1000. If a limit larger than the maximum is specified, the maximum is used. This same maximum applies to the fetch() method of the GqlQuery class.</p> <p>Note: Like the offset parameter for the fetch() method, an OFFSET in a GQL query string does not reduce the number of entities fetched from the datastore. It only affects which results are returned by the fetch() method. A query with an offset has performance characteristics that correspond linearly with the offset size.</p> </blockquote> <p>From <a href="http://code.google.com/appengine/docs/datastore/queryclass.html" rel="nofollow">http://code.google.com/appengine/docs/datastore/queryclass.html</a></p> <blockquote> <p>The limit and offset arguments control how many results are fetched from the datastore, and how many are returned by the fetch() method:</p> <ul> <li><p>The datastore fetches offset + limit results to the application. The first offset results are <strong>not</strong> skipped by the datastore itself.</p></li> <li><p>The fetch() method skips the first offset results, then returns the rest (limit results).</p></li> <li><p>The query has performance characteristics that correspond linearly with the offset amount plus the limit.</p></li> </ul> </blockquote> <h2>What this means is </h2> <p>If you have a singular query, there is no way to request anything outside the range 0-1000. </p> <p>Increasing offset will just raise the 0, so</p> <pre><code>LIMIT 1000 OFFSET 0 </code></pre> <p>Will return 1000 rows, </p> <p>and </p> <pre><code>LIMIT 1000 OFFSET 1000 </code></pre> <p>Will return <strong>0 rows</strong>, thus, making it impossible to, with a single query syntax, fetch 2000 results either manually or using the API. </p> <h2>The only plausible exception</h2> <p>Is to create a numeric index on the table, ie: </p> <pre><code> SELECT * FROM Foo WHERE ID &gt; 0 AND ID &lt; 1000 SELECT * FROM Foo WHERE ID &gt;= 1000 AND ID &lt; 2000 </code></pre> <p>If your data or query can't have this 'ID' hardcoded identifier, then you are <strong>out of luck</strong></p>
14
2008-11-05T02:07:43Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
264,183
<p>The 1000 record limit is a hard limit in Google AppEngine.</p> <p>This presentation <a href="http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine" rel="nofollow">http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine</a> explains how to efficiently page through data using AppEngine.</p> <p>(Basically by using a numeric id as key and specifying a WHERE clause on the id.)</p>
7
2008-11-05T02:17:22Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
264,204
<p>To add the contents of the two queries together:</p> <pre><code>list1 = first query list2 = second query list1 += list2 </code></pre> <p>List 1 now contains all 2000 results.</p>
0
2008-11-05T02:33:05Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
264,334
<p>Every time this comes up as a limitation, I always wonder "<em>why</em> do you need more than 1,000 results?" Did you know that Google themselves doesn't serve up more than 1,000 results? Try this search: <a href="http://www.google.ca/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla:en-US:official&amp;hs=qhu&amp;q=1000+results&amp;start=1000&amp;sa=N" rel="nofollow">http://www.google.ca/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla:en-US:official&amp;hs=qhu&amp;q=1000+results&amp;start=1000&amp;sa=N</a> I didn't know that until recently, because I'd never taken the time to click into the 100th page of search results on a query.</p> <p>If you're actually returning more than 1,000 results back to the user, then I think there's a bigger problem at hand than the fact that the data store won't let you do it.</p> <p>One possible (legitimate) reason to need that many results is if you were doing a large operation on the data and presenting a summary (for example, what is the average of all this data). The solution to this problem (which is talked about in the Google I/O talk) is to calculate the summary data on-the-fly, as it comes in, and save it.</p>
17
2008-11-05T04:21:46Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
721,858
<p>App Engine gives you a nice way of "paging" through the results by 1000 by ordering on Keys and using the last key as the next offset. They even provide some sample code here:</p> <p><a href="http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Queries_on_Keys">http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Queries_on_Keys</a></p> <p>Although their example spreads the queries out over many requests, you can change the page size from 20 to 1000 and query in a loop, combining the querysets. Additionally you might use itertools to link the queries without evaluating them before they're needed.</p> <p>For example, to count how many rows beyond 1000:</p> <pre><code>class MyModel(db.Expando): @classmethod def count_all(cls): """ Count *all* of the rows (without maxing out at 1000) """ count = 0 query = cls.all().order('__key__') while count % 1000 == 0: current_count = query.count() if current_count == 0: break count += current_count if current_count == 1000: last_key = query.fetch(1, 999)[0].key() query = query.filter('__key__ &gt; ', last_key) return count </code></pre>
19
2009-04-06T14:59:46Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
1,000,121
<p>The proposed solution only works if entries are sorted by key... If you are sorting by another column first, you still have to use a limit(offset, count) clause, then the 1000 entries limitation still apply. It is the same if you use two requests : one for retrieving indexes (with conditions and sort) and another using where index in () with a subset of indexes from the first result, as the first request cannot return more than 1000 keys ? (The Google <em>Queries on Keys</em> section does not state clearly if we have to sort by <em>key</em> to remove the 1000 results limitation)</p>
0
2009-06-16T08:04:30Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
1,338,456
<p>JJG: your solution above is awesome, except that it causes an infinite loop if you have 0 records. (I found this out while testing some of my reports locally).</p> <p>I modified the start of the while loop to look like this:</p> <pre><code>while count % 1000 == 0: current_count = query.count() if current_count == 0: break </code></pre>
1
2009-08-27T01:45:38Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
1,477,027
<pre><code>class Count(object): def getCount(self,cls): class Count(object): def getCount(self,cls): """ Count *all* of the rows (without maxing out at 1000) """ count = 0 query = cls.all().order('__key__') while 1: current_count = query.count() count += current_count if current_count == 0: break last_key = query.fetch(1, current_count-1)[0].key() query = query.filter('__key__ &gt; ', last_key) return count </code></pre>
2
2009-09-25T12:29:42Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
2,204,144
<p>This 1K limit issue is resolved.</p> <p>query = MyModel.all() for doc in query: print doc.title</p> <p>By treating the Query object as an iterable: The iterator retrieves results from the datastore in small batches, allowing for the app to stop iterating on results to avoid fetching more than is needed. Iteration stops when all of the results that match the query have been retrieved. As with fetch(), the iterator interface does not cache results, so creating a new iterator from the Query object will re-execute the query.</p> <p>The max batch size is 1K. And you still have the auto Datastore quotas as well.</p> <p>But with the plan 1.3.1 SDK, they've introduced cursors that can be serialized and saved so that a future invocation can begin the query where it last left off at.</p>
10
2010-02-04T23:58:37Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
2,305,538
<p>Just for the record - fetch limit of 1000 entries is now gone:</p> <p><a href="http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html">http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html</a></p> <p>Quotation:</p> <blockquote> <p>No more 1000 result limit - That's right: with addition of Cursors and the culmination of many smaller Datastore stability and performance improvements over the last few months, we're now confident enough to remove the maximum result limit altogether. Whether you're doing a fetch, iterating, or using a Cursor, there's no limits on the number of results.</p> </blockquote>
23
2010-02-21T10:08:56Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
3,543,527
<p>Starting with Version 1.3.6 (released Aug-17-2010) you <strong>CAN</strong> </p> <p><a href="http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.3.6_-_August_17,_2010">From the changelog:</a></p> <blockquote> <p>Results of datastore count() queries <strong>and offsets for all datastore queries are no longer capped at 1000</strong>.</p> </blockquote>
36
2010-08-22T21:38:31Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
3,681,636
<p>we are using something in our <code>ModelBase</code> class that is:</p> <pre><code>@classmethod def get_all(cls): q = cls.all() holder = q.fetch(1000) result = holder while len(holder) == 1000: holder = q.with_cursor(q.cursor()).fetch(1000) result += holder return result </code></pre> <p>This gets around the 1000 query limit on every model without having to think about it. I suppose a keys version would be just as easy to implement.</p>
3
2010-09-10T00:58:32Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
5,320,613
<p>This is close to the solution provided by Gabriel, but doesn't fetch the results it just counts them:</p> <pre><code>count = 0 q = YourEntityClass.all().filter('myval = ', 2) countBatch = q.count() while countBatch &gt; 0: count += countBatch countBatch = q.with_cursor(q.cursor()).count() logging.info('Count=%d' % count) </code></pre> <p>Works perfectly for my queries, and fast too (1.1 seconds to count 67,000 entities)</p> <p>Note that the query must not be an inequality filter or a set or the cursor will not work and you'll get this exception:</p> <blockquote> <p>AssertionError: No cursor available for a MultiQuery (queries using "IN" or "!=" operators)</p> </blockquote>
0
2011-03-16T03:07:51Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
7,017,248
<pre><code>entities = [] for entity in Entity.all(): entities.append(entity) </code></pre> <p>Simple as that. Note that there is an RPC made for every entity which is much slower than fetching in chunks. So if you're concerned about performance, do the following:</p> <p>If you have less than 1M items:</p> <pre><code>entities = Entity.all().fetch(999999) </code></pre> <p>Otherwise, use a cursor.</p> <p>It should also be noted that:</p> <pre><code>Entity.all().fetch(Entity.all().count()) </code></pre> <p>returns 1000 max and should not be used.</p>
2
2011-08-10T20:21:05Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
24,514,424
<p>Fetching though the remote api still has issues when more than 1000 records. We wrote this tiny function to iterate over a table in chunks:</p> <pre><code>def _iterate_table(table, chunk_size = 200): offset = 0 while True: results = table.all().order('__key__').fetch(chunk_size+1, offset = offset) if not results: break for result in results[:chunk_size]: yield result if len(results) &lt; chunk_size+1: break offset += chunk_size </code></pre>
5
2014-07-01T15:44:55Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How to fetch more than 1000?
264,154
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
46
2008-11-05T01:56:20Z
35,268,792
<p>If you're using NDB:</p> <pre><code>@staticmethod def _iterate_table(table, chunk_size=200): offset = 0 while True: results = table.query().order(table.key).fetch(chunk_size + 1, offset=offset) if not results: break for result in results[:chunk_size]: yield result if len(results) &lt; chunk_size + 1: break offset += chunk_size </code></pre>
0
2016-02-08T11:40:54Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
setting the gzip timestamp from Python
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
3
2008-11-05T02:50:59Z
264,297
<p>In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:</p> <pre><code>def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method fname = self.filename[:-3] flags = 0 if fname: flags = FNAME self.fileobj.write(chr(flags)) write32u(self.fileobj, long(time.time())) # The current time! self.fileobj.write('\002') self.fileobj.write('\377') if fname: self.fileobj.write(fname + '\000') </code></pre> <p>As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will "return the time as a floating point number expressed in seconds since the epoch, in UTC." So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!</p>
0
2008-11-05T03:44:19Z
[ "python", "gzip" ]
setting the gzip timestamp from Python
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
3
2008-11-05T02:50:59Z
264,303
<p>Yeah, you don't have any pretty options. The time is written with this line in _write_gzip_header:</p> <pre><code>write32u(self.fileobj, long(time.time())) </code></pre> <p>Since they don't give you a way to override the time, you can do one of these things:</p> <ol> <li>Derive a class from GzipFile, and copy the <code>_write_gzip_header</code> function into your derived class, but with a different value in this one line.</li> <li>After importing the gzip module, assign new code to its time member. You will essentially be providing a new definition of the name time in the gzip code, so you can change what time.time() means.</li> <li>Copy the entire gzip module, and name it my_stable_gzip, and change the line you need to.</li> <li>Pass a CStringIO object in as fileobj, and modify the bytestream after gzip is done.</li> <li>Write a fake file object that keeps track of the bytes written, and passes everything through to a real file, except for the bytes for the timestamp, which you write yourself.</li> </ol> <p>Here's an example of option #2 (untested):</p> <pre><code>class FakeTime: def time(self): return 1225856967.109 import gzip gzip.time = FakeTime() # Now call gzip, it will think time doesn't change! </code></pre> <p>Option #5 may be the cleanest in terms of not depending on the internals of the gzip module (untested):</p> <pre><code>class GzipTimeFixingFile: def __init__(self, realfile): self.realfile = realfile self.pos = 0 def write(self, bytes): if self.pos == 4 and len(bytes) == 4: self.realfile.write("XYZY") # Fake time goes here. else: self.realfile.write(bytes) self.pos += len(bytes) </code></pre>
7
2008-11-05T03:49:51Z
[ "python", "gzip" ]
setting the gzip timestamp from Python
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
3
2008-11-05T02:50:59Z
264,348
<p>It's not pretty, but you could monkeypatch time.time temporarily with something like this:</p> <pre><code>import time def fake_time(): return 100000000.0 def do_gzip(content): orig_time = time.time time.time = fake_time # result = do gzip stuff here time.time = orig_time return result </code></pre> <p>It's not pretty, but it would probably work.</p>
0
2008-11-05T04:32:23Z
[ "python", "gzip" ]
setting the gzip timestamp from Python
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
3
2008-11-05T02:50:59Z
265,445
<p>Submit a <a href="http://www.python.org/dev/patches/" rel="nofollow">patch</a> in which the computation of the time stamp is factored out. It would almost certainly be accepted.</p>
2
2008-11-05T15:17:54Z
[ "python", "gzip" ]
setting the gzip timestamp from Python
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
3
2008-11-05T02:50:59Z
270,315
<p>I've taken Mr. Coventry's advice and <a href="http://bugs.python.org/issue4272" rel="nofollow">submitted a patch</a>. However, given the current state of the Python release schedule, with 3.0 just around the corner, I don't expect it to show up in a release anytime soon. Still, we'll see what happens!</p> <p>In the meantime, I like Mr. Batchelder's option 5 of piping the gzip stream through a small custom filter that sets the timestamp field correctly. It sounds like the cleanest approach. As he demonstrates, the code required is actually quite small, though his example does depend for some of its simplicity on the (currently valid) assumption that the <code>gzip</code> module implementation will choose to write the timestamp using exactly one four-byte call to <code>write()</code>. Still, I don't think it would be very difficult to come up with a fully general version if needed.</p> <p>The monkey-patching approach (a.k.a. option 2) is quite tempting for its simplicity but gives me pause because I'm writing a library that calls <code>gzip</code>, not just a standalone program, and it seems to me that somebody might try to call <code>gzip</code> from another thread before my module is ready to reverse its change to the <code>gzip</code> module's global state. This would be especially unfortunate if the other thread were trying to pull a similar monkey-patching stunt! I admit this potential problem doesn't sound very likely to come up in practice, but imagine how painful it would be to diagnose such a mess!</p> <p>I can vaguely imagine trying to do something tricky and complicated and perhaps not so future-proof to somehow import a private copy of the <code>gzip</code> module and monkey-patch <em>that</em>, but by that point a filter seems simpler and more direct.</p>
1
2008-11-06T21:17:09Z
[ "python", "gzip" ]
setting the gzip timestamp from Python
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
3
2008-11-05T02:50:59Z
36,034,315
<p>From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually.</p> <pre><code>import gzip content = b"Some content" f = open("/tmp/f.gz", "wb") gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0) gz.write(content) gz.close() f.close() </code></pre>
2
2016-03-16T11:25:36Z
[ "python", "gzip" ]
using jython and open office 2.4 to convert docs to pdf
264,540
<p>I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf. Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno.</p> <p>This also means that my conversion code is broken, and I need to now make use of the java libraries instead of the pyuno libs.</p> <blockquote> <p>import com.sun.star.beans.PropertyValue as PropertyValue<br /> import com.sun.star.bridge.XUnoUrlResolver as XUnoUrlResolver<br /> import com.sun.star.comp.helper.Bootstrap as Bootstrap<br /> ->> import com.sun.star.frame.XComponentLoader as XComponentLoader<br /> ->> import com.sun.star.frame.XStorable as XStorable<br /> import com.sun.star.lang.XMultiComponentFactory as XMultiComponentFactory<br /> import com.sun.star.uno.UnoRuntime as UnoRuntime<br /> import com.sun.star.uno.XComponentContext as XComponentContext </p> </blockquote> <p>The includes with the '->>' do not import the compiler does not recognise the com.sun.star.frame cant see the 'frame' bit. These are the libs I have included.</p> <p><img src="http://www.freeimagehosting.net/uploads/eda5cda76d.jpg" alt="alt text" /></p> <p>Some advice on this matter would be well received</p> <blockquote> <p>context = XComponentContext<br /> xMultiCompFactory = XMultiComponentFactory<br /> xcomponentloader = XComponentLoader </p> <p>//used in python<br /> ctx = None<br /> smgr = None<br /> doc = None<br /> url = None </p> <p>context = Bootstrap.bootstrap()<br /> xMultiCompFactory = self.context.getServiceManager()<br /> xcomponentloader = UnoRuntime.queryInterface(XComponentLoader.class, ....xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", context)) </p> <p>file = "file:\\" + file<br /> // also what is the equivalent of url = uno.systemPathToFileUrl(file) in Java so that I can make use of it to nicely format my path<br /> properties = []<br /> p = PropertyValue()<br /> p.Name = "Hidden"<br /> p.Value = True<br /> properties.append(p)<br /> properties = tuple(properties)<br /> doc = xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) </p> </blockquote>
2
2008-11-05T07:17:32Z
264,860
<p>Using Jython is a great idea for this I think. But why could you not use two scripts, one with pyuno/2.3 and one with pymssql/2.5 (or whatever db adapter you are using)?.</p> <p>The intermediate format could be anything like a pickle, or json, or XML.</p> <p>Edit: I should add that I have used pyuno quite extensively, and I feel your pain.</p>
0
2008-11-05T11:09:58Z
[ "python", "jython", "openoffice.org" ]
using jython and open office 2.4 to convert docs to pdf
264,540
<p>I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf. Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno.</p> <p>This also means that my conversion code is broken, and I need to now make use of the java libraries instead of the pyuno libs.</p> <blockquote> <p>import com.sun.star.beans.PropertyValue as PropertyValue<br /> import com.sun.star.bridge.XUnoUrlResolver as XUnoUrlResolver<br /> import com.sun.star.comp.helper.Bootstrap as Bootstrap<br /> ->> import com.sun.star.frame.XComponentLoader as XComponentLoader<br /> ->> import com.sun.star.frame.XStorable as XStorable<br /> import com.sun.star.lang.XMultiComponentFactory as XMultiComponentFactory<br /> import com.sun.star.uno.UnoRuntime as UnoRuntime<br /> import com.sun.star.uno.XComponentContext as XComponentContext </p> </blockquote> <p>The includes with the '->>' do not import the compiler does not recognise the com.sun.star.frame cant see the 'frame' bit. These are the libs I have included.</p> <p><img src="http://www.freeimagehosting.net/uploads/eda5cda76d.jpg" alt="alt text" /></p> <p>Some advice on this matter would be well received</p> <blockquote> <p>context = XComponentContext<br /> xMultiCompFactory = XMultiComponentFactory<br /> xcomponentloader = XComponentLoader </p> <p>//used in python<br /> ctx = None<br /> smgr = None<br /> doc = None<br /> url = None </p> <p>context = Bootstrap.bootstrap()<br /> xMultiCompFactory = self.context.getServiceManager()<br /> xcomponentloader = UnoRuntime.queryInterface(XComponentLoader.class, ....xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", context)) </p> <p>file = "file:\\" + file<br /> // also what is the equivalent of url = uno.systemPathToFileUrl(file) in Java so that I can make use of it to nicely format my path<br /> properties = []<br /> p = PropertyValue()<br /> p.Name = "Hidden"<br /> p.Value = True<br /> properties.append(p)<br /> properties = tuple(properties)<br /> doc = xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) </p> </blockquote>
2
2008-11-05T07:17:32Z
267,651
<p>And so it goes, according to this guy, you need some oil.... and it works like a charm</p> <p><a href="http://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263" rel="nofollow">http://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263</a></p> <p>include this lib C:\OpenOffice_24\program\classes\unoil.jar</p>
1
2008-11-06T04:38:37Z
[ "python", "jython", "openoffice.org" ]
Python - one variable equals another variable when it shouldn't
264,575
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p> <pre><code>i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)&lt;10**-2): break; i=i+1 </code></pre> <p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p> <p>Here is the issue. Everytime </p> <pre><code>x_present[j:j+1]=[value] </code></pre> <p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p> <pre><code>x_past=x_present </code></pre> <p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p> <p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p> <p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
5
2008-11-05T07:54:08Z
264,579
<p>What are x_past and x_present? I don't know much Python, but from a .NET/Java perspective, if they're references to some data structure (a map or whatever) then making them references to the same object (as you do at the start) will mean that any changes made through one variable will be visible through the other. It sounds like you need to take a copy of the data structure instead of just doing a reference assignment. Does the data structure you're working with have any kind of "clone" functionality available?</p> <p>As I say though, I don't know much Python so this could be totally wrong...</p>
4
2008-11-05T08:00:34Z
[ "python", "variables" ]
Python - one variable equals another variable when it shouldn't
264,575
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p> <pre><code>i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)&lt;10**-2): break; i=i+1 </code></pre> <p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p> <p>Here is the issue. Everytime </p> <pre><code>x_present[j:j+1]=[value] </code></pre> <p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p> <pre><code>x_past=x_present </code></pre> <p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p> <p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p> <p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
5
2008-11-05T07:54:08Z
264,580
<p>It looks as if x_present is a list. I suspect that this means that the assignment x_last = x_present makes x_last into an alias, i.e. they reference the same variable. Might this be the case?</p>
0
2008-11-05T08:02:06Z
[ "python", "variables" ]
Python - one variable equals another variable when it shouldn't
264,575
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p> <pre><code>i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)&lt;10**-2): break; i=i+1 </code></pre> <p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p> <p>Here is the issue. Everytime </p> <pre><code>x_present[j:j+1]=[value] </code></pre> <p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p> <pre><code>x_past=x_present </code></pre> <p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p> <p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p> <p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
5
2008-11-05T07:54:08Z
264,592
<p>Yes, I think the answers here show your problem. Just to try and clarify a little bit.</p> <p>You're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate:</p> <pre><code>&gt;&gt;&gt; x_present = [4,5,6] &gt;&gt;&gt; &gt;&gt;&gt; x_past = x_present &gt;&gt;&gt; &gt;&gt;&gt; x_past [4, 5, 6] &gt;&gt;&gt; &gt;&gt;&gt; x_present.append(7) &gt;&gt;&gt; &gt;&gt;&gt; x_past [4, 5, 6, 7] &gt;&gt;&gt; </code></pre> <p>If you want a copy of the list you have to do do this, <strong>listcopy = mylist[:]</strong>.</p> <pre><code>&gt;&gt;&gt; x_past = x_present[:] &gt;&gt;&gt; x_past [4, 5, 6, 7] &gt;&gt;&gt; &gt;&gt;&gt; x_present.append(8) &gt;&gt;&gt; &gt;&gt;&gt; x_past [4, 5, 6, 7] </code></pre>
30
2008-11-05T08:13:16Z
[ "python", "variables" ]
Python - one variable equals another variable when it shouldn't
264,575
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p> <pre><code>i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)&lt;10**-2): break; i=i+1 </code></pre> <p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p> <p>Here is the issue. Everytime </p> <pre><code>x_present[j:j+1]=[value] </code></pre> <p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p> <pre><code>x_past=x_present </code></pre> <p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p> <p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p> <p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
5
2008-11-05T07:54:08Z
264,593
<p>try changing the <code>x_past = x_present</code> line to <code>x_past = [x for x in x_present]</code> and see if it helps.</p> <p>the list copy shorthand is my favorite python feature since i can do one-liners that are not possible in other languages:</p> <p><code>greaterthan100 = [x for x in number if x &gt; 100]</code></p> <p><code>notinblacklist = [x for x in mylist if x not in blacklist]</code></p> <p><code>firstchildofbigfamily = [x.child[0] for x in familylist if len(x.child) &gt; 10]</code></p>
0
2008-11-05T08:14:10Z
[ "python", "variables" ]
Python - one variable equals another variable when it shouldn't
264,575
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p> <pre><code>i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)&lt;10**-2): break; i=i+1 </code></pre> <p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p> <p>Here is the issue. Everytime </p> <pre><code>x_present[j:j+1]=[value] </code></pre> <p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p> <pre><code>x_past=x_present </code></pre> <p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p> <p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p> <p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
5
2008-11-05T07:54:08Z
264,618
<p>In Python, everything is an object. So the statement x_past = x_present point to the same reference.</p>
0
2008-11-05T08:36:39Z
[ "python", "variables" ]
Python - one variable equals another variable when it shouldn't
264,575
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p> <pre><code>i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)&lt;10**-2): break; i=i+1 </code></pre> <p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p> <p>Here is the issue. Everytime </p> <pre><code>x_present[j:j+1]=[value] </code></pre> <p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p> <pre><code>x_past=x_present </code></pre> <p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p> <p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p> <p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
5
2008-11-05T07:54:08Z
264,715
<p>As others pointed out the answer is to replace: <code>x_past = x_present</code> by <code>x_past = x_present[:]</code>. In general you could use a <code>copy</code> module to copy an object in Python.</p> <pre><code>&gt;&gt;&gt; import copy &gt;&gt;&gt; a = range(10) &gt;&gt;&gt; a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] &gt;&gt;&gt; b = a &gt;&gt;&gt; a += 10, 11 &gt;&gt;&gt; a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] &gt;&gt;&gt; b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] &gt;&gt;&gt; c = copy.copy(a) # shallow copy &gt;&gt;&gt; c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] &gt;&gt;&gt; del a[3:] &gt;&gt;&gt; a [0, 1, 2] &gt;&gt;&gt; b [0, 1, 2] &gt;&gt;&gt; c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] </code></pre> <p>Your code is unpythonic to say the least.</p> <p>It could be replaced by something like the following code:</p> <pre><code>import copy # assert(len(x_present) &gt;= len(eqn)) first = True while True: x_past = copy.copy(x_present) # copy for j, eqj in enumerate(eqn): x_present[j] = sum(x_present[k] * eqj[k] for k in range(j if first else len(eqj)) if k != j) x_present[j] += eqj[j] print "X_PAST\n%s\nX_PRESENT\n%s" % (x_past, x_present) if allequal(x_past, x_present, tolerance=10**-2): break first = False </code></pre> <p>Here's a definition of <code>allequal()</code> (using an absolute error. It might or might not be a good idea in your case (you could use a relative error instead)):</p> <pre><code>def allequal(x, y, tolerance): return (len(x) == len(y) and all(-tolerance &lt; (xx - yy) &lt; tolerance for xx, yy in zip(x, y))) </code></pre>
3
2008-11-05T09:50:22Z
[ "python", "variables" ]
Why the Global Interpreter Lock?
265,687
<p>What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?</p>
70
2008-11-05T16:23:48Z
265,731
<p>The following is from the <a href="http://www.python.org/doc/2.5.2/api/threads.html">official Python/C API Reference Manual</a>:</p> <blockquote> <p>The Python interpreter is not fully thread safe. In order to support multi-threaded Python programs, there's a global lock that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice. </p> <p>Therefore, the rule exists that only the thread that has acquired the global interpreter lock may operate on Python objects or call Python/C API functions. In order to support multi-threaded Python programs, the interpreter regularly releases and reacquires the lock -- by default, every 100 bytecode instructions (this can be changed with sys.setcheckinterval()). The lock is also released and reacquired around potentially blocking I/O operations like reading or writing a file, so that other threads can run while the thread that requests the I/O is waiting for the I/O operation to complete.</p> </blockquote> <p>I think it sums up the issue pretty well.</p>
27
2008-11-05T16:32:37Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
Why the Global Interpreter Lock?
265,687
<p>What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?</p>
70
2008-11-05T16:23:48Z
265,733
<p>The global interpreter lock is a big mutex-type lock that protects reference counters from getting hosed. If you are writing pure python code, this all happens behind the scenes, but if you embedding Python into C, then you might have to explicitly take/release the lock.</p> <p>This mechanism is not related to Python being compiled to bytecode. It's not needed for Java. In fact, it's not even needed for <a href="http://www.jython.org/">Jython</a> (python compiled to jvm).</p> <p>see also <a href="http://stackoverflow.com/questions/105095/are-locks-unnecessary-in-multi-threaded-python-code-because-of-the-gil">this question</a></p>
16
2008-11-05T16:32:50Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
Why the Global Interpreter Lock?
265,687
<p>What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?</p>
70
2008-11-05T16:23:48Z
265,746
<p>Regarding your second question, not all scripting languages use this, but it only makes them less powerful. For instance, the threads in Ruby are <a href="http://en.wikipedia.org/wiki/Green_threads" rel="nofollow">green</a> and not native.</p> <p>In Python, the threads are native and the GIL only prevents them from running on different cores.</p> <p>In Perl, the threads are even worse. They just copy the whole interpreter, and are far from being as usable as in Python.</p>
4
2008-11-05T16:35:11Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
Why the Global Interpreter Lock?
265,687
<p>What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?</p>
70
2008-11-05T16:23:48Z
265,795
<p>In general, for any thread safety problem you will need to protect your internal data structures with locks. This can be done with various levels of granularity.</p> <ul> <li><p>You can use fine-grained locking, where every separate structure has its own lock.</p></li> <li><p>You can use coarse-grained locking where one lock protects everything (the GIL approach).</p></li> </ul> <p>There are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads can execute in parallel when they don't share any resources. However there is a much larger administrative overhead. For every line of code, you may need to acquire and release several locks.</p> <p>The coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism.</p> <p>There have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machines due to lock contention. </p> <blockquote> <p>Do other languages that are compiled to bytecode employ a similar mechanism?</p> </blockquote> <p>It varies, and it probably shouldn't be considered a language property so much as an implementation property. For instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving <a href="http://www.infoq.com/news/2007/05/ruby-threading-futures" rel="nofollow">towards</a> introducing a GIL.</p>
56
2008-11-05T16:44:11Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
Why the Global Interpreter Lock?
265,687
<p>What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?</p>
70
2008-11-05T16:23:48Z
266,111
<p>Python, like perl 5, was not designed from the ground up to be thread safe. Threads were grafted on after the fact, so the global interpreter lock is used to maintain mutual exclusion to where only one thread is executing code at a given time in the bowels of the interpreter.</p> <p>Individual Python threads are cooperatively multitasked by the interpreter itself by cycling the lock every so often.</p> <p>Grabbing the lock yourself is needed when you are talking to Python from C when other Python threads are active to 'opt in' to this protocol and make sure that nothing unsafe happens behind your back.</p> <p>Other systems that have a single-threaded heritage that later evolved into mulithreaded systems often have some mechanism of this sort. For instance, the Linux kernel has the "Big Kernel Lock" from its early SMP days. Gradually over time as multi-threading performance becomes an issue there is a tendency to try to break these sorts of locks up into smaller pieces or replace them with lock-free algorithms and data structures where possible to maximize throughput.</p>
10
2008-11-05T18:18:32Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
Why the Global Interpreter Lock?
265,687
<p>What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?</p>
70
2008-11-05T16:23:48Z
266,426
<p>Maybe <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235" rel="nofollow">this</a> article by the BDFL will help.</p>
2
2008-11-05T20:02:27Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
HTTP Request Timeout
265,720
<p>In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow">http://docs.python.org/library/httplib.html#httplib.HTTPConnection</a></p> <p>However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the <b>request</b>, not the connection. This doesn't seem to be supported by httplib.</p> <p>Is there any way to emulate this behavior?</p>
2
2008-11-05T16:30:22Z
265,741
<p>You can set a global socket timeout <sup>(*)</sup>:</p> <pre><code>import socket timeout = 10 socket.setdefaulttimeout(timeout) </code></pre> <hr> <p><sup>(*)</sup> <strong>EDIT</strong>: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.</p>
9
2008-11-05T16:34:28Z
[ "python", "http" ]
HTTP Request Timeout
265,720
<p>In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow">http://docs.python.org/library/httplib.html#httplib.HTTPConnection</a></p> <p>However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the <b>request</b>, not the connection. This doesn't seem to be supported by httplib.</p> <p>Is there any way to emulate this behavior?</p>
2
2008-11-05T16:30:22Z
268,174
<p>No, there isn't.</p> <p>It's because the <a href="http://www.greenbytes.de/tech/webdav/rfc2616.html">HTTP spec</a> does not provide anything for the client to specify time-to-live information with a HTTP request. You can do this only on TCP level, as you mentioned.</p> <p>On the other hand, the server may inform the client about timeout situations with HTTP status codes <a href="http://www.greenbytes.de/tech/webdav/rfc2616.html#status.408">408 Request Timeout</a> resp. <a href="http://www.greenbytes.de/tech/webdav/rfc2616.html#status.504">504 Gateway Timeout</a>.</p>
7
2008-11-06T10:09:21Z
[ "python", "http" ]
HTTP Request Timeout
265,720
<p>In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow">http://docs.python.org/library/httplib.html#httplib.HTTPConnection</a></p> <p>However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the <b>request</b>, not the connection. This doesn't seem to be supported by httplib.</p> <p>Is there any way to emulate this behavior?</p>
2
2008-11-05T16:30:22Z
4,453,301
<p>You could also use <code>settimeout</code> on the socket of the connection (works with Python 2.5):</p> <pre><code>connection = HTTPConnection('slow.service.com') connection.request(...) connection.sock.settimeout(5.0) response = connection.getresponse() response.read() connection.close() </code></pre> <p>If the server cannot send the response within 5 seconds, a <code>socket.error</code> will be raised.</p>
4
2010-12-15T18:03:27Z
[ "python", "http" ]
How do I process a string such as this using regular expressions?
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
0
2008-11-05T16:47:56Z
265,839
<p>The problem is that because you're allowing spaces in filenames and using spaces to separate fields, the solution is ambiguous. You either need to use a different field separator character that can't appear in filenames, or use some other method of representing filenames with spaces in them, e.g. putting them in quotation marks.</p>
4
2008-11-05T16:54:22Z
[ "python", "regex" ]
How do I process a string such as this using regular expressions?
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
0
2008-11-05T16:47:56Z
265,884
<p>it is theoretically possible, but you are making things incredibly difficult for yourself. You have a number of problems here:</p> <p>1) You are using space as a separator and you are also allowing spaces in the path names. You can avoid this by forcing the application to use paths without spaces in them.</p> <p>2) You have 2 optional parameters on the end. This means that with the line ending "C:\LogTo Path 256 300" you have no idea if the path is C:\LogTo Path 256 300 with no optional parameters or C:\Log To Path 256 with one optional parameter or C:\LogTo Path with 2 optional parameters.</p> <p>This would be easily remedied with a replacement algorithm on the output. Replacing spaces with underscore and underscore with double underscore. Therefore you could reverse this reliably after you have split the log file on spaces.</p> <p>Even as a human you could not reliably perform this function 100%. </p> <p>If you presume that all paths either end with a asterisk, a backslash or .log you could use positive lookahead to find the end of the paths, but without some kind of rules regarding this you are stuffed.</p> <p>I get the feeling that a single regex would be too difficult for this and would make anyone trying to maintain the code insane. I am a regex whore, using them whenever possible and I would not attempt this. </p>
3
2008-11-05T17:09:56Z
[ "python", "regex" ]
How do I process a string such as this using regular expressions?
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
0
2008-11-05T16:47:56Z
265,940
<p>You need to restrict the fields between the paths in a way that the regexp can distinct them from the pathnames.</p> <p>So unless you put in a special separator, the sequence</p> <pre><code>&lt;OUTPUTPATH&gt; &lt;LOGTO&gt; </code></pre> <p>with optional spaces will not work.</p> <p>And if a path can look like those fields, you might get surprising results. e.g.</p> <pre><code>c:\ 12 bin \ 250 bin \output </code></pre> <p>for </p> <pre><code>&lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; </code></pre> <p>is indistinguishable.</p> <p>So, let's try to restrict allowed characters a bit:</p> <pre><code>&lt;SERVER&gt;, &lt;SERVERKEY&gt;, &lt;COMMAND&gt; no spaces -&gt; [^]+ &lt;FOLDERPATH&gt; allow anything -&gt; .+ &lt;RETENTION&gt; integer -&gt; [0-9]+ &lt;TRANSFERMODE&gt; allow only bin and ascii -&gt; (bin|ascii) &lt;OUTPUTPATH&gt; allow anything -&gt; .+ &lt;LOGTO&gt; allow anything -&gt; .+ &lt;OPTIONAL-MAXSIZE&gt;[0-9]* &lt;OPTIONAL-OFFSET&gt;[0-9]* </code></pre> <p>So, i'd go with something along the lines of</p> <pre><code>[^]+ [^]+ [^]+ .+ [0-9]+ (bin|ascii) .+ \&gt; .+( [0-9]* ( [0-9]*)?)? </code></pre> <p>With a ">" to separate the two pathes. You might want to quote the pathnames instead.</p> <p>NB: This was done in a hurry.</p>
0
2008-11-05T17:23:44Z
[ "python", "regex" ]
How do I process a string such as this using regular expressions?
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
0
2008-11-05T16:47:56Z
266,010
<p>Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work.</p> <p>Some assumptions I had in mind:</p> <ul> <li><code>SERVER</code>, <code>SERVERKEY</code> and <code>COMMAND</code> not containing any spaces: <code>\S+</code></li> <li><code>FOLDERPATH</code> beginning with a slash: <code>/.*?</code></li> <li><code>RETENTION</code> being a number: <code>\d+</code></li> <li><code>TRANSFERMODE</code> not containing any spaces: <code>\S+</code></li> <li><code>OUTPUTPATH</code> beginning with a drive and ending with a slash: <code>[A-Z]:\\.*?\\</code></li> <li><code>LOGTO</code> either being the word "<code>NO</code>", or a path beginning with a drive: <code>[A-Z]:\\.*?</code></li> <li><code>MAXSIZE</code> and <code>OFFSET</code> being a number: <code>\d+</code></li> </ul> <p>Putting it all together:</p> <pre><code>^\s* (?P&lt;SERVER&gt;\S+)\s+ (?P&lt;SERVERKEY&gt;\S+)\s+ (?P&lt;COMMAND&gt;\S+)\s+ (?P&lt;FOLDERPATH&gt;/.*?)\s+ # Slash not that important, but should start with non-whitespace (?P&lt;RETENTION&gt;\d+)\s+ (?P&lt;TRANSFERMODE&gt;\S+)\s+ (?P&lt;OUTPUTPATH&gt;[A-Z]:\\.*?\\)\s+ # Could also support network paths (?P&lt;LOGTO&gt;NO|[A-Z]:\\.*?) (?: \s+(?P&lt;MAXSIZE&gt;\d+) (?: \s+(?P&lt;OFFSET&gt;\d+) )? )? \s*$ </code></pre> <p>In one line:</p> <pre><code>^\s*(?P&lt;SERVER&gt;\S+)\s+(?P&lt;SERVERKEY&gt;\S+)\s+(?P&lt;COMMAND&gt;\S+)\s+(?P&lt;FOLDERPATH&gt;/.*?)\s+(?P&lt;RETENTION&gt;\d+)\s+(?P&lt;TRANSFERMODE&gt;\S+)\s+(?P&lt;OUTPUTPATH&gt;[A-Z]:\\.*?\\)\s+(?P&lt;LOGTO&gt;NO|[A-Z]:\\.*?)(?:\s+(?P&lt;MAXSIZE&gt;\d+)(?:\s+(?P&lt;OFFSET&gt;\d+))?)?\s*$ </code></pre> <p>Testing:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; p = re.compile(r'^(?P&lt;SERVER&gt;\S+)\s+(?P&lt;SERVERKEY&gt;\S+)\s+(?P&lt;COMMAND&gt;\S+)\s+(?P&lt;FOLDERPATH&gt;/.*?)\s+(?P&lt;RETENTION&gt;\d+)\s+(?P&lt;TRANSFERMODE&gt;\S+)\s+(?P&lt;OUTPUTPATH&gt;[A-Z]:\\.*?\\)\s+(?P&lt;LOGTO&gt;NO|[A-Z]:\\.*?)(?:\s+(?P&lt;MAXSIZE&gt;\d+)(?:\s+(?P&lt;OFFSET&gt;\d+))?)?\s*$',re.M) &gt;&gt;&gt; data = r"""loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 ... loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 ... loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256""" &gt;&gt;&gt; import pprint &gt;&gt;&gt; for match in p.finditer(data): ... print pprint.pprint(match.groupdict()) ... {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': '300', 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/hats*', 'LOGTO': 'C:\\log\\love.log', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\no\\', 'RETENTION': '300', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'ascii'} &gt;&gt;&gt; </code></pre>
1
2008-11-05T17:44:39Z
[ "python", "regex" ]
How do I process a string such as this using regular expressions?
265,814
<p>How can I create a regex for a string such as this:</p> <pre><code>&lt;SERVER&gt; &lt;SERVERKEY&gt; &lt;COMMAND&gt; &lt;FOLDERPATH&gt; &lt;RETENTION&gt; &lt;TRANSFERMODE&gt; &lt;OUTPUTPATH&gt; &lt;LOGTO&gt; &lt;OPTIONAL-MAXSIZE&gt; &lt;OPTIONAL-OFFSET&gt; </code></pre> <p>Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended.</p> <p>Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file.</p> <p>The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset.</p> <p>Heres some examples:</p> <pre><code>loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 </code></pre> <p>Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath.</p> <p>Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't.</p> <p>Heres my regex:</p> <pre><code>^(\s+)?(?P&lt;SRCHOST&gt;.+)(\s+)(?P&lt;SRCKEY&gt;.+)(\s+)(?P&lt;COMMAND&gt;COPY)(\s+)(?P&lt;SRCDIR&gt;.+)(\s+)(?P&lt;RETENTION&gt;\d+)(\s+)(?P&lt;TRANSFER_MODE&gt;BIN|ASC|BINARY|ASCII)(\s+)(?P&lt;DSTDIR&gt;.+)(\s+)(?P&lt;LOGFILE&gt;.+)(\s+)?(?P&lt;SIZE&gt;\d+)?(\s+)?(?P&lt;OFFSET&gt;\d+)?$ </code></pre>
0
2008-11-05T16:47:56Z
266,018
<p>Are less than/greater than allowed inside the values? Because if not you have a very simple solution:</p> <p>Just replace ever occurance of "&gt; " with just "&gt;", split on "&gt;&lt;", and strip out all less than/greater than from each item. It's probably longer than the regex code, but it will be clearer what's going on.</p>
-1
2008-11-05T17:48:06Z
[ "python", "regex" ]
Django Forms, Display Error on ModelMultipleChoiceField
265,888
<p>I'm having an issue getting validation error messages to display for a particular field in a Django form, where the field in question is a <strong>ModelMultipleChoiceField</strong>.</p> <p>In the <code>clean(self)</code> method for the Form, I try to add the error message to the field like so:</p> <pre><code>msg = 'error' self._errors['field_name'] = ErrorList([msg]) raise forms.ValidationError(msg) </code></pre> <p>This works okay where 'field_name' points to other field types, but for ModelMultipleChoiceField it just won't display. Should this be handled differently?</p>
1
2008-11-05T17:10:57Z
314,830
<p>Why are you instantiating an ErrorList and writing to self._errors directly? Calling "raise forms.ValidationError(msg)" takes care of all that already. </p> <p>And what does your template look like?</p>
0
2008-11-24T17:19:27Z
[ "python", "django", "validation", "forms" ]
Django Forms, Display Error on ModelMultipleChoiceField
265,888
<p>I'm having an issue getting validation error messages to display for a particular field in a Django form, where the field in question is a <strong>ModelMultipleChoiceField</strong>.</p> <p>In the <code>clean(self)</code> method for the Form, I try to add the error message to the field like so:</p> <pre><code>msg = 'error' self._errors['field_name'] = ErrorList([msg]) raise forms.ValidationError(msg) </code></pre> <p>This works okay where 'field_name' points to other field types, but for ModelMultipleChoiceField it just won't display. Should this be handled differently?</p>
1
2008-11-05T17:10:57Z
1,265,411
<p>Yeah, it sounds like you're doing it wrong.</p> <p>You should be using the <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute" rel="nofollow">clean_</a> method instead. Read through that whole document, in fact - it's very informative.</p>
2
2009-08-12T10:37:18Z
[ "python", "django", "validation", "forms" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
265,995
<p>Not necessarily simpler, but a different way, if you are more familiar with the re family. </p> <pre><code>import re, string s = "string. With. Punctuation?" # Sample string out = re.sub('[%s]' % re.escape(string.punctuation), '', s) </code></pre>
16
2008-11-05T17:39:55Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
265,996
<p>Do search and replace using the regex functions, as seen <a href="http://www.amk.ca/python/howto/regex/regex.html#SECTION000620000000000000000" rel="nofollow">here.</a>. If you have to repeatedly perform the operation, you can keep a compiled copy of the regex pattern (your punctuation) around, which will speed things up a bit.</p>
0
2008-11-05T17:40:08Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
266,000
<p>I usually use something like this:</p> <pre><code>&gt;&gt;&gt; s = "string. With. Punctuation?" # Sample string &gt;&gt;&gt; import string &gt;&gt;&gt; for c in string.punctuation: ... s= s.replace(c,"") ... &gt;&gt;&gt; s 'string With Punctuation' </code></pre>
20
2008-11-05T17:41:27Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
266,162
<p>From an efficiency perspective, you're not going to beat translate() - it's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code. If speed isn't a worry, another option though is:</p> <pre><code>exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) </code></pre> <p>This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.</p> <p>Timing code:</p> <pre><code>import re, string, timeit s = "string. With. Punctuation" exclude = set(string.punctuation) table = string.maketrans("","") regex = re.compile('[%s]' % re.escape(string.punctuation)) def test_set(s): return ''.join(ch for ch in s if ch not in exclude) def test_re(s): # From Vinko's solution, with fix. return regex.sub('', s) def test_trans(s): return s.translate(table, string.punctuation) def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000) print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000) print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000) print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000) </code></pre> <p>This gives the following results:</p> <pre><code>sets : 19.8566138744 regex : 6.86155414581 translate : 2.12455511093 replace : 28.4436721802 </code></pre>
383
2008-11-05T18:36:11Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
2,402,306
<pre><code>myString.translate(None, string.punctuation) </code></pre>
39
2010-03-08T15:19:09Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
6,577,965
<p>This might not be the best solution however this is how I did it.</p> <pre><code>import string f = lambda x: ''.join([i for i in x if i not in string.punctuation]) </code></pre>
4
2011-07-05T04:30:07Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
7,268,456
<p>string.punctuation is ascii ONLY! A more correct (but also much slower) way is to use the unicodedata module:</p> <pre><code># -*- coding: utf-8 -*- from unicodedata import category s = u'String — with - «punctation »...' s = ''.join(ch for ch in s if category(ch)[0] != 'P') print 'stripped', s </code></pre>
12
2011-09-01T09:29:45Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
15,853,920
<p>I like to use a function like this:</p> <pre><code>def scrub(abc): while abc[-1] is in list(string.punctuation): abc=abc[:-1] while abc[0] is in list(string.punctuation): abc=abc[1:] return abc </code></pre>
-2
2013-04-06T17:28:57Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
16,799,238
<p>Regular expressions are simple enough, if you know them. </p> <pre><code>import re s = "string. With. Punctuation?" s = re.sub(r'[^\w\s]','',s) </code></pre>
27
2013-05-28T18:47:47Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
18,570,395
<p>For Python 3 <code>str</code> or Python 2 <code>unicode</code> values, <a href="http://docs.python.org/3/library/stdtypes.html#str.translate" rel="nofollow"><code>str.translate()</code></a> only takes a dictionary; codepoints (integers) are looked up in that mapping and anything mapped to <code>None</code> is removed.</p> <p>To remove (some?) punctuation then, use:</p> <pre><code>import string remove_punct_map = dict.fromkeys(map(ord, string.punctuation)) s.translate(remove_punct_map) </code></pre> <p>The <a href="http://docs.python.org/3/library/stdtypes.html#dict.fromkeys" rel="nofollow"><code>dict.fromkeys()</code> class method</a> makes it trivial to create the mapping, setting all values to <code>None</code> based on the sequence of keys.</p> <p>To remove <em>all</em> punctuation, not just ASCII punctuation, your table needs to be a little bigger; see <a href="http://stackoverflow.com/questions/11066400/remove-punctuation-from-unicode-formatted-strings/11066687#11066687">J.F. Sebastian's answer</a> (Python 3 version):</p> <pre><code>import unicodedata import sys remove_punct_map = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')) </code></pre>
5
2013-09-02T09:57:54Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
32,719,664
<p>This question is over 6 years old, but I'd figured I chime in with a function I wrote. It's not very efficient, but it is simple and you can add or remove any punctuation that you desire:</p> <pre><code>def stripPunc(wordList): """Strips punctuation from list of words""" puncList = [".",";",":","!","?","/","\\",",","#","@","$","&amp;",")","(","\""] for punc in puncList: for word in wordList: wordList=[word.replace(punc,'') for word in wordList] return wordList </code></pre>
2
2015-09-22T14:30:47Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
33,192,523
<p>One liner might be helpful in not very strict cases:</p> <pre><code>''.join([c for c in s if c.isalnum() or c.isspace()]) </code></pre>
0
2015-10-17T23:03:59Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
36,122,360
<p>Here's a one liner for python 3.5:</p> <pre><code>import string "l*ots! o(f. p@u)n[c}t]u[a'ti\"on#$^?/".translate(str.maketrans({a:None for a in string.punctuation})) </code></pre>
3
2016-03-21T02:46:47Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
37,221,663
<p>For the convenience of usage, I sum up the note of striping punctuation from a string in both Python2 and Python3. Please refer to other answers for the detailed description.</p> <hr> <p><strong>Python2</strong></p> <pre><code>import string s = "string. With. Punctuation?" table = string.maketrans("","") new_s = s.translate(table, string.punctuation) # Output: string without punctuation </code></pre> <hr> <p><strong>Python3</strong></p> <pre><code>import string s = "string. With. Punctuation?" table = str.maketrans({key: None for key in string.punctuation}) new_s = s.translate(table) # Output: string without punctuation </code></pre>
3
2016-05-14T01:57:29Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
37,894,054
<p>I haven't seen this answer yet. Just use a regex removes all characters besides word characters (<code>\w</code>) and number characters (<code>\d</code>), followed by a whitespace character (<code>\s</code>):</p> <pre><code>import re s = "string. With. Punctuation?" # Sample string out = re.sub(ur'[^\w\d\s]+', '', s) </code></pre>
0
2016-06-18T06:38:57Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
39,115,253
<pre><code>&gt;&gt;&gt; s = "string. With. Punctuation?" &gt;&gt;&gt; s = re.sub(r'[^\w\s]','',s) &gt;&gt;&gt; re.split(r'\s*', s) ['string', 'With', 'Punctuation'] </code></pre>
0
2016-08-24T05:43:58Z
[ "python", "string", "punctuation" ]
Best way to strip punctuation from a string in Python
265,960
<p>It seems like there should be a simpler way than:</p> <pre><code>import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) </code></pre> <p>Is there?</p>
282
2008-11-05T17:30:32Z
39,901,522
<p><code>string.punctuation</code> misses loads of punctation marks that are commonly used in the real world. How about a solution that works for non-ascii punctuation?</p> <pre><code>import regex s = u"string. With. Some・Really Weird、Non?ASCII。 「(Punctuation)」?" remove = regex.compile(ur'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE) remove.sub(u" ", s).strip() </code></pre> <p>Personally, I beleive this is the best way to remove punctuation from a string in python because:</p> <ul> <li>It removes all unicode punctuation </li> <li>It's easily modifiable, e.g. you can remove the <code>\{S}</code> if you want to remove punctuation but keep symbols like <code>$</code>. </li> <li>You can get really specific about what you want to keep and what you want to remove, for example <code>\{Pd}</code> will only remove dashes.</li> <li>This regex also normalizes whitespace. It maps tabs, carriage returns, and other oddities to nice, single spaces.</li> </ul> <p>This uses unicode character properties, which <a href="https://en.wikipedia.org/wiki/Unicode_character_property" rel="nofollow">you can read more about on wikipedia</a>.</p>
0
2016-10-06T16:46:01Z
[ "python", "string", "punctuation" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
266,132
<p>What you're looking for is Mod_Python. It's an Apache-based interpreter for Python. Check it out here:</p> <p><a href="http://www.modpython.org/" rel="nofollow">http://www.modpython.org/</a></p>
0
2008-11-05T18:24:26Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
266,209
<p>Most Python applications are moving away from mod_python. It can vary by framework or provider, but most development effort is going into mod_wsgi.</p> <p>Using the <a href="https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow">WSGI</a> standard will make your Python application server agnostic, and allow for other nice additions like WSGI middleware. Other providers may only provide <a href="http://en.wikipedia.org/wiki/Common_Gateway_Interface" rel="nofollow">CGI</a> (which won't scale well performance wise), or <a href="http://en.wikipedia.org/wiki/FastCGI" rel="nofollow">FastCGI</a>.</p>
2
2008-11-05T19:00:06Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
266,298
<p><a href="http://code.google.com/appengine/" rel="nofollow">Google App Engine</a> has done it for you. Some limitations but it works great, and it gives you a path to hosting free.</p>
0
2008-11-05T19:35:59Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
266,509
<p>I've worked with <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> using only the included server in the <code>manager.py</code> script and have not had any trouble moving to a production environment.</p> <p>If you put your application in a host that does the environment configuration for you (like <a href="https://www.webfaction.com/" rel="nofollow">WebFaction</a>) you should not have problems moving from development to production.</p>
1
2008-11-05T20:23:53Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
266,615
<p>Of course Mac OS X, in recent versions, comes with Python and Apache. However you may want to have more flexibility in the versions you use, or you may not like the tweaks Apple has made to the way they are configured. A good way to get a more generic set of tools, including MySQL, is to install them anew. This will help your portability issues. The frameworks can be installed relatively easily with one of these open source package providers.</p> <ul> <li><a href="http://www.finkproject.org/" rel="nofollow">Fink</a></li> <li><a href="http://www.macports.org/" rel="nofollow">MacPorts</a></li> <li><a href="http://sourceforge.net/projects/mamp" rel="nofollow">MAMP</a></li> </ul>
0
2008-11-05T20:50:52Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
266,736
<p>FWIW, we've found virtualenv [<a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">http://pypi.python.org/pypi/virtualenv</a>] to be an invaluable part of our dev setup. We typically work on multiple projects that use different versions of Python libraries etc. It's very difficult to do this on one machine without some way to provide a localized, customized Python environment, as virtualenv does.</p>
2
2008-11-05T21:18:42Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
267,522
<p>You may want to look into <a href="http://www.web2py.com" rel="nofollow">web2py</a>. It includes an administration interface to develop via your browser. All you need in one package, including <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a>.</p>
0
2008-11-06T02:51:18Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
275,578
<p>I run a Linux virtual machine on my Mac laptop. This allows me to keep my development environment and production environments perfectly in sync (and make snapshots for easy experimentation / rollback). I've found <a href="http://www.vmware.com/download/fusion/" rel="nofollow">VMWare Fusion</a> works the best, but there are free open source alternatives such as <a href="http://www.virtualbox.org/wiki/Downloads" rel="nofollow">VirtualBox</a> if you just want to get your feet wet.</p> <p>I share the source folders from the guest Linux operating system on my Mac and edit them with the Mac source editor of my choosing (I use <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="nofollow">Eclipse</a> / <a href="https://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a> because the otherwise excellent <a href="http://en.wikipedia.org/wiki/TextMate" rel="nofollow">TextMate</a> doesn't deal well with Chinese text yet). I've documented the software setup for the guest Linux operating system <a href="http://wiki.slicehost.com/doku.php?id=dream_geodjango_server" rel="nofollow">here</a>; it's optimized for serving multiple <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> applications (including geodjango).</p> <p>For extra added fun, you can edit your Mac's /etc/hosts file to make yourdomainname.com resolve to your guest Linux boxes internal IP address and have a simple way to work on / test multiple web projects online or offline without too much hassle.</p>
1
2008-11-09T03:54:34Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
624,603
<p>Check out <a href="http://www.webfaction.com" rel="nofollow">WebFaction</a>—although I don't use them (nor am I related to / profit from their business in any way). I've read over and over how great their service is and particularly how <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a>-friendly they are. There's a specific <a href="http://forum.webfaction.com/viewtopic.php?id=1119" rel="nofollow">post in their forums</a> about getting up and running with Django and <code>mod_wsgi</code>.</p> <p>Like others before me in this thread, I highly recommend using Ian Bicking's <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> to isolate your development environment; there's a <a href="http://code.google.com/p/modwsgi/wiki/VirtualEnvironments" rel="nofollow">dedicated page in the <code>mod_wsgi</code> documentation</a> for exactly that sort of setup. </p> <p>I'd also urge you to check out <a href="http://pip.openplans.org/" rel="nofollow">pip</a>, which is basically a smarter easy_install which knows about virtualenv. Pip does two really nice things for virtualenv-style development:</p> <ul> <li>Knows how to install from source control (<a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="nofollow">SVN</a>, <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="nofollow">Git</a>, etc...)</li> <li>Knows how to "freeze" an existing development environement's requirements so that you can create that environment somewhere else—very very nice for multiple developers or deployment.</li> </ul>
0
2009-03-09T00:13:13Z
[ "python", "mysql", "apache", "osx" ]
Setting up a Python web development environment on OS X
266,114
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac&nbsp;OS&nbsp;X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p> <p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
2
2008-11-05T18:19:44Z
624,751
<p><code>mod_wsgi</code> is really, really simple.</p> <p><a href="http://github.com/dbr/pyerweb/blob/070e354c1837e7d22a8bd5160d7f0897391bf382/pyerweb.py#L64" rel="nofollow">Pyerweb</a> is a really simple (~90 lines including comments/whitespace) WSGI-compliant routing-framework I wrote. Basically the WSGI API is just a function that gets passed <code>environ</code>, and <code>wsgi_start_response</code>, and it returns a string.</p> <p><code>envrion</code> is a dict with the request info, for example <code>environ['PATH_INFO']</code> is the request URI)</p> <p><code>wsgi_start_response</code> which is a callable function which you execute to set the headers,:</p> <pre><code>wsgi_start_response(output_response, output_headers) </code></pre> <p><code>output_response</code> is the string containing the HTTP status you wish to send (<code>200 OK</code> etc), and <code>output_headers</code> is a list-of-tuples containing your headers (for example, <code>[("Content-type", "text/html")]</code> would set the content-type)</p> <p>Then the function returns a string containing your output.. That's all there is to it!</p> <p>To run it, using <a href="http://pypi.python.org/pypi/Spawning/0.7" rel="nofollow"><code>spawning</code></a> you can just do <code>spawn scriptname.my_wsgi_function_nae</code> and it will start listening on port 8080.</p> <p>To use it via mod_wsgi, it's documentation is good, <a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide" rel="nofollow">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a> and there is a <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango" rel="nofollow">django specific section</a></p> <p>The up-side to using mod_wsgi is it's the standard for serving Python web-applications. I recently decided to play with Google App Engine, and was surprised when Pyerweb (which I linked to at the start of this answer) worked <em>perfectly</em> on it, completely unintentionally. I was even more impressed when I noticed Django applications run on it too.. Standardisation is a good thing!</p>
0
2009-03-09T01:48:17Z
[ "python", "mysql", "apache", "osx" ]
Python: Check if uploaded file is jpg
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
15
2008-11-05T21:00:36Z
266,724
<p>You might have to check the bytes of the image <a href="http://www.obrador.com/essentialjpeg/headerinfo.htm" rel="nofollow">http://www.obrador.com/essentialjpeg/headerinfo.htm</a> describes how the jpeg header is set up</p>
-2
2008-11-05T21:17:02Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
Python: Check if uploaded file is jpg
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
15
2008-11-05T21:00:36Z
266,731
<p>If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is:</p> <pre><code>Start Marker | JFIF Marker | Header Length | Identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0" </code></pre> <p>so a quick recogniser would be:</p> <pre><code>def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0': return False if data[6:] != 'JFIF\0': return False return True </code></pre> <p>However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with <a href="http://www.pythonware.com/products/pil/">PIL</a>. eg:</p> <pre><code>from PIL import Image def is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return False </code></pre>
36
2008-11-05T21:17:54Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
Python: Check if uploaded file is jpg
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
15
2008-11-05T21:00:36Z
266,774
<p>Use <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>. If it can open the file, it's an image.</p> <p>From the tutorial...</p> <pre><code>&gt;&gt;&gt; import Image &gt;&gt;&gt; im = Image.open("lena.ppm") &gt;&gt;&gt; print im.format, im.size, im.mode </code></pre>
0
2008-11-05T21:29:10Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
Python: Check if uploaded file is jpg
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
15
2008-11-05T21:00:36Z
1,040,027
<p>No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage.</p> <p>See <a href="http://docs.python.org/library/imghdr.html">http://docs.python.org/library/imghdr.html</a></p> <pre><code>import imghdr image_type = imghdr.what(filename) if not image_type: print "error" else: print image_type </code></pre> <p>As you have an image from a stream you may use the stream option probably like this :</p> <pre><code>image_type = imghdr.what(filename, incomming_image) </code></pre> <p><hr /></p> <p>Actualy this works for me in Pylons (even if i have not finished everything) : in the Mako template :</p> <pre><code>${h.form(h.url_for(action="save_image"), multipart=True)} Upload file: ${h.file("upload_file")} &lt;br /&gt; ${h.submit("Submit", "Submit")} ${h.end_form()} </code></pre> <p>in the upload controler :</p> <pre><code>def save_image(self): upload_file = request.POST["upload_file"] image_type = imghdr.what(upload_file.filename, upload_file.value) if not image_type: return "error" else: return image_type </code></pre>
32
2009-06-24T18:18:02Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
Python: Check if uploaded file is jpg
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
15
2008-11-05T21:00:36Z
5,717,194
<p>A more general solution is to use the Python binding to the Unix "file" command. For this, install the package python-magic. Example:</p> <pre><code>import magic ms = magic.open(magic.MAGIC_NONE) ms.load() type = ms.file("/path/to/some/file") print type f = file("/path/to/some/file", "r") buffer = f.read(4096) f.close() type = ms.buffer(buffer) print type ms.close() </code></pre>
1
2011-04-19T13:34:07Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
Python: Check if uploaded file is jpg
266,648
<p>How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?</p> <p>This is how far I got by now:</p> <p>Script receives image via HTML Form Post and is processed by the following code</p> <pre><code>... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... </code></pre> <p>I found mimetypes.guess_type, but it does not work for me.</p>
15
2008-11-05T21:00:36Z
28,907,255
<p>The last byte of the JPEG file specification seems to vary beyond just e0. Capturing the first three is 'good enough' of a heuristic signature to reliably identify whether the file is a jpeg. Please see below modified proposal: </p> <pre><code>def is_jpg(filename): data = open("uploads/" + filename,'rb').read(11) if (data[:3] == "\xff\xd8\xff"): return True elif (data[6:] == 'JFIF\0'): return True else: return False </code></pre>
0
2015-03-06T20:39:54Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
Using Python's smtplib with Tor
266,849
<p>I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?</p>
3
2008-11-05T21:50:04Z
275,164
<p>Because of abuse by spammers, many Tor egress nodes decline to emit port 25 (SMTP) traffic, so you may have problems.</p>
1
2008-11-08T20:37:17Z
[ "python", "smtp", "tor" ]
Using Python's smtplib with Tor
266,849
<p>I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?</p>
3
2008-11-05T21:50:04Z
8,490,148
<p><a href="http://bent.latency.net/smtpprox/" rel="nofollow">http://bent.latency.net/smtpprox/</a> I found this earlier, but haven't tried it</p>
1
2011-12-13T13:37:47Z
[ "python", "smtp", "tor" ]
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
267,436
<p>For example, if I have a <em>unicode</em> string, I can encode it as an <em>ASCII</em> string like so:</p> <pre><code>&gt;&gt;&gt; u'\u003cfoo/\u003e'.encode('ascii') '&lt;foo/&gt;' </code></pre> <p>However, I have e.g. this <em>ASCII</em> string:</p> <pre><code>'\u003foo\u003e' </code></pre> <p>... that I want to turn into the same <em>ASCII</em> string as in my first example above:</p> <pre><code>'&lt;foo/&gt;' </code></pre>
20
2008-11-06T01:55:40Z
267,444
<p>It's a little dangerous depending on where the string is coming from, but how about:</p> <pre><code>&gt;&gt;&gt; s = '\u003cfoo\u003e' &gt;&gt;&gt; eval('u"'+s.replace('"', r'\"')+'"').encode('ascii') '&lt;foo&gt;' </code></pre>
-1
2008-11-06T02:01:12Z
[ "python", "unicode", "ascii" ]
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
267,436
<p>For example, if I have a <em>unicode</em> string, I can encode it as an <em>ASCII</em> string like so:</p> <pre><code>&gt;&gt;&gt; u'\u003cfoo/\u003e'.encode('ascii') '&lt;foo/&gt;' </code></pre> <p>However, I have e.g. this <em>ASCII</em> string:</p> <pre><code>'\u003foo\u003e' </code></pre> <p>... that I want to turn into the same <em>ASCII</em> string as in my first example above:</p> <pre><code>'&lt;foo/&gt;' </code></pre>
20
2008-11-06T01:55:40Z
267,475
<p>It took me a while to figure this one out, but <a href="http://www.egenix.com/www2002/python/unicode-proposal.txt">this page</a> had the best answer:</p> <pre><code>&gt;&gt;&gt; s = '\u003cfoo/\u003e' &gt;&gt;&gt; s.decode( 'unicode-escape' ) u'&lt;foo/&gt;' &gt;&gt;&gt; s.decode( 'unicode-escape' ).encode( 'ascii' ) '&lt;foo/&gt;' </code></pre> <p>There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy).</p> <p>EDIT: See also <a href="http://www.python.org/doc/2.5.2/lib/standard-encodings.html">Python Standard Encodings</a>.</p>
36
2008-11-06T02:26:05Z
[ "python", "unicode", "ascii" ]
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
267,436
<p>For example, if I have a <em>unicode</em> string, I can encode it as an <em>ASCII</em> string like so:</p> <pre><code>&gt;&gt;&gt; u'\u003cfoo/\u003e'.encode('ascii') '&lt;foo/&gt;' </code></pre> <p>However, I have e.g. this <em>ASCII</em> string:</p> <pre><code>'\u003foo\u003e' </code></pre> <p>... that I want to turn into the same <em>ASCII</em> string as in my first example above:</p> <pre><code>'&lt;foo/&gt;' </code></pre>
20
2008-11-06T01:55:40Z
1,750,741
<p>On Python 2.5 the correct encoding is "unicode_escape", not "unicode-escape" (note the underscore).</p> <p>I'm not sure if the newer version of Python changed the unicode name, but here only worked with the underscore. </p> <p>Anyway, this is it.</p>
1
2009-11-17T18:14:37Z
[ "python", "unicode", "ascii" ]
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
267,436
<p>For example, if I have a <em>unicode</em> string, I can encode it as an <em>ASCII</em> string like so:</p> <pre><code>&gt;&gt;&gt; u'\u003cfoo/\u003e'.encode('ascii') '&lt;foo/&gt;' </code></pre> <p>However, I have e.g. this <em>ASCII</em> string:</p> <pre><code>'\u003foo\u003e' </code></pre> <p>... that I want to turn into the same <em>ASCII</em> string as in my first example above:</p> <pre><code>'&lt;foo/&gt;' </code></pre>
20
2008-11-06T01:55:40Z
11,281,948
<p><em>Ned Batchelder</em> said:</p> <blockquote> <p>It's a little dangerous depending on where the string is coming from, but how about:</p> <pre><code>&gt;&gt;&gt; s = '\u003cfoo\u003e' &gt;&gt;&gt; eval('u"'+s.replace('"', r'\"')+'"').encode('ascii') '&lt;foo&gt;' </code></pre> </blockquote> <p>Actually this method can be made safe like so:</p> <pre><code>&gt;&gt;&gt; s = '\u003cfoo\u003e' &gt;&gt;&gt; s_unescaped = eval('u"""'+s.replace('"', r'\"')+'-"""')[:-1] </code></pre> <p>Mind the triple-quote string and the dash right before the closing 3-quotes.</p> <ol> <li>Using a 3-quoted string will ensure that if the user enters ' \\" ' (spaces added for visual clarity) in the string it would not disrupt the evaluator;</li> <li>The dash at the end is a failsafe in case the user's string ends with a ' \" ' . Before we assign the result we slice the inserted dash with [:-1]</li> </ol> <p>So there would be no need to worry about what the users enter, as long as it is captured in raw format.</p>
1
2012-07-01T12:29:51Z
[ "python", "unicode", "ascii" ]
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
267,436
<p>For example, if I have a <em>unicode</em> string, I can encode it as an <em>ASCII</em> string like so:</p> <pre><code>&gt;&gt;&gt; u'\u003cfoo/\u003e'.encode('ascii') '&lt;foo/&gt;' </code></pre> <p>However, I have e.g. this <em>ASCII</em> string:</p> <pre><code>'\u003foo\u003e' </code></pre> <p>... that I want to turn into the same <em>ASCII</em> string as in my first example above:</p> <pre><code>'&lt;foo/&gt;' </code></pre>
20
2008-11-06T01:55:40Z
22,726,482
<p>At some point you will run into issues when you encounter special characters like Chinese characters or emoticons in a string you want to decode i.e. errors that look like this:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 109-123: ordinal not in range(128) </code></pre> <p>For my case (twitter data processing), I decoded as follows to allow me to see all characters with no errors</p> <pre><code>&gt;&gt;&gt; s = '\u003cfoo\u003e' &gt;&gt;&gt; s.decode( 'unicode-escape' ).encode( 'utf-8' ) &gt;&gt;&gt; &lt;foo&gt; </code></pre>
0
2014-03-29T03:06:42Z
[ "python", "unicode", "ascii" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
267,654
<p>I think both FL Studio and Reason can be configured as the default MIDI playback device. To send MIDI messages to either from VB.NET, you'll need to PInvoke the midiOutOpen, midiOutShortMsg and midiOutClose API calls. Here's a link to code samples:</p> <p><a href="http://www.answers.com/topic/midioutopen" rel="nofollow">http://www.answers.com/topic/midioutopen</a></p> <p>They're for VB6, but they should be easy to translate to VB.NET.</p> <p>I know FL Studio can be "driven" from a plugin authored for FL (or a VSTx plugin), but I think these are always written in C or C++.</p> <p>Edit: I just learned that Windows Vista dropped the MIDI Mapper (which would have made setting up FL or Reason as the default MIDI device simple). Amazing. Here is a link I found with an alternative solution:</p> <p><a href="http://akkordwechsel.de/15-windows-vista-und-der-midi-mapper/" rel="nofollow">http://akkordwechsel.de/15-windows-vista-und-der-midi-mapper/</a></p> <p>I just tried it out (it's just a *.CPL file that you double-click to run) and it appears to work (although the GM Synth is the only option available on my laptop, so I'm not sure if it will pick up FL or Reason as choices).</p>
2
2008-11-06T04:40:03Z
[ "python", "vb.net", "music" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
267,680
<p>Note: This answer doesn't exactly answer the question you asked but it might achieve the result you want :)</p> <p>You can author a VST plugin in Java using jVSTWrapper (<a href="http://jvstwrapper.sourceforge.net/" rel="nofollow">http://jvstwrapper.sourceforge.net/</a>). If you really wanted to use Python you could use Jython to interface to java and do it that way. Alternatively you could just write the plugin in Java or another scripting language for the JVM like Groovy.</p>
2
2008-11-06T04:57:01Z
[ "python", "vb.net", "music" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
268,066
<p>When it comes to Reason, you can do with it to much because of it's closed architecture - you can use VST plugins (or any other type like DirectX ones) - your only option is to use MIDI.</p> <p>Regarding Fruity Loops, you could write a VST plugin that can take an input from a scripting language (VB, Python or whatever) but in order to write such thing you would have to use Delphi or C++.</p> <p>Alternatively, you can check out <a href="http://www.cycling74.com/" rel="nofollow">MAX made by Cycling74</a> - it's something like a IDE for music ;-) - and I'm pretty sure you can use Python with it.</p>
0
2008-11-06T09:30:56Z
[ "python", "vb.net", "music" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
268,684
<p>You could write a <a href="http://en.wikipedia.org/wiki/ReWire" rel="nofollow">Rewire</a> host. Though, you will have to get a license (the license is free, but your application must be proprietary, so no open source).</p> <p>Alternatively, you could interface through MIDI messages.</p> <p>Finally, you could implement a dummy audio device which would route the audio to/from wherever you want or process it in some way. I imagine all of these would be reasonably difficult. MIDI is probably the easiest of the three (I have no idea how easy or hard the Rewire protocol is to use).</p>
0
2008-11-06T13:30:11Z
[ "python", "vb.net", "music" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
2,840,001
<p>Both applications support MIDI. It's just that they don't see each other. </p> <p>In order to send messages via MIDI between applications, you need to install a <strong>virtual midi port</strong>.</p> <p>There are several freely available, but this one works: <a href="http://www.midiox.com/zip/MidiYokeSetup.msi" rel="nofollow">http://www.midiox.com/zip/MidiYokeSetup.msi</a></p> <p>You'll get a virtual MIDI output port that you can write to as if it's a normal MIDI device. In Fruity Loops or Rebirth you choose that port as the input. That's all you need to do to connect the programs.</p> <p>It'll work like this:</p> <p><code>Your Application</code> --> <code>Virtual MIDI Port</code> --> <code>FruityLoops</code></p>
3
2010-05-15T11:55:02Z
[ "python", "vb.net", "music" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
2,840,034
<p>What you need is a VST MIDI scripter / scripting plugin to create a logic of MIDI events that can be sent to any MIDI channel. You would need to set a MIDI channel in FL for the VST instrument/effect you need to tweak its values. Google for it there are some plugins around and please share them back here if you find anything useful :)</p>
1
2010-05-15T12:06:08Z
[ "python", "vb.net", "music" ]
scripting fruityloops or propellerheads reason from VB or Python?
267,628
<p>I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.</p> <p>Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?</p> <p>Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.</p> <p>Update 2 : If you're interested in this question, <a href="http://stackoverflow.com/questions/427037/scripting-lmms-from-python">check out this too</a>.</p>
9
2008-11-06T04:19:54Z
4,439,944
<p>There's an opensource music workstation, called Frinika, and you can script that in Javascript. (Insert / delete notes , change midi effects like pitch wheel etc.) It can import / export regular midi files, so it will work with Fruity loops or whatever else you have.</p> <pre><code>// Insert New song.newLane("MyMidiLane", type("Midi")); lane = song.getLane("MyMidiLane"); part = lane.newPart( time("10.0:000"), time("4.0:000") ); part.insertNote(note("c#3"), time("11.2:000"), time("2:0"), 120 ); part.insertNote(note("f3"), time("11.3:000"), time("1:0"), 100 ); part.insertNote(note("g#3"), time("11.3:000"), time("1:0"), 100 ); part.insertNote(note("b3"), time("11.3:000"), time("0:64"), 100 ); part.removeNote(note("f3"), time("11.3:000")); part = song.newLane("MyTextLane", type("Text")).newPart(time("24.0:000"), time("10.0:000")); part.text = "This is the test text to be inserted."; part.lane.parts[0].remove(); // remove initially inserted text-part </code></pre> <p>Another example for reading/changing notes:</p> <pre><code>lane = song.getLane("MyMidiLane"); // a lane has a fixed instrument assigned lane.parts[0].notes[0].duration=64 lane.parts[0].notes[1].duration=32 lane.parts[0].notes[1].startTick=120 // Parts are blocks of notes that you can drag around together in the Frinika GUI. // They're like patterns in trackers. for (i in lane.parts[0].notes){ println("i: "+i+", n: "+noteName(lane.parts[0].notes[i].note)); println("i: "+i+", dur: "+lane.parts[0].notes[i].duration); println("i: "+i+", startT: "+lane.parts[0].notes[i].startTick); } </code></pre> <p><a href="http://frinika.appspot.com/" rel="nofollow">http://frinika.appspot.com/</a> It has a Java Webstart launcher as well, so you don't even have to install.</p> <p>It used to bundle the Javadoc documentation as well, but for some reason their latest downloads don't include that. It's a pity, because that's where the Javascript bindings are documented. So, now you have to browse the source or build the Javadoc yourself. (It has some built-in examples that are accessible from the scripting window, you should check them out first. My first example is from there.) </p> <p>Here is the sourcefile where you'll find the Javascript docs:</p> <p><a href="http://www.google.com/url?sa=D&amp;q=http://frinika.svn.sourceforge.net/viewvc/frinika/frinika/trunk/src/com/frinika/project/scripting/javascript/JavascriptScope.java%3Frevision%3D154%26view%3Dmarkup&amp;usg=AFQjCNFQOlOjiUG76zrs_LxT8-P0mP_xZA" rel="nofollow">frinika Javascript doc/source</a></p> <p>But there are other options as well. You can check out <a href="http://code.google.com/p/mingus/" rel="nofollow">mingus</a> too, which is a Python library for music theory and midi file handling. It requires Fluidsynth, and the demo apps require GamePython too, so it's a bit more complicated to setup than Frinika.</p> <p>P.S.: Frinika has a particular bug: when dragging around neighbouring notes, some might not sound the right length. You can help that by transposing forth and back the consecutive notes (fairly fast in piano roll view), or dragging the part that contains the notes forth and back. Restarting Frinika will also help, but that's the slower way. So this bug won't affect saved files, neither midi export.</p>
0
2010-12-14T14:01:38Z
[ "python", "vb.net", "music" ]
How to create a picture with animated aspects programmatically
267,660
<p>Background</p> <p>I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. </p> <p>The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds.</p> <p>The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays.</p> <p><strong>My question is what is the best way to do this? What frameworks/libraries are best suited for this job?</strong></p> <p>I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this. The client will present this as a slide in a presentation in a windows machine.</p>
1
2008-11-06T04:44:47Z
267,676
<p>It depends largely on the effort you want to expend on this, but the basic outline of an easy way. Would be to load an image of an arrow, and use a drawing library to color and rotate it in the direction you want to point(or draw it using shapes/curves).</p> <p>Finally to actually animate it interpolate between the coordinates based on time.</p> <p>If its just for a presentation though, I would use Macromedia Flash, or a similar animation program.(would do the same as above but you don't need to program anything)</p>
1
2008-11-06T04:53:21Z
[ "python", "image", "graphics", "animation", "drawing" ]
How to create a picture with animated aspects programmatically
267,660
<p>Background</p> <p>I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. </p> <p>The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds.</p> <p>The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays.</p> <p><strong>My question is what is the best way to do this? What frameworks/libraries are best suited for this job?</strong></p> <p>I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this. The client will present this as a slide in a presentation in a windows machine.</p>
1
2008-11-06T04:44:47Z
267,698
<blockquote> <p>The client will present this as a slide in a presentation in a windows machine</p> </blockquote> <p>I think this is the key to your answer. Before going to a 3d implementation and writing all the code in the world to create this feature, you need to look at the presentation software. Chances are, your options will boil down to two things:</p> <ol> <li>Animated Gif</li> <li>Custom Presentation Scripts</li> </ol> <p>Obviously, an animated gif is not ideal due to the fact that it repeats when it is done rendering, and to make it last a long time would make a large gif.</p> <p>Custom Presentation Scripts would probably be the other way to allow him to bring it up in a presentation without running any side-programs, or doing anything strange. I'm not sure which presentation application is the target, but this could be valuable information.</p> <p>He sounds like he's more non-technical and requesting something he doesn't realize will be difficult. I think you should come up with some options, explain the difficulty in implementing them, and suggest another solution that falls into the 'bang for your buck' range.</p>
2
2008-11-06T05:07:21Z
[ "python", "image", "graphics", "animation", "drawing" ]
How to create a picture with animated aspects programmatically
267,660
<p>Background</p> <p>I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. </p> <p>The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds.</p> <p>The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays.</p> <p><strong>My question is what is the best way to do this? What frameworks/libraries are best suited for this job?</strong></p> <p>I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this. The client will present this as a slide in a presentation in a windows machine.</p>
1
2008-11-06T04:44:47Z
267,888
<p>If you are adventurous use OpenGL :)</p> <p>You can draw bezier curves in 3d space on top of a textured plane (earth map), you can specify a thickness for them and you can draw a point (small cone) at the end. It's easy and it looks nice, problem is learning the basics of OpenGL if you haven't used it before but that would be fun and probably useful if your in to programing graphics.</p> <p>You can use OpenGL from python either with <a href="http://pyopengl.sourceforge.net/" rel="nofollow">pyopengl</a> or <a href="http://www.pyglet.org/" rel="nofollow">pyglet</a>.</p> <p>If you make the animation this way you can capture it to an avi file (using <a href="http://www.techsmith.com/camtasia.asp" rel="nofollow">camtasia</a> or something similar) that can be put onto a presentation slide.</p>
1
2008-11-06T07:52:57Z
[ "python", "image", "graphics", "animation", "drawing" ]