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
list
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
780,829
<p>In my opinion, best approach is to use existing logging libraries such as <a href="http://logging.apache.org/" rel="nofollow">log4j (or it's variations for other languages)</a>. It gives you control on how your messages are formatted and you can change it without ever touching your code. It follows best practices, robust and used by millions of users. Of course, you can write you own logging framework, but that would be very odd thing to do, unless you need something very specific. In any case, walk though their documentation and see how log statements are presented there.</p> <p>Check out log4py - Python ported version of log4j, I think there are several implementations for Python out there..</p>
1
2009-04-23T08:48:56Z
[ "python", "logging", "methodology" ]
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
2,043,176
<p>Python's logging library are thread-safe for single process threads.</p>
0
2010-01-11T16:31:06Z
[ "python", "logging", "methodology" ]
how get last number in range in python
780,057
<p>there is a way to get the last number <strong>in range</strong> i need to get the last number in fibonacci sequence for first 20 terms or can to do with a list instead range?</p>
0
2009-04-23T02:13:42Z
780,063
<p>Is this what you're after?</p> <pre><code>somerange = range(0,20) print len(somerange) # if you want 20 print len(somerange)-1 # if you want 19 </code></pre> <p>now if you want the number or item contained in a list...</p> <pre><code>x = [1,2,3,4] print x[len(x)-1] # OR print x[-1] # go back 1 element from current index 0, takes you to list end </code></pre>
0
2009-04-23T02:16:05Z
[ "python", "range", "fibonacci" ]
how get last number in range in python
780,057
<p>there is a way to get the last number <strong>in range</strong> i need to get the last number in fibonacci sequence for first 20 terms or can to do with a list instead range?</p>
0
2009-04-23T02:13:42Z
780,075
<p>Not quite sure what you are after here but here goes:</p> <pre><code>rangeList = range(0,21) lastNumber = rangeList[len(rangeList)-1:][0] </code></pre> <p>or:</p> <pre><code>lastNumber = rangeList[-1] </code></pre>
4
2009-04-23T02:20:11Z
[ "python", "range", "fibonacci" ]
how get last number in range in python
780,057
<p>there is a way to get the last number <strong>in range</strong> i need to get the last number in fibonacci sequence for first 20 terms or can to do with a list instead range?</p>
0
2009-04-23T02:13:42Z
780,079
<p>by <em>in a range</em>, do you mean last value provided by a generator? If so, you can do something like this:</p> <pre><code>def fibonacci(iterations): # generate your fibonacci numbers here... [x for x in fibonacci(20)][-1] </code></pre> <p>That would get you the last generated value.</p>
2
2009-04-23T02:21:27Z
[ "python", "range", "fibonacci" ]
how get last number in range in python
780,057
<p>there is a way to get the last number <strong>in range</strong> i need to get the last number in fibonacci sequence for first 20 terms or can to do with a list instead range?</p>
0
2009-04-23T02:13:42Z
780,087
<p>I don't think anyone considered that you need fibonacci numbers. No, you'll have to store each number to build the fibonacci sequence recursively, but there is a formula to get the nth term of the fibonacci sequence. </p> <p><a href="http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html" rel="nofollow">Binet's Formula</a> </p> <p>If you need the last number of a list, use myList[-1].</p>
1
2009-04-23T02:25:33Z
[ "python", "range", "fibonacci" ]
Installing bitarray in Python 2.6 on Windows
780,127
<p>I would like to install <a href="http://pypi.python.org/pypi/bitarray/" rel="nofollow">bitarray</a> in Windows running python 2.6.</p> <p>I have mingw32 installed, and I have <code>C:\Python26\Lib\distutils\distutils.cfg</code> set to:</p> <pre><code>[build] compiler = mingw32 </code></pre> <p>If I type, in a <code>cmd.exe</code> window:</p> <pre><code>C:\Documents and Settings\john\My Documents\bitarray-0.3.5&gt;python setup.py install </code></pre> <p>I get:</p> <pre><code>[normal python messages skipped] C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c bitarray/_bitarray.c -o build\temp.win32-2.6\Release\bitarray\_bitarray.o bitarray/_bitarray.c:2197: error: initializer element is not constant bitarray/_bitarray.c:2197: error: (near initialization for `BitarrayIter_Type.tp_getattro') bitarray/_bitarray.c:2206: error: initializer element is not constant bitarray/_bitarray.c:2206: error: (near initialization for `BitarrayIter_Type.tp_iter') bitarray/_bitarray.c:2232: error: initializer element is not constant bitarray/_bitarray.c:2232: error: (near initialization for `Bitarraytype.tp_getattro') bitarray/_bitarray.c:2253: error: initializer element is not constant bitarray/_bitarray.c:2253: error: (near initialization for `Bitarraytype.tp_alloc') bitarray/_bitarray.c:2255: error: initializer element is not constant bitarray/_bitarray.c:2255: error: (near initialization for `Bitarraytype.tp_free') error: command 'gcc' failed with exit status 1 </code></pre> <p>Can anyone help?</p>
0
2009-04-23T02:48:41Z
780,613
<p>MingW cannot compile the bitarray sources, I tried with version 3.4.5 and get the same errors. However, it compiles fine with the Microsoft compiler.</p> <p>For your convenience I've build msi and exe installers for Python 2.6:</p> <p><a href="http://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.msi" rel="nofollow">http://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.msi</a></p> <p><a href="http://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.exe" rel="nofollow">http://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.exe</a></p> <p>Please point the bitarray author to them so that he can upload them to pypi.</p>
3
2009-04-23T07:11:03Z
[ "python", "c", "mingw", "bitarray" ]
Installing bitarray in Python 2.6 on Windows
780,127
<p>I would like to install <a href="http://pypi.python.org/pypi/bitarray/" rel="nofollow">bitarray</a> in Windows running python 2.6.</p> <p>I have mingw32 installed, and I have <code>C:\Python26\Lib\distutils\distutils.cfg</code> set to:</p> <pre><code>[build] compiler = mingw32 </code></pre> <p>If I type, in a <code>cmd.exe</code> window:</p> <pre><code>C:\Documents and Settings\john\My Documents\bitarray-0.3.5&gt;python setup.py install </code></pre> <p>I get:</p> <pre><code>[normal python messages skipped] C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c bitarray/_bitarray.c -o build\temp.win32-2.6\Release\bitarray\_bitarray.o bitarray/_bitarray.c:2197: error: initializer element is not constant bitarray/_bitarray.c:2197: error: (near initialization for `BitarrayIter_Type.tp_getattro') bitarray/_bitarray.c:2206: error: initializer element is not constant bitarray/_bitarray.c:2206: error: (near initialization for `BitarrayIter_Type.tp_iter') bitarray/_bitarray.c:2232: error: initializer element is not constant bitarray/_bitarray.c:2232: error: (near initialization for `Bitarraytype.tp_getattro') bitarray/_bitarray.c:2253: error: initializer element is not constant bitarray/_bitarray.c:2253: error: (near initialization for `Bitarraytype.tp_alloc') bitarray/_bitarray.c:2255: error: initializer element is not constant bitarray/_bitarray.c:2255: error: (near initialization for `Bitarraytype.tp_free') error: command 'gcc' failed with exit status 1 </code></pre> <p>Can anyone help?</p>
0
2009-04-23T02:48:41Z
2,305,630
<p>I needed to build bitarray for myself (I needed bit shift), so I couldn't use your pre-built binaries. The problem lies in mingw not working properly with __declspec(dllimport). Python already solves this problem for cygwin builds by using auto-import instead of declspec. However, this is not enabled for mingw builds. So you either need to modify the PyAPI_FUNC macro in pyport.h or add</p> <pre><code>#define __CYGWIN__ </code></pre> <p>to the bitarray sources.</p>
0
2010-02-21T10:55:46Z
[ "python", "c", "mingw", "bitarray" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
780,201
<p>Collision detection for arbitrary shapes is usually quite tricky since you have to figure out if any pixel collides.</p> <p>This is actually easier with circles. If you have two circles of radius r1 and r2, a collision has occurred if the distance between the centers is less than r1+r2.</p> <p>The distance between the two centers (x1,y1) and (x2,y2) can be calculated and compared as:</p> <pre><code>d = sqrt((y2-y1) * (y2-y1) + (x2-x1) * (x2-x1)); if (d &lt; r1 + r2) { ... bang ... } </code></pre> <p>Or, as jfclavette points out, square roots are expensive so it may be better to calculate using just simple operations:</p> <pre><code>dsqrd = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1); if (dsqrd &lt; (r1+r2)*(r1+r2)) { ... bang ... } </code></pre> <p>The tricky bit comes in calculating the new movement vectors (the rate at which (x,y) changes over time for a given object) since you need to take into account the current movement vectors and the point of contact.</p> <p>I think as a first cut, you should just reverse the movement vectors to test if the collision detection works first.</p> <p>Then ask another question - it's better to keep individual questions specific so answers can be targeted.</p>
9
2009-04-23T03:29:34Z
[ "python", "collision-detection" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
780,226
<p>Detecting collisions was covered well by <a href="http://stackoverflow.com/questions/780169/how-do-i-create-collision-detections-for-my-bouncing-balls/780201#780201">Pax's answer</a>. With respect to having objects bounce off one another, I suggest checking out the following links concerning <a href="http://en.wikipedia.org/wiki/Elastic%5Fcollision" rel="nofollow">elastic collisions</a>, <a href="http://en.wikipedia.org/wiki/Inelastic%5Fcollision" rel="nofollow">inelastic collisions</a>, and <a href="http://en.wikipedia.org/wiki/Coefficient%5Fof%5Frestitution" rel="nofollow">coefficients of restitution</a>.</p> <p><strong>EDIT:</strong> I just noticed that this was covered in <a href="http://stackoverflow.com/questions/345838/ball-to-ball-collision-detection-and-handling">another SO question</a>, albeit not specifically for Python. You should also check there for some good links.</p>
1
2009-04-23T03:44:19Z
[ "python", "collision-detection" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
780,240
<p>Detecting a collision is only the first step. Let's break that down.</p> <p>The fastest thing to do is calculate their square bounding boxes and see if those collide. Two of the sides need to cross (top of 1 and bottom or 2, and left of 1 and right of 2, or vice versa) in order for the bounding boxes to overlap. No overlap, no collision.</p> <p>Now, when they <em>do</em> overlap, you need to calculate the distance between them. If this distance is more than the sums of the radii of the balls, then no collision.</p> <p>Okay! We have two balls colliding. <em>Now</em> what? Well, they have to bounce off each other. Which way they bounce depends on a few factors.</p> <p>The first is their elasticity. Two rubber balls bouncing off each other rebound differently than two glass balls.</p> <p>The second is their initial velocity. Inertia states that they'll want to keep going in mostly the same direction they started in.</p> <p>The third is the mass of the balls. A ball with smaller mass will rebound off a much larger mass with a higher velocity.</p> <p>Let's deal with the second and third factors first, since they are intertwined.</p> <p>Two balls will rarely hit exactly dead on. Glancing blows are far more likely. In any case, the impact will happen along the normal of the tangent where the balls collide. You need to calculate the vector component of both along this normal given their initial velocities. This will result in a pair of normal velocities that both balls will bring to the collision. Add up the sum and store it somewhere handy.</p> <p>Now we have to figure out what each ball will take away from it. The resulting normal velocity of each ball is inversely proportional to the given ball's mass. That is to say, take the reciprocal of each ball's mass, add both masses together, and then parcel out the resultant normal velocity away from the collision based on the ratio of the ball's mass to the sum of the reciprocal of both ball's masses. Then add the tangential velocity to this, and you get the resultant velocity of the ball.</p> <p>Elasticity is mostly the same, except it requires some basic calculus due to the fact that the balls are still moving even as they compress. I'll leave it to you to find the relevant math.</p>
3
2009-04-23T03:49:51Z
[ "python", "collision-detection" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
780,321
<p>I think there is somehthing simpler that you guys are missing espeically considering he's using pygame.</p> <p>Calling the <code>get_rect</code> function can set probably boundraies for the images and <code>Rect</code> that is created, is used for calculating the position of the image and if there are more than one object in the animation, it can be used for detecting collisions. </p> <p><code>colliderect</code> &amp; <code>rect</code> can be used, problem is i have no idea how you would implement it especially for an unkown number of balls. </p> <p>Keeping in mind it's python.</p>
1
2009-04-23T04:30:17Z
[ "python", "collision-detection" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
782,683
<p>Back in the good old times when CPU cycles were a premium coders used a simple trick to detect collision: they used such colours that they could tell from the pixel colour if it was background or an object. This was done on at least some C64 games.</p> <p>Don't know if you are willing to go this route, though..</p>
0
2009-04-23T17:08:29Z
[ "python", "collision-detection" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
1,140,987
<p>First you need to check collision with <code>rect.colliderect(other_rect)</code></p> <p>after that if they are colliding, you can check pixel perfect collision. So you don't mess with object's radius or shape.</p> <p>For pixel perfect collision checking, I use Masks: Make both mask objects with <code>mask.from_surface</code>, then put them to <code>Mask.overlap</code> function.</p>
0
2009-07-17T00:31:55Z
[ "python", "collision-detection" ]
How do I create collision detections for my bouncing balls?
780,169
<p>I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really appreciate any help that can be offered.</p> <pre><code>import pygame import random import sys class Ball: def __init__(self,X,Y): self.velocity = [1,1] self.ball_image = pygame.image.load ('Beachball.jpg'). convert() self.ball_boundary = self.ball_image.get_rect (center=(X,Y)) self.sound = pygame.mixer.Sound ('Thump.wav') self.rect = self.ball_image.get_rect (center=(X,Y)) if __name__ =='__main__': width = 800 height = 600 background_colour = 0,0,0 pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Bouncing Ball animation") num_balls = 3 ball_list = [] for number in range(num_balls): ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) ) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) window.fill (background_colour) for ball in ball_list: if ball.ball_boundary.left &lt; 0 or ball.ball_boundary.right &gt; width: ball.sound.play() ball.velocity[0] = -1 * ball.velocity[0] if ball.ball_boundary.top &lt; 0 or ball.ball_boundary.bottom &gt; height: ball.sound.play() ball.velocity[1] = -1 * ball.velocity[1] ball.ball_boundary = ball.ball_boundary.move (ball.velocity) window.blit (ball.ball_image, ball.ball_boundary) pygame.display.flip() </code></pre>
6
2009-04-23T03:13:56Z
39,060,229
<p>I made a python collision detection if statement, here it is: </p> <pre><code>if beach ball 1 x &lt; beach ball 2 x + beach ball 1 width and beach ball 1 x + beach ball 2 width &gt; beach ball 2 x and beach ball 1 y &lt; beach ball 2 y + beach ball 1 height and beach ball 2 height + beach ball 1 y &gt; beach ball 2 y: #put needed code here </code></pre> <p>In your case, with 3 bouncing balls, you will have to make 2 if statements of this format for each ball to make sure that the collision detection is flawless. I hope this helps.</p>
0
2016-08-21T02:02:06Z
[ "python", "collision-detection" ]
Unescape Python Strings From HTTP
780,334
<p>I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?</p> <pre><code>myemail%40gmail.com -&gt; myemail@gmail.com </code></pre> <p>Would urllib.unquote() be the way to go?</p>
14
2009-04-23T04:36:55Z
780,344
<p>I am pretty sure that urllib's <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>unquote</code></a> is the common way of doing this.</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; urllib.unquote("myemail%40gmail.com") 'myemail@gmail.com' </code></pre> <p>There's also <a href="http://docs.python.org/library/urllib.html#urllib.unquote%5Fplus"><code>unquote_plus</code></a>:</p> <blockquote> <p>Like unquote(), but also replaces plus signs by spaces, as required for unquoting HTML form values.</p> </blockquote>
33
2009-04-23T04:41:14Z
[ "python", "http", "header", "urllib2", "mod-wsgi" ]
Unescape Python Strings From HTTP
780,334
<p>I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?</p> <pre><code>myemail%40gmail.com -&gt; myemail@gmail.com </code></pre> <p>Would urllib.unquote() be the way to go?</p>
14
2009-04-23T04:36:55Z
780,350
<p>Yes, it appears that <a href="http://docs.python.org/library/urllib.html#urllib.unquote" rel="nofollow"><code>urllib.unquote()</code></a> accomplishes that task. (I <a href="http://codepad.org/SerdBuAK" rel="nofollow">tested it against your example on codepad</a>.)</p>
2
2009-04-23T04:42:59Z
[ "python", "http", "header", "urllib2", "mod-wsgi" ]
Unescape Python Strings From HTTP
780,334
<p>I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?</p> <pre><code>myemail%40gmail.com -&gt; myemail@gmail.com </code></pre> <p>Would urllib.unquote() be the way to go?</p>
14
2009-04-23T04:36:55Z
28,435,067
<p>In Python 3, these functions are <a href="https://docs.python.org/3.4/library/urllib.parse.html#urllib.parse.unquote" rel="nofollow"><code>urllib.parse.unquote</code></a> and <a href="https://docs.python.org/3.4/library/urllib.parse.html#urllib.parse.unquote" rel="nofollow"><code>urllib.parse.unquote_plus</code></a>.</p> <p>The latter is used for example for query strings in the HTTP URLs, where the space characters (<code></code>) are traditionally encoded as plus character (<code>+</code>), and the <code>+</code> is percent-encoded to <code>%2B</code>.</p> <p>In addition to these there is the <a href="https://docs.python.org/3.4/library/urllib.parse.html#urllib.parse.unquote_to_bytes" rel="nofollow"><code>unquote_to_bytes</code></a> that converts the given encoded string to <code>bytes</code>, which can be used when the encoding is not known or the encoded data is binary data. However there is no <code>unquote_plus_to_bytes</code>, if you need it, you can do:</p> <pre><code>def unquote_plus_to_bytes(s): if isinstance(s, bytes): s = s.replace(b'+', b' ') else: s = s.replace('+', ' ') return unquote_to_bytes(s) </code></pre> <hr> <p>More information on whether to use <code>unquote</code> or <code>unquote_plus</code> is available at <a href="http://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20">URL encoding the space character: + or %20</a>.</p>
0
2015-02-10T15:09:14Z
[ "python", "http", "header", "urllib2", "mod-wsgi" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
780,403
<p>You mean this?</p> <pre><code>num = 1234 lst = [int(i) for i in str(num)] </code></pre>
47
2009-04-23T05:22:12Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
780,407
<p>You could do this:</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = map(int, str(num)) &gt;&gt;&gt; lst, type(lst) ([1, 2, 3], &lt;type 'list'&gt;) </code></pre>
10
2009-04-23T05:23:15Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
780,409
<pre><code>a = 123456 b = str(a) c = [] for digit in b: c.append (int(digit)) print c </code></pre>
6
2009-04-23T05:26:02Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
780,433
<p>Don't use the word <em>list</em> as variable name! It is a name of python built in data type.</p> <p>Also, please clarify your question. If you are looking for a way to create a one-member list, do the following:</p> <pre><code>a = 123 my_list = [a] </code></pre> <p>and "pythonizing" Cannonade's answer:</p> <pre><code>a = 123 my_list = [int(d) for d in str(a)] </code></pre>
5
2009-04-23T05:48:21Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
780,484
<pre><code>magic = lambda num: map(int, str(num)) </code></pre> <p>then just do</p> <pre><code>magic(12345) </code></pre> <p>or </p> <pre><code>magic(someInt) #or whatever </code></pre>
6
2009-04-23T06:19:11Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
10,471,209
<p>Just use : </p> <pre><code>a= str (num) lst = list(a) </code></pre>
1
2012-05-06T14:16:33Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
10,471,766
<pre><code>&gt;&gt;&gt; from collections import deque &gt;&gt;&gt; def magic(num): digits = deque() while True: num,r = divmod(num,10) digits.appendleft(r) if num == 0: break return list(digits) &gt;&gt;&gt; magic(123) [1, 2, 3] </code></pre> <p>According to my timings, this solution is considerably faster than the string method (<code>magic2</code>), even for smaller examples.</p> <pre><code>&gt;&gt;&gt; def magic2(num): return [int(i) for i in str(num)] </code></pre> <p><strong>Timings:</strong></p> <p><code>magic</code></p> <pre><code>&gt;&gt;&gt; timeit.timeit(setup='from __main__ import magic', stmt='magic(123)') 1.3874572762508706 &gt;&gt;&gt; timeit.timeit(setup='from __main__ import magic', stmt='magic(999999999)') 3.2624468999981673 </code></pre> <p><code>magic2</code> </p> <pre><code>&gt;&gt;&gt; timeit.timeit(setup='from __main__ import magic2', stmt='magic2(123)') 3.693756106896217 &gt;&gt;&gt; timeit.timeit(setup='from __main__ import magic2', stmt='magic2(999999999)') 10.485281719412114 </code></pre>
5
2012-05-06T15:31:04Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
28,144,400
<pre><code>num = map(int, list(str(num))) </code></pre>
0
2015-01-26T03:24:05Z
[ "python", "list", "integer" ]
Convert a number to a list of integers
780,390
<p>How do I write the <code>magic</code> function below?</p> <pre><code>&gt;&gt;&gt; num = 123 &gt;&gt;&gt; lst = magic(num) &gt;&gt;&gt; &gt;&gt;&gt; print lst, type(lst) [1, 2, 3], &lt;type 'list'&gt; </code></pre>
13
2009-04-23T05:14:20Z
35,940,131
<p>If it is named as magic, why not just use magic:</p> <pre><code>def magic(x): if x &lt; 10: return [x] else: return magic(x//10) + [x%10] </code></pre>
0
2016-03-11T12:19:18Z
[ "python", "list", "integer" ]
How to automatically reload a python file when it is changed
780,526
<p>If I make some changes to one of the files belonging to a running app, is there a way to tell the python runtime to automatically reload the module/file?</p> <p>Cheers Naren</p>
8
2009-04-23T06:40:03Z
780,624
<p>Here is a very old module that I posted nearly ten years ago. I may no longer work with current Python versions (I have not checked) but it may give some ideas.</p> <p><a href="http://mail.python.org/pipermail/python-list/2000-April/031568.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2000-April/031568.html</a></p>
4
2009-04-23T07:15:02Z
[ "python" ]
How to automatically reload a python file when it is changed
780,526
<p>If I make some changes to one of the files belonging to a running app, is there a way to tell the python runtime to automatically reload the module/file?</p> <p>Cheers Naren</p>
8
2009-04-23T06:40:03Z
780,698
<p>Take look at <a href="http://code.djangoproject.com/svn/django/trunk/django/utils/autoreload.py" rel="nofollow">Django's autoreload module</a>. It works very well.</p>
4
2009-04-23T07:42:43Z
[ "python" ]
How to automatically reload a python file when it is changed
780,526
<p>If I make some changes to one of the files belonging to a running app, is there a way to tell the python runtime to automatically reload the module/file?</p> <p>Cheers Naren</p>
8
2009-04-23T06:40:03Z
780,769
<p>Take at look at <a href="http://www.cherrypy.org/attachment/wiki/AutoReload/autoreload.py" rel="nofollow" rel="nofollow">CherryPy's Autoreload feature</a>. I think it looks quite simple and always worked well for me.</p>
5
2009-04-23T08:16:30Z
[ "python" ]
Python base class method call: unexpected behavior
780,670
<p>Why does <code>str(A())</code> seemingly call <code>A.__repr__()</code> and not <code>dict.__str__()</code> in the example below?</p> <pre><code>class A(dict): def __repr__(self): return 'repr(A)' def __str__(self): return dict.__str__(self) class B(dict): def __str__(self): return dict.__str__(self) print 'call: repr(A) expect: repr(A) get:', repr(A()) # works print 'call: str(A) expect: {} get:', str(A()) # does not work print 'call: str(B) expect: {} get:', str(B()) # works </code></pre> <p>Output:</p> <pre><code>call: repr(A) expect: repr(A) get: repr(A) call: str(A) expect: {} get: repr(A) call: str(B) expect: {} get: {} </code></pre>
5
2009-04-23T07:31:02Z
780,728
<p><code>str(A())</code> does call <code>__str__</code>, in turn calling <code>dict.__str__()</code>. </p> <p>It is <code>dict.__str__()</code> that returns the value repr(A).</p>
9
2009-04-23T07:58:52Z
[ "python", "inheritance", "dictionary" ]
Python base class method call: unexpected behavior
780,670
<p>Why does <code>str(A())</code> seemingly call <code>A.__repr__()</code> and not <code>dict.__str__()</code> in the example below?</p> <pre><code>class A(dict): def __repr__(self): return 'repr(A)' def __str__(self): return dict.__str__(self) class B(dict): def __str__(self): return dict.__str__(self) print 'call: repr(A) expect: repr(A) get:', repr(A()) # works print 'call: str(A) expect: {} get:', str(A()) # does not work print 'call: str(B) expect: {} get:', str(B()) # works </code></pre> <p>Output:</p> <pre><code>call: repr(A) expect: repr(A) get: repr(A) call: str(A) expect: {} get: repr(A) call: str(B) expect: {} get: {} </code></pre>
5
2009-04-23T07:31:02Z
780,765
<p>I have modified the code to clear things out:</p> <pre><code>class A(dict): def __repr__(self): print "repr of A called", return 'repr(A)' def __str__(self): print "str of A called", return dict.__str__(self) class B(dict): def __str__(self): print "str of B called", return dict.__str__(self) </code></pre> <p>And the output is:</p> <pre><code>&gt;&gt;&gt; print 'call: repr(A) expect: repr(A) get:', repr(A()) call: repr(A) expect: repr(A) get: repr of A called repr(A) &gt;&gt;&gt; print 'call: str(A) expect: {} get:', str(A()) call: str(A) expect: {} get: str of A called repr of A called repr(A) &gt;&gt;&gt; print 'call: str(B) expect: {} get:', str(B()) call: str(B) expect: {} get: str of B called {} </code></pre> <p>Meaning that str function calls the repr function automatically. And since it was redefined with class A, it returns the 'unexpected' value.</p>
3
2009-04-23T08:14:37Z
[ "python", "inheritance", "dictionary" ]
Python base class method call: unexpected behavior
780,670
<p>Why does <code>str(A())</code> seemingly call <code>A.__repr__()</code> and not <code>dict.__str__()</code> in the example below?</p> <pre><code>class A(dict): def __repr__(self): return 'repr(A)' def __str__(self): return dict.__str__(self) class B(dict): def __str__(self): return dict.__str__(self) print 'call: repr(A) expect: repr(A) get:', repr(A()) # works print 'call: str(A) expect: {} get:', str(A()) # does not work print 'call: str(B) expect: {} get:', str(B()) # works </code></pre> <p>Output:</p> <pre><code>call: repr(A) expect: repr(A) get: repr(A) call: str(A) expect: {} get: repr(A) call: str(B) expect: {} get: {} </code></pre>
5
2009-04-23T07:31:02Z
1,659,474
<p>I have posted a workaround solution to it. Check it out ... you might find it useful: <a href="http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html" rel="nofollow">http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html</a></p> <p>P.S. Read the original post where I introduced the issue as well ... There problem is the unexpected behavior that catches you by surprise ...</p>
2
2009-11-02T04:58:58Z
[ "python", "inheritance", "dictionary" ]
Playing and controlling mp3 files in Python?
780,711
<p>First things first, I am a Python beginner, with a typical C++/Java background for object oriented stuff.</p> <p>I was convinced to try Python for this current endeavor I am working on, and so far I like it. One issue I am having though is finding a good mp3 module.</p> <p>I have tried TkSnack, which installed and ran fine with no errors(as long as my audio device wasn't busy) but it could never actually produce a sound, it just did nothing... I went online for help, and was disappointed with the amount of documentation. </p> <p>So I decided to switch. I tried PyMad because it is in the standard repositories for Ubuntu as well. There was even less documentation on this, but I could make it play a sound. The only problem is that it requires a loop to constantly write/play the audio buffer. This makes it particularly hairy to handle playback control(in my opinion) cause I would have to run this in a separate thread or process, and somehow control the seek position for pause and such. This is a little too low level for why I am using Python. I liked the simplicity of TkSnack for its easy commands like "mysound.play()" or "mysound.pause()" rather than controlling a loop.</p> <p>I also looked at pyMedia, which looks like it is the most up to date with documentation, but I can't get it to install on my machine. I get a "gcc exited with value 1" error or something like that when running the "python setup.py build" command. </p> <p>So I am looking for any suggestions or help on one of these modules, or a completely different one, that is high level and easy to use for mp3s(and preferably other formats too) I am trying to have basic playback control(pause, stop, skip, seek) and I may also be streaming files too eventually(if I ever get there). </p> <p><strong>EDIT</strong>: I like the python bindings for Gstreamer, but is this a cross-platform solution?? I forgot to mention that as a requirement. But I always just associated GStreamer with Linux, would this work on other OSs? </p> <p><strong>EDIT</strong>: Wikipedia says <a href="http://en.wikipedia.org/wiki/GStreamer" rel="nofollow">yes</a>. </p>
4
2009-04-23T07:49:49Z
780,757
<p>Sorry I can't help you with PyMad or pyMedia, but I have other suggestions.</p> <p>Existing music players written in Python:</p> <ul> <li><a href="http://www.exaile.org/" rel="nofollow">Exaile</a></li> <li><a href="http://fuplayer.org/" rel="nofollow">FUPlayer</a></li> <li><a href="http://listengnome.free.fr/" rel="nofollow">Listen</a></li> </ul> <p>All of the above use the <a href="http://gstreamer.freedesktop.org/modules/gst-python.html" rel="nofollow">Python bindings</a> for the <a href="http://gstreamer.freedesktop.org/documentation/" rel="nofollow">GStreamer</a> multimedia framework. Docs for the bindings are scarce, but check <a href="http://pygstdocs.berlios.de/pygst-tutorial/index.html" rel="nofollow">here</a>, <a href="http://pygstdocs.berlios.de/" rel="nofollow">here</a>, <a href="http://www.jonobacon.org/2006/08/28/getting-started-with-gstreamer-with-python/" rel="nofollow">here</a>, and examples from the source distribution <a href="http://cgit.freedesktop.org/gstreamer/gst-python/tree/examples" rel="nofollow">here</a>.</p>
2
2009-04-23T08:09:34Z
[ "python", "audio", "mp3", "audio-streaming" ]
Playing and controlling mp3 files in Python?
780,711
<p>First things first, I am a Python beginner, with a typical C++/Java background for object oriented stuff.</p> <p>I was convinced to try Python for this current endeavor I am working on, and so far I like it. One issue I am having though is finding a good mp3 module.</p> <p>I have tried TkSnack, which installed and ran fine with no errors(as long as my audio device wasn't busy) but it could never actually produce a sound, it just did nothing... I went online for help, and was disappointed with the amount of documentation. </p> <p>So I decided to switch. I tried PyMad because it is in the standard repositories for Ubuntu as well. There was even less documentation on this, but I could make it play a sound. The only problem is that it requires a loop to constantly write/play the audio buffer. This makes it particularly hairy to handle playback control(in my opinion) cause I would have to run this in a separate thread or process, and somehow control the seek position for pause and such. This is a little too low level for why I am using Python. I liked the simplicity of TkSnack for its easy commands like "mysound.play()" or "mysound.pause()" rather than controlling a loop.</p> <p>I also looked at pyMedia, which looks like it is the most up to date with documentation, but I can't get it to install on my machine. I get a "gcc exited with value 1" error or something like that when running the "python setup.py build" command. </p> <p>So I am looking for any suggestions or help on one of these modules, or a completely different one, that is high level and easy to use for mp3s(and preferably other formats too) I am trying to have basic playback control(pause, stop, skip, seek) and I may also be streaming files too eventually(if I ever get there). </p> <p><strong>EDIT</strong>: I like the python bindings for Gstreamer, but is this a cross-platform solution?? I forgot to mention that as a requirement. But I always just associated GStreamer with Linux, would this work on other OSs? </p> <p><strong>EDIT</strong>: Wikipedia says <a href="http://en.wikipedia.org/wiki/GStreamer" rel="nofollow">yes</a>. </p>
4
2009-04-23T07:49:49Z
781,853
<p>I just had to deal with this, and from my research I think your best bets are <a href="http://www.pyglet.org" rel="nofollow">pyglet</a> and <a href="http://www.pygame.org" rel="nofollow">pygame</a>. They're interface packages with built-in a/v support.</p>
0
2009-04-23T14:00:03Z
[ "python", "audio", "mp3", "audio-streaming" ]
SQLAlchemy - Dictionary of tags
780,774
<p>I have question regarding the SQLAlchemy. How can I add into my mapped class the dictionary-like attribute, which maps the string keys into string values and which will be stored in the database (in the same or another table as original mapped object). I want this add support for arbitrary tags of my objects.</p> <p>I found the following example in SQLAlchemy documentation:</p> <pre><code>from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection mapper(Item, items_table, properties={ # key by column 'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)), # or named attribute 'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')), # or any callable 'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b)) }) item = Item() item.notes['color'] = Note('color', 'blue') </code></pre> <p>But I want the following behavior:</p> <pre><code>mapper(Item, items_table, properties={ # key by column 'notes': relation(...), }) item = Item() item.notes['color'] = 'blue' </code></pre> <p>It is possible in SQLAlchemy?</p> <p>Thank you</p>
14
2009-04-23T08:19:36Z
781,137
<p>The simple answer is 'no'.</p> <p>SQLAlchemy is wrapper on a SQL database.</p> <p>The relation examples you quote translate a relationship between SQL tables into a Python map-like structure to make it slightly simpler to do the SQL SELECT statements and locate rows in another table.</p> <p>The </p> <pre><code>item.notes['color'] = Note('color', 'blue') </code></pre> <p>is essential because the <code>Note</code> is a separate table with two columns. You can't leave the <code>Note</code> part out.</p> <p>You must define this other SQL table, and you must create objects which are mapped to that SQL table.</p>
-5
2009-04-23T10:25:39Z
[ "python", "sqlalchemy" ]
SQLAlchemy - Dictionary of tags
780,774
<p>I have question regarding the SQLAlchemy. How can I add into my mapped class the dictionary-like attribute, which maps the string keys into string values and which will be stored in the database (in the same or another table as original mapped object). I want this add support for arbitrary tags of my objects.</p> <p>I found the following example in SQLAlchemy documentation:</p> <pre><code>from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection mapper(Item, items_table, properties={ # key by column 'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)), # or named attribute 'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')), # or any callable 'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b)) }) item = Item() item.notes['color'] = Note('color', 'blue') </code></pre> <p>But I want the following behavior:</p> <pre><code>mapper(Item, items_table, properties={ # key by column 'notes': relation(...), }) item = Item() item.notes['color'] = 'blue' </code></pre> <p>It is possible in SQLAlchemy?</p> <p>Thank you</p>
14
2009-04-23T08:19:36Z
784,095
<p>The simple answer is <strong>yes</strong>.</p> <p>Just use an association proxy:</p> <pre><code>from sqlalchemy import Column, Integer, String, Table, create_engine from sqlalchemy import orm, MetaData, Column, ForeignKey from sqlalchemy.orm import relation, mapper, sessionmaker from sqlalchemy.orm.collections import column_mapped_collection from sqlalchemy.ext.associationproxy import association_proxy </code></pre> <p>Create a test environment:</p> <pre><code>engine = create_engine('sqlite:///:memory:', echo=True) meta = MetaData(bind=engine) </code></pre> <p>Define the tables:</p> <pre><code>tb_items = Table('items', meta, Column('id', Integer, primary_key=True), Column('name', String(20)), Column('description', String(100)), ) tb_notes = Table('notes', meta, Column('id_item', Integer, ForeignKey('items.id'), primary_key=True), Column('name', String(20), primary_key=True), Column('value', String(100)), ) meta.create_all() </code></pre> <p>Classes (note the <code>association_proxy</code> in the class):</p> <pre><code>class Note(object): def __init__(self, name, value): self.name = name self.value = value class Item(object): def __init__(self, name, description=''): self.name = name self.description = description notes = association_proxy('_notesdict', 'value', creator=Note) </code></pre> <p>Mapping:</p> <pre><code>mapper(Note, tb_notes) mapper(Item, tb_items, properties={ '_notesdict': relation(Note, collection_class=column_mapped_collection(tb_notes.c.name)), }) </code></pre> <p>Then just test it:</p> <pre><code>Session = sessionmaker(bind=engine) s = Session() i = Item('ball', 'A round full ball') i.notes['color'] = 'orange' i.notes['size'] = 'big' i.notes['data'] = 'none' s.add(i) s.commit() print i.notes </code></pre> <p>That prints:</p> <pre><code>{u'color': u'orange', u'data': u'none', u'size': u'big'} </code></pre> <p>But, are those in the notes table?</p> <pre><code>&gt;&gt;&gt; print list(tb_notes.select().execute()) [(1, u'color', u'orange'), (1, u'data', u'none'), (1, u'size', u'big')] </code></pre> <p>It works!! :)</p>
21
2009-04-24T00:21:28Z
[ "python", "sqlalchemy" ]
How to set correct value for Django ROOT_URLCONF setting in different branches
781,211
<p>I've put site directory created by <code>django-admin startproject</code> under version control (Mercurial). Let's say, the site is called <code>frobnicator</code>.</p> <p>Now I want to make some serious refactoring, so I clone the site using command</p> <pre><code>hg clone frobnicator frobnicator-refactoring` </code></pre> <p>but <code>ROOT_URLCONF</code> in <code>settings.py</code> still says <code>frobnicator.urls</code>.</p> <p>Is there a better way to overcome this problem rather than moving the site in a wrapper directory and storing this directory under version control (to maintain the same site name after branching) or using local branches?</p>
7
2009-04-23T10:54:32Z
781,404
<p>Simply remove project name form <code>ROOT_URLCONF</code> definition - it is optional. Then you can have project folder with different names.</p>
13
2009-04-23T12:01:26Z
[ "python", "django", "mercurial" ]
CSS parser + XHTML generator, advice needed
781,382
<p>Guys, I need to develop a tool which would meet following requirements:</p> <ol> <li>Input: XHTML document with CSS rules within <code>head</code> section. </li> <li>Output: XHTML document with CSS rules computed in tag attributes</li> </ol> <p>The best way to illustrate the behavior I want is as follows.</p> <p>Example input:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css" media="screen"&gt; .a { color: red; } p { font-size: 12px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;p class="a"&gt;Lorem Ipsum&lt;/p&gt; &lt;div class="a"&gt; &lt;p&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Example output:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;body&gt; &lt;p style="color: red; font-size: 12px;"&gt;Lorem Ipsum&lt;/p&gt; &lt;div style="color: red;"&gt; &lt;p style="font-size: 12px;"&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What tools/libraries will fit best for such task? I'm not sure if BeautifulSoup and cssutils is capable of doing this. </p> <p>Python is not a requirement. Any recommendations will be highly appreciated. </p>
5
2009-04-23T11:53:09Z
782,055
<p>Depends on how complicated your CSS is going to be. If it's a simple matter of elements ("p {}", "a {}"), IDs/Classes (#test {}), then probably easiest to use regular expressions. You'd have to have one to find all the style definitions and then parse them, then use more regular expressions to find instances of tags that match.</p> <p>For, for example, if you found you had a style for A tags, you could use a regular expression like:</p> <pre><code>&lt;a\b[^&gt;]*&gt;(.*?)&lt;/a&gt; </code></pre> <p>To get them, then you'd have to do a replace to add the style. Of course you'd want the regex to accept the tag as a parameter (the A tag in this case).</p> <p>If you got into child selection or anything more than just root elements and ID/classes this could get messy fast. </p> <p>Consider just defining the styles inline to begin with?</p>
0
2009-04-23T14:38:25Z
[ "python", "css", "parsing", "xhtml" ]
CSS parser + XHTML generator, advice needed
781,382
<p>Guys, I need to develop a tool which would meet following requirements:</p> <ol> <li>Input: XHTML document with CSS rules within <code>head</code> section. </li> <li>Output: XHTML document with CSS rules computed in tag attributes</li> </ol> <p>The best way to illustrate the behavior I want is as follows.</p> <p>Example input:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css" media="screen"&gt; .a { color: red; } p { font-size: 12px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;p class="a"&gt;Lorem Ipsum&lt;/p&gt; &lt;div class="a"&gt; &lt;p&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Example output:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;body&gt; &lt;p style="color: red; font-size: 12px;"&gt;Lorem Ipsum&lt;/p&gt; &lt;div style="color: red;"&gt; &lt;p style="font-size: 12px;"&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What tools/libraries will fit best for such task? I'm not sure if BeautifulSoup and cssutils is capable of doing this. </p> <p>Python is not a requirement. Any recommendations will be highly appreciated. </p>
5
2009-04-23T11:53:09Z
782,094
<p>Try premailer</p> <p><a href="http://code.dunae.ca/premailer.web/" rel="nofollow">code.dunae.ca/premailer.web</a></p> <p>More info: <a href="http://www.campaignmonitor.com/blog/post/2455/automatically-generate-inline/" rel="nofollow">campaignmonitor.com</a></p>
3
2009-04-23T14:48:14Z
[ "python", "css", "parsing", "xhtml" ]
CSS parser + XHTML generator, advice needed
781,382
<p>Guys, I need to develop a tool which would meet following requirements:</p> <ol> <li>Input: XHTML document with CSS rules within <code>head</code> section. </li> <li>Output: XHTML document with CSS rules computed in tag attributes</li> </ol> <p>The best way to illustrate the behavior I want is as follows.</p> <p>Example input:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css" media="screen"&gt; .a { color: red; } p { font-size: 12px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;p class="a"&gt;Lorem Ipsum&lt;/p&gt; &lt;div class="a"&gt; &lt;p&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Example output:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;body&gt; &lt;p style="color: red; font-size: 12px;"&gt;Lorem Ipsum&lt;/p&gt; &lt;div style="color: red;"&gt; &lt;p style="font-size: 12px;"&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What tools/libraries will fit best for such task? I'm not sure if BeautifulSoup and cssutils is capable of doing this. </p> <p>Python is not a requirement. Any recommendations will be highly appreciated. </p>
5
2009-04-23T11:53:09Z
782,208
<p>While I do not know any specific tool to do this, here is the basic approach I would take: <br></p> <p>Load as xml document <br> Extract the css classes and styles from document <br> For each pair of css class and style <br> &nbsp;&nbsp;Construct xpath query from css class <br> &nbsp;&nbsp;For each matching node<br> &nbsp;&nbsp;&nbsp;&nbsp;Set the style attribute for that class <br> Remove style node from document Convert document to string</p>
1
2009-04-23T15:17:44Z
[ "python", "css", "parsing", "xhtml" ]
CSS parser + XHTML generator, advice needed
781,382
<p>Guys, I need to develop a tool which would meet following requirements:</p> <ol> <li>Input: XHTML document with CSS rules within <code>head</code> section. </li> <li>Output: XHTML document with CSS rules computed in tag attributes</li> </ol> <p>The best way to illustrate the behavior I want is as follows.</p> <p>Example input:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css" media="screen"&gt; .a { color: red; } p { font-size: 12px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;p class="a"&gt;Lorem Ipsum&lt;/p&gt; &lt;div class="a"&gt; &lt;p&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Example output:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;body&gt; &lt;p style="color: red; font-size: 12px;"&gt;Lorem Ipsum&lt;/p&gt; &lt;div style="color: red;"&gt; &lt;p style="font-size: 12px;"&gt;Oh hai&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What tools/libraries will fit best for such task? I'm not sure if BeautifulSoup and cssutils is capable of doing this. </p> <p>Python is not a requirement. Any recommendations will be highly appreciated. </p>
5
2009-04-23T11:53:09Z
1,693,936
<p>There is a <a href="http://pypi.python.org/pypi/premailer" rel="nofollow">premailer python package on Pypi</a></p>
1
2009-11-07T18:17:01Z
[ "python", "css", "parsing", "xhtml" ]
Python3 Http Web Server: virtual hosts
781,466
<p>I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok. </p> <p>There is only one requirement for this project, which I can't implement on my own - virtual hosts. I need to have at least two virtual hosts, defined in config files. The problem is, that I can't find a way how can I implement them in python. Does anyone have any guides, articles, maybe some simple implementation how can this be done?</p> <p>I would be grateful for any help.</p>
2
2009-04-23T12:20:12Z
781,474
<p>Virtual hosts work by obeying the Host: header in the HTTP request.</p> <p>Just read the headers of the request, and take action based on the value of the Host: header</p>
10
2009-04-23T12:22:59Z
[ "python", "http", "python-3.x", "virtualhost" ]
Python3 Http Web Server: virtual hosts
781,466
<p>I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok. </p> <p>There is only one requirement for this project, which I can't implement on my own - virtual hosts. I need to have at least two virtual hosts, defined in config files. The problem is, that I can't find a way how can I implement them in python. Does anyone have any guides, articles, maybe some simple implementation how can this be done?</p> <p>I would be grateful for any help.</p>
2
2009-04-23T12:20:12Z
961,575
<p>For a simple HTTP web server, you can start with the <a href="http://docs.python.org/3.0/library/wsgiref.html#module-wsgiref">WSGI reference implementation</a>:</p> <blockquote> <p>wsgiref is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. It provides utilities for manipulating WSGI environment variables and response headers, base classes for implementing WSGI servers, <strong>a demo HTTP server that serves WSGI applications</strong>,...</p> </blockquote> <p>Modifying the example server to check the <code>HTTP_HOST</code> header, here is a simple app that responds, depending on the virtual host, with a different text. (Extending the example to use a configuration file is left as an exercise).</p> <pre><code>import wsgiref from wsgiref.simple_server import make_server def my_app(environ,start_response): from io import StringIO stdout = StringIO() host = environ["HTTP_HOST"].split(":")[0] if host == "127.0.0.1": print("This is virtual host 1", file=stdout) elif host == "localhost": print("This is virtual host 2", file=stdout) else: print("Unknown virtual host", file=stdout) print("Hello world!", file=stdout) print(file=stdout) start_response(b"200 OK", [(b'Content-Type',b'text/plain; charset=utf-8')]) return [stdout.getvalue().encode("utf-8")] def test1(): httpd = make_server('', 8000, my_app) print("Serving HTTP on port 8000...") # Respond to requests until process is killed httpd.serve_forever() </code></pre>
5
2009-06-07T09:36:36Z
[ "python", "http", "python-3.x", "virtualhost" ]
Communicating with a Python service
781,594
<p><strong>Problem:</strong></p> <p>I have a python script that I have running as a service. It's a subclass of the win32 class win32serviceutil.ServiceFramework. I want a simple straightforward way of sending arbitrary commands to it via the command line. </p> <p><strong>What I've looked at:</strong></p> <p>It looks like the standard way of controlling the service once it's started is by using another program and sending it command signals, but I need to be able to send a short string to it as well as an argument. It looks like using a NamedPipe might be a good idea, but it's really too complex for what I wanted to do, is there any other simpler way?</p>
0
2009-04-23T13:06:03Z
781,778
<p>Not really.</p> <p>You have many, many ways to do "Interprocess Communication" (IPC) in Python.</p> <ul> <li><p><a href="http://docs.python.org/library/socket.html" rel="nofollow">Sockets</a></p></li> <li><p>Named Pipes (see <a href="http://developers.sun.com/solaris/articles/named_pipes.html" rel="nofollow">http://developers.sun.com/solaris/articles/named_pipes.html</a>) -- it involves a little bit of OS magic to create, but then it's just a file that you read and write.</p></li> <li><p>Shared Memory (see <a href="http://en.wikipedia.org/wiki/Shared_memory" rel="nofollow">http://en.wikipedia.org/wiki/Shared_memory</a>) -- this also involves a fair amount of OS-level magic.</p></li> <li><p>Semphores and Locks; <a href="http://docs.python.org/library/posixfile.html" rel="nofollow">files with locks</a> can work well for IPC.</p></li> <li><p>Higher-level protocols built on sockets...</p> <ul> <li><p>HTTP; this is what WSGI is all about.</p></li> <li><p>FTP</p></li> <li><p>etc.</p></li> </ul></li> </ul> <p>A common solution is to use HTTP and define "RESTful" commands. Your service listens on port 80 for HTTP requests that contain arguments and parameters. Look at <a href="http://docs.python.org/library/wsgiref.html" rel="nofollow">wsgiref</a> for more information on this.</p>
2
2009-04-23T13:45:33Z
[ "python", "winapi", "command-line", "service" ]
How to hide __methods__ in python?
781,667
<p>I just wondered, how to hide special </p> <pre><code>__.*__ </code></pre> <p>methods in python*? Especially I am using an interactive python interpreter with tab-completion, and I would like to display only the methods my modules expose ... </p> <p>thanks,</p> <p>/ myyn /</p> <p>*(at least from the user, who uses a python shell)</p> <p><hr /></p> <p>it looks like this now:</p> <pre><code>h[2] &gt;&gt;&gt; Q. Q.ALL( Q.__delattr__( Q.__getattribute__( Q.__package__ Q.__sizeof__( Q.find_values( Q.json Q.DEFAULT_CONDITION( Q.__dict__ Q.__hash__( Q.__reduce__( Q.__str__( Q.get_loops_total_platform( Q.jsonlib Q.SUCCESSFUL( Q.__doc__ Q.__init__( Q.__reduce_ex__( Q.__subclasshook__( Q.get_platforms( Q.memoize( Q.__all__ Q.__file__ Q.__name__ Q.__repr__( Q.cached_open( Q.get_snippets( Q.__class__( Q.__format__( Q.__new__( Q.__setattr__( Q.find_results( Q.get_subjects( h[2] &gt;&gt;&gt; Q. </code></pre> <p>and I wish it looked like:</p> <pre><code>h[2] &gt;&gt;&gt; Q. Q.ALL( Q.find_values( Q.json Q.DEFAULT_CONDITION( Q.get_loops_total_platform( Q.jsonlib Q.SUCCESSFUL( Q.get_platforms( Q.memoize( Q.cached_open( Q.get_snippets( Q.find_results( Q.get_subjects( h[2] &gt;&gt;&gt; Q. </code></pre>
5
2009-04-23T13:25:29Z
781,790
<p>I think you should look for a way to get that particular environment/interpreter to stop displaying the "private" methods when you press TAB. I don't think there is a way to "hide" methods from Python itself, that would be very weird.</p>
3
2009-04-23T13:49:04Z
[ "python", "hide", "magic-methods", "facade" ]
How to hide __methods__ in python?
781,667
<p>I just wondered, how to hide special </p> <pre><code>__.*__ </code></pre> <p>methods in python*? Especially I am using an interactive python interpreter with tab-completion, and I would like to display only the methods my modules expose ... </p> <p>thanks,</p> <p>/ myyn /</p> <p>*(at least from the user, who uses a python shell)</p> <p><hr /></p> <p>it looks like this now:</p> <pre><code>h[2] &gt;&gt;&gt; Q. Q.ALL( Q.__delattr__( Q.__getattribute__( Q.__package__ Q.__sizeof__( Q.find_values( Q.json Q.DEFAULT_CONDITION( Q.__dict__ Q.__hash__( Q.__reduce__( Q.__str__( Q.get_loops_total_platform( Q.jsonlib Q.SUCCESSFUL( Q.__doc__ Q.__init__( Q.__reduce_ex__( Q.__subclasshook__( Q.get_platforms( Q.memoize( Q.__all__ Q.__file__ Q.__name__ Q.__repr__( Q.cached_open( Q.get_snippets( Q.__class__( Q.__format__( Q.__new__( Q.__setattr__( Q.find_results( Q.get_subjects( h[2] &gt;&gt;&gt; Q. </code></pre> <p>and I wish it looked like:</p> <pre><code>h[2] &gt;&gt;&gt; Q. Q.ALL( Q.find_values( Q.json Q.DEFAULT_CONDITION( Q.get_loops_total_platform( Q.jsonlib Q.SUCCESSFUL( Q.get_platforms( Q.memoize( Q.cached_open( Q.get_snippets( Q.find_results( Q.get_subjects( h[2] &gt;&gt;&gt; Q. </code></pre>
5
2009-04-23T13:25:29Z
782,231
<p>I would take a look into ipython. Maybe your are able to hook ipythons interactive shell without an subprocess into your app and apply the private method filtering from there.</p>
1
2009-04-23T15:21:24Z
[ "python", "hide", "magic-methods", "facade" ]
How to hide __methods__ in python?
781,667
<p>I just wondered, how to hide special </p> <pre><code>__.*__ </code></pre> <p>methods in python*? Especially I am using an interactive python interpreter with tab-completion, and I would like to display only the methods my modules expose ... </p> <p>thanks,</p> <p>/ myyn /</p> <p>*(at least from the user, who uses a python shell)</p> <p><hr /></p> <p>it looks like this now:</p> <pre><code>h[2] &gt;&gt;&gt; Q. Q.ALL( Q.__delattr__( Q.__getattribute__( Q.__package__ Q.__sizeof__( Q.find_values( Q.json Q.DEFAULT_CONDITION( Q.__dict__ Q.__hash__( Q.__reduce__( Q.__str__( Q.get_loops_total_platform( Q.jsonlib Q.SUCCESSFUL( Q.__doc__ Q.__init__( Q.__reduce_ex__( Q.__subclasshook__( Q.get_platforms( Q.memoize( Q.__all__ Q.__file__ Q.__name__ Q.__repr__( Q.cached_open( Q.get_snippets( Q.__class__( Q.__format__( Q.__new__( Q.__setattr__( Q.find_results( Q.get_subjects( h[2] &gt;&gt;&gt; Q. </code></pre> <p>and I wish it looked like:</p> <pre><code>h[2] &gt;&gt;&gt; Q. Q.ALL( Q.find_values( Q.json Q.DEFAULT_CONDITION( Q.get_loops_total_platform( Q.jsonlib Q.SUCCESSFUL( Q.get_platforms( Q.memoize( Q.cached_open( Q.get_snippets( Q.find_results( Q.get_subjects( h[2] &gt;&gt;&gt; Q. </code></pre>
5
2009-04-23T13:25:29Z
782,676
<p>Well, you could create a subclass of <code>rlcompleter.Completer</code>, override the methods in question, and install that into <code>readline</code>.</p> <pre><code>import rlcompleter import readline class MyCompleter(rlcompleter.Completer): def global_matches(self, text): .... def attr_matches(self, text): .... import readline readline.set_completer(MyCompleter().complete) </code></pre> <p>These code snippets allow case-insensitive tab completion:</p> <p><a href="http://www.nabble.com/Re%3A-Tab-completion-question-p22905952.html" rel="nofollow">http://www.nabble.com/Re%3A-Tab-completion-question-p22905952.html</a></p>
3
2009-04-23T17:06:45Z
[ "python", "hide", "magic-methods", "facade" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
781,909
<p>This has the potential to hammer your CPU, even when there is nothing to process.</p> <p><strong>Edit:</strong> Actually <a href="http://docs.python.org/library/time.html#time.sleep" rel="nofollow"><code>sleep()</code></a> takes an argument as a number of seconds, not milliseconds so I don't think the CPU is going to be a problem. Still, perhaps you could use a cron job to schedule something like this.</p>
0
2009-04-23T14:10:24Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
781,913
<p>Instead of sleeping for 15 seconds, it might be better to have a callback which restarts your job when new files arrive.</p> <ul> <li>Process available files</li> <li>Check for new files every 60 seconds or whatever interval you choose</li> <li>When a new file arrives, process it and any others which may have arrived since the last interval</li> </ul>
1
2009-04-23T14:11:03Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
781,930
<p>Why not just use a cron job to run a script every minute or so? At least you are not depending on your own loop to be continuously running in the background.</p>
1
2009-04-23T14:12:58Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
781,934
<p>Besides the cost of hammering your cpu, there is the cost of the <em>morejobs()</em> call. You can mitigate by using a higher value for <em>sleep()</em>, or you can use some sort of mailbox that receives requests and then fires the <em>zipfile()</em> operation.</p> <p>It is normal for some operations to have a background thread scheduled that temporarily checks for something. In this case the best is to use sensible values for <em>sleep()</em>.</p>
0
2009-04-23T14:13:41Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
781,948
<p>If it takes (and these figures are examples) 20 seconds for a file to arrive and 5 seconds for you to process it, what is the harm in your process waiting for, on average, another 7.5 seconds before it even detects that the file is there?</p> <p>A sleeping process should have as close to zero impact on the CPU as it is possible to get.</p> <p>So no, I would not be concerned about this aspect at all.</p> <p>The one thing you should be concerned about is how to restart the process automatically if it fails. I would run a cron job every 5 minutes (your choice of actual frequency) to kill off the old copy (politely, and only if it's running) and then start a new one. That way, there'll only be a 5-minute downtime at most if something goes wrong.</p> <p>I say politely because the old one may be in the middle of processing files and you should not interrupt that unless it's recoverable.</p>
1
2009-04-23T14:16:01Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
781,980
<p>Sleep involves no overhead. The Linux OS uses a very simple signal to wake a sleeping process.</p> <p>What you're showing is the "busy-waiting" design pattern.</p> <p>To eliminate overhead, you want to be woken ONLY when there's work to do.</p> <p>Ways to do this.</p> <ol> <li><p>Wait on read.</p></li> <li><p>Wait on a select function call. See <a href="http://docs.python.org/library/select.html" rel="nofollow">http://docs.python.org/library/select.html</a></p></li> <li><p>Wait for a lock to be released. See <a href="http://docs.python.org/library/posixfile.html" rel="nofollow">http://docs.python.org/library/posixfile.html</a>.</p></li> </ol> <p>Of these, waiting on a read is perhaps easiest. Reading from a pipe or a socket is what you want to do. </p> <p>I'm guessing that you have a "multiple-writers-single-reader" design pattern. In this case, there are two candidate solutions.</p> <ol> <li><p>Multiple requests per socket. This is the FTP-like solution where you write a simple server that listens for connections on one socket and opens a dedicated connection for each client. Then you use select to determine which client is sending a file.</p></li> <li><p>Single request per socket. This is the HTTP-like solution where you receive requests in some socket and the request is a big flood of data. When the request is all finished, the socket is closed so another client can get it.</p></li> </ol> <p>In these two cases, you're not sleeping -- you're waiting for I/O's to complete.</p>
4
2009-04-23T14:22:10Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
783,881
<p>"A thousand reasoned opinions are worth one measurement". </p> <p>Just try it.</p>
0
2009-04-23T22:50:54Z
[ "python", "resources", "performance", "queue" ]
Penalties of a script constantly looping in the background
781,896
<p>I know this topic has been <a href="http://stackoverflow.com/questions/680921#681336">discussed</a> in the <a href="http://stackoverflow.com/questions/379231">past</a>, but I am a tiny bit paranoid about resource usage.</p> <p>I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:</p> <pre><code>while True: while morejobs(): zipfile() sleep(15seconds) </code></pre> <p>What sort of resources would be consumed by a process constantly looping away in the background (provided there is nothing to zip)? Is there anything i should be aware of or careful of? <br/><br/> <h2> Edit:</h2> It looks like most of the answers are concerned about the duration of the sleep. I blindly set it to sleep (in the code example) for 15 milliseconds at a time. I actually intended it to be 15 seconds, and i have 'updated' the code to reflect that.</p> <p><h2> Edit Again:</h2> What would be the lowest reasonable time for the script to be sleeping? Is 5 seconds to low? I have no idea what the load of this app would be or how often new jobs would be added to the queue.</p>
0
2009-04-23T14:08:25Z
784,315
<p>As an alternative you can lower the priority of your process. (I'm only familiar with the windows method)</p> <p>On Windows:</p> <pre><code>def setpriority(pid=None,priority=1): """ Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the priority of the current python process but can take any valid process ID. """ import win32api,win32process,win32con priorityclasses = [win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS] if pid == None: pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityclasses[priority]) </code></pre> <p>from: <a href="http://code.activestate.com/recipes/496767/" rel="nofollow">http://code.activestate.com/recipes/496767/</a></p>
1
2009-04-24T02:30:45Z
[ "python", "resources", "performance", "queue" ]
Qt and context menu
782,255
<p>i need to create a context menu on right clicking at my window. But i really don't know what should i do. Are there any widgets or i must make it by my hands? Programming language: Python Graphical lib: Qt (PyQt).</p>
14
2009-04-23T15:26:41Z
782,462
<p>I can't speak for python, but it's fairly easy in C++.</p> <p>first after creating the widget you set the policy:</p> <pre><code>w-&gt;setContextMenuPolicy(Qt::CustomContextMenu); </code></pre> <p>then you connect the context menu event to a slot:</p> <pre><code>connect(w, SIGNAL(customContextMenuRequested(const QPoint &amp;)), this, SLOT(ctxMenu(const QPoint &amp;))); </code></pre> <p>Finally, you implement the slot:</p> <pre><code>void A::ctxMenu(const QPoint &amp;pos) { QMenu *menu = new QMenu; menu-&gt;addAction(tr("Test Item"), this, SLOT(test_slot())); menu-&gt;exec(w-&gt;mapToGlobal(pos)); } </code></pre> <p>that's how you do it in c++ , shouldn't be too different in the python API.</p> <p><strong>EDIT:</strong> after looking around on google, here's the setup portion of my example in python:</p> <pre><code>self.w = QWhatever(); self.w.setContextMenuPolicy(Qt.CustomContextMenu) self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu) </code></pre>
39
2009-04-23T16:14:44Z
[ "python", "qt", "pyqt", "menu" ]
Qt and context menu
782,255
<p>i need to create a context menu on right clicking at my window. But i really don't know what should i do. Are there any widgets or i must make it by my hands? Programming language: Python Graphical lib: Qt (PyQt).</p>
14
2009-04-23T15:26:41Z
958,969
<p>Another example which shows how to use actions in a toolbar and context menu.</p> <pre><code>class Foo( QtGui.QWidget ): def __init__(self): QtGui.QWidget.__init__(self, None) mainLayout = QtGui.QVBoxLayout() self.setLayout(mainLayout) # Toolbar toolbar = QtGui.QToolBar() mainLayout.addWidget(toolbar) # Action are added/created using the toolbar.addAction # which creates a QAction, and returns a pointer.. # .. instead of myAct = new QAction().. toolbar.AddAction(myAct) # see also menu.addAction and others self.actionAdd = toolbar.addAction("New", self.on_action_add) self.actionEdit = toolbar.addAction("Edit", self.on_action_edit) self.actionDelete = toolbar.addAction("Delete", self.on_action_delete) self.actionDelete.setDisabled(True) # Tree self.tree = QtGui.QTreeView() mainLayout.addWidget(self.tree) self.tree.setContextMenuPolicy( Qt.CustomContextMenu ) self.connect(self.tree, QtCore.SIGNAL('customContextMenuRequested(const QPoint&amp;)'), self.on_context_menu) # Popup Menu is not visible, but we add actions from above self.popMenu = QtGui.QMenu( self ) self.popMenu.addAction( self.actionEdit ) self.popMenu.addAction( self.actionDelete ) self.popMenu.addSeparator() self.popMenu.addAction( self.actionAdd ) def on_context_menu(self, point): self.popMenu.exec_( self.tree.mapToGlobal(point) ) </code></pre>
14
2009-06-06T04:07:47Z
[ "python", "qt", "pyqt", "menu" ]
Emacs function to message the python function I'm in
782,357
<p>I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead?</p> <pre><code>(defun python-show-function-name() "Message the name of the function the point is in" (interactive) (save-excursion (beginning-of-defun) (message (format "%s" (thing-at-point 'line))))) </code></pre>
10
2009-04-23T15:50:22Z
782,411
<p>C-c C-u (py-goto-block-up) might be what you want.</p>
0
2009-04-23T16:00:53Z
[ "python", "emacs", "elisp" ]
Emacs function to message the python function I'm in
782,357
<p>I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead?</p> <pre><code>(defun python-show-function-name() "Message the name of the function the point is in" (interactive) (save-excursion (beginning-of-defun) (message (format "%s" (thing-at-point 'line))))) </code></pre>
10
2009-04-23T15:50:22Z
782,413
<p>You may find decent results with <a href="http://www.gnu.org/software/emacs/manual/html%5Fnode/emacs/Which-Function.html">which-function-mode</a>:</p> <blockquote> <p>Which Function mode is a minor mode that displays the current function name in the mode line, updating it as you move around in a buffer.</p> <p>To either enable or disable Which Function mode, use the command M-x which-function-mode. This command is global; it applies to all buffers, both existing ones and those yet to be created. However, it takes effect only in certain major modes, those listed in the value of which-func-modes. If the value is t, then Which Function mode applies to all major modes that know how to support it—in other words, all the major modes that support Imenu.</p> </blockquote> <p>Although I see it getting a little confused in one Python file that I have here...</p>
21
2009-04-23T16:01:39Z
[ "python", "emacs", "elisp" ]
Emacs function to message the python function I'm in
782,357
<p>I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead?</p> <pre><code>(defun python-show-function-name() "Message the name of the function the point is in" (interactive) (save-excursion (beginning-of-defun) (message (format "%s" (thing-at-point 'line))))) </code></pre>
10
2009-04-23T15:50:22Z
782,445
<p>Did you try <code>py-beginning-of-def-or-class</code>?</p> <pre><code>(defun python-show-function-name() "Message the name of the function the point is in" (interactive) (save-excursion (py-beginning-of-def-or-class) (message (format "%s" (thing-at-point 'line))))) </code></pre> <p>I find it gives me better results than your <code>beginning-of-defun</code>, but if that's not the problem you're having, then maybe I'm just seeing another symptom of the cause of the wonkiness in <a href="http://stackoverflow.com/questions/782357/emacs-function-to-message-the-python-function-im-in/782413#782413">my other answer</a>.</p>
2
2009-04-23T16:09:00Z
[ "python", "emacs", "elisp" ]
Implementing a 'function-calling function'
782,605
<p>I would like to write a bit of code that calls a function specified by a given argument. EG:</p> <pre><code>def caller(func): return func() </code></pre> <p>However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments specified (if any).</p> <pre><code>def caller(func, args): # calls func with the arguments specified in args </code></pre> <p>Is there a simple, pythonic way to do this?</p>
0
2009-04-23T16:50:16Z
782,609
<p>You can do this by using <a href="http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow">arbitrary argument lists</a> and <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">unpacking argument lists</a>.</p> <pre><code>&gt;&gt;&gt; def caller(func, *args, **kwargs): ... return func(*args, **kwargs) ... &gt;&gt;&gt; def hello(a, b, c): ... print a, b, c ... &gt;&gt;&gt; caller(hello, 1, b=5, c=7) 1 5 7 </code></pre> <p>Not sure <em>why</em> you feel the need to do it, though.</p>
12
2009-04-23T16:51:20Z
[ "function", "functional-programming", "python" ]
Implementing a 'function-calling function'
782,605
<p>I would like to write a bit of code that calls a function specified by a given argument. EG:</p> <pre><code>def caller(func): return func() </code></pre> <p>However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments specified (if any).</p> <pre><code>def caller(func, args): # calls func with the arguments specified in args </code></pre> <p>Is there a simple, pythonic way to do this?</p>
0
2009-04-23T16:50:16Z
782,627
<p>This already exists as the <a href="http://docs.python.org/library/functions.html#apply" rel="nofollow">apply</a> function, though it is considered obsolete due to the new *args and **kwargs syntax.</p> <pre><code>&gt;&gt;&gt; def foo(a,b,c): print a,b,c &gt;&gt;&gt; apply(foo, (1,2,3)) 1 2 3 &gt;&gt;&gt; apply(foo, (1,2), {'c':3}) # also accepts keyword args </code></pre> <p>However, the * and ** syntax is generally a better solution. The above is equivalent to:</p> <pre><code>&gt;&gt;&gt; foo(*(1,2), **{'c':3}) </code></pre>
7
2009-04-23T16:56:01Z
[ "function", "functional-programming", "python" ]
wxPython: Using EVT_IDLE
783,023
<p>I defined an handler for <code>EVT_IDLE</code> that does a certain background task for me. (That task is to take completed work from a few processes and integrate it into some object, making a visible change in the GUI.)</p> <p>The problem is that when the user is not moving the mouse or doing anything, <code>EVT_IDLE</code> doesn't get called more than once. I would like this handler to be working all the time. So I tried calling <code>event.RequestMore()</code> at the end of the handler. Works, but now it takes a whole lot of CPU. (I'm guessing it's just looping excessively on that task.)</p> <p>I'm willing to limit the number of times the task will be carried out per second; How do I do that?</p> <p>Or do you have another solution in mind?</p>
3
2009-04-23T18:45:30Z
783,386
<p>Something like this (executes at most every second):</p> <pre><code>... def On_Idle(self, event): if not self.queued_batch: wx.CallLater(1000, self.Do_Batch) self.queued_batch = True def Do_Batch(self): # &lt;- insert your stuff here self.queued_batch = False ... </code></pre> <p>Oh, and don't forget to set self.queued_batch to False in the constructor and maybe call event.RequestMore() in some way in On_Idle.</p>
2
2009-04-23T20:27:04Z
[ "python", "wxpython" ]
wxPython: Using EVT_IDLE
783,023
<p>I defined an handler for <code>EVT_IDLE</code> that does a certain background task for me. (That task is to take completed work from a few processes and integrate it into some object, making a visible change in the GUI.)</p> <p>The problem is that when the user is not moving the mouse or doing anything, <code>EVT_IDLE</code> doesn't get called more than once. I would like this handler to be working all the time. So I tried calling <code>event.RequestMore()</code> at the end of the handler. Works, but now it takes a whole lot of CPU. (I'm guessing it's just looping excessively on that task.)</p> <p>I'm willing to limit the number of times the task will be carried out per second; How do I do that?</p> <p>Or do you have another solution in mind?</p>
3
2009-04-23T18:45:30Z
783,439
<p>This sounds like a use case for wxTimerEvent instead of wxIdleEvent. When there is processing to do call wxTimerEvent.Start(). When there isn't any to do, call wxTimerEvent.Stop() and call your methods to do processing from EVT_TIMER.</p> <p>(note: i use from wxWidghets for C++ and am not familiar with wxPython but I assume they have a similar API)</p>
0
2009-04-23T20:43:20Z
[ "python", "wxpython" ]
English and/or Finnish text validation
783,189
<p>Is there an easy-to-use python module that'd do english or finnish text validation?</p> <p>It'd be ok if I could just check the words exist in user-defined dictionary and possibly checking that the grammar is somewhat okay.</p> <p>I am planning to implement a fancy validation for a directory contents I did while ago back. This involves some simple stuff like checking that the config scripts won't crash and does it all well. It's all quite easy otherwise.</p> <p>For the validator I should just be able to input whole files or strings of unicode text.</p>
0
2009-04-23T19:27:10Z
783,207
<p>I'm not sure what you're trying to do, but if you're looking for something that can say 'this is valid English' or 'this is valid Finnish', then you're looking at a class of problems that is quite likely unsolvable.</p> <p>If not, then use a dictionary and/or letter frequencies and Bayesian analysis to determine whether or not given text is English-like or Finnish-like. If you're trying to auto-detect a language, this is likely the best route, although you'll run into problems with mixed-language text.</p>
2
2009-04-23T19:32:06Z
[ "python" ]
Creating a tree from a list of tuples
783,217
<p>I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that</p> <pre><code>(id, parent_id, value) </code></pre> <p>So that it is a representation of the tree as a flattend list of list of tree nodes.</p> <p>For example the input</p> <pre><code>(1, None, '...') (3, 2', '...') (2, 1, '...') (4, 1, '...') (5, 2, '...') (6, None, '...') </code></pre> <p>Should sorted like that afterwards</p> <pre><code>(1, None, '...') (2, 1, '...') (3, 2', '...') (5, 2, '...') (4, 1, '...') (6, None, '...') </code></pre> <p>Any hint would be highly appreciated. Thanks in advance.</p>
2
2009-04-23T19:34:26Z
783,240
<p>Python sorts tuples from left to right, so if you arrange your tuples so the first sort key is the first item and so forth, it'll be reasonably efficient.</p> <p>The mapping from a list of tuples to a tree is not clear from what you're describing. Please draw it out, or explain it more thoroughly. For example, your example appears to be:</p> <p><img src="http://web.sabi.net/temp/tree.png" alt="tree diagram" /></p> <p>If you've got two nodes with no parent, that is more like a forest than a tree. What are you trying to represent with the tree? What does "sorted" mean in this context?</p>
2
2009-04-23T19:44:51Z
[ "python", "sorting", "tree" ]
Creating a tree from a list of tuples
783,217
<p>I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that</p> <pre><code>(id, parent_id, value) </code></pre> <p>So that it is a representation of the tree as a flattend list of list of tree nodes.</p> <p>For example the input</p> <pre><code>(1, None, '...') (3, 2', '...') (2, 1, '...') (4, 1, '...') (5, 2, '...') (6, None, '...') </code></pre> <p>Should sorted like that afterwards</p> <pre><code>(1, None, '...') (2, 1, '...') (3, 2', '...') (5, 2, '...') (4, 1, '...') (6, None, '...') </code></pre> <p>Any hint would be highly appreciated. Thanks in advance.</p>
2
2009-04-23T19:34:26Z
783,313
<p>I'm not sure I've quite follows what you are exactly trying to do, but if you have a forest as a list of nodes, can't you just read it and build the tree structure, then write it out as a bread-first traversal of all the trees? Any particular reason to avoid this?</p>
1
2009-04-23T20:04:04Z
[ "python", "sorting", "tree" ]
Creating a tree from a list of tuples
783,217
<p>I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that</p> <pre><code>(id, parent_id, value) </code></pre> <p>So that it is a representation of the tree as a flattend list of list of tree nodes.</p> <p>For example the input</p> <pre><code>(1, None, '...') (3, 2', '...') (2, 1, '...') (4, 1, '...') (5, 2, '...') (6, None, '...') </code></pre> <p>Should sorted like that afterwards</p> <pre><code>(1, None, '...') (2, 1, '...') (3, 2', '...') (5, 2, '...') (4, 1, '...') (6, None, '...') </code></pre> <p>Any hint would be highly appreciated. Thanks in advance.</p>
2
2009-04-23T19:34:26Z
1,790,387
<p>Oliver, if I understand correctly, I think you can either (a) retrieve all tuples from your database into a dictionary or list, and then construct the tree, OR (b) use an ORDER BY clause when you retrieve the tuples so that they are in the order in which you will add them to the tree. </p> <p>If changes to the tree may be made in your application and then propagated to the database, I would opt for a, but if changes are always made as database inserts, updates or deletes, and apart from these your tree is read-only, then option b should be faster and require less resources.</p> <p>Roland</p>
0
2009-11-24T14:22:51Z
[ "python", "sorting", "tree" ]
Send data to the browser while waiting (Python)
783,262
<p>I have the following code</p> <pre><code>print "Starting stage 1&lt;br&gt;" # Something that takes about 5 seconds time.sleep(5) print "Stage 1 complete" </code></pre> <p>I view the script with my browser as it's part of a web-app, the problem is that it's displaying all of it together. I want it to display first the starting message before it starts and then add the completion message after it's complete.</p> <p>What do I use to push information to the browser in this fashion?</p>
3
2009-04-23T19:47:43Z
783,268
<p>Try flush the output after the first print using sys.stdout.<a href="http://docs.python.org/library/stdtypes.html#file.flush" rel="nofollow">flush()</a></p>
5
2009-04-23T19:49:38Z
[ "python" ]
Pylons or TurboGears vs. .NET or Java
783,488
<p>We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're used to enterprisey stuff).</p> <p>Their web app will have some data analysis that we'll offload as well as a twang of social networking features. (basically all they have so far is some Flex mockups for UX)</p> <p>I'm looking for some evidence with regard to development time, or other reasons that will help our argument to reassure the customer.</p> <p>The other options is that we're barking up the wrong tree and have no idea. I hope that's not the case.</p> <p>Any references to case studies or whatnot would be nice. The best I could find are</p> <p><a href="http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html" rel="nofollow">http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html</a></p> <p>and </p> <p><a href="http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html" rel="nofollow">http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html</a></p> <p>which are a bit dated (wrt to TG2 and whatnot)</p> <p>Thanks!</p>
4
2009-04-23T20:57:23Z
783,515
<p>It's almost easier to build a quick Proof of Concept service that demonstrates how clean and simple it is.</p> <p>A simple SQLAlchemy mapping with a quick demo of query processing.</p> <p>A simple template showing how cool Mako is.</p> <p>A simple Pylons app to put the two together.</p> <p>Most important -- use their application and their data. Not a lame hello world; not an existing tutorial.</p> <p>If they want to compare your clean, elegant demo of their app with .NET and J2EE, they'll see that other languages lead to a much, much bigger code base.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>Show them this: <a href="http://python.org/about/success/" rel="nofollow">http://python.org/about/success/</a></p> <p>Also, one of the best Python demos is to do things the way the SQLAlchemy and Django tutorials do things -- in interactive python from the <code>&gt;&gt;&gt;</code> prompt. Nothing is more exciting than programming which is so simple you can do it interactively.</p> <p>You won't find a lot of compelling case studies. Python is a community. .Net and J2EE are products. .Net has Microsoft's advertising backing it; Microsoft can afford to do extensive surveys and studies of their product. Same for Sun (soon to be Oracle) and J2EE -- lots of marketing hype backing up their claims.</p> <p>Python just has what's on the Python.org site (<a href="http://python.org/about/" rel="nofollow">http://python.org/about/</a>). The various related projects (Pylons, Mako and SQLAlchemy) don't have lavish case study whitepapers. They do have a large number of downloads, and lots of word of mouth. </p> <p>But if someone's looking for "proof" that Python works better than .Net, there's not going to be much.</p>
3
2009-04-23T21:03:33Z
[ "java", "python", "java-ee", "pylons", "wsgi" ]
Pylons or TurboGears vs. .NET or Java
783,488
<p>We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're used to enterprisey stuff).</p> <p>Their web app will have some data analysis that we'll offload as well as a twang of social networking features. (basically all they have so far is some Flex mockups for UX)</p> <p>I'm looking for some evidence with regard to development time, or other reasons that will help our argument to reassure the customer.</p> <p>The other options is that we're barking up the wrong tree and have no idea. I hope that's not the case.</p> <p>Any references to case studies or whatnot would be nice. The best I could find are</p> <p><a href="http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html" rel="nofollow">http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html</a></p> <p>and </p> <p><a href="http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html" rel="nofollow">http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html</a></p> <p>which are a bit dated (wrt to TG2 and whatnot)</p> <p>Thanks!</p>
4
2009-04-23T20:57:23Z
784,406
<p>If you're looking for a success story for a customer, <a href="http://virgincharter.com/" rel="nofollow">Virgin Charter</a> is using Pylons with SQLAlchemy for their site. This is a high-value transaction system as people are booking very expensive flights through the site.</p> <p>For a more high-traffic site, Reddit is now running on Pylons, along with <a href="http://www.charlierose.com/" rel="nofollow">Charlie Rose</a>.</p> <p>SQLAlchemy and Mako were both designed by Mike Bayer (A veteran Java programmer), SQLAlchemy being based on the best of Hibernate and with the same powerful principles and patterns that Hibernate supports.</p> <p>If they're wary of deploying something they're not familiar with, Pylons runs on Jython, and the latest SQLAlchemy (0.6 branch) is about ready on Jython too. This would let you package up a full Pylons app into a WAR file for deployment which would reassure their Java-types.</p> <p>For general Python, consider pointing out all the big animation studios that use it, and the other various srouces S.Lott points out.</p>
5
2009-04-24T03:37:22Z
[ "java", "python", "java-ee", "pylons", "wsgi" ]
Pylons or TurboGears vs. .NET or Java
783,488
<p>We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're used to enterprisey stuff).</p> <p>Their web app will have some data analysis that we'll offload as well as a twang of social networking features. (basically all they have so far is some Flex mockups for UX)</p> <p>I'm looking for some evidence with regard to development time, or other reasons that will help our argument to reassure the customer.</p> <p>The other options is that we're barking up the wrong tree and have no idea. I hope that's not the case.</p> <p>Any references to case studies or whatnot would be nice. The best I could find are</p> <p><a href="http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html" rel="nofollow">http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html</a></p> <p>and </p> <p><a href="http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html" rel="nofollow">http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html</a></p> <p>which are a bit dated (wrt to TG2 and whatnot)</p> <p>Thanks!</p>
4
2009-04-23T20:57:23Z
821,380
<p>They are crazy if they want to use j2ee imho. Visual Studio/C# is very nice, especially if you are not trying to do anything tricky. However, if you want to customize the C# way of doing things beyond what it was explicitly designed for it can quickly turn into a mess -- you get mired in automatically generated XML configuration files &amp;c. Of course, I also think that Pylons with SQLAlchemy might turn into a mess because they too generate so much stuff that you ultimatly might end up having to reconfigure. If you want complete control, I would recommend a less intrusive environment, like Werkzueg. <a href="http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1200.wwiki" rel="nofollow">Please read my essay on writing MVC with no invisible means of support.</a></p>
-1
2009-05-04T18:52:04Z
[ "java", "python", "java-ee", "pylons", "wsgi" ]
how to run a python script in the background?
783,531
<p>I have a script which checking something on my pc every 5 min and I dont want python to show on my tasktray</p> <p>is there any way to make python run in the background and force him not to show in my task tray ?</p> <p>thanks</p> <p>im using windows by the way</p>
10
2009-04-23T21:07:49Z
783,541
<p>cron it on linux; schedule it on windows [control panel > scheduled tasks > Add scheduled task]</p>
1
2009-04-23T21:10:36Z
[ "python", "windows", "backgrounding" ]
how to run a python script in the background?
783,531
<p>I have a script which checking something on my pc every 5 min and I dont want python to show on my tasktray</p> <p>is there any way to make python run in the background and force him not to show in my task tray ?</p> <p>thanks</p> <p>im using windows by the way</p>
10
2009-04-23T21:07:49Z
783,544
<p>Look for Schedule Tasks in the control panel.</p>
2
2009-04-23T21:11:09Z
[ "python", "windows", "backgrounding" ]
how to run a python script in the background?
783,531
<p>I have a script which checking something on my pc every 5 min and I dont want python to show on my tasktray</p> <p>is there any way to make python run in the background and force him not to show in my task tray ?</p> <p>thanks</p> <p>im using windows by the way</p>
10
2009-04-23T21:07:49Z
783,555
<p>If you run a console script using <code>pythonw.exe</code>, it will neither display a window nor appear in the task bar. For example, I use the following command to launch <a href="http://ntlmaps.sourceforge.net/">ntlmaps</a> on startup:</p> <pre><code>C:\BenBlank\Python2.6\pythonw.exe scripts/ntlmaps </code></pre> <p>Be aware, however, that there is no way to interact with the script, nor to terminate it save via the Task Manager.</p>
37
2009-04-23T21:15:11Z
[ "python", "windows", "backgrounding" ]
how to run a python script in the background?
783,531
<p>I have a script which checking something on my pc every 5 min and I dont want python to show on my tasktray</p> <p>is there any way to make python run in the background and force him not to show in my task tray ?</p> <p>thanks</p> <p>im using windows by the way</p>
10
2009-04-23T21:07:49Z
783,559
<p>Just another option you have:</p> <p>You can create a shortcut to your Python script, then <code>right-click the shortcut --&gt; Properties --&gt; Shortcut tab</code></p> <p>There is a drop-down box under the Run option which lets you <strong>run the command minimized.</strong></p>
2
2009-04-23T21:17:50Z
[ "python", "windows", "backgrounding" ]
how to run a python script in the background?
783,531
<p>I have a script which checking something on my pc every 5 min and I dont want python to show on my tasktray</p> <p>is there any way to make python run in the background and force him not to show in my task tray ?</p> <p>thanks</p> <p>im using windows by the way</p>
10
2009-04-23T21:07:49Z
810,596
<p>You could run it as a service. See <a href="http://code.activestate.com/recipes/551780/" rel="nofollow">here</a></p>
1
2009-05-01T08:07:51Z
[ "python", "windows", "backgrounding" ]
Python equivalent of PHP's compact() and extract()
783,781
<p><a href="http://www.php.net/compact">compact</a>() and <a href="http://www.php.net/extract">extract</a>() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,</p> <pre><code>$foo = 'what'; $bar = 'ever'; $a = compact('foo', 'bar'); $a['foo'] # what $a['baz'] = 'another' extract(a) $baz # another </code></pre> <p>Is there a way to do the same in Python? I've looked all around and the closest I've come is <a href="http://markmail.org/message/r52hym6zfy7hd2ch">this thread</a>, which seems to frown on it.</p> <p>I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?</p> <p>Does Python have something even better that obviates the need for this?</p>
7
2009-04-23T22:21:29Z
783,812
<p>I guess the equivalent of <code>extract($x)</code> is <code>globals().update(x)</code>, as for <code>compact()</code> it's a subset of <code>vars()</code></p> <pre><code>&gt;&gt;&gt; foo, bar, baz = 1, 2, 3 # extract &gt;&gt;&gt; globals().update({"foo": 4, "qux": 5}) &gt;&gt;&gt; foo 4 &gt;&gt;&gt; qux 5 # compact &gt;&gt;&gt; d = dict((k, v) for k, v in vars().iteritems() if k in ["foo", "bar"]) &gt;&gt;&gt; d {'bar': 2, 'foo': 1} </code></pre>
2
2009-04-23T22:32:56Z
[ "php", "python", "dictionary" ]
Python equivalent of PHP's compact() and extract()
783,781
<p><a href="http://www.php.net/compact">compact</a>() and <a href="http://www.php.net/extract">extract</a>() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,</p> <pre><code>$foo = 'what'; $bar = 'ever'; $a = compact('foo', 'bar'); $a['foo'] # what $a['baz'] = 'another' extract(a) $baz # another </code></pre> <p>Is there a way to do the same in Python? I've looked all around and the closest I've come is <a href="http://markmail.org/message/r52hym6zfy7hd2ch">this thread</a>, which seems to frown on it.</p> <p>I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?</p> <p>Does Python have something even better that obviates the need for this?</p>
7
2009-04-23T22:21:29Z
783,839
<p>I'm afraid there are no equivalents in Python. To some extent, you can simulate their effect using (and passing) <code>locals</code>:</p> <pre><code>&gt;&gt;&gt; def compact(locals, *keys): ... return dict((k, locals[k]) for k in keys) ... &gt;&gt;&gt; a = 10 &gt;&gt;&gt; b = 2 &gt;&gt;&gt; compact(locals(), 'a', 'b') {'a': 10, 'b': 2} &gt;&gt;&gt; def extract(locals, d): ... for k, v in d.items(): ... locals[k] = v ... &gt;&gt;&gt; extract(locals(), {'a': 'foo', 'b': 'bar'} &gt;&gt;&gt; a 'foo' &gt;&gt;&gt; b 'bar' </code></pre> <p>Nevertheless, I don't think these functions are "tremendously handy". Dynamic global/local variables are evil and error-prone -- PHP guys learned that when they discouraged register_globals. From my experience, few experienced PHP programmers or major frameworks use <code>compact()</code> or <code>extract()</code>.</p> <p>In Python, <a href="http://www.python.org/dev/peps/pep-0020/">explicit is better than implicit</a>:</p> <pre><code>a = 1 b = 2 # compact c = dict(a=a, b=b) # extract a, b = d['a'], d['b'] </code></pre>
8
2009-04-23T22:40:07Z
[ "php", "python", "dictionary" ]
Python equivalent of PHP's compact() and extract()
783,781
<p><a href="http://www.php.net/compact">compact</a>() and <a href="http://www.php.net/extract">extract</a>() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,</p> <pre><code>$foo = 'what'; $bar = 'ever'; $a = compact('foo', 'bar'); $a['foo'] # what $a['baz'] = 'another' extract(a) $baz # another </code></pre> <p>Is there a way to do the same in Python? I've looked all around and the closest I've come is <a href="http://markmail.org/message/r52hym6zfy7hd2ch">this thread</a>, which seems to frown on it.</p> <p>I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?</p> <p>Does Python have something even better that obviates the need for this?</p>
7
2009-04-23T22:21:29Z
783,867
<p>It's not very Pythonic, but if you really must:</p> <pre><code>import inspect def compact(*names): caller = inspect.stack()[1][0] # caller of compact() vars = {} for n in names: if n in caller.f_locals: vars[n] = caller.f_locals[n] elif n in caller.f_globals: vars[n] = caller.f_globals[n] return vars def extract(vars): caller = inspect.stack()[1][0] # caller of extract() for n, v in vars.items(): caller.f_locals[n] = v # NEVER DO THIS - not guaranteed to work </code></pre> <p>I've used these implementations quite a bit, and they work, but technically modifying <code>f_locals</code> is not supported.</p> <p>Seriously though, if you really feel you have a need to use these functions, you're probably doing something the wrong way. It seems to run against <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Python's philosophy</a> on at least three counts: "explicit is better than implicit", "simple is better than complex", "if the implementation is hard to explain, it's a bad idea", maybe more (and really, if you have enough experience in Python you know that stuff like this just isn't done). I could see it being useful for a debugger or post-mortem analysis, or perhaps for some sort of <em>very general</em> framework that frequently needs to create variables with dynamically chosen names and values, but it's a stretch.</p> <p>If you are going to use these functions, you should at least keep the <code>extract</code>ed variables contained to within small scopes. Wrap them in functions that you can then consider to be "black boxes". The main reason <code>extract</code> is bad is that it puts variables in your symbol table in a way that isn't clear from inspecting the code. If you keep the effects of those variables localized to a very small function, and explain what you're doing with clear code and comments, it's not that big of a problem.</p>
9
2009-04-23T22:47:46Z
[ "php", "python", "dictionary" ]
Python equivalent of PHP's compact() and extract()
783,781
<p><a href="http://www.php.net/compact">compact</a>() and <a href="http://www.php.net/extract">extract</a>() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,</p> <pre><code>$foo = 'what'; $bar = 'ever'; $a = compact('foo', 'bar'); $a['foo'] # what $a['baz'] = 'another' extract(a) $baz # another </code></pre> <p>Is there a way to do the same in Python? I've looked all around and the closest I've come is <a href="http://markmail.org/message/r52hym6zfy7hd2ch">this thread</a>, which seems to frown on it.</p> <p>I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?</p> <p>Does Python have something even better that obviates the need for this?</p>
7
2009-04-23T22:21:29Z
784,681
<p>Is it worth pointing out that <code>extract()</code> (and to a lesser extent, <code>compact()</code>) is one of the most "evil" features of PHP (along with <code>register_globals</code> and <code>eval</code>), and should be avoided?</p> <p><a href="http://php.net/manual/en/function.extract.php" rel="nofollow"><code>extract</code></a> makes it much harder to determine where a variable was defined. When it is harder to trace a variable back to where it was defined, it's harder to check for common security problems like using uninitialized variables, or unfiltered variables which originated from user input.</p> <p><a href="http://php.net/manual/en/function.compact.php" rel="nofollow"><code>compact</code></a> is not as bad, but if used badly can still make it more difficult than it would otherwise be to see where an array member gets set from a variable.</p> <p>The equivalent of <code>extract()</code> in many other languages is the <code>with</code> keyword. Python now has a <code>with</code> keyword, though it works a bit differently, making it not quite like <code>extract()</code>. However, in other languages such as Javascript, the <code>with</code> keyword <a href="http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/" rel="nofollow">also has a poor reputation</a>.</p> <p>I think the best advice would be to think differently - instead of trying to emulate a bad feature of PHP, think of other ways to do what you want to do with concise and readable code.</p>
6
2009-04-24T05:57:58Z
[ "php", "python", "dictionary" ]
Python equivalent of PHP's compact() and extract()
783,781
<p><a href="http://www.php.net/compact">compact</a>() and <a href="http://www.php.net/extract">extract</a>() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,</p> <pre><code>$foo = 'what'; $bar = 'ever'; $a = compact('foo', 'bar'); $a['foo'] # what $a['baz'] = 'another' extract(a) $baz # another </code></pre> <p>Is there a way to do the same in Python? I've looked all around and the closest I've come is <a href="http://markmail.org/message/r52hym6zfy7hd2ch">this thread</a>, which seems to frown on it.</p> <p>I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?</p> <p>Does Python have something even better that obviates the need for this?</p>
7
2009-04-23T22:21:29Z
864,868
<p>PHP's compact function in Python (works with 2.6; not guaranteed to work with earlier versions of Python):</p> <pre><code>import inspect def compact(*args): return dict([(i, inspect.currentframe().f_back.f_locals.get(i, None)) for i in args]) </code></pre> <p>I've written more extensively about this: <a href="http://www.elfsternberg.com/2009/05/14/python-can-be-just-as-ugly-as-php/" rel="nofollow">Python can be just as ugly as PHP</a>.</p>
3
2009-05-14T18:13:24Z
[ "php", "python", "dictionary" ]
Python equivalent of PHP's compact() and extract()
783,781
<p><a href="http://www.php.net/compact">compact</a>() and <a href="http://www.php.net/extract">extract</a>() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values. extract does the opposite. e.g.,</p> <pre><code>$foo = 'what'; $bar = 'ever'; $a = compact('foo', 'bar'); $a['foo'] # what $a['baz'] = 'another' extract(a) $baz # another </code></pre> <p>Is there a way to do the same in Python? I've looked all around and the closest I've come is <a href="http://markmail.org/message/r52hym6zfy7hd2ch">this thread</a>, which seems to frown on it.</p> <p>I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?</p> <p>Does Python have something even better that obviates the need for this?</p>
7
2009-04-23T22:21:29Z
39,669,396
<p>You <em>can</em> do this (though I would suggest only sparingly...) with the <code>locals()</code> function, which returns an updatable <code>dict</code>. Example:</p> <pre><code>$ python Python 2.7.12 (default, Jul 1 2016, 15:12:24) &gt;&gt;&gt; locals().update({'derek':'anderson'}) &gt;&gt;&gt; derek 'anderson' &gt;&gt;&gt; </code></pre> <p>So <code>locals()</code> would be "compact all" and <code>locals().update()</code> would be <code>extract</code>.</p> <p>Best of luck!</p>
1
2016-09-23T20:54:37Z
[ "php", "python", "dictionary" ]
seek(), then read(), then write() in python
783,792
<p>When running the following python code:</p> <pre><code>&gt;&gt;&gt; f = open(r"myfile.txt", "a+") &gt;&gt;&gt; f.seek(-1,2) &gt;&gt;&gt; f.read() 'a' &gt;&gt;&gt; f.write('\n') </code></pre> <p>I get the following (helpful) exception:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 0] Error </code></pre> <p>The same thing happens when openning with "r+". </p> <p>Is this supposed to fail? Why? </p> <p>Edit:</p> <ol> <li>Obviously, this is just an example, not what I am actually trying to execute. My actual goal was to verify that the files ends with "\n", or add one, before adding the new lines. </li> <li>I am working under Windows XP, and they problem exists in both Python 2.5 and Python 2.6. </li> <li><p>I managed to bypass the problem by calling seek() again:</p> <blockquote> <blockquote> <blockquote> <p>f = open(r"myfile.txt", "a+")<br /> f.seek(-1,2)<br /> f.read()<br /> 'a'<br /> f.seek(-10,2)<br /> f.write('\n') </p> </blockquote> </blockquote> </blockquote></li> </ol> <p>The actual parameters of the 2nd seek call don't seem to matter. </p>
6
2009-04-23T22:25:29Z
783,805
<p>the a+ mode is for appending, if you want to read &amp; write, you are looking for r+.</p> <p>try this:</p> <pre><code>&gt;&gt;&gt; f = open("myfile.txt", "r+") &gt;&gt;&gt; f.write('\n') </code></pre> <p><strong>Edit:</strong></p> <p>you should have specified your platform initially... there are known problems with seek within windows. When trying to seek, UNIX and Win32 have different line endings, LF and CRLF respectively. There is also an issue with reading to the end of a file. I think you are looking for the seek(2) offset for the end of the file, then carry on from there.</p> <p>these articles may be of interest to you (the second one more specifically):</p> <p><a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-08/2512.html" rel="nofollow">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-08/2512.html</a></p> <p><a href="http://mail.python.org/pipermail/python-list/2002-June/150556.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2002-June/150556.html</a></p>
1
2009-04-23T22:30:09Z
[ "python", "file-io" ]
seek(), then read(), then write() in python
783,792
<p>When running the following python code:</p> <pre><code>&gt;&gt;&gt; f = open(r"myfile.txt", "a+") &gt;&gt;&gt; f.seek(-1,2) &gt;&gt;&gt; f.read() 'a' &gt;&gt;&gt; f.write('\n') </code></pre> <p>I get the following (helpful) exception:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 0] Error </code></pre> <p>The same thing happens when openning with "r+". </p> <p>Is this supposed to fail? Why? </p> <p>Edit:</p> <ol> <li>Obviously, this is just an example, not what I am actually trying to execute. My actual goal was to verify that the files ends with "\n", or add one, before adding the new lines. </li> <li>I am working under Windows XP, and they problem exists in both Python 2.5 and Python 2.6. </li> <li><p>I managed to bypass the problem by calling seek() again:</p> <blockquote> <blockquote> <blockquote> <p>f = open(r"myfile.txt", "a+")<br /> f.seek(-1,2)<br /> f.read()<br /> 'a'<br /> f.seek(-10,2)<br /> f.write('\n') </p> </blockquote> </blockquote> </blockquote></li> </ol> <p>The actual parameters of the 2nd seek call don't seem to matter. </p>
6
2009-04-23T22:25:29Z
783,843
<p>This appears to be a Windows-specific problem - see <a href="http://bugs.python.org/issue1521491" rel="nofollow">http://bugs.python.org/issue1521491</a> for a similar issue.</p> <p>Even better, a workaround given and explained at <a href="http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html" rel="nofollow">http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html</a>, insert:</p> <pre><code>f.seek(f.tell()) </code></pre> <p>between the read() and write() calls.</p>
3
2009-04-23T22:41:18Z
[ "python", "file-io" ]
seek(), then read(), then write() in python
783,792
<p>When running the following python code:</p> <pre><code>&gt;&gt;&gt; f = open(r"myfile.txt", "a+") &gt;&gt;&gt; f.seek(-1,2) &gt;&gt;&gt; f.read() 'a' &gt;&gt;&gt; f.write('\n') </code></pre> <p>I get the following (helpful) exception:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 0] Error </code></pre> <p>The same thing happens when openning with "r+". </p> <p>Is this supposed to fail? Why? </p> <p>Edit:</p> <ol> <li>Obviously, this is just an example, not what I am actually trying to execute. My actual goal was to verify that the files ends with "\n", or add one, before adding the new lines. </li> <li>I am working under Windows XP, and they problem exists in both Python 2.5 and Python 2.6. </li> <li><p>I managed to bypass the problem by calling seek() again:</p> <blockquote> <blockquote> <blockquote> <p>f = open(r"myfile.txt", "a+")<br /> f.seek(-1,2)<br /> f.read()<br /> 'a'<br /> f.seek(-10,2)<br /> f.write('\n') </p> </blockquote> </blockquote> </blockquote></li> </ol> <p>The actual parameters of the 2nd seek call don't seem to matter. </p>
6
2009-04-23T22:25:29Z
783,852
<p>Works for me:</p> <pre><code>$ echo hello &gt; myfile.txt $ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; f = open('myfile.txt', 'r+') &gt;&gt;&gt; f.seek(-1, 2) &gt;&gt;&gt; f.tell() 5L &gt;&gt;&gt; f.read() '\n' &gt;&gt;&gt; f.write('\n') &gt;&gt;&gt; f.close() </code></pre> <p>Are you on windows? If so, try <code>'rb+'</code> instead of <code>'r+'</code> in the mode.</p>
0
2009-04-23T22:43:23Z
[ "python", "file-io" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
783,900
<pre><code>round(1.923328437452, 3) </code></pre> <p>See <a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex">Python's documentation on the standard types</a>. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.</p>
94
2009-04-23T22:59:15Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
783,905
<p>If you mean when printing, then the following should work:</p> <pre><code>print '%.3f' % number </code></pre>
-3
2009-04-23T23:01:35Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
783,914
<p>The result of <code>round</code> is a float, so watch out:</p> <pre><code>&gt;&gt;&gt; round(1.923328437452, 3) 1.923 &gt;&gt;&gt; round(1.23456, 3) 1.2350000000000001 </code></pre> <p>You will be better off when using a formatted string:</p> <pre><code>&gt;&gt;&gt; "%.3f" % 1.923328437452 '1.923' &gt;&gt;&gt; "%.3f" % 1.23456 '1.235' </code></pre>
20
2009-04-23T23:04:46Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
783,927
<p>First, the function, for those who just want some copy-and-paste code:</p> <pre><code>def truncate(f, n): '''Truncates/pads a float f to n decimal places without rounding''' s = '{}'.format(f) if 'e' in s or 'E' in s: return '{0:.{1}f}'.format(f, n) i, p, d = s.partition('.') return '.'.join([i, (d+'0'*n)[:n]]) </code></pre> <p>This is valid in Python 2.7 and 3.1+. For older versions, it's not possible to get the same "intelligent rounding" effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time:</p> <pre><code>def truncate(f, n): '''Truncates/pads a float f to n decimal places without rounding''' s = '%.12f' % f i, p, d = s.partition('.') return '.'.join([i, (d+'0'*n)[:n]]) </code></pre> <h1>Explanation</h1> <p>The core of the underlying method is to convert the value to a string at full precision and then just chop off everything beyond the desired number of characters. The latter step is easy; it can be done either with string manipulation</p> <pre><code>i, p, d = s.partition('.') '.'.join([i, (d+'0'*n)[:n]]) </code></pre> <p>or the <code>decimal</code> module</p> <pre><code>str(Decimal(s).quantize(Decimal((0, (1,), -n)), rounding=ROUND_DOWN)) </code></pre> <p>The first step, converting to a string, is quite difficult because there are some pairs of floating point literals (i.e. what you write in the source code) which both produce the same binary representation and yet should be truncated differently. For example, consider 0.3 and 0.29999999999999998. If you write <code>0.3</code> in a Python program, the compiler encodes it using the IEEE floating-point format into the sequence of bits (assuming a 64-bit float)</p> <pre><code>0011111111010011001100110011001100110011001100110011001100110011 </code></pre> <p>This is the closest value to 0.3 that can accurately be represented as an IEEE float. But if you write <code>0.29999999999999998</code> in a Python program, the compiler translates it into <em>exactly the same value</em>. In one case, you meant it to be truncated (to one digit) as <code>0.3</code>, whereas in the other case you meant it to be truncated as <code>0.2</code>, but Python can only give one answer. This is a fundamental limitation of Python, or indeed any programming language without lazy evaluation. The truncation function only has access to the binary value stored in the computer's memory, not the string you actually typed into the source code.<sup>1</sup></p> <p>If you decode the sequence of bits back into a decimal number, again using the IEEE 64-bit floating-point format, you get</p> <pre><code>0.2999999999999999888977697537484345957637... </code></pre> <p>so a naive implementation would come up with <code>0.2</code> even though that's probably not what you want. For more on floating-point representation error, <a href="https://docs.python.org/3/tutorial/floatingpoint.html">see the Python tutorial</a>.</p> <p>It's very rare to be working with a floating-point value that is so close to a round number and yet is <em>intentionally</em> not equal to that round number. So when truncating, it probably makes sense to choose the "nicest" decimal representation out of all that could correspond to the value in memory. Python 2.7 and up (but not 3.0) includes a <a href="https://bugs.python.org/issue1580">sophisticated algorithm to do just that</a>, which we can access through the default string formatting operation.</p> <pre><code>'{}'.format(f) </code></pre> <p>The only caveat is that this acts like a <code>g</code> format specification, in the sense that it uses exponential notation (<code>1.23e+4</code>) if the number is large or small enough. So the method has to catch this case and handle it differently. There are a few cases where using an <code>f</code> format specification instead causes a problem, such as trying to truncate <code>3e-10</code> to 28 digits of precision (it produces <code>0.0000000002999999999999999980</code>), and I'm not yet sure how best to handle those.</p> <p>If you actually <em>are</em> working with <code>float</code>s that are very close to round numbers but intentionally not equal to them (like 0.29999999999999998 or 99.959999999999994), this will produce some false positives, i.e. it'll round numbers that you didn't want rounded. In that case the solution is to specify a fixed precision.</p> <pre><code>'{0:.{1}f}'.format(f, sys.float_info.dig + n + 2) </code></pre> <p>The number of digits of precision to use here doesn't really matter, it only needs to be large enough to ensure that any rounding performed in the string conversion doesn't "bump up" the value to its nice decimal representation. I think <code>sys.float_info.dig + n + 2</code> may be enough in all cases, but if not that <code>2</code> might have to be increased, and it doesn't hurt to do so.</p> <p>In earlier versions of Python (up to 2.6, or 3.0), the floating point number formatting was a lot more crude, and would regularly produce things like</p> <pre><code>&gt;&gt;&gt; 1.1 1.1000000000000001 </code></pre> <p>If this is your situation, if you <em>do</em> want to use "nice" decimal representations for truncation, all you can do (as far as I know) is pick some number of digits, less than the full precision representable by a <code>float</code>, and round the number to that many digits before truncating it. A typical choice is 12,</p> <pre><code>'%.12f' % f </code></pre> <p>but you can adjust this to suit the numbers you're using.</p> <hr> <p><sup>1</sup>Well... I lied. Technically, you <em>can</em> instruct Python to re-parse its own source code and extract the part corresponding to the first argument you pass to the truncation function. If that argument is a floating-point literal, you can just cut it off a certain number of places after the decimal point and return that. However this strategy doesn't work if the argument is a variable, which makes it fairly useless. The following is presented for entertainment value only:</p> <pre><code>def trunc_introspect(f, n): '''Truncates/pads the float f to n decimal places by looking at the caller's source code''' current_frame = None caller_frame = None s = inspect.stack() try: current_frame = s[0] caller_frame = s[1] gen = tokenize.tokenize(io.BytesIO(caller_frame[4][caller_frame[5]].encode('utf-8')).readline) for token_type, token_string, _, _, _ in gen: if token_type == tokenize.NAME and token_string == current_frame[3]: next(gen) # left parenthesis token_type, token_string, _, _, _ = next(gen) # float literal if token_type == tokenize.NUMBER: try: cut_point = token_string.index('.') + n + 1 except ValueError: # no decimal in string return token_string + '.' + '0' * n else: if len(token_string) &lt; cut_point: token_string += '0' * (cut_point - len(token_string)) return token_string[:cut_point] else: raise ValueError('Unable to find floating-point literal (this probably means you called {} with a variable)'.format(current_frame[3])) break finally: del s, current_frame, caller_frame </code></pre> <p>Generalizing this to handle the case where you pass in a variable seems like a lost cause, since you'd have to trace backwards through the program's execution until you find the floating-point literal which gave the variable its value. If there even is one. Most variables will be initialized from user input or mathematical expressions, in which case the binary representation is all there is.</p>
53
2009-04-23T23:10:44Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
784,665
<pre><code>def trunc(num, digits): sp = str(num).split('.') return '.'.join([sp[0], sp[:digits]]) </code></pre> <p>This should work. It should give you the truncation you are looking for.</p>
7
2009-04-24T05:46:03Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
3,305,306
<pre><code>def trunc(f,n): return ('%.16f' % f)[:(n-16)] </code></pre>
1
2010-07-22T02:12:26Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
3,306,087
<p>Just wanted to mention that the old "make round() with floor()" trick of</p> <pre><code>round(f) = floor(f+0.5) </code></pre> <p>can be turned around to make floor() from round()</p> <pre><code>floor(f) = round(f-0.5) </code></pre> <p>Although both these rules break around negative numbers, so using it is less than ideal:</p> <pre><code>def trunc(f, n): if f &gt; 0: return "%.*f" % (n, (f - 0.5*10**-n)) elif f == 0: return "%.*f" % (n, f) elif f &lt; 0: return "%.*f" % (n, (f + 0.5*10**-n)) </code></pre>
1
2010-07-22T05:46:38Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
4,176,526
<pre><code>n = 1.923328437452 str(n)[:4] </code></pre>
11
2010-11-14T06:58:32Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
7,843,609
<p>int(16.5); this will give an integer value of 16, i.e. trunc, won't be able to specify decimals, but guess you can do that by </p> <pre><code>import math; def trunc(invalue, digits): return int(invalue*math.pow(10,digits))/math.pow(10,digits); </code></pre>
1
2011-10-20T23:52:03Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
11,869,006
<p>Am also a python newbie and after making use of some bits and pieces here, I offer my two cents</p> <pre><code>print str(int(time.time()))+str(datetime.now().microsecond)[:3] </code></pre> <p>str(int(time.time())) will take the time epoch as int and convert it to string and join with... str(datetime.now().microsecond)[:3] which returns the microseconds only, convert to string and truncate to first 3 chars</p>
0
2012-08-08T16:30:19Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
23,917,385
<p>The truely pythonic way of doing it is</p> <pre><code>from decimal import * with localcontext() as ctx: ctx.rounding = ROUND_DOWN print Decimal('1.923328437452').quantize(Decimal('0.001')) </code></pre>
6
2014-05-28T16:43:49Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
25,702,460
<p>I did something like this:</p> <pre><code>from math import trunc def truncate(number, decimals=0): if decimals &lt; 0: raise ValueError('truncate received an invalid value of decimals ({})'.format(decimals)) elif decimals == 0: return trunc(number) else: factor = float(10**decimals) return trunc(number*factor)/factor </code></pre>
2
2014-09-06T16:42:11Z
[ "python", "floating-point" ]
Truncating floats in Python
783,897
<p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p> <pre><code>1.923328437452 -&gt; 1.923 </code></pre> <p>I need to output as a string to another function, not print.</p> <p>Also I want to ignore the lost digits, not round them.</p>
46
2009-04-23T22:56:44Z
27,189,591
<p>Here is an easy way:</p> <pre><code>def truncate(num, res=3): return (floor(num*pow(10, res)+0.5))/pow(10, res) </code></pre> <p>for num = 1.923328437452, this outputs 1.923</p>
0
2014-11-28T13:19:53Z
[ "python", "floating-point" ]