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
kill subprocess when python process is killed?
1,603,658
<p>I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.</p> <p>When I kill the main process (cntl-C) the subprocess keeps running. How do I kill the subprocess too? The subprocess is likey to run a lon...
7
2009-10-21T21:08:21Z
1,603,828
<p>subprocess.Popen objects come with a kill and a terminate method (differs in which signal you send to the process).</p> <p>signal.signal allows you install signal handlers, in which you can call the child's kill method.</p>
0
2009-10-21T21:40:35Z
[ "python", "windows", "process" ]
kill subprocess when python process is killed?
1,603,658
<p>I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.</p> <p>When I kill the main process (cntl-C) the subprocess keeps running. How do I kill the subprocess too? The subprocess is likey to run a lon...
7
2009-10-21T21:08:21Z
28,664,402
<p>You can use python <code>atexit</code> module.</p> <p>For example:</p> <pre><code>import atexit def killSubprocess(): mySubprocess.kill() atexit.register(killSubprocess) </code></pre>
0
2015-02-22T23:00:17Z
[ "python", "windows", "process" ]
CherryPy, load image from matplotlib, or in general
1,603,669
<p>I am not sure what I am doing wrong, It would be great if you could point me toward what to read. I have taken the first CherryPy tutorial "hello world" added a little matplotlib plot. Question 1: how do I know where the file will be saved? It happens to be where I am running the file. Question 2: I don't seem to be...
4
2009-10-21T21:10:33Z
1,604,037
<p>Below are some things that have worked for me, but before you proceed further I recommend that you read <a href="http://www.cherrypy.org/wiki/StaticContent">this page</a> about how to configure directories which contain static content.</p> <p><strong>Question 1: How do I know where the file will be saved?</strong>...
5
2009-10-21T22:33:32Z
[ "python", "matplotlib", "cherrypy" ]
Why is this simple python class not working?
1,603,696
<p>I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far </p> <pre><code>class getlist: def newlist(self,*number): lst=[] self.number=number lst....
2
2009-10-21T21:15:55Z
1,603,733
<p>In Python, when you are writing methods inside an object, you need to prefix all references to variables belonging to that object with self. - like so:</p> <pre><code>class getlist: def newlist(self,*number): self.lst=[] self.lst += number #I changed this to add all args to the list def ...
7
2009-10-21T21:19:11Z
[ "python", "class", "list" ]
Why is this simple python class not working?
1,603,696
<p>I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far </p> <pre><code>class getlist: def newlist(self,*number): lst=[] self.number=number lst....
2
2009-10-21T21:15:55Z
1,603,741
<p>You should use "self.lst" instead of "lst". Without the "self", it's just internal variable to current method.</p>
3
2009-10-21T21:20:12Z
[ "python", "class", "list" ]
What is the right way to design an adventure game with PyGame?
1,603,928
<p>I have started development on a small 2d adventure side view game together with a couple of people. The game will consist of the regular elements: A room, a main character, an inventory, npcs, items and puzzles. We've chosen PyGame since we all are familiar with python from before. My question is quite theoretical, ...
2
2009-10-21T22:04:28Z
1,604,115
<p>Python Adventure Writing System - <a href="http://home.fuse.net/wolfonenet/PAWS.htm" rel="nofollow">http://home.fuse.net/wolfonenet/PAWS.htm</a> - might be useful</p> <p><a href="http://proquestcombo.safaribooksonline.com/1592000770" rel="nofollow">http://proquestcombo.safaribooksonline.com/1592000770</a> may also ...
1
2009-10-21T22:55:23Z
[ "python", "design", "pygame" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the libr...
11
2009-10-21T22:08:06Z
1,603,972
<p>Take a look at what jinja2 does here:</p> <p><a href="https://github.com/mitsuhiko/jinja2/blob/5b498453b5898257b2287f14ef6c363799f1405a/jinja2/debug.py" rel="nofollow">https://github.com/mitsuhiko/jinja2/blob/5b498453b5898257b2287f14ef6c363799f1405a/jinja2/debug.py</a></p> <p>It's ugly, but it seems to do what you...
6
2009-10-21T22:13:23Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the libr...
11
2009-10-21T22:08:06Z
1,843,184
<p>What about not changing the traceback? The two things you request can both be done more easily in a different way.</p> <ol> <li>If the exception from the library is caught in the developer's code and a new exception is raised instead, the original traceback will of course be tossed. This is how exceptions are gen...
1
2009-12-03T21:52:36Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the libr...
11
2009-10-21T22:08:06Z
12,381,678
<p>You might also be interested in <a href="http://www.python.org/dev/peps/pep-3134/" rel="nofollow">PEP-3134</a>, which is implemented in python 3 and allows you to tack one exception/traceback onto an upstream exception.</p> <p>This isn't quite the same thing as modifying the traceback, but it would probably be the ...
1
2012-09-12T05:24:01Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the libr...
11
2009-10-21T22:08:06Z
13,898,994
<p>You can remove the top of the traceback easily with by raising with the tb_next element of the traceback:</p> <pre><code>except: ei = sys.exc_info() raise ei[0], ei[1], ei[2].tb_next </code></pre> <p>tb_next is a read_only attribute, so I don't know of a way to remove stuff from the bottom. You might be a...
9
2012-12-16T05:50:38Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the libr...
11
2009-10-21T22:08:06Z
39,747,516
<p>This code might be of interest for you.</p> <p>It takes a traceback and removes the first file, which should not be shown. Then it simulates the Python behavior:</p> <pre><code>Traceback (most recent call last): </code></pre> <p>will only be shown if the traceback contains more than one file. This looks exactly a...
0
2016-09-28T12:27:44Z
[ "python", "traceback" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that i...
2
2009-10-21T22:11:59Z
1,603,987
<pre><code>b = B() b.__class__ b.__class__.__base__ b.__class__.__bases__ b.__class__.__base__.__subclasses__() </code></pre> <p>I strongly recommend checking out ipython and use the tab completion :-)</p>
5
2009-10-21T22:17:47Z
[ "python", "inheritance", "oop" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that i...
2
2009-10-21T22:11:59Z
1,604,131
<p>If instead of discovery of the baseclass (i.e reflection) you know the desired class in advance you could use the following <a href="http://python.org/doc/2.5/lib/built-in-funcs.html" rel="nofollow">built in functions</a></p> <p>eg:</p> <pre><code># With classes from original Question defined &gt;&gt;&gt; instance...
0
2009-10-21T23:00:15Z
[ "python", "inheritance", "oop" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that i...
2
2009-10-21T22:11:59Z
1,604,219
<p>The inspect module is really powerful also:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inst = B() &gt;&gt;&gt; inspect.getmro(inst.__class__) (&lt;class __main__.B at 0x012B42A0&gt;, &lt;class __main__.A at 0x012B4210&gt;) </code></pre>
6
2009-10-21T23:28:10Z
[ "python", "inheritance", "oop" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that i...
2
2009-10-21T22:11:59Z
1,604,936
<p>Another way to get the class hierarchy is to access the <strong>mro</strong> attribute:</p> <pre><code>class A(object): pass class B(A): pass instance = B() print(instance.__class__.__mro__) # (&lt;class '__main__.B'&gt;, &lt;class '__main__.A'&gt;, &lt;type 'object'&gt;) </code></pre> <p>Note that in Pyth...
3
2009-10-22T03:54:54Z
[ "python", "inheritance", "oop" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
1,604,000
<p>You're probably looking for the excellent paramiko library:</p> <p><a href="http://www.paramiko.org/" rel="nofollow">http://www.paramiko.org/</a></p>
13
2009-10-21T22:22:51Z
[ "python", "ssh", "sftp" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
1,604,001
<p>paramiko works nicely: <a href="http://www.paramiko.org/" rel="nofollow">Paramiko Homepage</a></p>
4
2009-10-21T22:22:52Z
[ "python", "ssh", "sftp" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
9,101,477
<p>Depending on what you're looking to do over ssh, you might also benefit from looking at the pexpect library: <a href="http://www.noah.org/wiki/pexpect" rel="nofollow">http://www.noah.org/wiki/pexpect</a></p>
1
2012-02-01T18:51:13Z
[ "python", "ssh", "sftp" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
34,361,424
<p>For SFTP, you can use <a href="https://pypi.python.org/pypi/pysftp" rel="nofollow">pysftp</a>, which is a thin wrapper over paramiko's SFTPClient (<code>pip install sftp</code>).</p> <p>Example to download a file:</p> <pre><code>import pysftp #pip install sftp import sys hostname = "128.65.45.12" username = "bob"...
1
2015-12-18T18:00:17Z
[ "python", "ssh", "sftp" ]
how to put in transaction
1,604,021
<p>I have a class:</p> <pre><code>class AccountTransaction(db.Model): account = db.ReferenceProperty(reference_class=Account) tran_date = db.DateProperty() debit_credit = db.IntegerProperty() ## -1, 1 amount = db.FloatProperty() comment = db.StringProperty() pair = db.SelfReferenceProperty() </...
1
2009-10-21T22:29:42Z
1,605,639
<p>Because your Account entities can't all be in the same entity group, you can't perform an update in a single transaction. There are techniques to do this, particularly in the 'money transfer' case you've encountered - I wrote <a href="http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine" rel="nofollo...
1
2009-10-22T07:56:50Z
[ "python", "google-app-engine" ]
Parsing a text file with Python?
1,604,074
<p>I have to do an assignment where i have a .txt file that contains something like this<br /> p<br /> There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... </p> <p>h1<br /> this is another example of what this text file looks like </p> <p>i am suppose to write...
1
2009-10-21T22:43:22Z
1,604,104
<p>Rather than going directly from the text file you describe to an XHTML file, I would transform it into an intermediate in-memory representation first.</p> <p>So I would build classes to represent the <code>p</code> and <code>h1</code> tags, and then go through the text file and build those objects and put them into...
1
2009-10-21T22:52:25Z
[ "python", "string", "parsing", "text-files" ]
Parsing a text file with Python?
1,604,074
<p>I have to do an assignment where i have a .txt file that contains something like this<br /> p<br /> There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... </p> <p>h1<br /> this is another example of what this text file looks like </p> <p>i am suppose to write...
1
2009-10-21T22:43:22Z
1,604,888
<p>You say you're very new to Python, so I'll start at the very low-level. You can iterate over the lines in a file very simply in Python</p> <pre><code>fyle = open("contents.txt") for lyne in fyle : # Do string processing here fyle.close() </code></pre> <p>Now how to parse it. If each formatting directive (e.g...
9
2009-10-22T03:31:21Z
[ "python", "string", "parsing", "text-files" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killin...
1
2009-10-21T22:43:57Z
1,604,402
<p>You could use a thread approach (maybe setting the <a href="http://docs.python.org/library/threading.html#threading.Thread.daemon" rel="nofollow">Thead.daemon</a> property would help--but I'm not sure). </p> <p>However, I would suggest looking into a task queuing system. You can place a task on a queue (which is v...
0
2009-10-22T00:28:54Z
[ "python", "pylons", "paste" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killin...
1
2009-10-21T22:43:57Z
1,639,490
<p>I think the best solution is messaging system because it can be configured to not loose the task if the pylons process goes down. I would always use processes over threads especially in this case. If you are using python 2.6+ use the built in <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollo...
0
2009-10-28T19:19:36Z
[ "python", "pylons", "paste" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killin...
1
2009-10-21T22:43:57Z
1,768,292
<p>Take a look at gearman, it was specifically made for farming out tasks to 'workers' to handle. They can even handle it in a different language entirely. You can come back and ask if the task was completed, or just let it complete. That should work well for many tasks.</p> <p>If you absolutely need to ensure it was ...
0
2009-11-20T04:10:49Z
[ "python", "pylons", "paste" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killin...
1
2009-10-21T22:43:57Z
1,843,498
<p>To answer your basic question directly, you should be able to use threads just as you'd like. The "killing hung threads" part is paste cleaning up its own threads, not yours.</p> <p>There are other packages that might help, etc, but I'd suggest you start with simple threads and see how far you get. Only then will...
0
2009-12-03T22:36:41Z
[ "python", "pylons", "paste" ]
Interacting with SVN from appengine
1,604,220
<p>I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine.</p> <ul> <li>Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)</li> <li>Commit changes to the svn (this...
5
2009-10-21T23:28:20Z
1,604,249
<p>you can try using <a href="http://svnkit.com/" rel="nofollow">SVNKit</a> with the java runtime</p>
4
2009-10-21T23:39:30Z
[ "java", "python", "svn", "google-app-engine" ]
Interacting with SVN from appengine
1,604,220
<p>I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine.</p> <ul> <li>Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)</li> <li>Commit changes to the svn (this...
5
2009-10-21T23:28:20Z
1,604,792
<p>DryDrop (<a href="http://drydrop.binaryage.com/" rel="nofollow">http://drydrop.binaryage.com/</a>) is a Git based solution you may want to look at for comparison of what you're trying to do.</p>
3
2009-10-22T03:00:42Z
[ "java", "python", "svn", "google-app-engine" ]
Interacting with SVN from appengine
1,604,220
<p>I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine.</p> <ul> <li>Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)</li> <li>Commit changes to the svn (this...
5
2009-10-21T23:28:20Z
3,500,644
<p>You can talk to a svn server(if setup with apache running <a href="http://svnbook.red-bean.com/en/1.0/ch06s04.html" rel="nofollow">mod_dav_svn</a>) using the <a href="http://en.wikipedia.org/wiki/WebDAV" rel="nofollow">webdav</a> protocol. See <a href="http://svn.apache.org/repos/asf/subversion/trunk/notes/http-and-...
1
2010-08-17T08:32:32Z
[ "java", "python", "svn", "google-app-engine" ]
Do dictionaries in Python have a single repr value?
1,604,281
<p>In this <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key">question</a>, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?</p...
2
2009-10-21T23:50:34Z
1,604,299
<p>That's not the case -- key ordering is arbitrary.</p> <p>If you'd like to use a dictionary as a key, it should be converted into a fixed form (such as a sorted tuple). Of course, this won't work for dictionaries with non-hashable values.</p>
2
2009-10-21T23:55:59Z
[ "python" ]
Do dictionaries in Python have a single repr value?
1,604,281
<p>In this <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key">question</a>, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?</p...
2
2009-10-21T23:50:34Z
1,604,310
<p>No, the order that keys are added to a dictionary can affect the internal data structure. When two items have the same hash value and end up in the same bucket then the order they are added to the dictionary matters.</p> <pre><code>&gt;&gt;&gt; (1).__hash__() 1 &gt;&gt;&gt; (1 &lt;&lt; 32).__hash__() 1 &gt;&gt;&gt;...
6
2009-10-21T23:59:28Z
[ "python" ]
Do dictionaries in Python have a single repr value?
1,604,281
<p>In this <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key">question</a>, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?</p...
2
2009-10-21T23:50:34Z
1,604,375
<p>If you want to store a dictionary in another dictionary, there is no need to do any transformations first. If you want to use a dictionary as the key to another dictionary, then you need to transform it, ideally into a sorted tuple of key/value tuples.</p>
0
2009-10-22T00:21:25Z
[ "python" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in...
5
2009-10-22T00:25:16Z
1,604,398
<p>Not a direct answer to your question but O'Reilly's <a href="http://rads.stackoverflow.com/amzn/click/0596008678" rel="nofollow">Head First Object-Oriented Analysis and Design</a> is an excellent place to start.</p> <p>Followed by <a href="http://rads.stackoverflow.com/amzn/click/0596007124" rel="nofollow">Head Fir...
5
2009-10-22T00:27:50Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in...
5
2009-10-22T00:25:16Z
1,604,403
<p>"My data is basically a list of accounts"</p> <p>Account is a class.</p> <p>"dicts that represent transactions"</p> <p>Transaction appears to be a class. You happen to have elected to represent this as a dict.</p> <p>That's your first pass at OO design. Focus on the Responsibilities and Collaborators.</p> <p>...
3
2009-10-22T00:29:07Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in...
5
2009-10-22T00:25:16Z
1,604,426
<p>There are many 'mindsets' that you could adopt to help in the design process (some of which point towards OO and some that don't). I think it is often better to start with questions rather than answers (i.e. rather than say, 'how can I apply inheritance to this' you should ask how this system might expect to change ...
1
2009-10-22T00:37:55Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in...
5
2009-10-22T00:25:16Z
1,604,427
<p>You don't have to throw out structured programming to do object-oriented programming. The code is still structured, it just belongs to the objects rather than being separate from them.</p> <p>In classical programming, code is the driving force that operates on data, leading to a dichotomy (and the possibility that ...
7
2009-10-22T00:38:02Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in...
5
2009-10-22T00:25:16Z
1,604,703
<p>Rather than using dicts to represent your transactions, a better container would be a namedtuple from the collections module. A namedtuple is a subclass of tuple which allows you to reference it's items by name as well as index number.</p> <p>Since you may possibly have thousands of transactions in your journal li...
-1
2009-10-22T02:18:27Z
[ "python", "oop" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
1,604,605
<p>A couple of implementations (just an illustration, not intended for use):</p> <pre><code>def to_int(bin): x = int(bin, 2) if bin[0] == '1': # "sign bit", big-endian x -= 2**len(bin) return x def to_int(bin): # from definition n = 0 for i, b in enumerate(reversed(bin)): if b == '1...
1
2009-10-22T01:42:08Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
1,604,701
<pre><code>&gt;&gt;&gt; bits_in_word=12 &gt;&gt;&gt; int('111111111111',2)-(1&lt;&lt;bits_in_word) -1 </code></pre> <p>This works because:</p> <blockquote> <p>The two's complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2^N ...
6
2009-10-22T02:17:14Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
1,605,553
<p>It's not built in, but if you want unusual length numbers then you could use the <a href="http://python-bitstring.googlecode.com" rel="nofollow">bitstring</a> module.</p> <pre><code>&gt;&gt;&gt; from bitstring import Bits &gt;&gt;&gt; a = Bits(bin='111111111111') &gt;&gt;&gt; a.int -1 </code></pre> <p>The same obj...
13
2009-10-22T07:30:14Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
9,147,327
<p>DANGER: gnibbler's answer (currently the highest ranked) isn't correct.<br> Sadly, I can't figure out how to add a comment to it.</p> <p>Two's compliment subtracts off <code>(1&lt;&lt;bits)</code> if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.</p> <p>A function for two's co...
40
2012-02-05T06:14:32Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
26,534,436
<p>Since erikb85 brought up performance, here's <a href="http://stackoverflow.com/a/9147327/908494">travc's answer</a> against <a href="http://stackoverflow.com/a/1605553/908494">Scott Griffiths'</a>:</p> <pre><code>In [534]: a = [0b111111111111, 0b100000000000, 0b1, 0] * 1000 In [535]: %timeit [twos_comp(x, 12) for x...
0
2014-10-23T18:03:44Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
29,036,858
<p>I'm using Python 3.4.0</p> <p>In Python 3 we have some problems with data types transformation.</p> <p>So... here I'll tell a tip for those (like me) that works a lot with hex strings.</p> <p>I'll take an hex data and make an complement it:</p> <pre><code>a = b'acad0109' compl = int(a,16)-pow(2,32) result=hex(...
0
2015-03-13T16:03:20Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
32,262,478
<p>Unfortunately there is no built-in function to cast an unsigned integer to a two's complement signed value, but we can define a function to do so using bitwise operations:</p> <pre><code>def s12(value): return -(value &amp; 0b100000000000) | (value &amp; 0b011111111111) </code></pre> <p>The first bitwise-and o...
0
2015-08-28T02:32:41Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
36,338,336
<p>This will give you the two's complement efficiently using bitwise logic:</p> <pre><code>def twos_complement(value, bitWidth): if value &gt;= 2**bitWidth: # This catches when someone tries to give a value that is out of range raise ValueError("Value: {} out of range of {}-bit value.".format(value...
0
2016-03-31T16:01:15Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
37,075,643
<p>Since Python 3.2, there are built-in functions for byte manipulation: <a href="https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes" rel="nofollow">https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes</a>.</p> <p>By combining to_bytes and from_bytes, you get</p> <pre class="lang-py prettyprint-...
0
2016-05-06T15:01:34Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
38,088,563
<p>This works for 3 bytes. <a href="https://repl.it/C6zx/3" rel="nofollow">Live code is here</a></p> <pre><code>def twos_compliment(byte_arr): a = byte_arr[0]; b = byte_arr[1]; c = byte_arr[2] out = ((a&lt;&lt;16)&amp;0xff0000) | ((b&lt;&lt;8)&amp;0xff00) | (c&amp;0xff) neg = (a &amp; (1&lt;&lt;7) != 0) # fi...
0
2016-06-29T00:51:41Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
38,703,883
<p>It's much easier than all that...</p> <p>for X on N bits: Comp = (-X) &amp; (2**N - 1)</p> <pre><code>def twoComplement(number, nBits): return (-number) &amp; (2**nBits - 1) </code></pre>
0
2016-08-01T16:36:29Z
[ "python", "bit-manipulation", "twos-complement" ]
How to get output?
1,604,811
<p>I am using the Python/C API with my app and am wondering how you can get console output with a gui app. When there is a script error, it is displayed via printf but this obviously has no effect with a gui app. I want to be able to obtain the output without creating a console. Can this be done?</p> <p>Edit - Im usin...
0
2009-10-22T03:06:24Z
1,604,822
<p>Use the <a href="http://www.python.org/doc/2.5/lib/module-logging.html" rel="nofollow"><code>logging</code></a> package instead of printf. You can use something similar if you need to log output from a C function.</p>
1
2009-10-22T03:10:24Z
[ "python", "user-interface" ]
How to get output?
1,604,811
<p>I am using the Python/C API with my app and am wondering how you can get console output with a gui app. When there is a script error, it is displayed via printf but this obviously has no effect with a gui app. I want to be able to obtain the output without creating a console. Can this be done?</p> <p>Edit - Im usin...
0
2009-10-22T03:06:24Z
1,604,842
<p>If by <code>printf</code> you mean exactly thqt call from C code, you need to redirect (and un-buffer) your standard output (file descriptor 0) to somewhere you can pick up the data from -- far from trivial, esp. in Windows, although maybe doable. But why not just change that call in your C code to something more s...
1
2009-10-22T03:16:37Z
[ "python", "user-interface" ]
Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll
1,605,006
<p>I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:</p> <blockquote> <p>error MSVCP90.dll: No such file or directory. </p> </blockquote> <p>I have already d...
9
2009-10-22T04:20:01Z
1,605,012
<p>Yes you should have it. You have to exclude it from py2exe.</p> <pre><code>options = { 'py2exe': { 'dll_excludes': [ 'MSVCP90.dll' ] } } setup(windows=["main.py"], options=options) </code></pre>
8
2009-10-22T04:21:42Z
[ "python", "dll", "wxwidgets", "py2exe", "gui2exe" ]
Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll
1,605,006
<p>I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:</p> <blockquote> <p>error MSVCP90.dll: No such file or directory. </p> </blockquote> <p>I have already d...
9
2009-10-22T04:20:01Z
5,768,777
<p>what you need is to go to microsoft's download site and get visual C++ 2008 redistributed package. Tell it to do a repair and search for the driver. Copy the driver to the DLL folder in the python directory</p>
1
2011-04-24T05:15:50Z
[ "python", "dll", "wxwidgets", "py2exe", "gui2exe" ]
What files do I need to include with my Python app?
1,605,022
<p>I have an app that uses the python/c api and I was wondering what files I need to distribute with it? The app runs on Windows and links with libpython31.a Are there any other files? I tried the app on a seperate Win2k system and it said that python31.dll was needed so theres at least one.</p> <p>Edit - My app is wr...
2
2009-10-22T04:29:08Z
1,605,039
<p>The best way to tell is to try it on 'clean' installations of windows and see what it complains about. Virtual machines are a good way to do that.</p>
2
2009-10-22T04:36:50Z
[ "python", "file", "runtime" ]
What files do I need to include with my Python app?
1,605,022
<p>I have an app that uses the python/c api and I was wondering what files I need to distribute with it? The app runs on Windows and links with libpython31.a Are there any other files? I tried the app on a seperate Win2k system and it said that python31.dll was needed so theres at least one.</p> <p>Edit - My app is wr...
2
2009-10-22T04:29:08Z
1,605,079
<p>You'll need at least Python's own DLL (release-specific) and the wincrt DLL version it requires, also Python version depended (if you want to run on releases of Windows that don't come with that DLL). The popular <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>, the not-widely-know but hugely powerful <a ...
1
2009-10-22T04:54:39Z
[ "python", "file", "runtime" ]
python fileinput changes permission
1,605,288
<p>In my python code, I use the fileinput module for inplace replacing:</p> <pre><code>import fileinput for line in fileinput.FileInput("permission.txt",inplace=1): line = line.strip() if not 'def' in line: print line else: line=line.replace(line,'zzz') print line fileinput.close...
1
2009-10-22T06:05:50Z
1,605,340
<p>If you can help it, don't run your script as root.</p> <p><strong>EDIT</strong> Well, the answer has been accepted, but it's not really much of an answer. In case you must run the script as root (or indeed as any other user), you can use <a href="http://docs.python.org/library/os.html#os.stat" rel="nofollow"><code>...
0
2009-10-22T06:23:03Z
[ "python", "file-permissions", "file-io" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This do...
7
2009-10-22T06:25:24Z
1,605,380
<p>This does the trick, but requires python-gtk:</p> <pre><code>import gtk.gdk import sys def PixelAt(x, y): w = gtk.gdk.get_default_root_window() sz = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) pix...
7
2009-10-22T06:37:29Z
[ "python", "linux", "shell", "imagemagick", "image" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This do...
7
2009-10-22T06:25:24Z
1,605,631
<p>If you are using KDE4 there is a Color Picker Widget that you can add to either your panel or your Desktop. To add the widget either right click on the Desktop and choose add widget OR right click on the panel and choose Panel Options > Add Widgets </p>
1
2009-10-22T07:53:59Z
[ "python", "linux", "shell", "imagemagick", "image" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This do...
7
2009-10-22T06:25:24Z
20,907,085
<p>Here is a much faster function based on <em>richq</em>'s <a href="http://stackoverflow.com/a/1605380">answer</a>.<br> This one reads only one pixel from the screen instead of getting a huge array of all the pixels.</p> <pre><code>import gtk.gdk def pixel_at(x, y): rw = gtk.gdk.get_default_root_window() pix...
3
2014-01-03T15:29:46Z
[ "python", "linux", "shell", "imagemagick", "image" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This do...
7
2009-10-22T06:25:24Z
27,406,714
<p>Using gi.repository Gdk, it's even smaller and works on either Python 2 or 3:</p> <pre><code>#!/usr/bin/python3 # Print RGB color values of screen pixel at location x, y from gi.repository import Gdk import sys def PixelAt(x, y): w = Gdk.get_default_root_window() pb = Gdk.pixbuf_get_from_window(w, x, y, 1, 1) ...
1
2014-12-10T17:01:34Z
[ "python", "linux", "shell", "imagemagick", "image" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,670
<p>Havent used django in a while, but i seem to remember that syncdb does perform alter commands on db tables. you have to drop the table then run again and it will create again.</p> <p>edit: sorry does NOT perform alter.</p>
2
2009-10-22T08:08:24Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,673
<h2>From Django 1.7 onwards</h2> <p>Django has built in support for migrations - take a look at <a href="https://docs.djangoproject.com/en/dev/topics/migrations/">the documentation</a>.</p> <h2>For Django 1.6 and earlier</h2> <p>Django doesn't support migrations out of the box. There is a pluggable app for Django th...
99
2009-10-22T08:09:17Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,680
<p>Django currently does not do this automatically. Your options are:</p> <ol> <li>Drop the table from the database, then recreate it in new form using syncdb.</li> <li>Print out SQL for the database using <code>python manage.py sql (appname)</code>, find the added line for the field and add it manually using <code>al...
13
2009-10-22T08:11:31Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,694
<p>Follow these steps:</p> <ol> <li>Export your data to a fixture using the <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs#dumpdata">dumpdata</a> management command</li> <li>Drop the table</li> <li>Run syncdb</li> <li>Reload your data from the fixture using the <a href="http://docs.django...
11
2009-10-22T08:15:01Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
6,127,375
<p>As suggested in top answer, I tried using <a href="http://south.aeracode.org/">South</a>, and after an hour of frustration with <a href="http://stackoverflow.com/questions/4840102/how-come-my-south-migrations-doesnt-work-for-django">obscure migration errors</a> decided to go with <a href="http://code.google.com/p/dj...
8
2011-05-25T15:57:56Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
27,652,020
<p>If you run Django with Apache and MySQL, restart apache after making migration with <em>makemigrations</em>.</p>
0
2014-12-26T01:22:51Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
37,202,110
<p>In django <strong>1.6</strong></p> <ul> <li><p>At first we have run - <code>python manage.py sql &lt;app name&gt;</code></p></li> <li><p>Then we have to run - <code>python manage.py syncdb</code></p></li> </ul>
0
2016-05-13T05:49:54Z
[ "python", "django", "django-models" ]
Django: How to detect if translation is activated?
1,605,706
<p><code>django.utils.translation.get_language()</code> returns default locale if translation is not activated. Is there a way to find out whether the translation is activated (via <code>translation.activate()</code>) or not?</p>
2
2009-10-22T08:18:24Z
1,696,958
<p>Always inspect source code for such question, it's faster than posting to Web!</p> <p>Django does it's black magic behind the scene, and uses some kind of dispatcher to simulate disabled translations.</p> <p>The best way for you to do is:</p> <pre><code>import setttings assert settings.USE_i18N == True </code></p...
-2
2009-11-08T15:59:48Z
[ "python", "django", "internationalization" ]
Django: How to detect if translation is activated?
1,605,706
<p><code>django.utils.translation.get_language()</code> returns default locale if translation is not activated. Is there a way to find out whether the translation is activated (via <code>translation.activate()</code>) or not?</p>
2
2009-10-22T08:18:24Z
2,450,201
<p>Horribly hacky, but should work in at least 1.1.1:</p> <pre><code>import django.utils.translation.trans_real as trans from django.utils.thread_support import currentThread def isactive(): return currentThread() in trans._active </code></pre>
2
2010-03-15T20:22:18Z
[ "python", "django", "internationalization" ]
Django: How to detect if translation is activated?
1,605,706
<p><code>django.utils.translation.get_language()</code> returns default locale if translation is not activated. Is there a way to find out whether the translation is activated (via <code>translation.activate()</code>) or not?</p>
2
2009-10-22T08:18:24Z
2,450,262
<p>Depends on application and architecture...</p> <p>Hack provided by Ignacio should works, but what is you will run in non activated yet thread?</p> <p>I would use Ignacio solution + add Queue visible by all threads, monkeypatch trans_real.activate function and set attribute in queue.</p>
0
2010-03-15T20:31:13Z
[ "python", "django", "internationalization" ]
How to modify the Python 'default' dictionary so that it always returns a default value
1,605,750
<p>I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED". </p> <p>I don't want to use <code>d.get(key,default)</code> but access dictionaries by <code>d[key]</code> so that if the key is not in d, it returns the default (that is ...
3
2009-10-22T08:27:22Z
1,605,802
<p>If you can migrate to Python 2.5, there is the <em>defaultdict</em> class, as shown <a href="http://docs.python.org/library/collections.html#collections.defaultdict">here</a>. You can pass it an initializer that returns what you want. Otherwise, you'll have to roll your own implementation of it, I fear.</p>
9
2009-10-22T08:37:59Z
[ "python", "dictionary", "python-2.4" ]
How to modify the Python 'default' dictionary so that it always returns a default value
1,605,750
<p>I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED". </p> <p>I don't want to use <code>d.get(key,default)</code> but access dictionaries by <code>d[key]</code> so that if the key is not in d, it returns the default (that is ...
3
2009-10-22T08:27:22Z
1,605,909
<p>If you can, use <a href="http://stackoverflow.com/questions/1605750/how-to-modify-the-python-default-dictionary-so-that-it-always-returns-a-default/1605802#1605802">Mario's solution</a>. </p> <p>If you can't, you just have to subclass a dictionary-like object. Now, you can do that by inheriting directly from "dict"...
4
2009-10-22T09:00:38Z
[ "python", "dictionary", "python-2.4" ]
How to modify the Python 'default' dictionary so that it always returns a default value
1,605,750
<p>I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED". </p> <p>I don't want to use <code>d.get(key,default)</code> but access dictionaries by <code>d[key]</code> so that if the key is not in d, it returns the default (that is ...
3
2009-10-22T08:27:22Z
23,388,871
<p>You can use the following class (tested in Python 2.7) Just change zero to any default value you like.</p> <pre><code>class cDefaultDict(dict): # dictionary that returns zero for missing keys # keys with zero values are not stored def __missing__(self,key): return 0 def __setitem__(self, k...
0
2014-04-30T13:03:33Z
[ "python", "dictionary", "python-2.4" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to...
1
2009-10-22T08:48:48Z
1,605,869
<p>To left-align instead of right-align, use <code>%-15s</code> instead of <code>%15s</code>.</p>
4
2009-10-22T08:51:24Z
[ "printing", "python", "string-formatting" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to...
1
2009-10-22T08:48:48Z
1,605,950
<p>Seeing that <code>p</code> seems to be a dict, how about:</p> <pre><code>print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p </code></pre>
2
2009-10-22T09:08:09Z
[ "printing", "python", "string-formatting" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to...
1
2009-10-22T08:48:48Z
1,605,963
<p>Or if your using python 2.6 you can use the <a href="http://docs.python.org/library/string.html?#string-formatting" rel="nofollow">format</a> method of the string:</p> <p>This defines a dictionary of values, and uses them for dipslay:</p> <pre><code>&gt;&gt;&gt; values = {'total':93, 'name':'john', 'x':33, 'y':993...
3
2009-10-22T09:11:29Z
[ "printing", "python", "string-formatting" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to...
1
2009-10-22T08:48:48Z
1,605,974
<p>Slightly off topic, but you can avoid performing explicit addition on <code>tot</code> using <a href="http://docs.python.org/3.1/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p> <pre><code>for tot, p in enumerate(players, start=1): print '...' </code></pre>
4
2009-10-22T09:13:05Z
[ "printing", "python", "string-formatting" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can d...
1
2009-10-22T09:50:15Z
1,606,215
<p>I'd split the range into a tuple and then inside your class, keep the items in an ordered list. You can use the <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a> module to make inserts O(n) and lookup O(logn).</p> <p>If you are converting a dict to your new class, you can build an unord...
5
2009-10-22T10:03:09Z
[ "python", "types" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can d...
1
2009-10-22T09:50:15Z
1,606,305
<p>If your integers have an upper bound that's less than a few million, then you simply expand the ranges into individual values.</p> <pre><code>class RangedDict( dict ): def addRange( self, iterator, value ): for k in iterator: self[k]= value d= RangedDict() d.addRange( xrange(0,257), "FOO" )...
2
2009-10-22T10:24:09Z
[ "python", "types" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can d...
1
2009-10-22T09:50:15Z
1,606,333
<pre><code>class dict2(dict): def __init__(self,obj): dict.__init__(self,obj) def __getitem__(self,key): if self.has_key(key): return super(dict2,self).__getitem__(key) else: for k in self: if '-' in k: ...
0
2009-10-22T10:30:21Z
[ "python", "types" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can d...
1
2009-10-22T09:50:15Z
1,606,561
<p>Given that you don't have any "gaps" in your keys, why you just don't store the beginning of each segment and then lookup with bisect like suggested?</p> <pre><code>doodahs = ( (0, "FOO"), (257, "BAR"), (258, "FISH"), (279, "MOOSE"), (280, "Darth Vader"), (65535, "Death to all newbies") ) </...
1
2009-10-22T11:24:08Z
[ "python", "types" ]
How can I make HTML safe for web browser with python?
1,606,201
<p>How can I make HTML from email safe to display in web browser with python?</p> <p>Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet.</p> <p>Other than spam emails should be displayed as closely as possible like i...
1
2009-10-22T10:00:21Z
1,606,315
<p>Use the HTMLparser module, or install BeautifulSoup, and use those to parse the HTML and disable or remove the tags. This will leave whatever link text was there, but it will not be highlighted and it will not be clickable, since you are displaying it with a web browser component.</p> <p>You could make it clearer ...
0
2009-10-22T10:25:27Z
[ "python", "html", "email", "browser", "html-sanitizing" ]
How can I make HTML safe for web browser with python?
1,606,201
<p>How can I make HTML from email safe to display in web browser with python?</p> <p>Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet.</p> <p>Other than spam emails should be displayed as closely as possible like i...
1
2009-10-22T10:00:21Z
1,611,676
<p><a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a> contains an HTML+CSS sanitizer. It allows too much currently, but it shouldn't be too hard to modify it to match the use case.</p> <p>Found it from <a href="http://jacobian.org/writing/untrusted-users-and-html/" rel="nofollow">here</a>.</p>
1
2009-10-23T06:26:45Z
[ "python", "html", "email", "browser", "html-sanitizing" ]
How can I make HTML safe for web browser with python?
1,606,201
<p>How can I make HTML from email safe to display in web browser with python?</p> <p>Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet.</p> <p>Other than spam emails should be displayed as closely as possible like i...
1
2009-10-22T10:00:21Z
1,611,820
<p>I'm not quite clear with what exactly you mean with "safe". It's a pretty big topic... but, for what it's worth:</p> <p>In my opinion, the <a href="http://code.activestate.com/recipes/52281/" rel="nofollow">stripping parser</a> from the ActiveState Cookbook is one of the easiest solutions. You can pretty much copy/...
1
2009-10-23T07:10:04Z
[ "python", "html", "email", "browser", "html-sanitizing" ]
Using multiple databases with Elixir
1,606,341
<p>I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice?</p> <p>The only thing I thought of is to:</p> <pre><code>from sys import argv ...
1
2009-10-22T10:32:18Z
1,606,389
<p>Your question seems to be more related to general argument parsing in python than with elixir.</p> <p>Anyway, I had a similar problem, and I have solved it by using different configuration files and parsing them with the <a href="http://docs.python.org/library/configparser.html" rel="nofollow">configparse</a> modul...
0
2009-10-22T10:44:38Z
[ "python", "python-elixir" ]
Using multiple databases with Elixir
1,606,341
<p>I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice?</p> <p>The only thing I thought of is to:</p> <pre><code>from sys import argv ...
1
2009-10-22T10:32:18Z
1,606,391
<p>I have some code that does this in a slightly nicer fashion than just using argv</p> <pre><code>from optparse import OptionParser parser = OptionParser() parser.add_option("-u", "--user", dest="user", help="Database username") parser.add_option("-p", "--password", dest="password", ...
1
2009-10-22T10:45:30Z
[ "python", "python-elixir" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
1,606,448
<p>No, you can only add doc strings to modules, classes and function (including methods)</p>
-1
2009-10-22T10:58:34Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
1,606,478
<p>You can achieve this by creating a simple, empty wrapper class around the returned value from <code>namedtuple</code>. Contents of a file I created (<code>nt.py</code>):</p> <pre><code>from collections import namedtuple Point_ = namedtuple("Point", ["x", "y"]) class Point(Point_): """ A point in 2d space """...
31
2009-10-22T11:03:35Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
3,349,937
<p>You could concoct your own version of the <a href="http://code.activestate.com/recipes/500261" rel="nofollow"><strong>namedtuple factory function</strong></a> by Raymond Hettinger and add an optional <code>docstring</code> argument.&nbsp;&nbsp;However it would be easier -- and arguably better -- to just define your ...
0
2010-07-28T04:23:11Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
15,667,772
<p>Came across this old question via Google while wondering the same thing.</p> <p>Just wanted to point out that you can tidy it up even more by calling namedtuple() right from the class declaration:</p> <pre><code>from collections import namedtuple class Point(namedtuple('Point', 'x y')): """Here is the docstri...
34
2013-03-27T19:30:28Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
20,388,499
<p>In Python 3, no wrapper is needed, as the <code>__doc__</code> attributes of types is writable.</p> <pre><code>from collections import namedtuple Point = namedtuple('Point', 'x y') Point.__doc__ = '''\ A 2-dimensional coordinate x - the abscissa y - the ordinate''' </code></pre> <p>This closely corresponds to a ...
30
2013-12-04T23:43:06Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
26,017,342
<p>No need to use a wrapper class as suggested by the accepted answer. Simply literally <strong>add</strong> a docstring:</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) Point.__doc__="A point in 2D space" </code></pre> <p>This results in: (example using <code>ipython3</code...
2
2014-09-24T12:48:47Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
28,568,351
<blockquote> <h1>Is it possible to add a documentation string to a namedtuple in an easy manner?</h1> </blockquote> <h1>Python 3</h1> <p>In Python 3, you can easily alter the doc on your namedtuple:</p> <pre><code>NT = collections.namedtuple('NT', 'foo bar') NT.__doc__ = """:param str foo: foo name :param list ba...
10
2015-02-17T18:19:22Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) p...
39
2009-10-22T10:55:53Z
39,320,627
<p>Since Python 3.5, docstrings for <code>namedtuple</code> objects can be updated.</p> <p>From the <a href="https://docs.python.org/3/whatsnew/3.5.html#collections" rel="nofollow">whatsnew</a>:</p> <blockquote> <p><code>Point = namedtuple('Point', ['x', 'y']) Point.__doc__ += ': Cartesian coodinate' Point.x.__...
0
2016-09-04T19:20:42Z
[ "python", "docstring", "namedtuple" ]
How to use PIL to resize and apply rotation EXIF information to the file?
1,606,587
<p>I am trying to use Python to resize picture. With my camera, files are all written is landscape way.</p> <p>The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information a...
20
2009-10-22T11:28:40Z
1,606,981
<p>First you have to make sure that your camera actually has a rotation sensor. Most camera models without sensor simply set the Orientation Tag to 1 (Horizontal) for ALL pictures.</p> <p>Then I recommend to use pyexiv2 and pyjpegtran in your case. PIL doesn't support lossless rotation, which is the domain of pyjpegtr...
2
2009-10-22T12:51:04Z
[ "python", "jpeg", "python-imaging-library", "rotation", "exif" ]
How to use PIL to resize and apply rotation EXIF information to the file?
1,606,587
<p>I am trying to use Python to resize picture. With my camera, files are all written is landscape way.</p> <p>The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information a...
20
2009-10-22T11:28:40Z
1,608,545
<p>Although PIL can read EXIF metadata, it doesn't have the ability to change it and write it back to an image file.</p> <p>A better choice is the <a href="http://tilloy.net/dev/pyexiv2/index.htm">pyexiv2</a> library. With this library it's quite simple flip the photo's orientation. Here's an example:</p> <pre><cod...
6
2009-10-22T16:52:27Z
[ "python", "jpeg", "python-imaging-library", "rotation", "exif" ]
How to use PIL to resize and apply rotation EXIF information to the file?
1,606,587
<p>I am trying to use Python to resize picture. With my camera, files are all written is landscape way.</p> <p>The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information a...
20
2009-10-22T11:28:40Z
1,608,846
<p>I finally used <a href="http://tilloy.net/dev/pyexiv2/">pyexiv2</a>, but it is a bit tricky to install on other platforms than GNU.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2008-2009 Rémy HUBSCHER &lt;natim@users.sf.net&gt; - http://www.trunat.fr/portfolio/python.html # This progra...
14
2009-10-22T17:47:02Z
[ "python", "jpeg", "python-imaging-library", "rotation", "exif" ]
Timer in Python
1,606,700
<p>I am writing a python app using Tkinter for buttons and graphics and having trouble getting a timer working, what I need is a sample app that has three buttons and a label.</p> <p>[start timer] [stop timer] [quit]</p> <p>When I press the start button a function allows the label to count up from zero every 5 secon...
1
2009-10-22T11:53:54Z
1,606,815
<p>Check the .after method of your Tk() object. This allows you to use Tk's timer to fire events within the gui's own loop by giving it a length of time and a callback method.</p>
2
2009-10-22T12:19:21Z
[ "python", "tkinter" ]
Python debugging in Netbeans
1,606,746
<p>I have a problem with debugging Python programs under the Netbeans IDE. When I start debugging, the debugger writes the following log and error. Thank you for help.</p> <pre> [LOG]PythonDebugger : overall Starting >>>[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ... [LOG]This window is an ...
4
2009-10-22T12:02:30Z
1,606,803
<p>I just installed Python for NetBeans yesterday and hadn't tried the debugger, so just tried it, and I got the same error. So I thought maybe it's a Firewall issue, disabled my Firewall and retried it, and then it worked.</p> <p>However I restarted the Firewall and now it's still working, so I don't know. I saw the ...
1
2009-10-22T12:16:04Z
[ "python", "netbeans" ]
Python debugging in Netbeans
1,606,746
<p>I have a problem with debugging Python programs under the Netbeans IDE. When I start debugging, the debugger writes the following log and error. Thank you for help.</p> <pre> [LOG]PythonDebugger : overall Starting >>>[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ... [LOG]This window is an ...
4
2009-10-22T12:02:30Z
1,636,617
<p>For Python I like WingIDE from Wingware.</p>
1
2009-10-28T11:14:12Z
[ "python", "netbeans" ]
catching stdout in realtime from subprocess
1,606,795
<p>I have read tons of posts but still can't seem to figure it out.</p> <p>I want to subprocess.Popen() rsync.exe in windows, and print the stdout in python.</p> <p>My code works, but it doesn't catch the progress until a file is done transfered! I want to print the progress for each file in realtime.</p> <p>Using p...
39
2009-10-22T12:14:43Z
1,606,859
<p>Change the stdout from the rsync process to be unbuffered.</p> <pre><code>p = subprocess.Popen(cmd, shell=True, bufsize=0, # 0=unbuffered, 1=line-buffered, else buffer-size stdin=subprocess.PIPE, stderr=subprocess.PIPE, ...
2
2009-10-22T12:26:39Z
[ "python", "subprocess", "stdout" ]