title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Is there a database implementation that has notifications and revisions? | 1,118,272 | <p>I am looking for a database library that can be used within an editor to replace a custom document format. In my case the document would contain a functional program.</p>
<p>I want application data to be persistent even while editing, so that when the program crashes, no data is lost. I know that all databases offer that.</p>
<p>On top of that, I want to access and edit the document from multiple threads, processes, possibly even multiple computers.</p>
<p>Format: a simple key/value database would totally suffice. SQL usually needs to be wrapped, and if I can avoid pulling in a heavy ORM dependency, that would be splendid.</p>
<p>Revisions: I want to be able to roll back changes up to the first change to the document that has ever been made, not only in one session, but also between sessions/program runs.</p>
<p>I need notifications: each process must be able to be notified of changes to the document so it can update its view accordingly.</p>
<p>I see these requirements as rather basic, a foundation to solve the usual tough problems of an editing application: undo/redo, multiple views on the same data. Thus, the database system should be lightweight and undemanding.</p>
<p>Thank you for your insights in advance :)</p>
| 0 | 2009-07-13T08:29:26Z | 1,118,299 | <p><a href="http://www.oracle.com/technology/products/berkeley-db/index.html" rel="nofollow">Berkeley DB</a> is an undemanding, light-weight key-value database that supports locking and transactions. There are bindings for it in a lot of programming languages, including C++ and python. You'll have to implement revisions and notifications yourself, but that's actually not all that difficult.</p>
| 1 | 2009-07-13T08:36:54Z | [
"c++",
"python",
"database-design",
"editor"
] |
Is there a database implementation that has notifications and revisions? | 1,118,272 | <p>I am looking for a database library that can be used within an editor to replace a custom document format. In my case the document would contain a functional program.</p>
<p>I want application data to be persistent even while editing, so that when the program crashes, no data is lost. I know that all databases offer that.</p>
<p>On top of that, I want to access and edit the document from multiple threads, processes, possibly even multiple computers.</p>
<p>Format: a simple key/value database would totally suffice. SQL usually needs to be wrapped, and if I can avoid pulling in a heavy ORM dependency, that would be splendid.</p>
<p>Revisions: I want to be able to roll back changes up to the first change to the document that has ever been made, not only in one session, but also between sessions/program runs.</p>
<p>I need notifications: each process must be able to be notified of changes to the document so it can update its view accordingly.</p>
<p>I see these requirements as rather basic, a foundation to solve the usual tough problems of an editing application: undo/redo, multiple views on the same data. Thus, the database system should be lightweight and undemanding.</p>
<p>Thank you for your insights in advance :)</p>
| 0 | 2009-07-13T08:29:26Z | 1,118,325 | <p>Check out ZODB. It doesn't have notifications built in, so you would need a messaging system there (since you may use separate computers). But it has transactions, you can roll back forever (unless you pack the database, which removes earlier revisions), you can access it directly as an integrated part of the application, or it can run as client/server (with multiple clients of course), you can have automatic persistency, there is no ORM, etc.</p>
<p>It's pretty much Python-only though (it's based on Pickles).</p>
<p><a href="http://en.wikipedia.org/wiki/Zope_Object_Database" rel="nofollow">http://en.wikipedia.org/wiki/Zope_Object_Database</a></p>
<p><a href="http://pypi.python.org/pypi/ZODB3" rel="nofollow">http://pypi.python.org/pypi/ZODB3</a></p>
<p><a href="http://wiki.zope.org/ZODB/guide/index.html" rel="nofollow">http://wiki.zope.org/ZODB/guide/index.html</a></p>
<p><a href="http://wiki.zope.org/ZODB/Documentation" rel="nofollow">http://wiki.zope.org/ZODB/Documentation</a></p>
| 0 | 2009-07-13T08:43:32Z | [
"c++",
"python",
"database-design",
"editor"
] |
Is there a database implementation that has notifications and revisions? | 1,118,272 | <p>I am looking for a database library that can be used within an editor to replace a custom document format. In my case the document would contain a functional program.</p>
<p>I want application data to be persistent even while editing, so that when the program crashes, no data is lost. I know that all databases offer that.</p>
<p>On top of that, I want to access and edit the document from multiple threads, processes, possibly even multiple computers.</p>
<p>Format: a simple key/value database would totally suffice. SQL usually needs to be wrapped, and if I can avoid pulling in a heavy ORM dependency, that would be splendid.</p>
<p>Revisions: I want to be able to roll back changes up to the first change to the document that has ever been made, not only in one session, but also between sessions/program runs.</p>
<p>I need notifications: each process must be able to be notified of changes to the document so it can update its view accordingly.</p>
<p>I see these requirements as rather basic, a foundation to solve the usual tough problems of an editing application: undo/redo, multiple views on the same data. Thus, the database system should be lightweight and undemanding.</p>
<p>Thank you for your insights in advance :)</p>
| 0 | 2009-07-13T08:29:26Z | 1,118,368 | <p>It might be a bit more power than what you ask for, but You should definitely look at <a href="http://couchdb.apache.org/" rel="nofollow">CouchDB</a>.</p>
<p>It is a document database with "document" being defined as a JSON record.
It stores all the changes to the documents as revisions, so you instantly get revisions.
It has powerful javascript based view engine to aggregate all the data you need from the database.</p>
<p>All the commits to the database are written to the end of the repository file and the writes are atomic, meaning that unsuccessful writes do not corrupt the database.</p>
<p>Another nice bonus You'll get is easy and flexible replication and of your database.</p>
<p>See the full feature list on <a href="http://couchdb.apache.org/docs/overview.html" rel="nofollow">their homepage</a></p>
<p>On the minus side (depending on Your point of view) is the fact that it is written in Erlang and (as far as I know) runs as an external process...</p>
<p>I don't know anything about notifications though - it seems that if you are working with replicated databases, the changes are instantly replicated/synchronized between databases. Other than that I suppose you should be able to roll your own notification schema...</p>
| 1 | 2009-07-13T08:56:55Z | [
"c++",
"python",
"database-design",
"editor"
] |
Non-Standard Optional Argument Defaults | 1,118,454 | <p>I have two functions:</p>
<pre><code>def f(a,b,c=g(b)):
blabla
def g(n):
blabla
</code></pre>
<p><code>c</code> is an optional argument in function <code>f</code>. If the user does not specify its value, the program should compute g(b) and that would be the value of <code>c</code>. But the code does not compile - it says name 'b' is not defined. How to fix that?</p>
<p>Someone suggested:</p>
<pre><code>def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
</code></pre>
<p>But this doesn't work. Maybe the user intended <code>c</code> to be None and then <code>c</code> will have another value.</p>
| 3 | 2009-07-13T09:23:48Z | 1,118,464 | <p>value of <code>c</code> will be evaluated (<code>g(b)</code>) at compilation time. You need <code>g</code> defined before <code>f</code> therefore. And of course you need a global <code>b</code> variable to be defined at that stage too.</p>
<pre><code>b = 4
def g(a):
return a+1
def test(a, c=g(b)):
print(c)
test(b)
</code></pre>
<p>prints 5.</p>
| 2 | 2009-07-13T09:26:07Z | [
"python",
"optional-arguments"
] |
Non-Standard Optional Argument Defaults | 1,118,454 | <p>I have two functions:</p>
<pre><code>def f(a,b,c=g(b)):
blabla
def g(n):
blabla
</code></pre>
<p><code>c</code> is an optional argument in function <code>f</code>. If the user does not specify its value, the program should compute g(b) and that would be the value of <code>c</code>. But the code does not compile - it says name 'b' is not defined. How to fix that?</p>
<p>Someone suggested:</p>
<pre><code>def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
</code></pre>
<p>But this doesn't work. Maybe the user intended <code>c</code> to be None and then <code>c</code> will have another value.</p>
| 3 | 2009-07-13T09:23:48Z | 1,118,465 | <p>You cannot do it that way.</p>
<p>Inside the function, check if c is specified. If not, do the calculation.</p>
<pre><code>def f(a,b,c=None):
if c == None:
c = g(b)
blabla
</code></pre>
| 2 | 2009-07-13T09:26:21Z | [
"python",
"optional-arguments"
] |
Non-Standard Optional Argument Defaults | 1,118,454 | <p>I have two functions:</p>
<pre><code>def f(a,b,c=g(b)):
blabla
def g(n):
blabla
</code></pre>
<p><code>c</code> is an optional argument in function <code>f</code>. If the user does not specify its value, the program should compute g(b) and that would be the value of <code>c</code>. But the code does not compile - it says name 'b' is not defined. How to fix that?</p>
<p>Someone suggested:</p>
<pre><code>def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
</code></pre>
<p>But this doesn't work. Maybe the user intended <code>c</code> to be None and then <code>c</code> will have another value.</p>
| 3 | 2009-07-13T09:23:48Z | 1,118,467 | <pre><code>def f(a,b,c=None):
if c is None:
c = g(b)
</code></pre>
<p>If <code>None</code> can be a valid value for <code>c</code> then you do this:</p>
<pre><code>sentinel = object()
def f(a,b,c=sentinel):
if c is sentinel:
c = g(b)
</code></pre>
| 19 | 2009-07-13T09:26:54Z | [
"python",
"optional-arguments"
] |
Non-Standard Optional Argument Defaults | 1,118,454 | <p>I have two functions:</p>
<pre><code>def f(a,b,c=g(b)):
blabla
def g(n):
blabla
</code></pre>
<p><code>c</code> is an optional argument in function <code>f</code>. If the user does not specify its value, the program should compute g(b) and that would be the value of <code>c</code>. But the code does not compile - it says name 'b' is not defined. How to fix that?</p>
<p>Someone suggested:</p>
<pre><code>def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
</code></pre>
<p>But this doesn't work. Maybe the user intended <code>c</code> to be None and then <code>c</code> will have another value.</p>
| 3 | 2009-07-13T09:23:48Z | 1,118,756 | <pre><code>def f(a,b,*args):
if len(args) == 1:
c = args[0]
elif len(args) == 0:
c = g(b)
else:
raise Exception('Function takes 2 or 3 parameters only.')
blabla
def g(n):
blabla
</code></pre>
<p>You can probably structure it better, but that's the main idea. Alternatively you can use <code>**kwargs</code> and use the function like <code>f(a,b,c=Something)</code>, you just have to modify <code>f</code> accordingly.</p>
<p><a href="http://docs.python.org/tutorial/controlflow.html#keyword-arguments" rel="nofollow">Documentation</a></p>
| 0 | 2009-07-13T10:39:09Z | [
"python",
"optional-arguments"
] |
Non-Standard Optional Argument Defaults | 1,118,454 | <p>I have two functions:</p>
<pre><code>def f(a,b,c=g(b)):
blabla
def g(n):
blabla
</code></pre>
<p><code>c</code> is an optional argument in function <code>f</code>. If the user does not specify its value, the program should compute g(b) and that would be the value of <code>c</code>. But the code does not compile - it says name 'b' is not defined. How to fix that?</p>
<p>Someone suggested:</p>
<pre><code>def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
</code></pre>
<p>But this doesn't work. Maybe the user intended <code>c</code> to be None and then <code>c</code> will have another value.</p>
| 3 | 2009-07-13T09:23:48Z | 2,893,677 | <p>The problem with</p>
<pre><code>sentinel = object()
def f(a, b, c=sentinel):
if c is sentinel:
c = g(b)
</code></pre>
<p>is that <code>sentinel</code> is global/public unless this code is part of a function/method. So someone might still be able to call <code>f(23, 42, sentinel)</code>. However, if <code>f</code> is global/public, you can use a closure to make <code>sentinel</code> local/private so that the caller cannot use it:</p>
<pre><code>def f():
sentinel = object()
def tmp(a, b, c=sentinel):
if c is sentinel:
c = g(b)
return tmp
f = f()
</code></pre>
<p>If you are concerned that static code analyzers could get the wrong idea about <code>f</code> then, you can use the same parameters for the factory:</p>
<pre><code>def f(a, b, c=object()): #@UnusedVariable
sentinel = object()
def tmp(a, b, c=sentinel):
if c is sentinel:
c = g(b)
return tmp
f = f(23, 42)
</code></pre>
| 1 | 2010-05-23T22:06:39Z | [
"python",
"optional-arguments"
] |
Interpret this particular REGEX | 1,118,672 | <p>I did a REGEX pattern some time ago and I don't remember its meaning. For me this is a write-only language :)</p>
<p>Here is the REGEX:</p>
<pre><code>"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"
</code></pre>
<p>I need to know, in plain English, what does it means.</p>
| 0 | 2009-07-13T10:19:11Z | 1,118,689 | <pre><code>(?!^[0-9]*$)
</code></pre>
<p>don't match only numbers,</p>
<pre><code>(?!^[a-zA-Z]*$)
</code></pre>
<p>don't match only letters,</p>
<pre><code>^([a-zA-Z0-9]{8,10})$
</code></pre>
<p>match letters and number 8 to 10 characters long.</p>
| 6 | 2009-07-13T10:22:24Z | [
"python",
"regex"
] |
Interpret this particular REGEX | 1,118,672 | <p>I did a REGEX pattern some time ago and I don't remember its meaning. For me this is a write-only language :)</p>
<p>Here is the REGEX:</p>
<pre><code>"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"
</code></pre>
<p>I need to know, in plain English, what does it means.</p>
| 0 | 2009-07-13T10:19:11Z | 1,118,702 | <p>Use something like <a href="http://www.ultrapico.com/Expresso.htm" rel="nofollow">expresso</a> to analyise it.</p>
| 1 | 2009-07-13T10:25:55Z | [
"python",
"regex"
] |
Interpret this particular REGEX | 1,118,672 | <p>I did a REGEX pattern some time ago and I don't remember its meaning. For me this is a write-only language :)</p>
<p>Here is the REGEX:</p>
<pre><code>"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"
</code></pre>
<p>I need to know, in plain English, what does it means.</p>
| 0 | 2009-07-13T10:19:11Z | 1,118,708 | <p><a href="http://www.regexbuddy.com/" rel="nofollow">RegexBuddy</a> says the following (!?!):</p>
<pre><code>(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$
Options: ^ and $ match at line breaks
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!^[0-9]*$)»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single character in the range between â0â and â9â «[0-9]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!^[a-zA-Z]*$)»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single character present in the list below «[a-zA-Z]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
A character in the range between âaâ and âzâ «a-z»
A character in the range between âAâ and âZâ «A-Z»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below and capture its match into backreference number 1 «([a-zA-Z0-9]{8,10})»
Match a single character present in the list below «[a-zA-Z0-9]{8,10}»
Between 8 and 10 times, as many times as possible, giving back as needed (greedy) «{8,10}»
A character in the range between âaâ and âzâ «a-z»
A character in the range between âAâ and âZâ «A-Z»
A character in the range between â0â and â9â «0-9»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
</code></pre>
| 2 | 2009-07-13T10:28:14Z | [
"python",
"regex"
] |
Interpret this particular REGEX | 1,118,672 | <p>I did a REGEX pattern some time ago and I don't remember its meaning. For me this is a write-only language :)</p>
<p>Here is the REGEX:</p>
<pre><code>"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"
</code></pre>
<p>I need to know, in plain English, what does it means.</p>
| 0 | 2009-07-13T10:19:11Z | 1,118,709 | <p><a href="http://www.perl.com/doc/manual/html/pod/perlre.html" rel="nofollow">Perl</a> (and <a href="http://docs.python.org/library/re.html" rel="nofollow">Python</a> accordingly) says to the <code>(?!...)</code> part:</p>
<blockquote>
<p>A zero-width negative lookahead assertion. For example <code>/foo(?!bar)/</code> matches any occurrence of 'foo' that isn't followed by 'bar'. Note however that lookahead and lookbehind are NOT the same thing. You cannot use this for lookbehind.</p>
</blockquote>
<p>That means,</p>
<pre><code>(?!^[0-9]*$)
</code></pre>
<p>means: <em>don't match, if the string contains <strong>only</strong> numbers.</em> (<code>^</code>: start of line/string, <code>$</code>: end of line/string) The other accordingly.</p>
<p>Your regexp matches any string, that contains <strong>both</strong> numbers and letters, but not only one of them.</p>
<p>Cheers,</p>
<p><strong>Update:</strong> For your future RegExp tailoring, take a look at the <code>(?#...)</code> pattern. It allows you to embed comments in your regexp. There is also a modifier, <code>re.X</code>, but I don't like this very much. It's your choice.</p>
| 4 | 2009-07-13T10:28:31Z | [
"python",
"regex"
] |
Migrating Django Application to Google App Engine? | 1,118,761 | <p>I'm developing a web application and considering Django, Google App Engine, and several other options. I wondered what kind of "penalty" I will incur if I develop a complete Django application assuming it runs on a dedicated server, and then later want to migrate it to Google App Engine.</p>
<p>I have a basic understanding of Google's data store, so please assume I will choose a column based database for my "stand-alone" Django application rather than a relational database, so that the schema could remain mostly the same and will not be a major factor.</p>
<p>Also, please assume my application does not maintain a huge amount of data, so that migration of tens of gigabytes is not required. I'm mainly interested in the effects on the code and software architecture.</p>
<p>Thanks</p>
| 9 | 2009-07-13T10:40:05Z | 1,118,790 | <p>There are a few things that you can't do on the App Engine that you can do on your own server like uploading of files. On the App Engine you kinda have to upload it and store the datastore which can cause a few problems.</p>
<p>Other than that it should be fine from the Presentation part. There are a number of other little things that are better on your own dedicated server but I think eventually a lot of those things will be in the App Engine</p>
| 1 | 2009-07-13T10:47:54Z | [
"python",
"django",
"google-app-engine"
] |
Migrating Django Application to Google App Engine? | 1,118,761 | <p>I'm developing a web application and considering Django, Google App Engine, and several other options. I wondered what kind of "penalty" I will incur if I develop a complete Django application assuming it runs on a dedicated server, and then later want to migrate it to Google App Engine.</p>
<p>I have a basic understanding of Google's data store, so please assume I will choose a column based database for my "stand-alone" Django application rather than a relational database, so that the schema could remain mostly the same and will not be a major factor.</p>
<p>Also, please assume my application does not maintain a huge amount of data, so that migration of tens of gigabytes is not required. I'm mainly interested in the effects on the code and software architecture.</p>
<p>Thanks</p>
| 9 | 2009-07-13T10:40:05Z | 1,118,791 | <p>Basically, you will change the data model base class and some APIs if you use them (PIL, urllib2, etc). </p>
<p>If your goal is app-engine, I would use the app engine helper <a href="http://code.google.com/appengine/articles/appengine_helper_for_django.html" rel="nofollow">http://code.google.com/appengine/articles/appengine_helper_for_django.html</a>. It can run it on your server with a file based DB and then push it to app-engine with no changes. </p>
| 2 | 2009-07-13T10:48:11Z | [
"python",
"django",
"google-app-engine"
] |
Migrating Django Application to Google App Engine? | 1,118,761 | <p>I'm developing a web application and considering Django, Google App Engine, and several other options. I wondered what kind of "penalty" I will incur if I develop a complete Django application assuming it runs on a dedicated server, and then later want to migrate it to Google App Engine.</p>
<p>I have a basic understanding of Google's data store, so please assume I will choose a column based database for my "stand-alone" Django application rather than a relational database, so that the schema could remain mostly the same and will not be a major factor.</p>
<p>Also, please assume my application does not maintain a huge amount of data, so that migration of tens of gigabytes is not required. I'm mainly interested in the effects on the code and software architecture.</p>
<p>Thanks</p>
| 9 | 2009-07-13T10:40:05Z | 1,119,377 | <p>Most (all?) of Django is available in GAE, so your main task is to avoid basing your designs around a reliance on anything from Django or the Python standard libraries which is not available on GAE.</p>
<p>You've identified the glaring difference, which is the database, so I'll assume you're on top of that. Another difference is the tie-in to Google Accounts and hence that if you want, you can do a fair amount of access control through the app.yaml file rather than in code. You don't have to use any of that, though, so if you don't envisage switching to Google Accounts when you switch to GAE, no problem.</p>
<p>I think the differences in the standard libraries can mostly be deduced from the fact that GAE has no I/O and no C-accelerated libraries unless explicitly stated, and my experience so far is that things I've expected to be there, have been there. I don't know Django and haven't used it on GAE (apart from templates), so I can't comment on that.</p>
<p>Personally I probably wouldn't target LAMP (where P = Django) with the intention of migrating to GAE later. I'd develop for both together, and try to ensure if possible that the differences are kept to the very top (configuration) and the very bottom (data model). The GAE version doesn't necessarily have to be perfect, as long as you know how to make it perfect should you need it.</p>
<p>It's not guaranteed that this is faster than writing and then porting, but my guess is it normally will be. The easiest way to spot any differences is to run the code, rather than relying on not missing anything in the GAE docs, so you'll likely save some mistakes that need to be unpicked. The Python SDK is a fairly good approximation to the real App Engine, so all or most of your tests can be run locally most of the time.</p>
<p>Of course if you eventually decide not to port then you've done unnecessary work, so you have to think about the probability of that happening, and whether you'd consider the GAE development to be a waste of your time if it's not needed.</p>
| 8 | 2009-07-13T13:16:36Z | [
"python",
"django",
"google-app-engine"
] |
Migrating Django Application to Google App Engine? | 1,118,761 | <p>I'm developing a web application and considering Django, Google App Engine, and several other options. I wondered what kind of "penalty" I will incur if I develop a complete Django application assuming it runs on a dedicated server, and then later want to migrate it to Google App Engine.</p>
<p>I have a basic understanding of Google's data store, so please assume I will choose a column based database for my "stand-alone" Django application rather than a relational database, so that the schema could remain mostly the same and will not be a major factor.</p>
<p>Also, please assume my application does not maintain a huge amount of data, so that migration of tens of gigabytes is not required. I'm mainly interested in the effects on the code and software architecture.</p>
<p>Thanks</p>
| 9 | 2009-07-13T10:40:05Z | 1,123,292 | <p>It sounds like you have awareness of the major limitation in building/migrating your app -- that AppEngine doesn't support Django's ORM.</p>
<p>Keep in mind that this doesn't just affect the code you write yourself -- it also limits your ability to use a lot of existing Django code. That includes other applications (such as the built-in admin and auth apps) and ORM-based features such as <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/" rel="nofollow">generic views</a>.</p>
| 2 | 2009-07-14T03:18:17Z | [
"python",
"django",
"google-app-engine"
] |
Python script: import sys failing on WinXP setup | 1,118,979 | <p>I'm trying out a hello world python script on WinXP. When I execute:</p>
<blockquote>
<p>python test.py arg1.log</p>
</blockquote>
<p>I get an error for the first line of the script, which is 'import sys':</p>
<pre><code>File "test.py", line 1, in <module>
i
NameError: name 'i' is not defined
</code></pre>
<p>Any suggestions?</p>
| 0 | 2009-07-13T11:38:23Z | 1,118,998 | <p>You've saved the file as Windows Unicode (aka UTF-16, aka UCS-2) rather than ASCII or UTF-8.</p>
<p>If your editor has an Encoding option (or something under "Save As" for the encoding) change it to UTF-8.</p>
<p>If your editor has no such option, you can load it into Notepad and save it as UTF-8.</p>
| 10 | 2009-07-13T11:44:05Z | [
"python",
"windows-xp"
] |
PyQt: event is not triggered, what's wrong with my code? | 1,119,110 | <p>I'm a Python newbie and I'm trying to write a trivial app with an event handler that gets activated when an item in a custom QTreeWidget is clicked. For some reason it doesn't work. Since I'm only at the beginning of learning it, I can't figure out what I'm doing wrong. Here is the code:</p>
<pre><code>#!/usr/bin/env python
import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QApplication
from PyQt4.QtGui import QMainWindow
from PyQt4.QtGui import QTreeWidget
from PyQt4.QtGui import QTreeWidgetItem
class MyTreeItem(QTreeWidgetItem):
def __init__(self, s, parent = None):
super(MyTreeItem, self).__init__(parent, [s])
class MyTree(QTreeWidget):
def __init__(self, parent = None):
super(MyTree, self).__init__(parent)
self.setMinimumWidth(200)
self.setMinimumHeight(200)
for s in ['foo', 'bar']:
MyTreeItem(s, self)
self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*, column)'), self.onClick)
def onClick(self, item, column):
print item
class MainWindow(QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.tree = MyTree(self)
def main():
app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
<p>My initial goal is to make MyTree.onClick() print something when I click a tree item (and have access to the clicked item in this handler).</p>
| 4 | 2009-07-13T12:14:45Z | 1,119,407 | <p>You should have said</p>
<pre><code>self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClick)
</code></pre>
<p>Notice it says <strong>int</strong> rather than <em>column</em> in the first argument to <code>SIGNAL</code>. You also only need to do the <code>connect</code> call once for the tree widget, not once for each node in the tree.</p>
| 11 | 2009-07-13T13:20:59Z | [
"python",
"pyqt"
] |
How to put infinity and minus infinity in Django FloatField? | 1,119,497 | <p>I am trying to put infinity in a FloatField, but that doesn't seem to work. How do I solve this?</p>
<pre><code>f = DjangoModel(float_value=float('inf')) #ok
f.save() #crashes
</code></pre>
<p>Results in:</p>
<pre><code>Traceback (most recent call last):
...
ProgrammingError: column "inf" does not exist
LINE 1: ... "float_value") VALUES (inf)
</code></pre>
<p>I'm using Django 1.0.2 with PostgreSQL 8.3</p>
| 3 | 2009-07-13T13:38:44Z | 1,119,513 | <p>It should be 'infinity' shouldn't it? However, I don't know if that can be stored in a float field. float('infinity') returns inf, and that would be a char field.</p>
<p>Edit: Unfortunately, it is hard to say what C library Django uses without digging deep. I'd say figure out what the value stored in the float field actually is, or at least determine what is being returned. If it is indeed "inf", then that cannot be stored properly in a float field.</p>
| 0 | 2009-07-13T13:41:15Z | [
"python",
"django",
"infinity"
] |
How to put infinity and minus infinity in Django FloatField? | 1,119,497 | <p>I am trying to put infinity in a FloatField, but that doesn't seem to work. How do I solve this?</p>
<pre><code>f = DjangoModel(float_value=float('inf')) #ok
f.save() #crashes
</code></pre>
<p>Results in:</p>
<pre><code>Traceback (most recent call last):
...
ProgrammingError: column "inf" does not exist
LINE 1: ... "float_value") VALUES (inf)
</code></pre>
<p>I'm using Django 1.0.2 with PostgreSQL 8.3</p>
| 3 | 2009-07-13T13:38:44Z | 1,120,260 | <p>It seems like Djangos ORM doesn't have any special handling for this. Pythons representaton of the values are inf and -inf, while PostgrSQL wants 'Infinity' and '-Infinity'. Obviously Djangos ORM doesn't handle that conversion.</p>
<p>So you need to fix the ORM, I guess. And then think about the fact that other SQL databases may very well want other formats, or won't handle infinities at all.</p>
| 3 | 2009-07-13T15:43:01Z | [
"python",
"django",
"infinity"
] |
Live RX and TX rates in linux | 1,119,683 | <p>I'm looking for a way to programatically (whether calling a library, or a standalone program) monitor live ip traffic in linux. I don't want totals, i want the current bandwidth that is being used. I'm looking for a tool similar (but non-graphical) to OS X's istat menu's network traffic monitor.</p>
<p>I'm fairly certain something like this exists, but I'm not sure where to look, and i'd rather not have to reinvent the wheel. </p>
<p>Is it as simple as monitoring a socket? Or do I need a utility that handles alot of overhead for me?</p>
| 2 | 2009-07-13T14:12:37Z | 1,119,916 | <p>We have byte and packet counters in /proc/net/dev, so:</p>
<pre><code>import time
last={}
def diff(col): return counters[col] - last[iface][col]
while True:
print "\n%10s: %10s %10s %10s %10s"%("interface","bytes recv","bytes sent", "pkts recv", "pkts sent")
for line in open('/proc/net/dev').readlines()[2:]:
iface, counters = line.split(':')
counters = map(int,counters.split())
if iface in last:
print "%10s: %10d %10d %10d %10d"%(iface,diff(0), diff(8), diff(1), diff(9))
last[iface] = counters
time.sleep(1)
</code></pre>
| 9 | 2009-07-13T14:50:05Z | [
"c++",
"python",
"c"
] |
Live RX and TX rates in linux | 1,119,683 | <p>I'm looking for a way to programatically (whether calling a library, or a standalone program) monitor live ip traffic in linux. I don't want totals, i want the current bandwidth that is being used. I'm looking for a tool similar (but non-graphical) to OS X's istat menu's network traffic monitor.</p>
<p>I'm fairly certain something like this exists, but I'm not sure where to look, and i'd rather not have to reinvent the wheel. </p>
<p>Is it as simple as monitoring a socket? Or do I need a utility that handles alot of overhead for me?</p>
| 2 | 2009-07-13T14:12:37Z | 1,123,176 | <p>I use a little program known as <a href="http://dag.wieers.com/home-made/dstat/" rel="nofollow"><code>dstat</code></a> It combines a lot "stat" like functions into 1 quick output. Very customizable. It will give you current network throughput as well as much more. </p>
<p>In linux the program <code>netstat</code> will give you raw network statistics. You could parse these stats yourself to produce meaningful output (which is what dstat does).</p>
| 1 | 2009-07-14T02:31:08Z | [
"c++",
"python",
"c"
] |
Live RX and TX rates in linux | 1,119,683 | <p>I'm looking for a way to programatically (whether calling a library, or a standalone program) monitor live ip traffic in linux. I don't want totals, i want the current bandwidth that is being used. I'm looking for a tool similar (but non-graphical) to OS X's istat menu's network traffic monitor.</p>
<p>I'm fairly certain something like this exists, but I'm not sure where to look, and i'd rather not have to reinvent the wheel. </p>
<p>Is it as simple as monitoring a socket? Or do I need a utility that handles alot of overhead for me?</p>
| 2 | 2009-07-13T14:12:37Z | 29,800,657 | <p>You can get network throughput and packet counts using the following <code>dstat</code> command:</p>
<pre><code>dstat -n --net-packets -f 10
</code></pre>
<p>Or if you want to monitor specific interfaces, you can do:</p>
<pre><code>dstat -n --net-packets -N eth0,wlan0 10
</code></pre>
<p>If you prefer the more conventional <code>bits per second</code> output:</p>
<pre><code>dstat -n --net-packets -N eth0,wlan0 --bits 10
</code></pre>
<p>This will provide you with 10 second averages. If you prefer to write this out for post-processing, you can export to a CSV file using:</p>
<pre><code>dstat -n --net-packets -N eth0,wlan0 --bits 10
</code></pre>
<p>Dstat ships with a lot plugins to correlate these metrics to other metrics in your system, and it gives you the flexibility to add your own (python) plugins if you need to customize data or monitor something specific to your environment.</p>
| 0 | 2015-04-22T14:24:56Z | [
"c++",
"python",
"c"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,708 | <p>Have you considered running <a href="http://www.jython.org/" rel="nofollow">Jython</a> on the Java VM?</p>
| 4 | 2009-07-13T14:16:46Z | [
"java",
"python",
"integration"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,711 | <p>Why not use <a href="http://www.jython.org/">Jython</a>? The only downside I can immediately think of is if your library uses CPython native extensions.</p>
<p>EDIT: If you can use Jython <em>now</em> but think you may have problems with a later version of the library, I suggest you try to isolate the library from your app (e.g. some sort of adapter interface). Go with the simplest thing that works for the moment, then consider JNI/CPython/etc if and when you ever need to. There's little to be gained by going the (painful) JNI route unless you really have to.</p>
| 24 | 2009-07-13T14:17:25Z | [
"java",
"python",
"integration"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,714 | <p>If you can get your Python code to work in Jython, then you should be able to use that to call it from Java:</p>
<ul>
<li><a href="http://jython.sourceforge.net/cgi-bin/faqw.py?req=show&file=faq06.001.htp" rel="nofollow">http://jython.sourceforge.net/cgi-bin/faqw.py?req=show&file=faq06.001.htp</a></li>
</ul>
| 3 | 2009-07-13T14:17:55Z | [
"java",
"python",
"integration"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,735 | <p>I've investigated a similar setup with JNI. Maybe this will help if haven't seen it yet:</p>
<p><a href="http://wiki.cacr.caltech.edu/danse/index.php/Communication_between_Java_and_Python" rel="nofollow">http://wiki.cacr.caltech.edu/danse/index.php/Communication_between_Java_and_Python</a></p>
<p><a href="http://jpe.sourceforge.net/" rel="nofollow">http://jpe.sourceforge.net/</a> </p>
| 3 | 2009-07-13T14:21:39Z | [
"java",
"python",
"integration"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,752 | <p>You could use a messaging service like <a href="http://activemq.apache.org/" rel="nofollow">ActiveMQ</a>. It has both <a href="http://activemq.apache.org/python.html" rel="nofollow">Python</a> and Java support. This way, you can leave the complicated JNI or C bindings as they are and deal solely with what I consider a simple interface. Moreover, when the library gets updated, you don't need to change much, if anything.</p>
| 3 | 2009-07-13T14:24:21Z | [
"java",
"python",
"integration"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,884 | <p>Frankly <strong>most ways to somehow run Python directly from within JVM don't work</strong>. They are either not-quite-compatible (new release of your third party library can use python 2.6 features and will not work with Jython 2.5) or hacky (it will break with cryptic JVM stacktrace not really leading to solution).</p>
<p><strong>My preferred way to integrate the two would use RPC</strong>. <a href="http://en.wikipedia.org/wiki/XML-RPC">XML RPC</a> is not a bad choice here, if you have moderate amounts of data. It is pretty well supported — Python has it in its standard library. Java libraries are also easy to find. Now depending on your setup either Java or Python part would be a server accepting connection from other language.</p>
<p>A less popular but worth considering alternative way to do RPCs is Google protobuffers, which have 2/3 of support for <a href="http://code.google.com/apis/protocolbuffers/docs/reference/java-generated.html#service">nice rpc</a>. You just need to provide your transport layer. Not that much work and the convenience of writing is reasonable.</p>
<p>Another option is to write a C wrapper around that pieces of Python functionality that you need to expose to Java and use it via JVM native plugins. You can ease the pain by going with SWIG <a href="http://www.swig.org/">SWIG</a>.</p>
<p>Essentially in your case it works like that: </p>
<ol>
<li>Create a SWIG interface for all method calls from Java to C++.</li>
<li>Create C/C++ code that will receive your calls and internally call python interpreter with right params.</li>
<li>Convert response you get from python and send it via swig back to your Java code.</li>
</ol>
<p>This solution is fairly complex, a bit of an overkill in most cases. Still it is worth doing if you (for some reason) cannot afford RPCs. RPC still would be my preferred choice, though.</p>
| 10 | 2009-07-13T14:44:27Z | [
"java",
"python",
"integration"
] |
Java Python Integration | 1,119,696 | <p>I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.</p>
<p>Any thoughts on the best way to do this would be appreciated. Thanks.</p>
| 32 | 2009-07-13T14:15:23Z | 1,119,887 | <blockquote>
<p>My other thought is to use JNI to communicate with the C bindings for Python.</p>
</blockquote>
<p>I like very much <a href="https://github.com/twall/jna/">JNA</a>:</p>
<blockquote>
<p>JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java codeâno JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation.</p>
</blockquote>
<p>My 0.02$ :)</p>
| 5 | 2009-07-13T14:45:12Z | [
"java",
"python",
"integration"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,119,762 | <p>You probably want base64, not base62. There's an URL-compatible version of it floating around, so the extra two filler characters shouldn't be a problem.</p>
<p>The process is fairly simple; consider that base64 represents 6 bits and a regular byte represents 8. Assign a value from 000000 to 111111 to each of the 64 characters chosen, and put the 4 values together to match a set of 3 base256 bytes. Repeat for each set of 3 bytes, padding at the end with your choice of padding character (0 is generally useful).</p>
| 4 | 2009-07-13T14:26:05Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,119,768 | <p>Sorry, I can't help you with a library here. I would prefer using base64 and just adding to extra characters to your choice -- if possible!</p>
<p>Then you can use the base64 module.</p>
<p>If this is really, really not possible:</p>
<p>You can do it yourself this way (this is pseudo-code):</p>
<pre><code>base62vals = []
myBase = 62
while num > 0:
reminder = num % myBase
num = num / myBase
base62vals.insert(0, reminder)
</code></pre>
| 1 | 2009-07-13T14:26:58Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,119,769 | <p>There is no standard module for this, but I have written my own functions to achieve that.</p>
<pre class="lang-py prettyprint-override"><code>BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(num, alphabet=BASE62):
"""Encode a positive number in Base X
Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
num, rem = divmod(num, base)
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)
def decode(string, alphabet=BASE62):
"""Decode a Base X encoded string into the number
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
"""
base = len(alphabet)
strlen = len(string)
num = 0
idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1
return num
</code></pre>
<p>Notice the fact that you can give it any alphabet to use for encoding and decoding. If you leave the <code>alphabet</code> argument out, you are going to get the 62 character alphabet defined on the first line of code, and hence encoding/decoding to/from 62 base.</p>
<p>Hope this helps.</p>
<p>PS - For URL shorteners, I have found that it's better to leave out a few confusing characters like 0Ol1oI etc. Thus I use this alphabet for my URL shortening needs - <code>"23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"</code></p>
<p>Have fun.</p>
| 106 | 2009-07-13T14:27:01Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,119,967 | <p>you can download zbase62 module from <a href="http://pypi.python.org/pypi/zbase62" rel="nofollow">pypi</a></p>
<p>eg </p>
<pre><code>>>> import zbase62
>>> zbase62.b2a("abcd")
'1mZPsa'
</code></pre>
| 2 | 2009-07-13T15:00:35Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,123,373 | <p>Personally I like the solution from Baishampayan, mostly because of stripping the confusing characters.</p>
<p>For completeness, and solution with better performance, <a href="http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/" rel="nofollow">this post</a> shows a way to use the Python base64 module.</p>
| 1 | 2009-07-14T03:55:44Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,486,460 | <p>I have a Python library for doing exactly that here: <a href="http://www.djangosnippets.org/snippets/1431/" rel="nofollow">http://www.djangosnippets.org/snippets/1431/</a></p>
| 3 | 2009-09-28T10:59:20Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 1,487,304 | <p>The following decoder-maker works with any reasonable base, has a much tidier loop, and gives an explicit error message when it meets an invalid character.</p>
<pre><code>def base_n_decoder(alphabet):
"""Return a decoder for a base-n encoded string
Argument:
- `alphabet`: The alphabet used for encoding
"""
base = len(alphabet)
char_value = dict(((c, v) for v, c in enumerate(alphabet)))
def f(string):
num = 0
try:
for char in string:
num = num * base + char_value[char]
except KeyError:
raise ValueError('Unexpected character %r' % char)
return num
return f
if __name__ == "__main__":
func = base_n_decoder('0123456789abcdef')
for test in ('0', 'f', '2020', 'ffff', 'abqdef'):
print test
print func(test)
</code></pre>
| 8 | 2009-09-28T14:20:24Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 2,549,514 | <p>I once wrote a script to do this aswell, I think it's quite elegant :)</p>
<pre><code>import string
BASE_LIST = string.digits + string.letters + '_@'
BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST))
def base_decode(string, reverse_base=BASE_DICT):
length = len(reverse_base)
ret = 0
for i, c in enumerate(string[::-1]):
ret += (length ** i) * reverse_base[c]
return ret
def base_encode(integer, base=BASE_LIST):
if integer == 0:
return base[0]
length = len(base)
ret = ''
while integer != 0:
ret = base[integer % length] + ret
integer /= length
return ret
</code></pre>
<p>Example usage:</p>
<pre><code>for i in range(100):
print i, base_decode(base_encode(i)), base_encode(i)
</code></pre>
| 38 | 2010-03-30T23:58:33Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 4,634,454 | <p>If all you need is to generate a short ID (since you mention URL shorteners) rather than encode/decode something, this module might help:</p>
<p><a href="https://github.com/stochastic-technologies/shortuuid/" rel="nofollow">https://github.com/stochastic-technologies/shortuuid/</a></p>
| 3 | 2011-01-08T14:59:07Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 4,728,421 | <p>I have benefited greatly from others' posts here. I needed the python code originally for a Django project, but since then I have turned to node.js, so here's a <strong><em>javascript version</em></strong> of the code (the encoding part) that Baishampayan Ghose provided.</p>
<pre><code>var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function base62_encode(n, alpha) {
var num = n || 0;
var alphabet = alpha || ALPHABET;
if (num == 0) return alphabet[0];
var arr = [];
var base = alphabet.length;
while(num) {
rem = num % base;
num = (num - rem)/base;
arr.push(alphabet.substring(rem,rem+1));
}
return arr.reverse().join('');
}
console.log(base62_encode(2390687438976, "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"));
</code></pre>
| 2 | 2011-01-18T19:58:32Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 5,137,148 | <p>I wrote this a while back and it's worked pretty well (negatives and all included)</p>
<pre><code>def code(number,base):
try:
int(number),int(base)
except ValueError:
raise ValueError('code(number,base): number and base must be in base10')
else:
number,base = int(number),int(base)
if base < 2:
base = 2
if base > 62:
base = 62
numbers = [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t","u","v","w","x","y",
"z","A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"]
final = ""
loc = 0
if number < 0:
final = "-"
number = abs(number)
while base**loc <= number:
loc = loc + 1
for x in range(loc-1,-1,-1):
for y in range(base-1,-1,-1):
if y*(base**x) <= number:
final = "{}{}".format(final,numbers[y])
number = number - y*(base**x)
break
return final
def decode(number,base):
try:
int(base)
except ValueError:
raise ValueError('decode(value,base): base must be in base10')
else:
base = int(base)
number = str(number)
if base < 2:
base = 2
if base > 62:
base = 62
numbers = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f",
"g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v",
"w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L",
"M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
final = 0
if number.startswith("-"):
neg = True
number = list(number)
del(number[0])
temp = number
number = ""
for x in temp:
number = "{}{}".format(number,x)
else:
neg = False
loc = len(number)-1
number = str(number)
for x in number:
if numbers.index(x) > base:
raise ValueError('{} is out of base{} range'.format(x,str(base)))
final = final+(numbers.index(x)*(base**loc))
loc = loc - 1
if neg:
return -final
else:
return final
</code></pre>
<p>sorry about the length of it all</p>
| 1 | 2011-02-28T00:36:23Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 14,259,141 | <p>If you're looking for the highest efficiency (like django), you'll want something like the following. This code is a combination of efficient methods from Baishampayan Ghose and WoLpH and John Machin.</p>
<pre><code># Edit this list of characters as desired.
BASE_ALPH = tuple("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
BASE_DICT = dict((c, v) for v, c in enumerate(BASE_ALPH))
BASE_LEN = len(BASE_ALPH)
def base_decode(string):
num = 0
for char in string:
num = num * BASE_LEN + BASE_DICT[char]
return num
def base_encode(num):
if not num:
return BASE_ALPH[0]
encoding = ""
while num:
num, rem = divmod(num, BASE_LEN)
encoding = BASE_ALPH[rem] + encoding
return encoding
</code></pre>
<p>You may want to also calculate your dictionary in advance. (Note: Encoding with a string shows more efficiency than with a list, even with very long numbers.)</p>
<pre><code>>>> timeit.timeit("for i in xrange(1000000): base.base_decode(base.base_encode(i))", setup="import base", number=1)
2.3302059173583984
</code></pre>
<p>Encoded and decoded 1 million numbers in under 2.5 seconds. (2.2Ghz i7-2670QM)</p>
| 6 | 2013-01-10T13:33:19Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 15,694,685 | <pre><code>BASE_LIST = tuple("23456789ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz")
BASE_DICT = dict((c, v) for v, c in enumerate(BASE_LIST))
BASE_LEN = len(BASE_LIST)
def nice_decode(str):
num = 0
for char in str[::-1]:
num = num * BASE_LEN + BASE_DICT[char]
return num
def nice_encode(num):
if not num:
return BASE_LIST[0]
encoding = ""
while num:
num, rem = divmod(num, BASE_LEN)
encoding += BASE_LIST[rem]
return encoding
</code></pre>
| 1 | 2013-03-29T00:50:19Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 16,945,658 | <p>I hope the following snippet could help. </p>
<pre><code>def num2sym(num, sym, join_symbol=''):
if num == 0:
return sym[0]
if num < 0 or type(num) not in (int, long):
raise ValueError('num must be positive integer')
l = len(sym) # target number base
r = []
div = num
while div != 0: # base conversion
div, mod = divmod(div, l)
r.append(sym[mod])
return join_symbol.join([x for x in reversed(r)])
</code></pre>
<p>Usage for your case:</p>
<pre><code>number = 367891
alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print num2sym(number, alphabet) # will print '1xHJ'
</code></pre>
<p>Obviously, you can specify another alphabet, consisting of lesser or greater number of symbols, then it will convert your number to the lesser or greater number base. For example, providing '01' as an alphabet will output string representing input number as binary.</p>
<p>You may shuffle the alphabet initially to have your unique representation of the numbers. It can be helpful if you're making URL shortener service.</p>
| 2 | 2013-06-05T16:54:30Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 26,386,020 | <p>Here is an recurive and iterative way to do that. The iterative one is a little faster depending on the count of execution.</p>
<pre><code>def base62_encode_r(dec):
s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
return s[dec] if dec < 62 else base62_encode_r(dec / 62) + s[dec % 62]
print base62_encode_r(2347878234)
def base62_encode_i(dec):
s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ret = ''
while dec > 0:
ret = s[dec % 62] + ret
dec /= 62
return ret
print base62_encode_i(2347878234)
def base62_decode_r(b62):
s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
if len(b62) == 1:
return s.index(b62)
x = base62_decode_r(b62[:-1]) * 62 + s.index(b62[-1:]) % 62
return x
print base62_decode_r("2yTsnM")
def base62_decode_i(b62):
s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ret = 0
for i in xrange(len(b62)-1,-1,-1):
ret = ret + s.index(b62[i]) * (62**(len(b62)-i-1))
return ret
print base62_decode_i("2yTsnM")
if __name__ == '__main__':
import timeit
print(timeit.timeit(stmt="base62_encode_r(2347878234)", setup="from __main__ import base62_encode_r", number=100000))
print(timeit.timeit(stmt="base62_encode_i(2347878234)", setup="from __main__ import base62_encode_i", number=100000))
print(timeit.timeit(stmt="base62_decode_r('2yTsnM')", setup="from __main__ import base62_decode_r", number=100000))
print(timeit.timeit(stmt="base62_decode_i('2yTsnM')", setup="from __main__ import base62_decode_i", number=100000))
0.270266867033
0.260915645986
0.344734796766
0.311662500262
</code></pre>
| 1 | 2014-10-15T15:13:04Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 30,479,452 | <p>There is now a python library for this.</p>
<p>I'm working on making a pip package for this.</p>
<p>I recommend you use my bases.py <a href="https://github.com/kamijoutouma/bases.py" rel="nofollow">https://github.com/kamijoutouma/bases.py</a> which was inspired by bases.js</p>
<pre><code>from bases import Bases
bases = Bases()
bases.toBase16(200) // => 'c8'
bases.toBase(200, 16) // => 'c8'
bases.toBase62(99999) // => 'q0T'
bases.toBase(200, 62) // => 'q0T'
bases.toAlphabet(300, 'aAbBcC') // => 'Abba'
bases.fromBase16('c8') // => 200
bases.fromBase('c8', 16) // => 200
bases.fromBase62('q0T') // => 99999
bases.fromBase('q0T', 62) // => 99999
bases.fromAlphabet('Abba', 'aAbBcC') // => 300
</code></pre>
<p>refer to <a href="https://github.com/kamijoutouma/bases.py#known-basesalphabets" rel="nofollow">https://github.com/kamijoutouma/bases.py#known-basesalphabets</a>
for what bases are usable</p>
| 1 | 2015-05-27T10:12:10Z | [
"python",
"math",
"base62"
] |
Base 62 conversion | 1,119,722 | <p>How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').</p>
<p>I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.</p>
| 56 | 2009-07-13T14:19:41Z | 36,875,787 | <p>Here's my solution:</p>
<pre><code>def base62(a):
baseit = (lambda a=a, b=62: (not a) and '0' or
baseit(a-a%b, b*62) + '0123456789abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[a%b%61 or -1*bool(a%b)])
return baseit()
</code></pre>
<hr>
<h2>explanation</h2>
<p>In any base every number is equal to <code>a1+a2*base**2+a3*base**3...</code> So the goal is to find all the <code>a</code>s.</p>
<p>For every <code>N=1,2,3...</code> the code isolates the <code>aN*base**N</code> by "moduloing" by <code>b</code> for <code>b=base**(N+1)</code> which slices all <code>a</code>s bigger than <code>N</code>, and slicing all the <code>a</code>s so that their serial is smaller than <code>N</code> by decreasing <code>a</code> everytime the function is called recursively by the current <code>aN*base**N</code>.</p>
<p><code>Base%(base-1)==1</code> therefore <code>base**p%(base-1)==1</code> and therefore <code>q*base^p%(base-1)==q</code> with only one exception, when <code>q==base-1</code> which returns <code>0</code>. To fix that case it returns <code>0</code>. The function checks for <code>0</code> from the beginning.</p>
<hr>
<h2>advantages</h2>
<p>In this sample there's only one multiplication (instead of a division) and some modulus operations, which are all relatively fast.</p>
| 0 | 2016-04-26T21:07:57Z | [
"python",
"math",
"base62"
] |
Using Python to convert color formats? | 1,119,754 | <p>I'm working on a Python tool to convert image data into these color formats:</p>
<ul>
<li>RGB565</li>
<li>RGBA5551</li>
<li>RGBA4444.</li>
</ul>
<p>What's the simplest way to achieve this?</p>
<p>I've used the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library (PIL)</a> frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point.</p>
<p>Is there an easier way? Perhaps some type of 'formatter' plugin for PIL?</p>
<p>Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code.</p>
<p>Or is there a better library than PIL to accomplish this in Python?</p>
<p>Any tips would be appreciated. Thanks!</p>
| 2 | 2009-07-13T14:24:42Z | 1,120,077 | <p>Changing something from 8 to 5 bits is trivial. In 8 bits the value is between 0 and 255, in 5 bits it's between 8 and 31, so all you need to do is divide the value with 8. Or 4 in the case for green in RGB565 mode. Or 16 in RGBA4444 mode as it uses 4 bits per channel, etc.</p>
<p>Edit: Reading through your question again, I think there is a confusion (either with me or you). RGB555 and RGBA4444 etc are not really formats, like GIF or JPG, they are color spaces. That conversion is trivial (see above). What file format you want to save it in later is another question. Most file formats have limited support for color spaces. I think for example that JPEG always saves it in YCbCr (but I could be mistaken), GIF uses a palette (which in turn always is RGB888, I think) etc. </p>
| 1 | 2009-07-13T15:15:10Z | [
"python"
] |
Using Python to convert color formats? | 1,119,754 | <p>I'm working on a Python tool to convert image data into these color formats:</p>
<ul>
<li>RGB565</li>
<li>RGBA5551</li>
<li>RGBA4444.</li>
</ul>
<p>What's the simplest way to achieve this?</p>
<p>I've used the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library (PIL)</a> frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point.</p>
<p>Is there an easier way? Perhaps some type of 'formatter' plugin for PIL?</p>
<p>Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code.</p>
<p>Or is there a better library than PIL to accomplish this in Python?</p>
<p>Any tips would be appreciated. Thanks!</p>
| 2 | 2009-07-13T14:24:42Z | 1,299,963 | <p>There's a module called <a href="http://code.google.com/p/python-colormath/" rel="nofollow">Python Colormath</a> which provides a lot of different conversions. Highly recommended.</p>
| 1 | 2009-08-19T13:35:17Z | [
"python"
] |
Using Python to convert color formats? | 1,119,754 | <p>I'm working on a Python tool to convert image data into these color formats:</p>
<ul>
<li>RGB565</li>
<li>RGBA5551</li>
<li>RGBA4444.</li>
</ul>
<p>What's the simplest way to achieve this?</p>
<p>I've used the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library (PIL)</a> frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point.</p>
<p>Is there an easier way? Perhaps some type of 'formatter' plugin for PIL?</p>
<p>Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code.</p>
<p>Or is there a better library than PIL to accomplish this in Python?</p>
<p>Any tips would be appreciated. Thanks!</p>
| 2 | 2009-07-13T14:24:42Z | 1,561,517 | <p>I ended up doing the conversions manually as Lennart Regebro suggested.</p>
<p>However, pure Python (iterating over each pixel) turned out to be too slow.</p>
<p>My final solution used <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> to load the image and <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a> to operate on (convert) an array of pixels.</p>
| 0 | 2009-10-13T16:53:14Z | [
"python"
] |
Using Python to convert color formats? | 1,119,754 | <p>I'm working on a Python tool to convert image data into these color formats:</p>
<ul>
<li>RGB565</li>
<li>RGBA5551</li>
<li>RGBA4444.</li>
</ul>
<p>What's the simplest way to achieve this?</p>
<p>I've used the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library (PIL)</a> frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point.</p>
<p>Is there an easier way? Perhaps some type of 'formatter' plugin for PIL?</p>
<p>Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code.</p>
<p>Or is there a better library than PIL to accomplish this in Python?</p>
<p>Any tips would be appreciated. Thanks!</p>
| 2 | 2009-07-13T14:24:42Z | 1,631,026 | <p>Numpy is powerful indeed, but to get there and back to PIL requires two memory copies. Have you tried something along the following lines?</p>
<pre><code>im = Image.open('yourimage.png')
im.putdata([yourfunction(r,g,b) for (r,g,b) in im.getdata()])
</code></pre>
<p>This is quite fast (especially when you can use a lookup table). I am not familiar with the colour spaces you mention, but as I understand you know the conversion so implementation of <code>yourfunction(r,g,b)</code> should be straight forward.</p>
<p>Also <code>im.convert('RGBA', matrix)</code> might be very powerful as it is super fast in applying a colour transformation through the supplied matrix. However I have never gotten that to do what I wanted it to do... :-/</p>
| 1 | 2009-10-27T14:02:32Z | [
"python"
] |
Using Python to convert color formats? | 1,119,754 | <p>I'm working on a Python tool to convert image data into these color formats:</p>
<ul>
<li>RGB565</li>
<li>RGBA5551</li>
<li>RGBA4444.</li>
</ul>
<p>What's the simplest way to achieve this?</p>
<p>I've used the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library (PIL)</a> frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point.</p>
<p>Is there an easier way? Perhaps some type of 'formatter' plugin for PIL?</p>
<p>Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code.</p>
<p>Or is there a better library than PIL to accomplish this in Python?</p>
<p>Any tips would be appreciated. Thanks!</p>
| 2 | 2009-07-13T14:24:42Z | 4,043,391 | <p>There is also a module named <a href="http://code.google.com/p/grapefruit/" rel="nofollow">Grapefruit</a> that let you do conversions between quite a lot of color formats.</p>
| 1 | 2010-10-28T13:32:29Z | [
"python"
] |
Getting "Comment post not allowed (400)" when using Django Comments | 1,120,139 | <p>I'm going through a Django book and I seem to be stuck. The code base used in the book is .96 and I'm using 1.0 for my Django install. The portion I'm stuck at is related to Django comments (django.contrib.comments). When I submit my comments I get "Comment post not allowed (400) Why: Missing content_type or object_pk field". I've found the Django documentation to be a bit lacking in this area and I'm hoping to get some help.</p>
<p>The comment box is displayed just fine, it's when I submit the comment that I get the above error (or security warning as it truly appears).</p>
<p>My call to the comment form:</p>
<pre><code>{% render_comment_form for bookmarks.sharedbookmark shared_bookmark.id %}
</code></pre>
<p>My form.html code:</p>
<pre><code>{% if user.is_authenticated %}
<form action="/comments/post/" method="post">
<p><label>Post a comment:</label><br />
<textarea name="comment" rows="10" cols="60"></textarea></p>
<input type="hidden" name="options" value="{{ options }}" />
<input type="hidden" name="target" value="{{ target }}" />
<input type="hidden" name="gonzo" value="{{ hash }}" />
<input type="submit" name="post" value="submit comment" />
</form>
{% else %}
<p>Please <a href="/login/">log in</a> to post comments.</p>
{% endif %}
</code></pre>
<p>Any help would be much appreciated.</p>
<p>My view as requested:</p>
<pre><code>def bookmark_page(request, bookmark_id):
shared_bookmark = get_object_or_404(
SharedBookmark,
id=bookmark_id
)
variables = RequestContext(request, {
'shared_bookmark': shared_bookmark
})
return render_to_response('bookmark_page.html', variables)
</code></pre>
| 1 | 2009-07-13T15:25:50Z | 1,120,946 | <p>Django underwent a <em>huge</em> amount of change between 0.96 and 1.0, so it's not surprising you're having problems.</p>
<p>For your specific issue, see <a href="http://docs.djangoproject.com/en/dev/ref/contrib/comments/upgrade/" rel="nofollow">here</a>.</p>
<p>However I would suggest you find a more up-to-date book. It's not just the comments, but whole areas of Django are completely different from 0.96 - in particular the admin. If it's the official 'Django book', you can find the draft of version 2 (which targets Django 1.0) <a href="http://www.djangobook.com/en/2.0/" rel="nofollow">here</a>.</p>
| 0 | 2009-07-13T17:35:43Z | [
"python",
"django",
"comments"
] |
Getting "Comment post not allowed (400)" when using Django Comments | 1,120,139 | <p>I'm going through a Django book and I seem to be stuck. The code base used in the book is .96 and I'm using 1.0 for my Django install. The portion I'm stuck at is related to Django comments (django.contrib.comments). When I submit my comments I get "Comment post not allowed (400) Why: Missing content_type or object_pk field". I've found the Django documentation to be a bit lacking in this area and I'm hoping to get some help.</p>
<p>The comment box is displayed just fine, it's when I submit the comment that I get the above error (or security warning as it truly appears).</p>
<p>My call to the comment form:</p>
<pre><code>{% render_comment_form for bookmarks.sharedbookmark shared_bookmark.id %}
</code></pre>
<p>My form.html code:</p>
<pre><code>{% if user.is_authenticated %}
<form action="/comments/post/" method="post">
<p><label>Post a comment:</label><br />
<textarea name="comment" rows="10" cols="60"></textarea></p>
<input type="hidden" name="options" value="{{ options }}" />
<input type="hidden" name="target" value="{{ target }}" />
<input type="hidden" name="gonzo" value="{{ hash }}" />
<input type="submit" name="post" value="submit comment" />
</form>
{% else %}
<p>Please <a href="/login/">log in</a> to post comments.</p>
{% endif %}
</code></pre>
<p>Any help would be much appreciated.</p>
<p>My view as requested:</p>
<pre><code>def bookmark_page(request, bookmark_id):
shared_bookmark = get_object_or_404(
SharedBookmark,
id=bookmark_id
)
variables = RequestContext(request, {
'shared_bookmark': shared_bookmark
})
return render_to_response('bookmark_page.html', variables)
</code></pre>
| 1 | 2009-07-13T15:25:50Z | 1,131,472 | <p>It's not perfect, but I've worked around this. I used the form.html included with Django itself and that got me past the "Comment post not allowed (400)" message and posted my comment successfully. It includes a few other fields but since I didn't define my own form in forms.py that's to be expected I suppose. At any rate, I seem to have worked around it. Thanks for looking at my question.</p>
| 0 | 2009-07-15T13:40:57Z | [
"python",
"django",
"comments"
] |
Disabling Python nosetests | 1,120,148 | <p>When using nosetests for Python it is possible to disable a unit test by setting the test function's <code>__test__</code> attribute to false. I have implemented this using the following decorator:</p>
<pre><code>def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
<p>However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.</p>
| 30 | 2009-07-13T15:27:28Z | 1,120,180 | <p>Perhaps this will work:</p>
<pre><code>def unit_test_disabled(f):
f.__test__ = False
return f
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
| 1 | 2009-07-13T15:31:46Z | [
"python",
"nosetests"
] |
Disabling Python nosetests | 1,120,148 | <p>When using nosetests for Python it is possible to disable a unit test by setting the test function's <code>__test__</code> attribute to false. I have implemented this using the following decorator:</p>
<pre><code>def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
<p>However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.</p>
| 30 | 2009-07-13T15:27:28Z | 1,120,347 | <p>I think you will also need to rename your decorator to something that has not got test in. The below only fails on the second test for me and the first does not show up in the test suite. </p>
<pre><code>def unit_disabled(func):
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_disabled
def test_my_sample_test():
assert 1 <> 1
def test2_my_sample_test():
assert 1 <> 1
</code></pre>
| -14 | 2009-07-13T15:57:44Z | [
"python",
"nosetests"
] |
Disabling Python nosetests | 1,120,148 | <p>When using nosetests for Python it is possible to disable a unit test by setting the test function's <code>__test__</code> attribute to false. I have implemented this using the following decorator:</p>
<pre><code>def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
<p>However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.</p>
| 30 | 2009-07-13T15:27:28Z | 1,843,106 | <p>Nose already has a builtin decorator for this:</p>
<pre><code>from nose.tools import nottest
@nottest
def test_my_sample_test()
#code here ...
</code></pre>
<p>Also check out the other goodies that nose provides: <a href="https://nose.readthedocs.org/en/latest/testing_tools.html">https://nose.readthedocs.org/en/latest/testing_tools.html</a></p>
| 107 | 2009-12-03T21:39:10Z | [
"python",
"nosetests"
] |
Disabling Python nosetests | 1,120,148 | <p>When using nosetests for Python it is possible to disable a unit test by setting the test function's <code>__test__</code> attribute to false. I have implemented this using the following decorator:</p>
<pre><code>def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
<p>However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.</p>
| 30 | 2009-07-13T15:27:28Z | 7,687,714 | <p>There also is a skiptest plugin for nosetest, which will cause the test show in test output as skipped. Here is a decorator for that:</p>
<pre><code>def skipped(func):
from nose.plugins.skip import SkipTest
def _():
raise SkipTest("Test %s is skipped" % func.__name__)
_.__name__ = func.__name__
return _
</code></pre>
<p>Example output:</p>
<pre><code>$ nosetests tests
..........................................................................
..................................S.............
----------------------------------------------------------------------
Ran 122 tests in 2.160s
OK (SKIP=1)
</code></pre>
| 25 | 2011-10-07T13:08:28Z | [
"python",
"nosetests"
] |
Disabling Python nosetests | 1,120,148 | <p>When using nosetests for Python it is possible to disable a unit test by setting the test function's <code>__test__</code> attribute to false. I have implemented this using the following decorator:</p>
<pre><code>def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
<p>However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.</p>
| 30 | 2009-07-13T15:27:28Z | 28,630,874 | <p>You can also use <a href="https://docs.python.org/2/library/unittest.html#unittest.skip"><code>unittest.skip</code></a> decorator:</p>
<pre><code>import unittest
@unittest.skip("temporarily disabled")
class MyTestCase(unittest.TestCase):
...
</code></pre>
| 38 | 2015-02-20T14:06:06Z | [
"python",
"nosetests"
] |
Disabling Python nosetests | 1,120,148 | <p>When using nosetests for Python it is possible to disable a unit test by setting the test function's <code>__test__</code> attribute to false. I have implemented this using the following decorator:</p>
<pre><code>def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
</code></pre>
<p>However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.</p>
| 30 | 2009-07-13T15:27:28Z | 37,215,576 | <p><strong>You can just start the class, method or function name with an underscore and nose will ignore it.</strong></p>
<p><code>@nottest</code> has its uses but I find that it does not work well when classes derive from one another and some base classes must be ignored by nose. This happens often when I have a series of similar Django views to test. They often share characteristics that need testing. For instance, they are accessible only to users with certain permissions. Rather than write the same permission check for all of them, I put such shared test in an initial class from which the other classes derive. The problem though is that the base class is there only to be derived by the later classes and is not meant to be run on its own. Here's an example of the problem:</p>
<pre><code>from unittest import TestCase
class Base(TestCase):
def test_something(self):
print "Testing something in " + self.__class__.__name__
class Derived(Base):
def test_something_else(self):
print "Testing something else in " + self.__class__.__name__
</code></pre>
<p>And the output from running nose on it:</p>
<pre><code>$ nosetests test.py -s
Testing something in Base
.Testing something in Derived
.Testing something else in Derived
.
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
</code></pre>
<p>The <code>Base</code> class is included in the tests.</p>
<p>I cannot just slap <code>@nottest</code> on <code>Base</code> because it will mark the entire hierarchy. Indeed if you just add <code>@nottest</code> to the code above in front of <code>class Base</code>, then nose won't run any tests.</p>
<p>What I do is add an underscore in front of the base class:</p>
<pre><code>from unittest import TestCase
class _Base(TestCase):
def test_something(self):
print "Testing something in " + self.__class__.__name__
class Derived(_Base):
def test_something_else(self):
print "Testing something else in " + self.__class__.__name__
</code></pre>
<p>And when running it <code>_Base</code> is ignored:</p>
<pre><code>$ nosetests test3.py -s
Testing something in Derived
.Testing something else in Derived
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
</code></pre>
<p>This behavior is not well documented but the code that selects tests <a href="https://github.com/nose-devs/nose/blob/6f9dada1a5593b2365859bab92c7d1e468b64b7b/nose/selector.py#L72" rel="nofollow">explicitly checks for an underscore at the start of class names</a>.</p>
<p>A similar test is performed by nose on function and method names so it is possible to exclude them by adding an underscore at the start of the name.</p>
| 0 | 2016-05-13T16:59:47Z | [
"python",
"nosetests"
] |
How do you cast an instance to a derived class? | 1,120,156 | <p>I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the concept of an unapproved user, which is just like a user, with the addition of a single method.</p>
<p>The User class has some methods that return a User object. This will not work when I subclass, since I will end up having an UnapprovedUser return a User, preventing me from calling this method, among other things.</p>
<pre><code>class User(object):
base_dn = 'ou=Users,dc=example,dc=org'
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return User._from_ldap(ldap_data)
class UnapprovedUser(User):
base_dn = 'ou=UnapprovedUsers,dc=example,dc=org'
def approve(self):
new_dn = '' # the new DN
LdapUtil.move(self.dn, new_dn)
</code></pre>
<p>The <code>get()</code> and <code>_from_ldap()</code> methods are the same for both classes, though the <code>get()</code> method in UnapprovedUser needs to return an UnapprovedUser object, not a User.</p>
<p>How can I cast one of the instances of User that I get from <code>User.get()</code> into an UnapprovedUser? </p>
<p>I want to do something like:</p>
<pre><code>class UnapprovedUser(User):
# continued from before
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return (UnapprovedUser) user # invalid syntax
</code></pre>
<p>so that I can wrap the method from the parent and simply cast the returned value to the correct class. Then again, doing it that way could lead to the parent using their value for <code>self.base_dn</code>, which would break everything.</p>
| 5 | 2009-07-13T15:28:24Z | 1,120,176 | <p>Python is a dynamically-typed language, so the concept of "casting" doesn't exist. If the object is already an <code>UnapprovedUser</code>, then you can already call all methods that exist in that class, without having to cast.</p>
| 2 | 2009-07-13T15:31:17Z | [
"python",
"oop",
"inheritance"
] |
How do you cast an instance to a derived class? | 1,120,156 | <p>I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the concept of an unapproved user, which is just like a user, with the addition of a single method.</p>
<p>The User class has some methods that return a User object. This will not work when I subclass, since I will end up having an UnapprovedUser return a User, preventing me from calling this method, among other things.</p>
<pre><code>class User(object):
base_dn = 'ou=Users,dc=example,dc=org'
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return User._from_ldap(ldap_data)
class UnapprovedUser(User):
base_dn = 'ou=UnapprovedUsers,dc=example,dc=org'
def approve(self):
new_dn = '' # the new DN
LdapUtil.move(self.dn, new_dn)
</code></pre>
<p>The <code>get()</code> and <code>_from_ldap()</code> methods are the same for both classes, though the <code>get()</code> method in UnapprovedUser needs to return an UnapprovedUser object, not a User.</p>
<p>How can I cast one of the instances of User that I get from <code>User.get()</code> into an UnapprovedUser? </p>
<p>I want to do something like:</p>
<pre><code>class UnapprovedUser(User):
# continued from before
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return (UnapprovedUser) user # invalid syntax
</code></pre>
<p>so that I can wrap the method from the parent and simply cast the returned value to the correct class. Then again, doing it that way could lead to the parent using their value for <code>self.base_dn</code>, which would break everything.</p>
| 5 | 2009-07-13T15:28:24Z | 1,120,278 | <p>Rather than "casting", I think you really want to create an <code>UnapprovedUser</code> rather than a <code>User</code> when invoking <code>UnapprovedUser.get()</code>. To do that:</p>
<p>Change <code>User.get</code> to actually use the <code>cls</code> argument that's passed-in:</p>
<pre><code>@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return cls._from_ldap(ldap_data)
</code></pre>
<p>You'll need to do something similar in <code>_from_ldap</code>. You didn't list the code for <code>_from_ldap</code>, but I assume that at some point it does something like:</p>
<pre><code>result = User(... blah ...)
</code></pre>
<p>You want to replace this with:</p>
<pre><code>result = cls(... blah ...)
</code></pre>
<p>Remember: in Python a class object is a callable that constructs instances of that class. So you can use the <code>cls</code> parameter of a classmethod to construct instances of the class used to call the classmethod.</p>
| 7 | 2009-07-13T15:45:51Z | [
"python",
"oop",
"inheritance"
] |
How do you cast an instance to a derived class? | 1,120,156 | <p>I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the concept of an unapproved user, which is just like a user, with the addition of a single method.</p>
<p>The User class has some methods that return a User object. This will not work when I subclass, since I will end up having an UnapprovedUser return a User, preventing me from calling this method, among other things.</p>
<pre><code>class User(object):
base_dn = 'ou=Users,dc=example,dc=org'
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return User._from_ldap(ldap_data)
class UnapprovedUser(User):
base_dn = 'ou=UnapprovedUsers,dc=example,dc=org'
def approve(self):
new_dn = '' # the new DN
LdapUtil.move(self.dn, new_dn)
</code></pre>
<p>The <code>get()</code> and <code>_from_ldap()</code> methods are the same for both classes, though the <code>get()</code> method in UnapprovedUser needs to return an UnapprovedUser object, not a User.</p>
<p>How can I cast one of the instances of User that I get from <code>User.get()</code> into an UnapprovedUser? </p>
<p>I want to do something like:</p>
<pre><code>class UnapprovedUser(User):
# continued from before
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return (UnapprovedUser) user # invalid syntax
</code></pre>
<p>so that I can wrap the method from the parent and simply cast the returned value to the correct class. Then again, doing it that way could lead to the parent using their value for <code>self.base_dn</code>, which would break everything.</p>
| 5 | 2009-07-13T15:28:24Z | 1,120,339 | <p>In a class method, the class is passed in in the cls parameter. So instead of User.something do cls.something. Done!</p>
<p>That said, I'm not sure I would do this with two types of user. I'm not 100% sure what you mean with "Approved" here, I it seems to me to be one of two things. </p>
<ol>
<li><p>It may mean the user isn't really logged in yet. In that case I'd have a special Anonymous User instance for not logged in users. Since you are moving the DN when approving, this seems more likely to be what you are doing.</p></li>
<li><p>It may mean that the user hasn't been approved as a full member or something. This is just a special case of permission handling, and you are probably going to end up wanting to have more permissions later. I'd instead add support for giving the user roles, and making "Approved" a role.</p></li>
</ol>
<p>If you mean something else with approved, feel free to ignore this. :-)</p>
| 0 | 2009-07-13T15:56:01Z | [
"python",
"oop",
"inheritance"
] |
How do you cast an instance to a derived class? | 1,120,156 | <p>I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the concept of an unapproved user, which is just like a user, with the addition of a single method.</p>
<p>The User class has some methods that return a User object. This will not work when I subclass, since I will end up having an UnapprovedUser return a User, preventing me from calling this method, among other things.</p>
<pre><code>class User(object):
base_dn = 'ou=Users,dc=example,dc=org'
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return User._from_ldap(ldap_data)
class UnapprovedUser(User):
base_dn = 'ou=UnapprovedUsers,dc=example,dc=org'
def approve(self):
new_dn = '' # the new DN
LdapUtil.move(self.dn, new_dn)
</code></pre>
<p>The <code>get()</code> and <code>_from_ldap()</code> methods are the same for both classes, though the <code>get()</code> method in UnapprovedUser needs to return an UnapprovedUser object, not a User.</p>
<p>How can I cast one of the instances of User that I get from <code>User.get()</code> into an UnapprovedUser? </p>
<p>I want to do something like:</p>
<pre><code>class UnapprovedUser(User):
# continued from before
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return (UnapprovedUser) user # invalid syntax
</code></pre>
<p>so that I can wrap the method from the parent and simply cast the returned value to the correct class. Then again, doing it that way could lead to the parent using their value for <code>self.base_dn</code>, which would break everything.</p>
| 5 | 2009-07-13T15:28:24Z | 1,120,391 | <ul>
<li><p>super(UnapprovedUser, self) is wrong it should be super(UnapprovedUser, cls) because in class method you do not have self available</p></li>
<li><p>I will reiterate your question , in base class you are creating user and somehow you want to return derived class e.g. </p></li>
</ul>
<pre><code>
class User(object):
@classmethod
def get(cls, uid):
return User()
class UnapprovedUser(User):
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return user # invalid syntax
print UnapprovedUser.get("XXX")
</code></pre>
<p>it prints User object instead of UnapprovedUser object
here you want UnapprovedUser.get to return UnapprovedUser, for that you can create a factory function which wil return appropriate user and than fill it with ldap</p>
<pre><code>
class User(object):
@classmethod
def get(cls, uid):
return cls.getMe()
@classmethod
def getMe(cls):
return cls()
class UnapprovedUser(User):
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return user
print UnapprovedUser.get("XXX")
</code></pre>
<p>it prints UnapprovedUser object</p>
| 1 | 2009-07-13T16:04:20Z | [
"python",
"oop",
"inheritance"
] |
Platform for developing all things google? | 1,120,297 | <p>I am interested in developing things for google apps and android using python and java. I am new to both and was wondering if a environment set in <code>windows</code> or <code>linux</code> would be more productive for these tasks?</p>
| 4 | 2009-07-13T15:48:50Z | 1,120,511 | <p>Google has tools for Eclipse only for both <a href="http://developer.android.com/guide/developing/eclipse-adt.html" rel="nofollow">Android</a> and for <a href="http://code.google.com/appengine/docs/java/tools/eclipse.html" rel="nofollow">Google Apps</a>. They haven't made any other tools as far as I know.</p>
<p>Oh yeah, so to answer your question, it doesn't matter that much. Windows, Unix, or Mac, all the same really (people in our office use all of them).</p>
| 1 | 2009-07-13T16:21:04Z | [
"java",
"python",
"android",
"platform"
] |
Platform for developing all things google? | 1,120,297 | <p>I am interested in developing things for google apps and android using python and java. I am new to both and was wondering if a environment set in <code>windows</code> or <code>linux</code> would be more productive for these tasks?</p>
| 4 | 2009-07-13T15:48:50Z | 1,121,377 | <p>I'd throw down another vote for Eclipse. I've been using it on the mac and I find it to be very buggy. Not sure if that's just the nature of the beast... My experiences with it on XP have been more stable. Haven't had time to check it out on Ubuntu.</p>
| 0 | 2009-07-13T18:52:26Z | [
"java",
"python",
"android",
"platform"
] |
Platform for developing all things google? | 1,120,297 | <p>I am interested in developing things for google apps and android using python and java. I am new to both and was wondering if a environment set in <code>windows</code> or <code>linux</code> would be more productive for these tasks?</p>
| 4 | 2009-07-13T15:48:50Z | 1,122,211 | <p>Internally, I believe Google uses Eclipse running on Ubuntu for Android development, so that'd be your best bet if you're completely paranoid about avoiding all potential issues. Of course, this is impossible, and really you should just use whatever you're comfortable in.</p>
| 0 | 2009-07-13T21:34:29Z | [
"java",
"python",
"android",
"platform"
] |
Does Jython have the GIL? | 1,120,354 | <p>I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a <a href="http://journal.thobe.org/2008/03/next-step-to-increase-python.html">2008 post</a> which sort of looked like a joke at first glance but seemed to be serious at looking closer.</p>
<p><em>Edit:</em>
<strong>... and turned out to <em>be</em> a joke after looking even closer</strong>. Sorry for the confusion. Actually the comments on that post answer my question, as Nikhil has pointed out correctly.</p>
<blockquote>
<p>We realized that CPython is far ahead of us in this area, and that we are lacking in compatibility. After serious brainstorming (and a few glasses of wine), we decided that introducing a Global Interpreter Lock in Jython would solve the entire issue!</p>
</blockquote>
<p>Now, what's the status here? The <a href="http://jython.sourceforge.net/docs/differences.html">"differences" page on sourceforge</a> doesn't mention the GIL at all. Is there any official source I have overlooked?</p>
<p>Note also that I'm aware of the ongoing discussion whether the GIL matters at all, but I don't care about that for the moment.</p>
| 15 | 2009-07-13T15:58:36Z | 1,120,370 | <p>No, it does not. It's a part of the VM implementation, not the language.</p>
<p>See also:</p>
<pre><code>from __future__ import braces
</code></pre>
| 19 | 2009-07-13T16:00:43Z | [
"python",
"multithreading",
"jython"
] |
Does Jython have the GIL? | 1,120,354 | <p>I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a <a href="http://journal.thobe.org/2008/03/next-step-to-increase-python.html">2008 post</a> which sort of looked like a joke at first glance but seemed to be serious at looking closer.</p>
<p><em>Edit:</em>
<strong>... and turned out to <em>be</em> a joke after looking even closer</strong>. Sorry for the confusion. Actually the comments on that post answer my question, as Nikhil has pointed out correctly.</p>
<blockquote>
<p>We realized that CPython is far ahead of us in this area, and that we are lacking in compatibility. After serious brainstorming (and a few glasses of wine), we decided that introducing a Global Interpreter Lock in Jython would solve the entire issue!</p>
</blockquote>
<p>Now, what's the status here? The <a href="http://jython.sourceforge.net/docs/differences.html">"differences" page on sourceforge</a> doesn't mention the GIL at all. Is there any official source I have overlooked?</p>
<p>Note also that I'm aware of the ongoing discussion whether the GIL matters at all, but I don't care about that for the moment.</p>
| 15 | 2009-07-13T15:58:36Z | 1,121,385 | <p>Both <code>Jython</code> and <code>IronPython</code> "lack" the <code>GIL</code>, because it's an implementation detail of the underlying VM. There was a lot of information I've found sometime ago, now the only thing I could come up with <a href="http://74.125.93.132/search?q=cache:2E7sw0IZa8kJ:mail.python.org/pipermail/python-list/2003-October/229232.html+gil+python+jython&cd=2&hl=es&ct=clnk&gl=ar&client=firefox-a" rel="nofollow">is this</a>.</p>
<p>Remember that the <code>GIL</code> is only a problem on multiprocessor enviroment only, and that <a href="http://mail.python.org/pipermail/python-3000/2007-May/007414.html" rel="nofollow">it's unlikely to go away in the foreseable future</a> from <code>CPython</code>.</p>
| 3 | 2009-07-13T18:53:30Z | [
"python",
"multithreading",
"jython"
] |
Does Jython have the GIL? | 1,120,354 | <p>I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a <a href="http://journal.thobe.org/2008/03/next-step-to-increase-python.html">2008 post</a> which sort of looked like a joke at first glance but seemed to be serious at looking closer.</p>
<p><em>Edit:</em>
<strong>... and turned out to <em>be</em> a joke after looking even closer</strong>. Sorry for the confusion. Actually the comments on that post answer my question, as Nikhil has pointed out correctly.</p>
<blockquote>
<p>We realized that CPython is far ahead of us in this area, and that we are lacking in compatibility. After serious brainstorming (and a few glasses of wine), we decided that introducing a Global Interpreter Lock in Jython would solve the entire issue!</p>
</blockquote>
<p>Now, what's the status here? The <a href="http://jython.sourceforge.net/docs/differences.html">"differences" page on sourceforge</a> doesn't mention the GIL at all. Is there any official source I have overlooked?</p>
<p>Note also that I'm aware of the ongoing discussion whether the GIL matters at all, but I don't care about that for the moment.</p>
| 15 | 2009-07-13T15:58:36Z | 1,136,769 | <p>Google is making a Python implementation that is an modified cpython with performance improvements called unladen swallow. This will take care of removing the GIL.
See: <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan" rel="nofollow">Unladen Swallow</a></p>
| -1 | 2009-07-16T10:40:32Z | [
"python",
"multithreading",
"jython"
] |
Does Jython have the GIL? | 1,120,354 | <p>I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a <a href="http://journal.thobe.org/2008/03/next-step-to-increase-python.html">2008 post</a> which sort of looked like a joke at first glance but seemed to be serious at looking closer.</p>
<p><em>Edit:</em>
<strong>... and turned out to <em>be</em> a joke after looking even closer</strong>. Sorry for the confusion. Actually the comments on that post answer my question, as Nikhil has pointed out correctly.</p>
<blockquote>
<p>We realized that CPython is far ahead of us in this area, and that we are lacking in compatibility. After serious brainstorming (and a few glasses of wine), we decided that introducing a Global Interpreter Lock in Jython would solve the entire issue!</p>
</blockquote>
<p>Now, what's the status here? The <a href="http://jython.sourceforge.net/docs/differences.html">"differences" page on sourceforge</a> doesn't mention the GIL at all. Is there any official source I have overlooked?</p>
<p>Note also that I'm aware of the ongoing discussion whether the GIL matters at all, but I don't care about that for the moment.</p>
| 15 | 2009-07-13T15:58:36Z | 1,147,548 | <p>The quote you found was indeed a joke, here is a demo of Jython's implementation of the GIL:</p>
<pre><code>Jython 2.5.0 (trunk:6550M, Jul 20 2009, 08:40:15)
[Java HotSpot(TM) Client VM (Apple Inc.)] on java1.5.0_19
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import GIL
File "<stdin>", line 1
SyntaxError: Never going to happen!
>>>
</code></pre>
| 22 | 2009-07-18T13:35:07Z | [
"python",
"multithreading",
"jython"
] |
Join Records on Multiple Line File based on Criteria | 1,120,555 | <p>I am trying to write a python script</p>
<p>that takes record data like this</p>
<pre><code>6xxxxxxxx
7xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
6xxxxxxxx
6xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
7xxxxxxxx
</code></pre>
<p>and performs the following logic</p>
<pre><code>newline = ""
read in a record
if the record starts with a 6 and newline = ''
newline = record
if the records starts with a 7
newline = newline + record
if the record starts with a 6 and newline != ''
print newline
newline = record
</code></pre>
<p>So it should print out like this:</p>
<pre><code>6xxxxxx 7xxxxxxxx
6xxxxxx 7xxxxxxxx 7xxxxxxx 7xxxxxxx
6xxxxxx
6xxxxxx
etc..
</code></pre>
<p>Here is my code:</p>
<pre><code>han1 = open("file","r")
newline = ""
for i in han1:
if i[0] == "6" and newline == "":
newline = i
elif i[0] == "7":
newline = newline + i
elif i[0] == "6" and newline != "":
print newline
newline = ""
newline = i
han1.close()
</code></pre>
<p>When I run my script the output looks untouched. Where do you think I'm going wrong. Is it because the newline variable won't store values between iterations of the loop? Any guidance would be appreciated.</p>
| 1 | 2009-07-13T16:28:25Z | 1,120,622 | <p>None of the branches in your if statement finish with <code>newline</code> set to "". Therefore, the first branch will never evaluate because <code>newline</code> is never "" except for the very first case.</p>
| 0 | 2009-07-13T16:36:09Z | [
"python",
"file-io"
] |
Join Records on Multiple Line File based on Criteria | 1,120,555 | <p>I am trying to write a python script</p>
<p>that takes record data like this</p>
<pre><code>6xxxxxxxx
7xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
6xxxxxxxx
6xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
7xxxxxxxx
</code></pre>
<p>and performs the following logic</p>
<pre><code>newline = ""
read in a record
if the record starts with a 6 and newline = ''
newline = record
if the records starts with a 7
newline = newline + record
if the record starts with a 6 and newline != ''
print newline
newline = record
</code></pre>
<p>So it should print out like this:</p>
<pre><code>6xxxxxx 7xxxxxxxx
6xxxxxx 7xxxxxxxx 7xxxxxxx 7xxxxxxx
6xxxxxx
6xxxxxx
etc..
</code></pre>
<p>Here is my code:</p>
<pre><code>han1 = open("file","r")
newline = ""
for i in han1:
if i[0] == "6" and newline == "":
newline = i
elif i[0] == "7":
newline = newline + i
elif i[0] == "6" and newline != "":
print newline
newline = ""
newline = i
han1.close()
</code></pre>
<p>When I run my script the output looks untouched. Where do you think I'm going wrong. Is it because the newline variable won't store values between iterations of the loop? Any guidance would be appreciated.</p>
| 1 | 2009-07-13T16:28:25Z | 1,120,662 | <p>You can simplify this by simply appending a newline for a record that starts with 6, and not appending one if it doens't.</p>
<pre><code>for line in open('infile'):
if line[0] == '6':
print ''
print line.strip() ,
</code></pre>
<p>OK, this creates one empty line first in the file, and may not end the file with an newline. Still, that's easy to fix.</p>
<p>Or a solution that doens't have that problem and is closer to yours:</p>
<pre><code>newline = ''
for line in open('infile'):
if line[0] == '6':
if newline:
print newline
newline = ''
newline += ' ' + line.strip()
if newline:
print newline
</code></pre>
<p>Also works, but is slightly longer.</p>
<p>That said I think your main problem is that you don't strip the records, so you preserve the line feed.</p>
| 0 | 2009-07-13T16:44:08Z | [
"python",
"file-io"
] |
Join Records on Multiple Line File based on Criteria | 1,120,555 | <p>I am trying to write a python script</p>
<p>that takes record data like this</p>
<pre><code>6xxxxxxxx
7xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
6xxxxxxxx
6xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
7xxxxxxxx
</code></pre>
<p>and performs the following logic</p>
<pre><code>newline = ""
read in a record
if the record starts with a 6 and newline = ''
newline = record
if the records starts with a 7
newline = newline + record
if the record starts with a 6 and newline != ''
print newline
newline = record
</code></pre>
<p>So it should print out like this:</p>
<pre><code>6xxxxxx 7xxxxxxxx
6xxxxxx 7xxxxxxxx 7xxxxxxx 7xxxxxxx
6xxxxxx
6xxxxxx
etc..
</code></pre>
<p>Here is my code:</p>
<pre><code>han1 = open("file","r")
newline = ""
for i in han1:
if i[0] == "6" and newline == "":
newline = i
elif i[0] == "7":
newline = newline + i
elif i[0] == "6" and newline != "":
print newline
newline = ""
newline = i
han1.close()
</code></pre>
<p>When I run my script the output looks untouched. Where do you think I'm going wrong. Is it because the newline variable won't store values between iterations of the loop? Any guidance would be appreciated.</p>
| 1 | 2009-07-13T16:28:25Z | 1,123,029 | <p>if you file is not in GB, </p>
<pre><code>data=open("file").read().split()
a = [n for n,l in enumerate(data) if l.startswith("6") ]
for i,j in enumerate(a):
if i+1 == len(a):
r=data[a[i]:]
else:
r=data[a[i]:a[i+1]]
print ' '.join(r)
</code></pre>
| 0 | 2009-07-14T01:32:40Z | [
"python",
"file-io"
] |
Using Python to execute a command on every file in a folder | 1,120,707 | <p>I'm trying to create a Python script that would :</p>
<ol>
<li>Look into the folder "/input"</li>
<li>For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)</li>
<li>Once mencoder has finished his run, delete the original video.</li>
</ol>
<p>That doesn't seem too hard, but I suck at python :)</p>
<p>Any ideas on what the script should look like ?</p>
<p>Bonus question : Should I use</p>
<blockquote>
<p>os.system</p>
</blockquote>
<p>or</p>
<blockquote>
<p>subprocess.call</p>
</blockquote>
<p>?</p>
<p>Subprocess.call seems to allow for a more readable script, since I can write the command like this :</p>
<blockquote>
<p>cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]</p>
</blockquote>
<p>EDIT : Ok, that works :</p>
<pre><code>import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
</code></pre>
<p>I've removed the mencoder command, for clarity and because I'm still working on it.</p>
<p>Thanks to everyone for your input.</p>
| 23 | 2009-07-13T16:50:53Z | 1,120,736 | <p>To find all the filenames use <code>os.listdir()</code>.</p>
<p>Then you loop over the filenames. Like so:</p>
<pre><code>import os
for filename in os.listdir('dirname'):
callthecommandhere(blablahbla, filename, foo)
</code></pre>
<p>If you prefer subprocess, use subprocess. :-)</p>
| 41 | 2009-07-13T16:55:06Z | [
"python",
"foreach",
"mencoder"
] |
Using Python to execute a command on every file in a folder | 1,120,707 | <p>I'm trying to create a Python script that would :</p>
<ol>
<li>Look into the folder "/input"</li>
<li>For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)</li>
<li>Once mencoder has finished his run, delete the original video.</li>
</ol>
<p>That doesn't seem too hard, but I suck at python :)</p>
<p>Any ideas on what the script should look like ?</p>
<p>Bonus question : Should I use</p>
<blockquote>
<p>os.system</p>
</blockquote>
<p>or</p>
<blockquote>
<p>subprocess.call</p>
</blockquote>
<p>?</p>
<p>Subprocess.call seems to allow for a more readable script, since I can write the command like this :</p>
<blockquote>
<p>cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]</p>
</blockquote>
<p>EDIT : Ok, that works :</p>
<pre><code>import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
</code></pre>
<p>I've removed the mencoder command, for clarity and because I'm still working on it.</p>
<p>Thanks to everyone for your input.</p>
| 23 | 2009-07-13T16:50:53Z | 1,120,770 | <p>Use <a href="http://docs.python.org/library/os.html#os.walk">os.walk</a> to iterate recursively over directory content:</p>
<pre><code>import os
root_dir = '.'
for directory, subdirectories, files in os.walk(root_dir):
for file in files:
print os.path.join(directory, file)
</code></pre>
<p>No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.</p>
| 15 | 2009-07-13T17:01:45Z | [
"python",
"foreach",
"mencoder"
] |
Using Python to execute a command on every file in a folder | 1,120,707 | <p>I'm trying to create a Python script that would :</p>
<ol>
<li>Look into the folder "/input"</li>
<li>For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)</li>
<li>Once mencoder has finished his run, delete the original video.</li>
</ol>
<p>That doesn't seem too hard, but I suck at python :)</p>
<p>Any ideas on what the script should look like ?</p>
<p>Bonus question : Should I use</p>
<blockquote>
<p>os.system</p>
</blockquote>
<p>or</p>
<blockquote>
<p>subprocess.call</p>
</blockquote>
<p>?</p>
<p>Subprocess.call seems to allow for a more readable script, since I can write the command like this :</p>
<blockquote>
<p>cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]</p>
</blockquote>
<p>EDIT : Ok, that works :</p>
<pre><code>import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
</code></pre>
<p>I've removed the mencoder command, for clarity and because I'm still working on it.</p>
<p>Thanks to everyone for your input.</p>
| 23 | 2009-07-13T16:50:53Z | 1,120,814 | <p><code>AVI</code> to <code>MPG</code> (pick your extensions):</p>
<pre><code>files = os.listdir('/input')
for sourceVideo in files:
if sourceVideo[-4:] != ".avi"
continue
destinationVideo = sourceVideo[:-4] + ".mpg"
cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss',
'00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]
output1 = Popen(cmdLine, stdout=PIPE).communicate()[0]
print output1
output2 = Popen(['del', sourceVideo], stdout=PIPE).communicate()[0]
print output2
</code></pre>
| 2 | 2009-07-13T17:08:33Z | [
"python",
"foreach",
"mencoder"
] |
Using Python to execute a command on every file in a folder | 1,120,707 | <p>I'm trying to create a Python script that would :</p>
<ol>
<li>Look into the folder "/input"</li>
<li>For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)</li>
<li>Once mencoder has finished his run, delete the original video.</li>
</ol>
<p>That doesn't seem too hard, but I suck at python :)</p>
<p>Any ideas on what the script should look like ?</p>
<p>Bonus question : Should I use</p>
<blockquote>
<p>os.system</p>
</blockquote>
<p>or</p>
<blockquote>
<p>subprocess.call</p>
</blockquote>
<p>?</p>
<p>Subprocess.call seems to allow for a more readable script, since I can write the command like this :</p>
<blockquote>
<p>cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]</p>
</blockquote>
<p>EDIT : Ok, that works :</p>
<pre><code>import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
</code></pre>
<p>I've removed the mencoder command, for clarity and because I'm still working on it.</p>
<p>Thanks to everyone for your input.</p>
| 23 | 2009-07-13T16:50:53Z | 1,121,204 | <p>Or you could use the os.path.walk function, which does more work for you than just os.walk:</p>
<p>A stupid example:</p>
<pre><code>def walk_func(blah_args, dirname,names):
print ' '.join(('In ',dirname,', called with ',blah_args))
for name in names:
print 'Walked on ' + name
if __name__ == '__main__':
import os.path
directory = './'
arguments = '[args go here]'
os.path.walk(directory,walk_func,arguments)
</code></pre>
| 1 | 2009-07-13T18:24:06Z | [
"python",
"foreach",
"mencoder"
] |
Using Python to execute a command on every file in a folder | 1,120,707 | <p>I'm trying to create a Python script that would :</p>
<ol>
<li>Look into the folder "/input"</li>
<li>For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)</li>
<li>Once mencoder has finished his run, delete the original video.</li>
</ol>
<p>That doesn't seem too hard, but I suck at python :)</p>
<p>Any ideas on what the script should look like ?</p>
<p>Bonus question : Should I use</p>
<blockquote>
<p>os.system</p>
</blockquote>
<p>or</p>
<blockquote>
<p>subprocess.call</p>
</blockquote>
<p>?</p>
<p>Subprocess.call seems to allow for a more readable script, since I can write the command like this :</p>
<blockquote>
<p>cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]</p>
</blockquote>
<p>EDIT : Ok, that works :</p>
<pre><code>import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
</code></pre>
<p>I've removed the mencoder command, for clarity and because I'm still working on it.</p>
<p>Thanks to everyone for your input.</p>
| 23 | 2009-07-13T16:50:53Z | 1,121,416 | <p>Python might be overkill for this.</p>
<pre><code>for file in *; do mencoder -some options $file; rm -f $file ; done
</code></pre>
| 9 | 2009-07-13T18:58:39Z | [
"python",
"foreach",
"mencoder"
] |
Using Python to execute a command on every file in a folder | 1,120,707 | <p>I'm trying to create a Python script that would :</p>
<ol>
<li>Look into the folder "/input"</li>
<li>For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)</li>
<li>Once mencoder has finished his run, delete the original video.</li>
</ol>
<p>That doesn't seem too hard, but I suck at python :)</p>
<p>Any ideas on what the script should look like ?</p>
<p>Bonus question : Should I use</p>
<blockquote>
<p>os.system</p>
</blockquote>
<p>or</p>
<blockquote>
<p>subprocess.call</p>
</blockquote>
<p>?</p>
<p>Subprocess.call seems to allow for a more readable script, since I can write the command like this :</p>
<blockquote>
<p>cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]</p>
</blockquote>
<p>EDIT : Ok, that works :</p>
<pre><code>import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
</code></pre>
<p>I've removed the mencoder command, for clarity and because I'm still working on it.</p>
<p>Thanks to everyone for your input.</p>
| 23 | 2009-07-13T16:50:53Z | 3,583,829 | <p>I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.</p>
<p>It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD </p>
<p>I also add a small interface, hope someone else find it useful!</p>
<p>I put the code and file in here btw: <a href="http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/" rel="nofollow">http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/</a></p>
| 1 | 2010-08-27T11:53:07Z | [
"python",
"foreach",
"mencoder"
] |
Emulator Framework | 1,120,709 | <p>Are there any good open source frameworks for developing computer system emulators? I am particularly interested in something written in Python or Java that can reduce the effort involved in developing emulators for 8-bit processors (e.g. 6502, 6510, etc.).</p>
| 4 | 2009-07-13T16:51:04Z | 1,120,817 | <p>Isn't the 6510 in the C64?
You might be able to make use of the java libraries that emulate c64 code</p>
<p><a href="http://www.dreamfabric.com/c64/" rel="nofollow">http://www.dreamfabric.com/c64/</a></p>
<p><a href="http://www.jac64.com/jac64-java-based-c64-emulator.html" rel="nofollow">http://www.jac64.com/jac64-java-based-c64-emulator.html</a></p>
<p>If you aren't afraid of C++ try this general purpose one:</p>
<p><a href="http://cef.sourceforge.net/index.php" rel="nofollow">http://cef.sourceforge.net/index.php</a></p>
| 2 | 2009-07-13T17:09:11Z | [
"java",
"python",
"emulator",
"6502",
"6510"
] |
Emulator Framework | 1,120,709 | <p>Are there any good open source frameworks for developing computer system emulators? I am particularly interested in something written in Python or Java that can reduce the effort involved in developing emulators for 8-bit processors (e.g. 6502, 6510, etc.).</p>
| 4 | 2009-07-13T16:51:04Z | 1,120,882 | <p>I've developed a <a href="http://eli.thegreenplace.net/files/prog%5Fcode/perlmix.zip" rel="nofollow">complete emulator for the MIX machine</a> (Knuth's imaginary computer from TAOCP) in Perl a few years ago. The source code is well documented and the simulator is runnable, so one can practice with examples. It wasn't too difficult and I don't recall needing any special framework. The machine's registers are just state variables in the simulator, and the rest is interpreting instructions and changing this internal state.</p>
<p>Do you have more specific questions? Perhaps it will then be easier to point you in the right direction.</p>
| 1 | 2009-07-13T17:22:34Z | [
"java",
"python",
"emulator",
"6502",
"6510"
] |
Emulator Framework | 1,120,709 | <p>Are there any good open source frameworks for developing computer system emulators? I am particularly interested in something written in Python or Java that can reduce the effort involved in developing emulators for 8-bit processors (e.g. 6502, 6510, etc.).</p>
| 4 | 2009-07-13T16:51:04Z | 1,120,912 | <p>You may want to check out <a href="http://www.viceteam.org/" rel="nofollow">VICE</a>, which can emulates a variety of Commodore 8-bit computers: "the C64, the C64DTV, the C128, the VIC20, almost all PET models, the PLUS4 and the CBM-II (aka C610)". That includes 6502, 6510 and 8502 processors. VICE is released under <a href="http://www.viceteam.org/plain/COPYING" rel="nofollow">GPL</a> and is written in C.</p>
| 2 | 2009-07-13T17:31:22Z | [
"java",
"python",
"emulator",
"6502",
"6510"
] |
What's the simplest possible buildout.cfg to install Zope 2? | 1,120,758 | <p>I know that the reccomended way to install Zope is with Buildout, but I can't seem to find a simple buildout.cfg to install a minimal Zope 2 environment. There are lots to install Plone and other things.</p>
<p>I've tried:</p>
<pre><code>[buildout]
parts = zope
[zope]
recipe = plone.recipe.zope2install
eggs =
</code></pre>
<p>But I get:</p>
<pre><code>An internal error occured due to a bug in either zc.buildout or in a
recipe being used:
Traceback (most recent call last):
File "/tmp/tmp2wqykW/zc.buildout-1.3.0-py2.4.egg/zc/buildout/buildout.py", line 1519, in main
File "/tmp/tmp2wqykW/zc.buildout-1.3.0-py2.4.egg/zc/buildout/buildout.py", line 357, in install
File "/tmp/tmp2wqykW/zc.buildout-1.3.0-py2.4.egg/zc/buildout/buildout.py", line 898, in __getitem__
File "/tmp/tmp2wqykW/zc.buildout-1.3.0-py2.4.egg/zc/buildout/buildout.py", line 982, in _initialize
File "/home/analyser/site/eggs/plone.recipe.zope2install-3.1-py2.4.egg/plone/recipe/zope2install/__init__.py", line 73, in __init__
assert self.location or self.svn or self.url
AssertionError
</code></pre>
| 5 | 2009-07-13T16:59:56Z | 1,124,896 | <p>You need to tell plone.recipe.zope2install where to download Zope. Also, you'll need a zope2instance section, to create a Zope instance for you. These recipes are only needed for Zope up to version 2.11, as of 2.12 Zope has been fully eggified.</p>
<p>Here is a minimal Zope 2.11 buildout.cfg:</p>
<pre><code>[buildout]
parts = instance
[zope2]
recipe = plone.recipe.zope2install
url = http://www.zope.org/Products/Zope/2.11.3/Zope-2.11.3-final.tgz
[instance]
recipe = plone.recipe.zope2instance
zope2-location = ${zope2:location}
user = admin:admin
http-address = 127.0.0.1:8080
</code></pre>
<p>Note that the <code>instance</code> part pulls in the <code>zope2</code> part automatically as it depends on information provided by that part.</p>
<p>As of Zope 2.12 installation is fully egg based. The following sample buildout.cfg is all you need to install the latest beta:</p>
<pre><code>[buildout]
parts = scripts
extends = http://svn.zope.org/*checkout*/Zope/tags/2.12.0b3/versions.cfg
[versions]
Zope2 = 2.12.0b3
[scripts]
recipe = zc.recipe.egg:scripts
eggs = Zope2
</code></pre>
<p>Note the extends; it pulls in a list of versions for all Zope2 egg dependencies from the Zope subversion tag for 2.12.0b3, to make sure you get a stable combination of eggs. Without it you may end up with newer egg versions that have introduced incompatibilities.</p>
| 5 | 2009-07-14T11:50:25Z | [
"python",
"zope",
"buildout"
] |
Django templates: adding sections conditionally | 1,120,914 | <p>I just started using django for development. At the moment, I have the following issue: I have to write a page template able to represent different categories of data. For example, suppose I have a medical record of a patient. The represented information about this patient are, for example:</p>
<ol>
<li>name, surname and similar data</li>
<li>data about current treatments</li>
<li>..and beyond: specific data about any other analysis (eg. TAC, NMR, heart, blood, whatever)</li>
</ol>
<p>Suppose that for each entry at point 3, I need to present a specific section.
The template for this page would probably look like a long series of <code>if</code> statements, one for each data entry, which will be used only if that information is present. This would result in a very long template.</p>
<p>One possible solution is to use the <code>include</code> directive in the template, and then fragment the main template so that instead of a list of <code>if</code>'s i have a list of includes, one for each <code>if</code>.</p>
<p>Just out of curiosity, I was wondering if someone know an alternative strategy for this kind of pattern, either at the template level or at the view level.</p>
| 0 | 2009-07-13T17:31:23Z | 1,120,969 | <p>See this example: <a href="http://www.djangosnippets.org/snippets/1057/" rel="nofollow">http://www.djangosnippets.org/snippets/1057/</a></p>
<p>Essentially, you can loop through a model's fields in the template.</p>
<p>I assume you just want to display the data present in all of these different fields correct? Looping through each field should provide you with the results you're looking for.</p>
<p>Alternatively, you can set up what you want to display in the view by adding your conditionals there. It will make your view functions messier but will clean up the template. The view also makes it easier to test for the existence of certain sections.</p>
| 2 | 2009-07-13T17:39:58Z | [
"python",
"django",
"django-templates"
] |
Django templates: adding sections conditionally | 1,120,914 | <p>I just started using django for development. At the moment, I have the following issue: I have to write a page template able to represent different categories of data. For example, suppose I have a medical record of a patient. The represented information about this patient are, for example:</p>
<ol>
<li>name, surname and similar data</li>
<li>data about current treatments</li>
<li>..and beyond: specific data about any other analysis (eg. TAC, NMR, heart, blood, whatever)</li>
</ol>
<p>Suppose that for each entry at point 3, I need to present a specific section.
The template for this page would probably look like a long series of <code>if</code> statements, one for each data entry, which will be used only if that information is present. This would result in a very long template.</p>
<p>One possible solution is to use the <code>include</code> directive in the template, and then fragment the main template so that instead of a list of <code>if</code>'s i have a list of includes, one for each <code>if</code>.</p>
<p>Just out of curiosity, I was wondering if someone know an alternative strategy for this kind of pattern, either at the template level or at the view level.</p>
| 0 | 2009-07-13T17:31:23Z | 1,120,987 | <p>The answer to this depends a lot on how you've structured your data, which you don't say - are the extra bits of information in separate related tables, subclassed models, individual fields on the same model...?</p>
<p>In general, this sounds like a job for a template tag. I would probably write a custom tag that took your parent object as a parameter, and inspected the data to determine what to output. Each choice could potentially be rendered by a different sub-template, called by the tag itself.</p>
| 1 | 2009-07-13T17:43:25Z | [
"python",
"django",
"django-templates"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 1,120,938 | <p>It's really a matter of preference, but the first is probably preferable. I'd only use the second one if you don't know the name of the attribute that you're deleting ahead of time.</p>
| 12 | 2009-07-13T17:34:59Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 1,121,036 | <p>Unquestionably the former. In my view this is like asking whether <code>foo.bar</code> is better than <code>getattr(foo, "bar")</code>, and I don't think anyone is asking that question :)</p>
| 15 | 2009-07-13T17:55:06Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 1,121,068 | <p>The first is more efficient than the second. <code>del foo.bar</code> compiles to two bytecode instructions:</p>
<pre><code> 2 0 LOAD_FAST 0 (foo)
3 DELETE_ATTR 0 (bar)
</code></pre>
<p>whereas <code>delattr(foo, "bar")</code> takes five:</p>
<pre><code> 2 0 LOAD_GLOBAL 0 (delattr)
3 LOAD_FAST 0 (foo)
6 LOAD_CONST 1 ('bar')
9 CALL_FUNCTION 2
12 POP_TOP
</code></pre>
<p>This translates into the first running <em>slightly</em> faster (but it's not a huge difference â .15 μs on my machine).</p>
<p>Like the others have said, you should really only use the second form when the attribute that you're deleting is determined dynamically.</p>
<p>[Edited to show the bytecode instructions generated inside a function, where the compiler can use <code>LOAD_FAST</code> and <code>LOAD_GLOBAL</code>]</p>
| 161 | 2009-07-13T17:58:51Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 1,121,069 | <p>If you think <code>delattr</code> is more explicit, then why not used <code>getattr</code> all the time rather than <code>object.attr</code>?</p>
<p>As for under the hood... your guess is as good as mine. If not significantly better.</p>
| 0 | 2009-07-13T17:59:44Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 1,121,082 | <p>Just like getattr and setattr, delattr should only be used when the attribute name is unknown.</p>
<p>In that sense, it's roughly equivalent to several python features that are used to access built-in functionality at a lower level than you normally have available, such as <code>__import__</code> instead of <code>import</code> and <code>operator.add</code> instead of <code>+</code></p>
| 5 | 2009-07-13T18:00:48Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 1,121,103 | <p>Not sure about the inner workings, but from a code reusability and don't be a jerk coworker perspective, use del. It's more clear and understood by people coming from other languages as well.</p>
| 3 | 2009-07-13T18:03:59Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 19,380,479 | <ul>
<li><strong>del</strong> is more explicit and efficient;</li>
<li><strong>delattr</strong> allows dynamic attribute deleting.</li>
</ul>
<p>Consider the following examples:</p>
<pre><code>for name in ATTRIBUTES:
delattr(obj, name)
</code></pre>
<p>or:</p>
<pre><code>def _cleanup(self, name):
"""Do cleanup for an attribute"""
value = getattr(self, name)
self._pre_cleanup(name, value)
delattr(self, name)
self._post_cleanup(name, value)
</code></pre>
<p>You can't do it with <strong>del</strong>.</p>
| 17 | 2013-10-15T11:49:04Z | [
"python",
"del"
] |
Which is better in python, del or delattr? | 1,120,927 | <p>This may be silly, but its been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p>
| 99 | 2009-07-13T17:33:33Z | 24,630,541 | <p>It is an old question, but I would like to put my 2 cents in. </p>
<p>Though, <code>del foo.bar</code> is more elegant, at times you will need <code>delattr(foo, "bar")</code>. Say, if you have an interactive command line interface that allows a user to dynamically delete any member in the object by <em>typing the name</em>, then you have no choice but to use the latter form.</p>
| 1 | 2014-07-08T11:23:29Z | [
"python",
"del"
] |
How do you address data returned to a socket in python? | 1,120,976 | <p>Say you are telneting into IRC to figure out how it all works. As you issue commands the IRC server returns data telling you what it's doing. Once I have created a default script that basically is how a normal IRC connection between server and client occurs, if it ever deviates from that it won't tell me what is wrong. I need to be able to throw exceptions based on what the server returns to me. How do I do that in python?</p>
| 0 | 2009-07-13T17:40:52Z | 1,121,056 | <p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> is an event-driven networking engine written in Python, and includes support for <code>IRC</code> protocols. To access <code>IRC</code> functionality, import it:</p>
<pre><code>from twisted.words.protocols import irc
</code></pre>
<p>See an <a href="http://twistedmatrix.com/projects/words/documentation/examples/index.html" rel="nofollow">example here</a>: ircLogBot.py - connects to an IRC server and logs all messages. The example <code>__doc__</code>:</p>
<pre><code>"""An example IRC log bot - logs a channel's events to a file.
If someone says the bot's name in the channel followed by a ':',
e.g.
<foo> logbot: hello!
the bot will reply:
<logbot> foo: I am a log bot
Run this script with two arguments, the channel name the bot should
connect to, and file to log to, e.g.:
$ python ircLogBot.py test test.log
will log channel #test to the file 'test.log'.
"""
</code></pre>
| 0 | 2009-07-13T17:57:27Z | [
"python",
"sockets",
"irc"
] |
How do you address data returned to a socket in python? | 1,120,976 | <p>Say you are telneting into IRC to figure out how it all works. As you issue commands the IRC server returns data telling you what it's doing. Once I have created a default script that basically is how a normal IRC connection between server and client occurs, if it ever deviates from that it won't tell me what is wrong. I need to be able to throw exceptions based on what the server returns to me. How do I do that in python?</p>
| 0 | 2009-07-13T17:40:52Z | 1,121,162 | <p>Here's a tutorial which pretty much walks you through an IRC client using sockets in Python:</p>
<ul>
<li><a href="http://www.devshed.com/index2.php?option=content&task=view&id=607&pop=1&hide%5Fads=1&page=0&hide%5Fjs=1" rel="nofollow">Python and IRC</a></li>
</ul>
| 1 | 2009-07-13T18:14:26Z | [
"python",
"sockets",
"irc"
] |
Improve a IRC Client in Python | 1,121,002 | <p>How i can make some improvement in my IRC client made in Python. The improvement is: How i can put something that the user can type the <em>HOST, PORT, NICK, INDENT and REALNAME</em> strings and the message? And here is the code of the program:</p>
<blockquote>
<p>simplebot.py</p>
<pre><code>import sys
import socket
import string
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
</code></pre>
</blockquote>
<p>Remember that i'm starting in Python development. Here is where i have found this code: <a href="http://oreilly.com/pub/h/1968" rel="nofollow">http://oreilly.com/pub/h/1968</a>.Thanks.</p>
| 0 | 2009-07-13T17:47:09Z | 1,121,023 | <p>You already have the blueprint there for what you want it to do. You're doing:</p>
<pre><code>if(line[0]=="PING"):
</code></pre>
<p>No reason you couldn't adapt that scheme to accept input of <code>PORT</code>, <code>NICK</code>, etc.</p>
<p>Also, while 1 isn't very Pythonic. Yes it works, but really there is no reason not to use <code>True</code>. It's not a big deal, but it makes the code slightly more readable.</p>
| 2 | 2009-07-13T17:51:36Z | [
"python",
"sockets",
"client",
"python-3.x",
"irc"
] |
Improve a IRC Client in Python | 1,121,002 | <p>How i can make some improvement in my IRC client made in Python. The improvement is: How i can put something that the user can type the <em>HOST, PORT, NICK, INDENT and REALNAME</em> strings and the message? And here is the code of the program:</p>
<blockquote>
<p>simplebot.py</p>
<pre><code>import sys
import socket
import string
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
</code></pre>
</blockquote>
<p>Remember that i'm starting in Python development. Here is where i have found this code: <a href="http://oreilly.com/pub/h/1968" rel="nofollow">http://oreilly.com/pub/h/1968</a>.Thanks.</p>
| 0 | 2009-07-13T17:47:09Z | 1,121,110 | <p>Not a direct answer, but you should check the <code>IRC</code> implementation in <a href="http://twistedmatrix.com/" rel="nofollow">twisted</a>, an event-driven networking engine written in Python that includes support for <code>irc</code> in <code>twisted.words.protocols.irc</code>.</p>
| 1 | 2009-07-13T18:04:39Z | [
"python",
"sockets",
"client",
"python-3.x",
"irc"
] |
Improve a IRC Client in Python | 1,121,002 | <p>How i can make some improvement in my IRC client made in Python. The improvement is: How i can put something that the user can type the <em>HOST, PORT, NICK, INDENT and REALNAME</em> strings and the message? And here is the code of the program:</p>
<blockquote>
<p>simplebot.py</p>
<pre><code>import sys
import socket
import string
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
</code></pre>
</blockquote>
<p>Remember that i'm starting in Python development. Here is where i have found this code: <a href="http://oreilly.com/pub/h/1968" rel="nofollow">http://oreilly.com/pub/h/1968</a>.Thanks.</p>
| 0 | 2009-07-13T17:47:09Z | 1,121,163 | <p>If you're brand new to Python, an IRC client is quite an undertaking, especially if you haven't worked with similar clients before in other languages.</p>
<p>I would recommend you to look up on threading, so that you can put your IRC handler on a separate thread, and receive user input on another thread (If you do both on the same thread, one will block the other, making for a bad experience.)</p>
<p>To answer your question though, the simplest way to get input from the user in the console is to use <code>in =</code> <a href="http://docs.python.org/library/functions.html#raw%5Finput" rel="nofollow"><code>raw_input()</code></a>, but as I said, it will not interact well with the socket on the same thread.</p>
| 0 | 2009-07-13T18:15:05Z | [
"python",
"sockets",
"client",
"python-3.x",
"irc"
] |
Improve a IRC Client in Python | 1,121,002 | <p>How i can make some improvement in my IRC client made in Python. The improvement is: How i can put something that the user can type the <em>HOST, PORT, NICK, INDENT and REALNAME</em> strings and the message? And here is the code of the program:</p>
<blockquote>
<p>simplebot.py</p>
<pre><code>import sys
import socket
import string
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
</code></pre>
</blockquote>
<p>Remember that i'm starting in Python development. Here is where i have found this code: <a href="http://oreilly.com/pub/h/1968" rel="nofollow">http://oreilly.com/pub/h/1968</a>.Thanks.</p>
| 0 | 2009-07-13T17:47:09Z | 1,121,166 | <p>So you want the user to control the exact connection information that the IRC client uses? In order to do this, you must collect input from the user before you start your connection using the <a href="http://docs.python.org/library/functions.html#raw%5Finput" rel="nofollow">raw_input</a> function.</p>
<p>NOTE: raw_input will strip a trailing newline character.</p>
<pre><code>HOST = raw_input('Enter Host: ')
PORT = int(raw_input('Enter Port: '))
</code></pre>
<p>...for all of the values that you want the user to be able to configure.</p>
<p>Example:</p>
<pre><code>HOST = raw_input('Enter host: ')
print HOST
>>>
Enter host: stackoverflow.com
stackoverflow.com
>>>
</code></pre>
| 2 | 2009-07-13T18:15:52Z | [
"python",
"sockets",
"client",
"python-3.x",
"irc"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.