title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Python TCP stack implementation
1,581,087
<p>Is there a python library which implements a standalone TCP stack?</p> <p>I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (send a syn-ack) and then get the data sent by the other end (ack'ing appropriately).</p> <p>I was hoping there was some sort of TCP stack already written which I could utilize. Any ideas? I've used lwip in the past for a C project -- something along those lines in python would be perfect.</p>
7
2009-10-17T00:50:53Z
1,581,102
<p>You might be able to use the <a href="http://docs.python.org/library/ctypes.html#module-ctypes" rel="nofollow">ctypes</a> module to import lwip and use it again.</p>
0
2009-10-17T00:58:34Z
[ "python", "tcp", "network-programming", "network-protocols", "raw-sockets" ]
Python TCP stack implementation
1,581,087
<p>Is there a python library which implements a standalone TCP stack?</p> <p>I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (send a syn-ack) and then get the data sent by the other end (ack'ing appropriately).</p> <p>I was hoping there was some sort of TCP stack already written which I could utilize. Any ideas? I've used lwip in the past for a C project -- something along those lines in python would be perfect.</p>
7
2009-10-17T00:50:53Z
1,581,109
<p>Glancing over <a href="http://www.secdev.org/projects/scapy/doc/introduction.html?highlight=syn" rel="nofollow">Scapy</a>, it looks like it might be able to handle these low-level situations. I haven't used it myself so I can't confirm that it does what you've explained; I've only glanced over the documentation.</p>
2
2009-10-17T01:01:51Z
[ "python", "tcp", "network-programming", "network-protocols", "raw-sockets" ]
Python TCP stack implementation
1,581,087
<p>Is there a python library which implements a standalone TCP stack?</p> <p>I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (send a syn-ack) and then get the data sent by the other end (ack'ing appropriately).</p> <p>I was hoping there was some sort of TCP stack already written which I could utilize. Any ideas? I've used lwip in the past for a C project -- something along those lines in python would be perfect.</p>
7
2009-10-17T00:50:53Z
1,581,892
<p>You don't say which platform you are working on, but if you are working on linux, I'd open a <a href="http://www.kernel.org/pub/linux/kernel/people/marcelo/linux-2.4/Documentation/networking/tuntap.txt" rel="nofollow">tun/tap interface</a> and get the IP packets back into the kernel as a real network interface so the kernel can do all that tricky TCP stuff.</p> <p>This is how (for example) <a href="http://en.wikipedia.org/wiki/OpenVPN" rel="nofollow">OpenVPN</a> works - it receives the raw IP packets over UDP or TCP and tunnels them back into the kernel over a tun/tap interface.</p> <p>I think that there is a tun/tap interface for windows too now which was developed for the OpenVPN port to windows.</p>
7
2009-10-17T10:19:10Z
[ "python", "tcp", "network-programming", "network-protocols", "raw-sockets" ]
Python TCP stack implementation
1,581,087
<p>Is there a python library which implements a standalone TCP stack?</p> <p>I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (send a syn-ack) and then get the data sent by the other end (ack'ing appropriately).</p> <p>I was hoping there was some sort of TCP stack already written which I could utilize. Any ideas? I've used lwip in the past for a C project -- something along those lines in python would be perfect.</p>
7
2009-10-17T00:50:53Z
1,582,637
<p>If you are already committed to the software at the other end of the socket, that is forwarding TCP packets to you, then perhaps TCPWatch will show you how to get at the SYN packets. SCAPY is certainly great for sending exactly the packets that you want, but I'm not sure that it will work as a proxy.</p> <p><a href="http://hathawaymix.org/Software/TCPWatch" rel="nofollow">http://hathawaymix.org/Software/TCPWatch</a></p> <p>However, if you are not committed to what is on the sending end, then consider using Twisted Conch or Paramiko to do SSH forwarding. Even if you don't need encryption, you can still use these with blowfish which has a low impact on your CPU. This doesn't mean that you need Conch on the other end, since SSH is standardised so any SSH software should work. In the SSH world this is normally referred to as "port forwarding" and people use an SSH terminal client to log into an SSH server and set up the port forwarding tunnel. Conch and Paramiko allow you to build this into a Python application so that there is no need for the SSH terminal client.</p>
0
2009-10-17T16:47:41Z
[ "python", "tcp", "network-programming", "network-protocols", "raw-sockets" ]
How do I make these relative imports work in Python 3?
1,581,260
<p>I have a directory structure that looks like this:</p> <pre><code>project/ __init__.py foo/ __init.py__ first.py second.py third.py plum.py </code></pre> <p>In <code>project/foo/__init__.py</code> I import classes from <code>first.py</code>, <code>second.py</code> and <code>third.py</code> and put them in <code>__all__</code>.</p> <p>There's a class in <code>first.py</code> named <code>WonderfulThing</code> which I'd like to use in <code>second.py</code>, and want to import by importing <code>*</code> from <code>foo</code>. (It's outside of the scope of this question why I'd like to do so, assume I have a good reason.)</p> <p>In <code>second.py</code> I've tried <code>from .foo import *</code>, <code>from foo import *</code> and <code>from . import *</code> and in none of these cases is <code>WonderfulThing</code> imported. I also tried <code>from ..foo import *</code>, which raises an error "Attempted relative import beyond toplevel package".</p> <p>I've read the docs and the PEP, and I can't work out how to make this work. Any assistance would be appreciated.</p> <p><strong>Clarification/Edit:</strong> It seems like I may have been misunderstanding the way <code>__all__</code> works in packages. I was using it the same as in modules,</p> <pre><code>from .first import WonderfulThing __all__ = [ "WonderfulThing" ] </code></pre> <p>but looking at the docs again it seems to suggest that <code>__all__</code> may only be used in packages to specify the names of modules to be imported by default; there doesn't seem to be any way to include anything that's not a module.</p> <p>Is this correct?</p> <p><strong>Edit:</strong> A non-wildcard import failed (<code>cannot import name WonderfulThing</code>). Trying <code>from . import foo</code> failed, but <code>import foo</code> works. Unfortunately, <code>dir(foo)</code> shows nothing.</p>
2
2009-10-17T02:46:46Z
1,581,726
<p>Edit: I did misunderstand the question: No <code>__all__</code> is not restricted to just modules.</p> <p>One question is why you want to do a relative import. There is nothing wrong with doing <code>from project.foo import *</code>, here. Secondly, the <code>__all__</code> restriction on foo won't prevent you from doing <code>from project.foo.first import WonderfulThing</code>, or just <code>from .first import WonderfulThing</code>, which still will be the best way.</p> <p>And if you really want to import a a lot of things, it's probably best to do <code>from project import foo</code>, and then use the things with <code>foo.WonderfulThing</code> instead for doing an <code>import *</code> and then using <code>WonderfulThing</code> directly.</p> <p>However to answer your direct question, to import from the <code>__init__</code> file in second.py you do this:</p> <pre><code>from . import WonderfulThing </code></pre> <p>or</p> <pre><code>from . import * </code></pre>
3
2009-10-17T08:18:59Z
[ "python", "import", "python-3.x", "relative" ]
How to perform a "Group By" query in Django 1.1?
1,581,383
<p>I have seen a lot of talk about 1.1's aggregation, but I am not sure how to use it to perform a simple group by.</p> <p>I am trying to use Django's sitemap framework to create a sitemap.xml file that Google can crawl to find all the pages of my site. Currently I am passing it all the objects, as in <code>Model.objects.all()</code> - however all that really matters is that only 1 per name gets passed. There could be 5-10 Model instances with the same name but I only want to pass one to avoid having duplicates.</p> <p>If I do something like this:</p> <pre><code>Model.objects.values('name').annotate(Count('name')) </code></pre> <p>It gives me what I want, but then I am not retrieving all the fields from the model - the code that creates the sitemap would then be forced to re-query for every single Model to create the link. So how do I get it to group by the name while retrieving all the fields of the model?</p>
3
2009-10-17T04:16:42Z
1,581,449
<p>Django models are lazy loaded. It will be the same amount of overhead if your code walks across your model relationships as if the sitemap did. The models fields are essentially proxies until you request related models.</p>
1
2009-10-17T04:54:13Z
[ "python", "django" ]
How to perform a "Group By" query in Django 1.1?
1,581,383
<p>I have seen a lot of talk about 1.1's aggregation, but I am not sure how to use it to perform a simple group by.</p> <p>I am trying to use Django's sitemap framework to create a sitemap.xml file that Google can crawl to find all the pages of my site. Currently I am passing it all the objects, as in <code>Model.objects.all()</code> - however all that really matters is that only 1 per name gets passed. There could be 5-10 Model instances with the same name but I only want to pass one to avoid having duplicates.</p> <p>If I do something like this:</p> <pre><code>Model.objects.values('name').annotate(Count('name')) </code></pre> <p>It gives me what I want, but then I am not retrieving all the fields from the model - the code that creates the sitemap would then be forced to re-query for every single Model to create the link. So how do I get it to group by the name while retrieving all the fields of the model?</p>
3
2009-10-17T04:16:42Z
1,581,709
<p>May be Distinct will help you?</p> <blockquote> <p>Model.objects.values('name').all().distinct()</p> </blockquote>
1
2009-10-17T08:09:15Z
[ "python", "django" ]
Installing python-mysql with wamp's mysql
1,581,431
<p>(I'm not sure if this should be asked here or SU.. but seeing <a href="http://stackoverflow.com/questions/1458500/need-help-installing-mysql-for-python">this question</a> on SO, I am asking it here...)</p> <p>I have wamp (mysql-5.1.33) server setup on my vista machine, and I am trying to install python-mysql 1.2.3c1 to use the mysql version provided by wamp.</p> <p>At first, when I ran <code>python setup.py install</code>, I got an error saying it couldn't find the location of the mysql's bin folder. Looking into <code>setup_windows.py</code>, I noticed it was looking for a registry key and so I added that registry entry and I think it is able to find it now.</p> <p>But now, when I run <code>python setup.py install</code>, I get a different error saying <code>Unable to find vcvarsall.bat</code>.</p> <p>Any help on installing this appreciated.</p> <h3>Here is the output of <code>python setup.py install</code>:</h3> <pre><code>running install running bdist_egg running egg_info writing MySQL_python.egg-info\PKG-INFO writing top-level names to MySQL_python.egg-info\top_level.txt writing dependency_links to MySQL_python.egg-info\dependency_links.txt reading manifest file 'MySQL_python.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'MySQL_python.egg-info\SOURCES.txt' installing library code to build\bdist.win32\egg running install_lib running build_py copying MySQLdb\release.py -&gt; build\lib.win32-2.6\MySQLdb running build_ext building '_mysql' extension error: Unable to find vcvarsall.bat </code></pre> <p>Thanks a lot!</p>
3
2009-10-17T04:43:33Z
1,581,670
<p>It is looking for the Microsoft Visual Studio compiler to take care of some (presumably) C libraries.</p> <p>You need to install Visual Studio, or perhaps MINGW.</p>
0
2009-10-17T07:42:37Z
[ "python", "mysql", "mysql-python" ]
Installing python-mysql with wamp's mysql
1,581,431
<p>(I'm not sure if this should be asked here or SU.. but seeing <a href="http://stackoverflow.com/questions/1458500/need-help-installing-mysql-for-python">this question</a> on SO, I am asking it here...)</p> <p>I have wamp (mysql-5.1.33) server setup on my vista machine, and I am trying to install python-mysql 1.2.3c1 to use the mysql version provided by wamp.</p> <p>At first, when I ran <code>python setup.py install</code>, I got an error saying it couldn't find the location of the mysql's bin folder. Looking into <code>setup_windows.py</code>, I noticed it was looking for a registry key and so I added that registry entry and I think it is able to find it now.</p> <p>But now, when I run <code>python setup.py install</code>, I get a different error saying <code>Unable to find vcvarsall.bat</code>.</p> <p>Any help on installing this appreciated.</p> <h3>Here is the output of <code>python setup.py install</code>:</h3> <pre><code>running install running bdist_egg running egg_info writing MySQL_python.egg-info\PKG-INFO writing top-level names to MySQL_python.egg-info\top_level.txt writing dependency_links to MySQL_python.egg-info\dependency_links.txt reading manifest file 'MySQL_python.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'MySQL_python.egg-info\SOURCES.txt' installing library code to build\bdist.win32\egg running install_lib running build_py copying MySQLdb\release.py -&gt; build\lib.win32-2.6\MySQLdb running build_ext building '_mysql' extension error: Unable to find vcvarsall.bat </code></pre> <p>Thanks a lot!</p>
3
2009-10-17T04:43:33Z
3,373,317
<p>You can use a precompiled binary available at sourceforge page of mysql-python. The version 1.2.2 has the binary installer for python2.4 and python2.5</p> <p>If you are searching for python2.6 binaries, find it here - <a href="http://www.codegood.com/archives/4" rel="nofollow">http://www.codegood.com/archives/4</a></p>
0
2010-07-30T16:10:43Z
[ "python", "mysql", "mysql-python" ]
Installing python-mysql with wamp's mysql
1,581,431
<p>(I'm not sure if this should be asked here or SU.. but seeing <a href="http://stackoverflow.com/questions/1458500/need-help-installing-mysql-for-python">this question</a> on SO, I am asking it here...)</p> <p>I have wamp (mysql-5.1.33) server setup on my vista machine, and I am trying to install python-mysql 1.2.3c1 to use the mysql version provided by wamp.</p> <p>At first, when I ran <code>python setup.py install</code>, I got an error saying it couldn't find the location of the mysql's bin folder. Looking into <code>setup_windows.py</code>, I noticed it was looking for a registry key and so I added that registry entry and I think it is able to find it now.</p> <p>But now, when I run <code>python setup.py install</code>, I get a different error saying <code>Unable to find vcvarsall.bat</code>.</p> <p>Any help on installing this appreciated.</p> <h3>Here is the output of <code>python setup.py install</code>:</h3> <pre><code>running install running bdist_egg running egg_info writing MySQL_python.egg-info\PKG-INFO writing top-level names to MySQL_python.egg-info\top_level.txt writing dependency_links to MySQL_python.egg-info\dependency_links.txt reading manifest file 'MySQL_python.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'MySQL_python.egg-info\SOURCES.txt' installing library code to build\bdist.win32\egg running install_lib running build_py copying MySQLdb\release.py -&gt; build\lib.win32-2.6\MySQLdb running build_ext building '_mysql' extension error: Unable to find vcvarsall.bat </code></pre> <p>Thanks a lot!</p>
3
2009-10-17T04:43:33Z
4,580,035
<p>The reason is msvc9compiler.py in Python26\Lib\distutils don't analyse VC version properly. You can check find_vcvarsall(version) in msvc9compiler.py yourself: it always turns version = 9, means VC9(2008) will work, but never VC8(2005). The awkward way to compile something using setup.py with VC8 is make version = 8 manually in the function above, after build and install recover it to old.</p>
1
2011-01-02T19:19:54Z
[ "python", "mysql", "mysql-python" ]
Reposition a VLC window programmatically
1,581,782
<p>I'm sure others have run into this problem too...</p> <p>I often watch videos in a small VLC window while working on other tasks, but no matter where the window is placed, I eventually need to access something in the GUI behind it, and have to manually reposition the video window first.</p> <p>This could be solved by having the VLC window snap to another corner whenever the mouse pointer is moved over it. I haven't found an app that does this, so would like to write one. What technologies could I use to do this? Cross platform might be harder... so what if just on Windows?</p> <p>I'd prefer something in C# (or Python), but am willing to learn something new if need be.</p>
2
2009-10-17T09:04:18Z
1,581,792
<p>Here is a windows only solution. You dont need to actually put the mouse over the window. All you need to do is <a href="http://msdn.microsoft.com/en-us/library/ms633499%28VS.85%29.aspx" rel="nofollow">Find the window</a> using its name and <a href="http://msdn.microsoft.com/en-us/library/ms644950%28VS.85%29.aspx" rel="nofollow">send</a> WM_MOVE. I dont know the name of the window which VLC uses. You could use Spy++ to find its name.</p>
1
2009-10-17T09:12:19Z
[ "c#", "python", "windows", "cross-platform", "vlc" ]
Reposition a VLC window programmatically
1,581,782
<p>I'm sure others have run into this problem too...</p> <p>I often watch videos in a small VLC window while working on other tasks, but no matter where the window is placed, I eventually need to access something in the GUI behind it, and have to manually reposition the video window first.</p> <p>This could be solved by having the VLC window snap to another corner whenever the mouse pointer is moved over it. I haven't found an app that does this, so would like to write one. What technologies could I use to do this? Cross platform might be harder... so what if just on Windows?</p> <p>I'd prefer something in C# (or Python), but am willing to learn something new if need be.</p>
2
2009-10-17T09:04:18Z
1,582,934
<p>This is a bit OOT, but in Windows 7, shaking the active window will hide others to reveal the desktop (and so will clicking/hovering the rightmost taskbar button). Instead of hiding/moving vlc, you could just temporarily reveal the whole desktop. Shaking the active window again brings everything back.</p>
0
2009-10-17T18:55:25Z
[ "c#", "python", "windows", "cross-platform", "vlc" ]
How to draw a bitmap real quick in python using Tk only?
1,581,799
<p>Here is a problem. I want to visualize a specific vector field as a bitmap. It's ok with the representation itself, so I allready have some matrix of RGB lists like [255,255,115], but I have no good idea of how to draw it on screen. So far I make thousands of colored 1px rectangles, but this works too slow. I'm sure there is a better way to draw a bitmap.</p>
3
2009-10-17T09:18:39Z
1,582,896
<p><strong>ATTEMPT 3 - I swear last one...</strong></p> <p>I believe this is the fastest pure TK way to do this. Generates 10,000 RGB values in a list of lists, creates a Tkinter.PhotoImage and then puts the pixel values into it.</p> <pre><code>import Tkinter, random class App: def __init__(self, t): self.i = Tkinter.PhotoImage(width=100,height=100) colors = [[random.randint(0,255) for i in range(0,3)] for j in range(0,10000)] row = 0; col = 0 for color in colors: self.i.put('#%02x%02x%02x' % tuple(color),(row,col)) col += 1 if col == 100: row +=1; col = 0 c = Tkinter.Canvas(t, width=100, height=100); c.pack() c.create_image(0, 0, image = self.i, anchor=Tkinter.NW) t = Tkinter.Tk() a = App(t) t.mainloop() </code></pre> <p><strong>ATTEMPT 1 - using the create_rectangle method</strong></p> <p>I wrote this as a test. On my Intel Core 2 duo at 2.67 Ghz, it'll draw about 5000 pixels in 0.6 seconds including the time to generate my random RGB values:</p> <pre><code>from Tkinter import * import random def RGBs(num): # random list of list RGBs return [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)] def rgb2Hex(rgb_tuple): return '#%02x%02x%02x' % tuple(rgb_tuple) def drawGrid(w,colors): col = 0; row = 0 colors = [rgb2Hex(color) for color in colors] for color in colors: w.create_rectangle(col, row, col+1, row+1, fill=color, outline=color) col+=1 if col == 100: row += 1; col = 0 root = Tk() w = Canvas(root) w.grid() colors = RGBs(5000) drawGrid(w,colors) root.mainloop() </code></pre> <p><strong>ATTEMPT 2 - Using PIL</strong></p> <p>I know you said TK only but PIL makes this really easy and fast.</p> <pre><code>def rgb2Hex(rgb_tuple): return '#%02x%02x%02x' % tuple(rgb_tuple) num = 10000 #10,000 pixels in 100,100 image colors = [[random.randint(0,255) for i in range(0,3)] for j in range(0,num)] colors = [rgb2Hex(color) for color in colors] im = Image.fromstring('RGB',(100,100),"".join(colors)) tkpi = ImageTk.PhotoImage(im) ## add to a label or whatever... label_image = Tkinter.Label(root, image=tkpi) </code></pre>
12
2009-10-17T18:34:06Z
[ "python", "visualization", "tk" ]
How to draw a bitmap real quick in python using Tk only?
1,581,799
<p>Here is a problem. I want to visualize a specific vector field as a bitmap. It's ok with the representation itself, so I allready have some matrix of RGB lists like [255,255,115], but I have no good idea of how to draw it on screen. So far I make thousands of colored 1px rectangles, but this works too slow. I'm sure there is a better way to draw a bitmap.</p>
3
2009-10-17T09:18:39Z
26,158,702
<p>There is a faster pure tkinter method:</p> <pre><code>import Tkinter, random class App: def __init__(self, t): self.i = Tkinter.PhotoImage(width=100,height=100) colors = ([random.randint(0,255) for i in range(0,3)] for j in range(0,10000)) pixels=" ".join(("{"+" ".join(('#%02x%02x%02x' % tuple(next(colors)) for i in range(x)))+"}" for j in range(y))) self.i.put(pixels,(0,0,100,100)) c = Tkinter.Canvas(t, width=100, height=100); c.pack() c.create_image(0, 0, image = self.i, anchor=Tkinter.NW) t = Tkinter.Tk() a = App(t) t.mainloop() </code></pre> <p>You can use put() to draw a rectangle with some color data(a string), in this case the whole image. This way you dont need the loop which is quite expensive.</p>
3
2014-10-02T10:12:58Z
[ "python", "visualization", "tk" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,581,902
<p>The way I solved this (actually I did this in Scala, not Python) was to use both a Set and a Queue, only adding links to the queue (and set) if they did not already exist in the set.</p> <p>Both the set and queue were encapsulated in a single thread, exposing only a queue-like interface to the consumer threads.</p> <p>Edit: someone else suggested SQLite and that is also something I am considering, if the set of visited URLs needs to grow large. (Currently each crawl is only a few hundred pages so it easily fits in memory.) But the database is something that can also be encapsulated within the set itself, so the consumer threads need not be aware of it.</p>
1
2009-10-17T10:26:06Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,581,903
<p>SQLite is so simple to use and would fit perfectly... just a suggestion.</p>
2
2009-10-17T10:27:08Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,581,908
<p>Also, instead of a set you might try using a dictionary. Operations on sets tend to get rather slow when they're big, whereas a dictionary lookup is nice and quick.</p> <p>My 2c.</p>
-3
2009-10-17T10:32:23Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,581,913
<p>use:</p> <pre><code>url in q.queue </code></pre> <p>which returns True iff <code>url</code> is in the queue</p>
1
2009-10-17T10:34:52Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,581,920
<p>Why only use the array (ideally, a dictionary would be even better) to filter things you've already visited? Add things to your array/dictionary as soon as you queue them up, and only add them to the queue if they're not already in the array/dict. Then you have 3 simple separate things:</p> <ol> <li>Links not yet seen (neither in queue nor array/dict)</li> <li>Links scheduled to be visited (in both queue and array/dict)</li> <li>Links already visited (in array/dict, not in queue)</li> </ol>
1
2009-10-17T10:36:59Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,581,937
<p>If you don't care about the order in which items are processed, I'd try a subclass of <code>Queue</code> that uses <code>set</code> internally:</p> <pre><code>class SetQueue(Queue): def _init(self, maxsize): self.maxsize = maxsize self.queue = set() def _put(self, item): self.queue.add(item) def _get(self): return self.queue.pop() </code></pre> <p>As Paul McGuire pointed out, this would allow adding a duplicate item after it's been removed from the "to-be-processed" set and not yet added to the "processed" set. To solve this, you can store both sets in the <code>Queue</code> instance, but since you are using the larger set for checking if the item has been processed, you can just as well go back to <code>queue</code> which will order requests properly.</p> <pre><code>class SetQueue(Queue): def _init(self, maxsize): Queue._init(self, maxsize) self.all_items = set() def _put(self, item): if item not in self.all_items: Queue._put(self, item) self.all_items.add(item) </code></pre> <p>The advantage of this, as opposed to using a set separately, is that the <code>Queue</code>'s methods are thread-safe, so that you don't need additional locking for checking the other set.</p>
10
2009-10-17T10:46:37Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
1,582,421
<p>instead of "array of pages already visited" make an "array of pages already added to the queue"</p>
0
2009-10-17T15:13:21Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
24,183,479
<p>The put method also needs to be overwritten, if not a join call will block forever <a href="https://github.com/python/cpython/blob/master/Lib/queue.py#L147" rel="nofollow">https://github.com/python/cpython/blob/master/Lib/queue.py#L147</a> </p> <pre><code>class UniqueQueue(Queue): def put(self, item, block=True, timeout=None): if item not in self.queue: # fix join bug Queue.put(self, item, block, timeout) def _init(self, maxsize): self.queue = set() def _put(self, item): self.queue.add(item) def _get(self): return self.queue.pop() </code></pre>
3
2014-06-12T11:42:57Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
26,822,693
<p><em>Sadly, I have no enouch rating for comment the best Lukáš Lalinský’s answer.</em></p> <p>To add support for <code>SetQueue.task_done()</code> and <code>SetQueue.join()</code> for second variant of Lukáš Lalinský’s SetQueue add else brahch to the if:</p> <pre><code>def _put(self, item): if item not in self.all_items: Queue._put(self, item); self.all_items.add(item); else: self.unfinished_tasks -= 1; </code></pre> <p>Tested and works with Python 3.4.</p>
0
2014-11-08T22:15:46Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
29,691,803
<p>This is full version of <code>SetQueue</code></p> <pre><code>import Queue class SetQueue(Queue.Queue): def _init(self, maxsize): Queue.Queue._init(self, maxsize) self.all_items = set() def _put(self, item): if item not in self.all_items: Queue.Queue._put(self, item) self.all_items.add(item) def _get(self): item = Queue.Queue._get(self) self.all_items.remove(item) return item </code></pre>
1
2015-04-17T06:23:50Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
34,522,293
<p>What follows is an improvement over Lukáš Lalinský's latter <a href="https://stackoverflow.com/a/1581937/4117209">solution</a>. The important difference is that <code>put</code> is overridden in order to ensure <code>unfinished_tasks</code> is accurate and <code>join</code> works as expected.</p> <pre><code>from queue import Queue class UniqueQueue(Queue): def _init(self, maxsize): self.all_items = set() Queue._init(self, maxsize) def put(self, item, block=True, timeout=None): if item not in self.all_items: self.all_items.add(item) Queue.put(self, item, block, timeout) </code></pre>
1
2015-12-30T02:54:15Z
[ "python", "multithreading", "queue" ]
How check if a task is already in python Queue?
1,581,895
<p>I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but if there are more than one threads and they get the same links on different pages, they put duplicate links to the queue. So how can I find out whether some url is already in the queue to avoid putting it there again?</p>
10
2009-10-17T10:21:43Z
36,247,735
<p>I'm agree with @Ben James.Try to use both deque and set. </p> <p>here are code:</p> <pre><code>class SetUniqueQueue(Queue): def _init(self, maxsize): self.queue = deque() self.setqueue = set() def _put(self, item): if item not in self.setqueue: self.setqueue.add(item) self.queue.append(item) def _get(self): return self.queue.popleft() </code></pre>
0
2016-03-27T13:12:50Z
[ "python", "multithreading", "queue" ]
How to wrap a CLI program in Python (keeping the interactivity)?
1,582,026
<p>I'd like to write a wrapper for an interactive CLI Program (the Asterisk CLI).</p> <p>Basically, I need to keep the interaction with the CLI (including tab-completion) but I want to filter the output of Asterisk, in order to show only lines matching a given pattern.</p> <p>I tried a select() based approach, using popen.popen4 and putting asterisk stdout_and_stderr and sys.stdin in the read_fs, but it sort of didn't work.</p> <p>Can anyone give some good pointers to me?</p> <p>Thanks a lot, Andrea</p>
3
2009-10-17T11:44:55Z
1,582,035
<p>Pexpect might be useful for you: <a href="http://sourceforge.net/projects/pexpect/">http://sourceforge.net/projects/pexpect/</a></p> <p>Description from the webpage: "Pexpect is a Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. Pexpect is pure Python."</p>
6
2009-10-17T11:53:26Z
[ "python", "select", "wrapper", "command-line-interface", "interactive" ]
How to wrap a CLI program in Python (keeping the interactivity)?
1,582,026
<p>I'd like to write a wrapper for an interactive CLI Program (the Asterisk CLI).</p> <p>Basically, I need to keep the interaction with the CLI (including tab-completion) but I want to filter the output of Asterisk, in order to show only lines matching a given pattern.</p> <p>I tried a select() based approach, using popen.popen4 and putting asterisk stdout_and_stderr and sys.stdin in the read_fs, but it sort of didn't work.</p> <p>Can anyone give some good pointers to me?</p> <p>Thanks a lot, Andrea</p>
3
2009-10-17T11:44:55Z
12,582,187
<p><a href="http://code.google.com/p/py-asterisk/" rel="nofollow">http://code.google.com/p/py-asterisk/</a></p> <p><strong>Introduction</strong></p> <p>The Python Asterisk package (codenamed py-Asterisk) is an attempt to produce high quality, well documented Python bindings for the Asterisk Manager API.</p> <p>The eventual goal of the package is to allow rich specification of the Asterisk configuration in Python rather than in the quirky, unstructured, undocumented mess that we call the Asterisk configuration files.</p> <p><strong>Working Functionality</strong></p> <p>Python package implementing a manager client and event dispatcher. User-oriented command line interface to manager API.</p>
0
2012-09-25T11:40:29Z
[ "python", "select", "wrapper", "command-line-interface", "interactive" ]
Dynamic URL with CherryPY MethodDispatcher
1,582,297
<p>I need to configure a RESTful style URL that support the following URL scheme:</p> <ul> <li>/parent/ </li> <li>/parent/1 </li> <li>/parent/1/children</li> <li>/parent/1/chidren/1</li> </ul> <p>I want to use the MethodDispatcher so that each of the above can have GET/POST/PUT/DELETE functions. I have it working for the first and second, but can't figure out how to configure the dispatcher for the children portion. I have the book, but it barely covers this and I can't find any sample online.</p> <p>Here is how I have the MethodDispatcher configured currently.</p> <pre><code>root = Root() conf = {'/' : {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}} cherrypy.quickstart(root, '/parent', config=conf) </code></pre> <p>Any help would be appreciated.</p>
10
2009-10-17T14:19:25Z
1,582,444
<p><a href="http://tools.cherrypy.org/wiki/RestfulDispatch" rel="nofollow">http://tools.cherrypy.org/wiki/RestfulDispatch</a> might be what you're looking for.</p> <p>In CherryPy 3.2 (just now coming out of beta), there will be a new <code>_cp_dispatch</code> method you can use in your object tree to do the same thing, or even alter traversal as it happens, somewhat along the lines of Quixote's <code>_q_lookup</code> and <code>_q_resolve</code>. See <a href="https://bitbucket.org/cherrypy/cherrypy/wiki/WhatsNewIn32#!dynamic-dispatch-by-controllers" rel="nofollow">https://bitbucket.org/cherrypy/cherrypy/wiki/WhatsNewIn32#!dynamic-dispatch-by-controllers</a></p>
9
2009-10-17T15:27:00Z
[ "python", "rest", "cherrypy" ]
Dynamic URL with CherryPY MethodDispatcher
1,582,297
<p>I need to configure a RESTful style URL that support the following URL scheme:</p> <ul> <li>/parent/ </li> <li>/parent/1 </li> <li>/parent/1/children</li> <li>/parent/1/chidren/1</li> </ul> <p>I want to use the MethodDispatcher so that each of the above can have GET/POST/PUT/DELETE functions. I have it working for the first and second, but can't figure out how to configure the dispatcher for the children portion. I have the book, but it barely covers this and I can't find any sample online.</p> <p>Here is how I have the MethodDispatcher configured currently.</p> <pre><code>root = Root() conf = {'/' : {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}} cherrypy.quickstart(root, '/parent', config=conf) </code></pre> <p>Any help would be appreciated.</p>
10
2009-10-17T14:19:25Z
16,180,835
<pre><code>#!/usr/bin/env python import cherrypy class Items(object): exposed = True def __init__(self): pass # this line will map the first argument after / to the 'id' parameter # for example, a GET request to the url: # http://localhost:8000/items/ # will call GET with id=None # and a GET request like this one: http://localhost:8000/items/1 # will call GET with id=1 # you can map several arguments using: # @cherrypy.propargs('arg1', 'arg2', 'argn') # def GET(self, arg1, arg2, argn) @cherrypy.popargs('id') def GET(self, id=None): print "id: ", id if not id: # return all items else: # return only the item with id = id # HTML5 def OPTIONS(self): cherrypy.response.headers['Access-Control-Allow-Credentials'] = True cherrypy.response.headers['Access-Control-Allow-Origin'] = cherrypy.request.headers['ORIGIN'] cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET, PUT, DELETE' cherrypy.response.headers['Access-Control-Allow-Headers'] = cherrypy.request.headers['ACCESS-CONTROL-REQUEST-HEADERS'] class Root(object): pass root = Root() root.items = Items() conf = { 'global': { 'server.socket_host': '0.0.0.0', 'server.socket_port': 8000, }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), }, } cherrypy.quickstart(root, '/', conf) </code></pre>
2
2013-04-23T23:23:38Z
[ "python", "rest", "cherrypy" ]
Longest string in numpy object_ array
1,582,525
<p>I'm using a numpy object_ array to store variable length strings, e.g.</p> <pre><code>a = np.array(['hello','world','!'],dtype=np.object_) </code></pre> <p>Is there an easy way to find the length of the longest string in the array without looping over all elements?</p>
4
2009-10-17T16:05:56Z
1,582,556
<p>No as the only place the length of each string is known is by the string. So you have to find out from every string what its length is.</p>
0
2009-10-17T16:15:10Z
[ "python", "arrays", "numpy" ]
Longest string in numpy object_ array
1,582,525
<p>I'm using a numpy object_ array to store variable length strings, e.g.</p> <pre><code>a = np.array(['hello','world','!'],dtype=np.object_) </code></pre> <p>Is there an easy way to find the length of the longest string in the array without looping over all elements?</p>
4
2009-10-17T16:05:56Z
1,582,665
<p>If you store the string in a numpy array of dtype object, then you can't get at the size of the objects (strings) without looping. However, if you let np.array decide the dtype, then you can find out the length of the longest string by peeking at the dtype:</p> <pre><code>In [64]: a = np.array(['hello','world','!','Oooh gaaah booo gaah?']) In [65]: a.dtype Out[65]: dtype('|S21') In [72]: a.dtype.itemsize Out[72]: 21 </code></pre>
2
2009-10-17T16:59:52Z
[ "python", "arrays", "numpy" ]
Longest string in numpy object_ array
1,582,525
<p>I'm using a numpy object_ array to store variable length strings, e.g.</p> <pre><code>a = np.array(['hello','world','!'],dtype=np.object_) </code></pre> <p>Is there an easy way to find the length of the longest string in the array without looping over all elements?</p>
4
2009-10-17T16:05:56Z
1,582,670
<p><code>max(a, key=len)</code> gives you the longest string (and <code>len(max(a, key=len))</code> gives you its length) without requiring you to code an explicit loop, but of course <code>max</code> will do its own looping internally, as it couldn't possibly identify "the longest string" in any other way.</p>
4
2009-10-17T17:01:32Z
[ "python", "arrays", "numpy" ]
Longest string in numpy object_ array
1,582,525
<p>I'm using a numpy object_ array to store variable length strings, e.g.</p> <pre><code>a = np.array(['hello','world','!'],dtype=np.object_) </code></pre> <p>Is there an easy way to find the length of the longest string in the array without looping over all elements?</p>
4
2009-10-17T16:05:56Z
25,559,451
<p>Say I want to get the longest string in the second column:</p> <pre><code>data_array = [['BFNN' 'Forested bog without permafrost or patterning, no internal lawns'] ['BONS' 'Nonpatterned, open, shrub-dominated bog']] def get_max_len_column_value(data_array, column): return len(max(data_array[:,[column]], key=len)[0]) get_max_len_column_value(data_array, 1) &gt;&gt;&gt;64 </code></pre>
0
2014-08-28T23:18:07Z
[ "python", "arrays", "numpy" ]
asyncore not running handle_read
1,582,558
<p>I'm trying to just make a simple asyncore example where one socket is the sender and one is the receiver. For some reason, the handle_read() on the receiver is never called so I never get the 'test' data. Anyone know why? This is my first shot at asyncore, so it's probably something extremely simple.</p> <pre><code>import asyncore, socket, pdb, random class Sender(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) def handle_connect(self): print ('first connect') def writable(self): True def readable(self): return False def handle_write(self): pass def handle_close(self): self.close() class Receiver(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) def handle_connect(self): print ('first connect') def readable(self): return True def handle_read(self): print 'reading' def handle_write(self): print 'write' def handle_accept(self): self.conn_sock, addr = self.accept() print 'accepted' def handle_close(self): self.close() a = Sender() b = Receiver() addr = ('localhost', 12344) b.bind(addr) b.listen(1) a.connect(addr) asyncore.loop() a.send('test') </code></pre>
0
2009-10-17T16:16:06Z
1,582,565
<p><code>asyncore.loop</code> does not terminate, so the <code>a.send</code> doesn't happen, since you've coded it to happen in line <em>after</em> the exit of asyncore.loop.</p> <p>Once this is fixed, you run into the problem that you're running sender and receiver within a single thread and process, so unless you take very delicate steps to ensure everything happens in the right order, you ARE going to get deadlocked. asyncore is of course meant to be used among processes running separately, so the problem just doesn't appear in normal, real-world uses. If you're curious about exactly where you're deadlocking, make your own copy of asyncore and pepper it with print statements, or, try</p> <pre><code>python -m trace -t ast.py </code></pre> <p>Unfortunately, the latter gives a <em>lot</em> of output and doesn't show crucial variables' values. so, while painless and non-invasive to try, it's far less helpful than a few strategically placed <code>print</code>s (e.g., the r and w fd lists just before and after each select).</p> <p>I believe (but haven't debugged it in depth, since it's an unrealistic scenario anyway) that the select triggers only once (because you have both the accept/connect <em>and</em> the writing of bytes to the socket happen before the first select, they end up "collapsed" into a single event), but the handling of that one event can't know about the collapsing (wouldn't happen in normal use!-) so it only deals with the accept/connect. But if you take the time to debug in greater depth you may no doubt understand this anomalous scenario better!</p>
1
2009-10-17T16:18:42Z
[ "python", "asyncore" ]
asyncore not running handle_read
1,582,558
<p>I'm trying to just make a simple asyncore example where one socket is the sender and one is the receiver. For some reason, the handle_read() on the receiver is never called so I never get the 'test' data. Anyone know why? This is my first shot at asyncore, so it's probably something extremely simple.</p> <pre><code>import asyncore, socket, pdb, random class Sender(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) def handle_connect(self): print ('first connect') def writable(self): True def readable(self): return False def handle_write(self): pass def handle_close(self): self.close() class Receiver(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) def handle_connect(self): print ('first connect') def readable(self): return True def handle_read(self): print 'reading' def handle_write(self): print 'write' def handle_accept(self): self.conn_sock, addr = self.accept() print 'accepted' def handle_close(self): self.close() a = Sender() b = Receiver() addr = ('localhost', 12344) b.bind(addr) b.listen(1) a.connect(addr) asyncore.loop() a.send('test') </code></pre>
0
2009-10-17T16:16:06Z
11,226,559
<p>A lot late and not solving the issue as Alex points to the causes, but your code shows:</p> <pre><code>def writable(self): True </code></pre> <p>Shouldn't that be:</p> <pre><code>def writable(self): return True </code></pre>
1
2012-06-27T12:46:51Z
[ "python", "asyncore" ]
Using/Creating Python objects with Jython
1,582,674
<p>HI, </p> <p>lets say I have a Java interface B, something like this. B.java :</p> <pre><code>public interface B { String FooBar(String s); } </code></pre> <p>and I want to use it with a Python class D witch inherits B, like this. D.py :</p> <pre><code>class D(B): def FooBar(s) return s + 'e' </code></pre> <p>So now how do I get an instance of D in java? I'm sorry im asking such a n00b question but the Jython doc sucks / is partially off line. </p>
2
2009-10-17T17:03:37Z
1,582,800
<p>Code for your example above. You also need to change the FooBar implementation to take a self argument since it is not a static method.</p> <p>You need to have jython.jar on the classpath for this example to compile and run.</p> <pre><code>import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class Main { public static B create() { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("from D import D"); PyObject DClass = interpreter.get("D"); PyObject DObject = DClass.__call__(); return (B)DObject.__tojava__(B.class); } public static void main(String[] args) { B b = create(); System.out.println(b.FooBar("Wall-")); } } </code></pre> <p>For more info see the chapter on <a href="http://jythonpodcast.hostjava.net/jythonbook/chapter10.html" rel="nofollow">Jython and Java integration</a> in the <a href="http://jythonpodcast.hostjava.net/jythonbook/index.html" rel="nofollow">Jython Book</a></p>
3
2009-10-17T17:51:28Z
[ "java", "python", "jython" ]
Selenium IDE - can't select "table" tab
1,582,679
<p>Can someone tell me why I can't select the "table" tab?</p> <p>Here is a pic:</p> <p><img src="http://img110.imageshack.us/img110/935/imgzx.jpg" alt="alt text" /></p>
0
2009-10-17T17:06:25Z
1,582,827
<p>What "Format" are you using? The table is available in HTML only. I think. </p> <p>Select Options/Format/HTML from the menu and the Table tab should be activated.</p>
1
2009-10-17T18:05:39Z
[ "python" ]
Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead?
1,582,708
<p>I've been programming Python a while, but DJango and web programming in general is new to me.</p> <p>I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's an HTTP timeout. Fair enough, I understand that part.</p> <p>What's the best way to give an HTTPresponse back to my users immediately, then dynamically show the results of some python code within the page? I suspect the answer may lie in AJAX but I;m not sure how AJAX on the client can be fed from Python on the server, or even the modules one would commonly use to do such a thing.</p>
5
2009-10-17T17:19:45Z
1,582,726
<p>One way is to submit the task using AJAX/JS or the normal way, start it in background in your view and return immediately. Then use AJAX/JS on client side to periodically check if task is done. If it's done reload the page or provide a link to the client.</p> <blockquote> <p>CLIENT "Please start a task using this data."-> SERVER</p> <p>CLIENT &lt;- "Task started!" SERVER</p> <p>CLIENT "Done?"-> SERVER</p> <p>CLIENT &lt;- "Nope." SERVER</p> <p>CLIENT "Done?"-> SERVER</p> <p>CLIENT &lt;- "Yep, here's a link where you can view results" SERVER</p> </blockquote> <p>While sending data from server to client without client asking for it is possible, well kind a, (the technology is called <a href="http://en.wikipedia.org/wiki/Comet%5F%28programming%29">Comet</a>) it isn't really necessary in your case. </p>
5
2009-10-17T17:26:53Z
[ "python", "ajax", "django", "timeout" ]
Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead?
1,582,708
<p>I've been programming Python a while, but DJango and web programming in general is new to me.</p> <p>I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's an HTTP timeout. Fair enough, I understand that part.</p> <p>What's the best way to give an HTTPresponse back to my users immediately, then dynamically show the results of some python code within the page? I suspect the answer may lie in AJAX but I;m not sure how AJAX on the client can be fed from Python on the server, or even the modules one would commonly use to do such a thing.</p>
5
2009-10-17T17:19:45Z
1,582,971
<p>Ajax doesn't require any particular technology on the server side. All you need is to return a response in some form that some Javascript on the client side can understand. JSON is an excellent choice here, as it's easy to create in Python (there's a <code>json</code> library in 2.6, and Django has <code>django.utils.simplejson</code> for other versions).</p> <p>So all you need to do is to put your data in JSON form then send it just as you would any other response - ie by wrapping it in an <code>HTTPResponse</code>.</p>
7
2009-10-17T19:09:27Z
[ "python", "ajax", "django", "timeout" ]
Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead?
1,582,708
<p>I've been programming Python a while, but DJango and web programming in general is new to me.</p> <p>I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's an HTTP timeout. Fair enough, I understand that part.</p> <p>What's the best way to give an HTTPresponse back to my users immediately, then dynamically show the results of some python code within the page? I suspect the answer may lie in AJAX but I;m not sure how AJAX on the client can be fed from Python on the server, or even the modules one would commonly use to do such a thing.</p>
5
2009-10-17T17:19:45Z
1,583,261
<p>I'm not sure if this is what you are looking for, but <a href="http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python">maybe this question</a> (How to implement a minimal server for AJAX in Python?) is helpful. In my answer I give a minimal example (which is not very well written, for example I would now use jquery...).</p> <p>Edit: As requested by the OP, here is an example for the frontend with JQuery. Note that I'm no expert on this, so there might be issues. This example is supposed to work with a JSON-RPC backend, like <a href="http://www.freenet.org.nz/dojo/pyjson/" rel="nofollow">this one</a>.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;JSON-RPC test&lt;/title&gt; &lt;script type="text/javascript" src="jquery-1.3.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="json2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function test_button() { var data = $("[name=test_text]").val(); var json_object = {"method": "power", "params": [parseInt(data), 3], "id": "test_button"}; var json_string = JSON.stringify(json_object); $.post("frontend.html", json_string, test_callback, "json") } function test_callback(json_object) { $("#test_result").text(json_object.result.toString()); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="text" name="test_text" value="2" size="4"&gt; ** 3 = &lt;span id="test_result"&gt;0&lt;/span&gt; &lt;input type=button onClick="test_button();" value="calc" title="calculate value"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-10-17T21:21:46Z
[ "python", "ajax", "django", "timeout" ]
Best practice for the Python-then-profile-then-C design pattern?
1,582,718
<p>A popular software development pattern seems to be:</p> <ol> <li>Thrash out the logic and algorithms in Python.</li> <li>Profile to find out where the slow bits are.</li> <li>Replace those with C.</li> <li>Ship code that is the best trade-off between high-level and speedy.</li> </ol> <p>I say popular simply because I've seen people talk about it as being a great idea.</p> <p>But are there any large projects that have actually used this method? Preferably Free software projects so I can have a look and see how they did it - and maybe learn some best practices.</p>
4
2009-10-17T17:24:41Z
1,582,784
<p>Step 3 is wrong. In the modern world, more than half the time "the slow bits" are I/O or network bound, or limited by some other resource outside the process. Rewriting them in anything is only going to introduce bugs.</p>
0
2009-10-17T17:48:04Z
[ "python", "c", "refactoring", "profiling" ]
Best practice for the Python-then-profile-then-C design pattern?
1,582,718
<p>A popular software development pattern seems to be:</p> <ol> <li>Thrash out the logic and algorithms in Python.</li> <li>Profile to find out where the slow bits are.</li> <li>Replace those with C.</li> <li>Ship code that is the best trade-off between high-level and speedy.</li> </ol> <p>I say popular simply because I've seen people talk about it as being a great idea.</p> <p>But are there any large projects that have actually used this method? Preferably Free software projects so I can have a look and see how they did it - and maybe learn some best practices.</p>
4
2009-10-17T17:24:41Z
1,582,864
<p>There are lots of different ways that people approach development. </p> <p>Sometimes people follow your three steps and discover that the slow bits are due to the external environment, therefore rewriting Python into C does not address the problem. That type of slowness can sometimes be solved on the system side, and sometimes it can be solved in Python by applying a different algorithm. For instance you can cache network responses so that you don't have to go to the network every time, or in SQL you can offload work into `stored procedures which run on the server and reduce the size of the result set. Generally, when you do have something that needs to be rewritten in C, the first thing to do is to look for a pre-existing library and just create a Python wrapper, if one does not already exist. Lots of people have been down these paths before you.</p> <p>Often step 1 is to thrash out the application architecture, suspect that there may be a performance issue in some area, then choose a C library (perhaps already wrapped for Python) and use that. Then step 2 simply confirms that there are no really big performance issues that need to be addressed.</p> <p>I would say that it is better for a team with one or more experienced developers to attempt to predict performance bottlenecks and mitigate them with pre-existing modules right from the beginning. If you are a beginner with python, then your 3-step process is perfectly valid, i.e. get into building and testing code, knowing that there is a profiler and the possibility of fast C modules if you need it. And then there is psyco, and the various tools for freezing an application into a binary executable.</p> <p>An alternative approach to this, if you know that you will need to use some C or C++ modules, is to start from scratch writing the application in C but embedding Python to do most of the work. This works well for experienced C or C++ developers because they have a rough idea of the type of code that is tedious to do in C.</p>
3
2009-10-17T18:22:20Z
[ "python", "c", "refactoring", "profiling" ]
Best practice for the Python-then-profile-then-C design pattern?
1,582,718
<p>A popular software development pattern seems to be:</p> <ol> <li>Thrash out the logic and algorithms in Python.</li> <li>Profile to find out where the slow bits are.</li> <li>Replace those with C.</li> <li>Ship code that is the best trade-off between high-level and speedy.</li> </ol> <p>I say popular simply because I've seen people talk about it as being a great idea.</p> <p>But are there any large projects that have actually used this method? Preferably Free software projects so I can have a look and see how they did it - and maybe learn some best practices.</p>
4
2009-10-17T17:24:41Z
1,583,268
<p>I also thought that way when I started using Python</p> <p>I've done step 3 twice (that I can recall) in 12 years. Not often enough to call it a design pattern. Usually it's enough to wrap an existing C library. Usually someone else has already written the wrapper.</p>
2
2009-10-17T21:26:13Z
[ "python", "c", "refactoring", "profiling" ]
Best practice for the Python-then-profile-then-C design pattern?
1,582,718
<p>A popular software development pattern seems to be:</p> <ol> <li>Thrash out the logic and algorithms in Python.</li> <li>Profile to find out where the slow bits are.</li> <li>Replace those with C.</li> <li>Ship code that is the best trade-off between high-level and speedy.</li> </ol> <p>I say popular simply because I've seen people talk about it as being a great idea.</p> <p>But are there any large projects that have actually used this method? Preferably Free software projects so I can have a look and see how they did it - and maybe learn some best practices.</p>
4
2009-10-17T17:24:41Z
16,521,034
<p>Mercurial is a good example: it's written in <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Python and C</a> and it's about as fast as git, which is mostly written in C.</p>
0
2013-05-13T11:34:13Z
[ "python", "c", "refactoring", "profiling" ]
edit text file using Python
1,582,750
<p>I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.</p> <ol> <li><p>Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.</p></li> <li><p>Get the current IP address. It will change on a daily basis.</p></li> <li><p>Create variable CURRENT for the new IP.</p></li> <li><p>Compare (as strings) CURRENT to LASTKNOWN</p></li> <li><p>If they are the same, exit()</p></li> <li><p>If they differ, </p> <p>A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.<br /> C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"<br /> D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"<br /> E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf" </p></li> <li><p>exit()</p></li> </ol> <p>I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.</p> <p>I know how to use subprocess, so you don't need to comment on that. </p> <p>I don't want to replace entire lines; just a specific dotted quad. </p> <p>Thanks!</p>
6
2009-10-17T17:35:22Z
1,582,774
<p>Probably the simplest way would be to open a file using f=open(filename, mode). Then, read all the lines using f.readlines() (this will return a list of strings representing the lines of the program). </p> <p>You can then search these strings to find the address and replace it with the new one (using standard string replacing, regular expressions, or whatever you want).</p> <p>At the end, you can write the lines back to the file using f.writelines(lines), which conveniently takes back a list of lines.</p> <p>NOTE: This is not an efficient way to do this, it's just the easiest. Please</p> <p>Example code:</p> <pre><code>f = open(filename, "r") lines = f.readlines() # Assume that change_ip is a function that takes a string and returns a new one with the ip changed): example below ret_lines = [change_ip(lines) for line in lines] new_file = open(new_filename, "w") new_file.writelines(lines) def change_ip(str): ''' Gets a string, returns a new string where the ip is changed ''' # Add implementation, something like: return str.replace(old_ip, new_ip) or something similair. </code></pre>
1
2009-10-17T17:45:26Z
[ "python", "text", "editing" ]
edit text file using Python
1,582,750
<p>I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.</p> <ol> <li><p>Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.</p></li> <li><p>Get the current IP address. It will change on a daily basis.</p></li> <li><p>Create variable CURRENT for the new IP.</p></li> <li><p>Compare (as strings) CURRENT to LASTKNOWN</p></li> <li><p>If they are the same, exit()</p></li> <li><p>If they differ, </p> <p>A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.<br /> C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"<br /> D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"<br /> E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf" </p></li> <li><p>exit()</p></li> </ol> <p>I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.</p> <p>I know how to use subprocess, so you don't need to comment on that. </p> <p>I don't want to replace entire lines; just a specific dotted quad. </p> <p>Thanks!</p>
6
2009-10-17T17:35:22Z
1,582,781
<p>You're trying to "atomically" update the contents of a file, and there have been many delightful flame wars on the subject. But the general pattern is:</p> <p>1) Write the new file to a temp file, and make sure you flush and close.</p> <p>2) Use your operating system's facilities to atomically rename the temp file to the old file.</p> <p>Now, you simply can't atomically rename a file in Windows, but it sounds like you're on a unix-like system anyway. You atomically rename using <a href="http://docs.python.org/library/os.html" rel="nofollow">os.rename()</a>.</p>
2
2009-10-17T17:47:23Z
[ "python", "text", "editing" ]
edit text file using Python
1,582,750
<p>I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.</p> <ol> <li><p>Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.</p></li> <li><p>Get the current IP address. It will change on a daily basis.</p></li> <li><p>Create variable CURRENT for the new IP.</p></li> <li><p>Compare (as strings) CURRENT to LASTKNOWN</p></li> <li><p>If they are the same, exit()</p></li> <li><p>If they differ, </p> <p>A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.<br /> C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"<br /> D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"<br /> E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf" </p></li> <li><p>exit()</p></li> </ol> <p>I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.</p> <p>I know how to use subprocess, so you don't need to comment on that. </p> <p>I don't want to replace entire lines; just a specific dotted quad. </p> <p>Thanks!</p>
6
2009-10-17T17:35:22Z
1,582,903
<p>After checking the comments and the bit of code that you put on pastebin, here is a working solution. To begin with, the file /tmp/iiiipf.conf contains:</p> <pre><code>Simply a test file 175.48.204.168 And two times 175.48.204.168 on this line 175.48.204.168 Done. </code></pre> <p>After running the code, the file /tmp/iiiipf.conf contains:</p> <pre><code>Simply a test file 10.73.144.112 And two times 10.73.144.112 on this line 10.73.144.112 Done. </code></pre> <p>And here is the tested working code with my stuff merged into your pastebin code:</p> <pre><code>import socket import fileinput import subprocess import string import re CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] LASTKNOWN = '175.48.204.168' if CURRENT == LASTKNOWN: print 'Nevermind.' subprocess.sys.exit() else: cf = open("/tmp/iiiipf.conf", "r") lns = cf.readlines() # close it so that we can open for writing later cf.close() # assumes LASTKNOWN and CURRENT are strings with dotted notation IP addresses lns = "".join(lns) lns = re.sub(LASTKNOWN, CURRENT, lns) # This replaces all occurences of LASTKNOWN with CURRENT cf = open("/tmp/iiiipf.conf", "w") cf.write(lns) cf.close() </code></pre> <p>This bit of code will do what you need even if the IP address is used several times within the configuration file. It will also change it in comment lines.</p> <p>This method does not require copying to /tmp and uses one less subprocess call when restarting the firewall and NAT.</p>
0
2009-10-17T18:37:14Z
[ "python", "text", "editing" ]
edit text file using Python
1,582,750
<p>I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.</p> <ol> <li><p>Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.</p></li> <li><p>Get the current IP address. It will change on a daily basis.</p></li> <li><p>Create variable CURRENT for the new IP.</p></li> <li><p>Compare (as strings) CURRENT to LASTKNOWN</p></li> <li><p>If they are the same, exit()</p></li> <li><p>If they differ, </p> <p>A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.<br /> C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"<br /> D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"<br /> E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf" </p></li> <li><p>exit()</p></li> </ol> <p>I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.</p> <p>I know how to use subprocess, so you don't need to comment on that. </p> <p>I don't want to replace entire lines; just a specific dotted quad. </p> <p>Thanks!</p>
6
2009-10-17T17:35:22Z
1,584,198
<h2>Replace LASTKNOWN by CURRENT in /etc/ipf.conf</h2> <h3>Replace all at once</h3> <pre><code>filename = "/etc/ipf.conf" text = open(filename).read() open(filename, "w").write(text.replace(LASTKNOWN, CURRENT)) </code></pre> <h3>Replace line by line</h3> <pre><code>from __future__ import with_statement from contextlib import nested in_filename, outfilename = "/etc/ipf.conf", "/tmp/ipf.conf" with nested(open(in_filename), open(outfilename, "w")) as in_, out: for line in in_: out.write(line.replace(LASTKNOWN, CURRENT)) os.rename(outfilename, in_filename) </code></pre> <p>Note: "/tmp/ipf.conf" should be replaced by <code>tempfile.NamedTemporaryFile()</code> or similar<br /> Note: the code is not tested.</p>
3
2009-10-18T06:47:31Z
[ "python", "text", "editing" ]
edit text file using Python
1,582,750
<p>I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.</p> <ol> <li><p>Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.</p></li> <li><p>Get the current IP address. It will change on a daily basis.</p></li> <li><p>Create variable CURRENT for the new IP.</p></li> <li><p>Compare (as strings) CURRENT to LASTKNOWN</p></li> <li><p>If they are the same, exit()</p></li> <li><p>If they differ, </p> <p>A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.<br /> C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"<br /> D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"<br /> E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf" </p></li> <li><p>exit()</p></li> </ol> <p>I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.</p> <p>I know how to use subprocess, so you don't need to comment on that. </p> <p>I don't want to replace entire lines; just a specific dotted quad. </p> <p>Thanks!</p>
6
2009-10-17T17:35:22Z
2,363,893
<p>Another way to simply edit files in place is to use the <a href="http://www.google.co.uk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CC8QFjAA&amp;url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Ffileinput.html&amp;ei=TGeZUPCRHOfP0QXQhIHAAw&amp;usg=AFQjCNEmKT3Z55eqWRpCJIDCDyy1ACOGhg"><code>fileinput</code></a> module:</p> <pre><code>import fileinput, sys for line in fileinput.input(["test.txt"], inplace=True): line = line.replace("car", "truck") # sys.stdout is redirected to the file sys.stdout.write(line) </code></pre>
23
2010-03-02T14:43:26Z
[ "python", "text", "editing" ]
pycurl installation on Windows
1,582,814
<p>I am not able to install pycurl on Windows on Python2.6. Getting following error:</p> <pre><code>C:\Documents and Settings\vijayendra\Desktop\Downloads\pycurl-7.19.0&gt;python setup.py install --curl-dir="C:\Documents and Settings\vijayendra\Desktop\Downloads\ curl-7.19.5-win32-ssl\curl-7.19.5" Using curl directory: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5 Traceback (most recent call last): File "setup.py", line 210, in &lt;module&gt; assert os.path.isfile(o), o AssertionError: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5\lib\libcurl.lib </code></pre> <p>Any idea what is this error about and how to fix this?</p>
12
2009-10-17T17:57:36Z
1,582,852
<p>You install pyCURL on Windows via the provided win32-specific <a href="http://pycurl.sourceforge.net/download/" rel="nofollow">binaries</a>.</p>
1
2009-10-17T18:17:53Z
[ "python", "libcurl", "pycurl" ]
pycurl installation on Windows
1,582,814
<p>I am not able to install pycurl on Windows on Python2.6. Getting following error:</p> <pre><code>C:\Documents and Settings\vijayendra\Desktop\Downloads\pycurl-7.19.0&gt;python setup.py install --curl-dir="C:\Documents and Settings\vijayendra\Desktop\Downloads\ curl-7.19.5-win32-ssl\curl-7.19.5" Using curl directory: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5 Traceback (most recent call last): File "setup.py", line 210, in &lt;module&gt; assert os.path.isfile(o), o AssertionError: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5\lib\libcurl.lib </code></pre> <p>Any idea what is this error about and how to fix this?</p>
12
2009-10-17T17:57:36Z
1,585,749
<p>I built pycurl without ssl today for urlgrabber 3.9 and it worked. the dir i used was c:\Pycurl-7.19.0 and same as --curl-dir ,as given CURL_DIR in setup.py, but with fresh compiled libcurl.lib from sources using vc express 08, inside the dir in respective places ie it needs some include files also. try running after the step above for the next err or just check setup.py. </p>
0
2009-10-18T19:10:47Z
[ "python", "libcurl", "pycurl" ]
pycurl installation on Windows
1,582,814
<p>I am not able to install pycurl on Windows on Python2.6. Getting following error:</p> <pre><code>C:\Documents and Settings\vijayendra\Desktop\Downloads\pycurl-7.19.0&gt;python setup.py install --curl-dir="C:\Documents and Settings\vijayendra\Desktop\Downloads\ curl-7.19.5-win32-ssl\curl-7.19.5" Using curl directory: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5 Traceback (most recent call last): File "setup.py", line 210, in &lt;module&gt; assert os.path.isfile(o), o AssertionError: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5\lib\libcurl.lib </code></pre> <p>Any idea what is this error about and how to fix this?</p>
12
2009-10-17T17:57:36Z
2,689,993
<p><a href="http://wiki.woodpecker.org.cn/moin/PyCurl?action=AttachFile&amp;do=view&amp;target=pycurl-7.20.1-bin-win32-py26.zip" rel="nofollow">http://wiki.woodpecker.org.cn/moin/PyCurl?action=AttachFile&amp;do=view&amp;target=pycurl-7.20.1-bin-win32-py26.zip</a></p> <p>unzip it and copy all to your site-packages :)</p>
3
2010-04-22T10:32:29Z
[ "python", "libcurl", "pycurl" ]
pycurl installation on Windows
1,582,814
<p>I am not able to install pycurl on Windows on Python2.6. Getting following error:</p> <pre><code>C:\Documents and Settings\vijayendra\Desktop\Downloads\pycurl-7.19.0&gt;python setup.py install --curl-dir="C:\Documents and Settings\vijayendra\Desktop\Downloads\ curl-7.19.5-win32-ssl\curl-7.19.5" Using curl directory: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5 Traceback (most recent call last): File "setup.py", line 210, in &lt;module&gt; assert os.path.isfile(o), o AssertionError: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5\lib\libcurl.lib </code></pre> <p>Any idea what is this error about and how to fix this?</p>
12
2009-10-17T17:57:36Z
3,817,095
<p>Andelf's answer didn't work on my Win 7 x64 machine, but <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/">Christoph Gohlke's site</a> has a package that works for me.</p>
29
2010-09-28T21:12:00Z
[ "python", "libcurl", "pycurl" ]
pycurl installation on Windows
1,582,814
<p>I am not able to install pycurl on Windows on Python2.6. Getting following error:</p> <pre><code>C:\Documents and Settings\vijayendra\Desktop\Downloads\pycurl-7.19.0&gt;python setup.py install --curl-dir="C:\Documents and Settings\vijayendra\Desktop\Downloads\ curl-7.19.5-win32-ssl\curl-7.19.5" Using curl directory: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5 Traceback (most recent call last): File "setup.py", line 210, in &lt;module&gt; assert os.path.isfile(o), o AssertionError: C:\Documents and Settings\vijayendra\Desktop\Downloads\curl-7.19.5-win32-ssl\curl-7.19.5\lib\libcurl.lib </code></pre> <p>Any idea what is this error about and how to fix this?</p>
12
2009-10-17T17:57:36Z
17,894,696
<p>Here is the url,</p> <p>this sites packages are rocks <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pycurl" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pycurl</a></p>
0
2013-07-27T05:45:18Z
[ "python", "libcurl", "pycurl" ]
String matching in python with re
1,582,895
<p>I have a file in this structure:</p> <p><code>009/foo/bar/hi23123/foo/bar231123/foo/bar/yo232131</code></p> <p>What i need is to find the exact match of a string; e.g. only /foo/bar among /foo/bar/hi and /foo/bar/yo </p> <p>One solution came up in my mind is like to check for ending "/" for the input string. Because if there is ending "/" in the possible results, that means it got something different than only /foo/bar.</p> <p>For this solution, I must say that:</p> <pre><code>input = /foo/bar </code></pre> <p>and</p> <pre><code>match input without ending "/" </code></pre> <p>How can I do this by Regex in python?</p> <p>Btw, if there any other solution suggestion, you're welcome to share here. </p>
0
2009-10-17T18:34:02Z
1,582,906
<p>So you want <code>/foo/bar</code> <strong>not</strong> followed by a <code>/</code>? If so, then you're looking for a "negative lookahead", </p> <pre><code>r = re.compile(r'/foo/bar(?!/)') </code></pre> <p>and then <code>r.search</code> to your heart's content.</p>
8
2009-10-17T18:37:27Z
[ "python", "regex", "string-matching" ]
XML-RPC C# and Python RPC Server
1,583,017
<p>On my server, I'm using the standard example for Python (with an extra Hello World Method) and on the Client side I'm using the XML-RPC.NET Library in C#. But everytime I run my client I get the exception that the method is not found. Any Ideas how fix that. </p> <p>thanks!</p> <p>Python:</p> <pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) # Create server server = SimpleXMLRPCServer(("", 8000), requestHandler=RequestHandler) server.register_introspection_functions() # Register pow() function; this will use the value of # pow.__name__ as the name, which is just 'pow'. server.register_function(pow) # Register a function under a different name def adder_function(x,y): return x + y server.register_function(adder_function, 'add') def HelloWorld(): return "Hello Henrik" server.register_function(HelloWorld,'HelloWorld') # Register an instance; all the methods of the instance are # published as XML-RPC methods (in this case, just 'div'). class MyFuncs: def div(self, x, y): return x // y server.register_instance(MyFuncs()) # Run the server's main loop server.serve_forever() </code></pre> <p>C#</p> <pre><code>namespace XMLRPC_Test { [XmlRpcUrl("http://188.40.xxx.xxx:8000")] public interface HelloWorld : IXmlRpcProxy { [XmlRpcMethod] String HelloWorld(); } [XmlRpcUrl("http://188.40.xxx.xxx:8000")] public interface add : IXmlRpcProxy { [XmlRpcMethod] int add(int x, int y); } [XmlRpcUrl("http://188.40.xxx.xxx:8000")] public interface listMethods : IXmlRpcProxy { [XmlRpcMethod("system.listMethods")] String listMethods(); } class Program { static void Main(string[] args) { listMethods proxy = XmlRpcProxyGen.Create&lt;listMethods&gt;(); Console.WriteLine(proxy.listMethods()); Console.ReadLine(); } } } </code></pre>
4
2009-10-17T19:29:52Z
1,583,047
<p>Does it work if you change the declaration to this?</p> <pre><code>[XmlRpcUrl("http://188.40.xxx.xxx:8000/RPC2")] </code></pre> <p>From the <a href="http://docs.python.org/library/simplexmlrpcserver.html">Python docs</a>:</p> <blockquote> <p><code>SimpleXMLRPCRequestHandler.rpc_paths</code></p> <p>An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will result in a 404 “no such page” HTTP error. If this tuple is empty, all paths will be considered valid. The default value is ('/', '/RPC2').</p> </blockquote>
5
2009-10-17T19:47:08Z
[ "c#", "python", "xml-rpc" ]
Making a C extension to Python that requires another extension
1,583,077
<p>I have a couple of Python functions that I use to make game development with Pygame easier. I have them in a file called helper.py in my Python-path, so I can import them from any game I make. I thought, as an exercise to learn about Python extensions, to convert this module to C. My first problem is that I need to use functions from Pygame, and I'm not sure if this is possible. Pygame installs some header files, but they don't seem to have C versions of the Python functions. Maybe I'm missing something.</p> <p>How can I solve this? As a workaround, the function currently accepts a function parameter and calls that, but it's not the ideal solution.</p> <p>Using Windows XP, Python 2.6 and Pygame 1.9.1, by the way.</p>
4
2009-10-17T20:01:35Z
1,583,194
<p>You can import python modules from C code and call things defined in just like you can in python code. It is a bit long winded, but perfectly possible.</p> <p>When I want to work out how to do something like this I look at the <a href="http://docs.python.org/c-api/index.html" rel="nofollow">C API documentation</a>. The section on <a href="http://docs.python.org/c-api/import.html" rel="nofollow">importing modules</a> will help. You'll also need to read how to read attributes, call functions etc which is all in the docs.</p> <p>However I suspect what you really want to do is call the <a href="http://www.libsdl.org/" rel="nofollow">underlying library sdl</a> from C. This is a C library and is really easy to use from C.</p> <p>Here is some sample code to import a python module in C adapted from a bit of working code</p> <pre><code>PyObject *module = 0; PyObject *result = 0; PyObject *module_dict = 0; PyObject *func = 0; module = PyImport_ImportModule((char *)"pygame"); /* new ref */ if (module == 0) { PyErr_Print(); log("Couldn't find python module pygame"); goto out; } module_dict = PyModule_GetDict(module); /* borrowed */ if (module_dict == 0) { PyErr_Print(); log("Couldn't find read python module pygame"); goto out; } func = PyDict_GetItemString(module_dict, "pygame_function"); /* borrowed */ if (func == 0) { PyErr_Print(); log("Couldn't find pygame.pygame_function"); goto out; } result = PyEval_CallObject(func, NULL); /* new ref */ if (result == 0) { PyErr_Print(); log("Couldn't run pygame.pygame_function"); goto out; } /* do stuff with result */ out:; Py_XDECREF(result); Py_XDECREF(module); </code></pre>
3
2009-10-17T20:59:41Z
[ "python", "c", "pygame" ]
Making a C extension to Python that requires another extension
1,583,077
<p>I have a couple of Python functions that I use to make game development with Pygame easier. I have them in a file called helper.py in my Python-path, so I can import them from any game I make. I thought, as an exercise to learn about Python extensions, to convert this module to C. My first problem is that I need to use functions from Pygame, and I'm not sure if this is possible. Pygame installs some header files, but they don't seem to have C versions of the Python functions. Maybe I'm missing something.</p> <p>How can I solve this? As a workaround, the function currently accepts a function parameter and calls that, but it's not the ideal solution.</p> <p>Using Windows XP, Python 2.6 and Pygame 1.9.1, by the way.</p>
4
2009-10-17T20:01:35Z
1,583,235
<pre><code>/* get the sys.modules dictionary */ PyObject* sysmodules PyImport_GetModuleDict(); PyObject* pygame_module; if(PyMapping_HasKeyString(sysmodules, "pygame")) { pygame_module = PyMapping_GetItemString(sysmodules, "pygame"); } else { PyObject* initresult; pygame_module = PyImport_ImportModule("pygame"); if(!pygame_module) { /* insert error handling here! and exit this function */ } initresult = PyObject_CallMethod(pygame_module, "init", NULL); if(!initresult) { /* more error handling &amp;c */ } Py_DECREF(initresult); } /* use PyObject_CallMethod(pygame_module, ...) to your heart's contents */ /* and lastly, when done, don't forget, before you exit, to: */ Py_DECREF(pygame_module); </code></pre>
5
2009-10-17T21:15:23Z
[ "python", "c", "pygame" ]
Making a C extension to Python that requires another extension
1,583,077
<p>I have a couple of Python functions that I use to make game development with Pygame easier. I have them in a file called helper.py in my Python-path, so I can import them from any game I make. I thought, as an exercise to learn about Python extensions, to convert this module to C. My first problem is that I need to use functions from Pygame, and I'm not sure if this is possible. Pygame installs some header files, but they don't seem to have C versions of the Python functions. Maybe I'm missing something.</p> <p>How can I solve this? As a workaround, the function currently accepts a function parameter and calls that, but it's not the ideal solution.</p> <p>Using Windows XP, Python 2.6 and Pygame 1.9.1, by the way.</p>
4
2009-10-17T20:01:35Z
1,584,257
<p>Most functions in <code>pygame</code> module are just wrappers around SDL functions, that is where you have to look for C version of its functions. <code>pygame.h</code> defines a series of <code>import_pygame_*()</code> functions. Call <code>import_pygame_base()</code> and others once at initialization of extension module to get access to needed part of C API of pygame modules (it's defined in header file for each). Google code search will bring you <a href="http://www.google.com/codesearch?q=import%5Fpygame%5Fbase" rel="nofollow">some examples</a>.</p>
0
2009-10-18T07:31:08Z
[ "python", "c", "pygame" ]
Python: Int not iterable errror
1,583,148
<p>I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Any help would be appreciated. </p> <pre><code>n = 100 p = 0 while p&lt;n: p = p + 1 x = range(0, p) # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: sum(numbers) numcheck(x) </code></pre>
5
2009-10-17T20:42:08Z
1,583,167
<p>The <code>sum</code> function expects a list, not a single number.</p> <p>When you do <code>for numbers in</code>, then the variable <code>numbers</code> has a single integer object. Add a <code>print</code> statement, you'll see that <code>numbers</code> is a single number.</p> <p>You might want to accumulate all the multiples of 3 and 5 in a list. Once you have the list, you can then use the <code>sum</code> function on that list.</p>
1
2009-10-17T20:47:01Z
[ "python" ]
Python: Int not iterable errror
1,583,148
<p>I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Any help would be appreciated. </p> <pre><code>n = 100 p = 0 while p&lt;n: p = p + 1 x = range(0, p) # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: sum(numbers) numcheck(x) </code></pre>
5
2009-10-17T20:42:08Z
1,583,168
<p>numbers needs to be a list or similar when it is passed to sum(). In the code example above, it is an integer - one of the integers from x.</p> <p>Try something like:</p> <pre><code>numbers = [num for num in x if num%3==0 and num%5 ==0] print sum(numbers) </code></pre>
5
2009-10-17T20:47:15Z
[ "python" ]
Python: Int not iterable errror
1,583,148
<p>I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Any help would be appreciated. </p> <pre><code>n = 100 p = 0 while p&lt;n: p = p + 1 x = range(0, p) # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: sum(numbers) numcheck(x) </code></pre>
5
2009-10-17T20:42:08Z
1,583,171
<p>I think you want something like what follows.</p> <pre><code>def numcheck(x): total = 0 for number in x: if number % 3 == 0 or and number % 5 == 0: total += number print total </code></pre> <p>Alternatively, you could append each of the divisible numbers to a list, and then call sum() on that list.</p>
1
2009-10-17T20:48:45Z
[ "python" ]
Python: Int not iterable errror
1,583,148
<p>I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Any help would be appreciated. </p> <pre><code>n = 100 p = 0 while p&lt;n: p = p + 1 x = range(0, p) # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: sum(numbers) numcheck(x) </code></pre>
5
2009-10-17T20:42:08Z
1,583,183
<p>help(sum) Help on built-in function sum in module <strong>builtin</strong>:</p> <p>sum(...) sum(sequence[, start]) -> value</p> <pre><code>Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, returns start. </code></pre> <p>(END) </p> <p>You are passing numbers which is of type int to sum(), but sum takes a sequence.</p>
1
2009-10-17T20:54:47Z
[ "python" ]
Python: Int not iterable errror
1,583,148
<p>I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Any help would be appreciated. </p> <pre><code>n = 100 p = 0 while p&lt;n: p = p + 1 x = range(0, p) # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: sum(numbers) numcheck(x) </code></pre>
5
2009-10-17T20:42:08Z
1,583,189
<p>In the for-loop </p> <pre><code>for numbers in x: </code></pre> <p>"numbers" steps through the elements in x one at a time, for each pass through the loop. It would be perhaps better to name the variable "number" because you are only getting one number at a time. "numbers" equals an integer each time through the loop.</p> <pre><code>sum(numbers) </code></pre> <p>throws a TypeError because the function sum() expects an iterable object (like a list of numbers), not just one integer.</p> <p>So perhaps try:</p> <pre><code>def numcheck(x): s=0 for number in x: if number%3==0 and number%5==0: s+=number print(s) numcheck(range(1000)) </code></pre>
7
2009-10-17T20:56:49Z
[ "python" ]
Python: Int not iterable errror
1,583,148
<p>I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>Any help would be appreciated. </p> <pre><code>n = 100 p = 0 while p&lt;n: p = p + 1 x = range(0, p) # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: sum(numbers) numcheck(x) </code></pre>
5
2009-10-17T20:42:08Z
1,583,213
<p>Here is how I would do this:</p> <pre><code>n = 100 # the next 4 lines are just to confirm that xrange is n numbers starting at 0 junk = xrange(n) print junk[0] # print first number in sequence print junk[-1] # print last number in sequence print "================" # check to see if numbers are divisable by 3 or 5 def numcheck(x): for numbers in x: if numbers%3==0 and numbers%5==0: print numbers numcheck(xrange(n)) </code></pre> <p>You may find it strange that I pass xrange(n) as a parameter. This is an iterator that will eventually produce the list of n numbers as you go through the loop in numcheck. It's a bit like passing a pointer to a function in C. The key thing is that by using xrange, you do not need to allocate any memory for the list of numbers, so you can more easily run a check on the first billion integers, for instance.</p>
1
2009-10-17T21:08:29Z
[ "python" ]
positioning sound with pygame?
1,583,284
<p>Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels.</p>
2
2009-10-17T21:32:35Z
1,583,292
<p><a href="http://pysonic.sourceforge.net/" rel="nofollow">http://pysonic.sourceforge.net/</a></p> <p>Try this out, it's a wrapper over the FMOD sound library, it won't disappoint :)</p>
0
2009-10-17T21:36:22Z
[ "python", "audio", "pygame" ]
positioning sound with pygame?
1,583,284
<p>Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels.</p>
2
2009-10-17T21:32:35Z
1,583,298
<p>I think setting the separate channel volume is the only way. Pygame doesn't seem to have any notion of world space or positioning for sounds.</p>
0
2009-10-17T21:38:15Z
[ "python", "audio", "pygame" ]
positioning sound with pygame?
1,583,284
<p>Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels.</p>
2
2009-10-17T21:32:35Z
2,359,462
<p>You are correct - Pygame itself doesn't have any high-level way to position sound other than manually adjusting channel volumes (and it looks like it only supports stereo).</p> <p>The best way, to do 3D-audio, especially for games, is to use <a href="http://connect.creativelabs.com/openal/default.aspx" rel="nofollow">OpenAL</a>. Unfortunately, there's no way to this in Pygame (note that there is an OpenAL library in "<a href="http://www.mail-archive.com/pygame-users@seul.org/msg13620.html" rel="nofollow">pgreloaded</a>," the next version of Pygame). <a href="http://www.pyglet.org/" rel="nofollow">Pyglet</a>, however, <a href="http://www.pyglet.org/doc/programming_guide/positional_audio.html" rel="nofollow">does use OpenAL</a>. I've never tried mixing Pygame and pyglet, though - I wonder if it would work?</p>
1
2010-03-01T22:11:24Z
[ "python", "audio", "pygame" ]
Using SWIG with pointer to function in C struct
1,583,293
<p>I'm trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs. I can't figure out how to handle structs that contain function pointers. A simplified example follows.</p> <p>test.i:</p> <pre><code>/* test.i */ %module test %{ typedef struct { int (*my_func)(int); } test_struct; int add1(int n) { return n+1; } test_struct *init_test() { test_struct *t = (test_struct*) malloc(sizeof(test_struct)); t-&gt;my_func = add1; } %} typedef struct { int (*my_func)(int); } test_struct; extern test_struct *init_test(); </code></pre> <p>sample session:</p> <pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import test &gt;&gt;&gt; t = test.init_test() &gt;&gt;&gt; t &lt;test.test_struct; proxy of &lt;Swig Object of type 'test_struct *' at 0xa1cafd0&gt; &gt; &gt;&gt;&gt; t.my_func &lt;Swig Object of type 'int (*)(int)' at 0xb8009810&gt; &gt;&gt;&gt; t.my_func(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'PySwigObject' object is not callable </code></pre> <p>Anyone know if it's possible to get <strong>t.my_func(1)</strong> to return 2?</p> <p>Thanks!</p>
3
2009-10-17T21:36:33Z
1,583,346
<p>You forget to "return t;" in init_test():</p> <pre><code>#include &lt;stdlib.h> #include &lt;stdio.h> typedef struct { int (*my_func)(int); } test_struct; int add1(int n) { return n+1; } test_struct *init_test(){ test_struct *t = (test_struct*) malloc(sizeof(test_struct)); t->my_func = add1; return t; } int main(){ test_struct *s=init_test(); printf( "%i\n", s->my_func(1) ); } </code></pre>
0
2009-10-17T22:05:01Z
[ "python", "c", "function", "pointers", "swig" ]
Using SWIG with pointer to function in C struct
1,583,293
<p>I'm trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs. I can't figure out how to handle structs that contain function pointers. A simplified example follows.</p> <p>test.i:</p> <pre><code>/* test.i */ %module test %{ typedef struct { int (*my_func)(int); } test_struct; int add1(int n) { return n+1; } test_struct *init_test() { test_struct *t = (test_struct*) malloc(sizeof(test_struct)); t-&gt;my_func = add1; } %} typedef struct { int (*my_func)(int); } test_struct; extern test_struct *init_test(); </code></pre> <p>sample session:</p> <pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import test &gt;&gt;&gt; t = test.init_test() &gt;&gt;&gt; t &lt;test.test_struct; proxy of &lt;Swig Object of type 'test_struct *' at 0xa1cafd0&gt; &gt; &gt;&gt;&gt; t.my_func &lt;Swig Object of type 'int (*)(int)' at 0xb8009810&gt; &gt;&gt;&gt; t.my_func(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'PySwigObject' object is not callable </code></pre> <p>Anyone know if it's possible to get <strong>t.my_func(1)</strong> to return 2?</p> <p>Thanks!</p>
3
2009-10-17T21:36:33Z
1,586,452
<p>I found an answer. If I declare the function pointer as a SWIG "member function", it seems to work as expected:</p> <pre><code>%module test %{ typedef struct { int (*my_func)(int); } test_struct; int add1(int n) { return n+1; } test_struct *init_test() { test_struct *t = (test_struct*) malloc(sizeof(test_struct)); t-&gt;my_func = add1; return t; } %} typedef struct { int my_func(int); } test_struct; extern test_struct *init_test(); </code></pre> <p>Session:</p> <pre><code>$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import test &gt;&gt;&gt; t = test.init_test() &gt;&gt;&gt; t.my_func(1) 2 </code></pre> <p>I was hoping for something that wouldn't require writing any custom SWIG-specific code (I'd prefer to just "%include" my headers without modification), but this will do I guess.</p>
1
2009-10-19T00:31:42Z
[ "python", "c", "function", "pointers", "swig" ]
sqlite3 and cursor.description
1,583,350
<p>When using the sqlite3 module in python, all elements of cursor.description except the column names are set to None, so this tuple cannot be used to find the column types for a query result (unlike other DB-API compliant modules). Is the only way to get the types of the columns to use <code>pragma table_info(table_name).fetchall()</code> to get a description of the table, store it in memory, and then match the column names from cursor.description to that overall table description?</p>
4
2009-10-17T22:11:14Z
1,583,379
<p>No, it's not the only way. Alternatively, you can also fetch one row, iterate over it, and inspect the individual column Python objects and types. Unless the value is None (in which case the SQL field is NULL), this should give you a fairly precise indication what the database column type was.</p> <p>sqlite3 only uses <code>sqlite3_column_decltype</code> and <code>sqlite3_column_type</code> in one place, each, and neither are accessible to the Python application - so their is no "direct" way that you may have been looking for.</p>
4
2009-10-17T22:29:59Z
[ "python", "sqlite", "python-db-api" ]
sqlite3 and cursor.description
1,583,350
<p>When using the sqlite3 module in python, all elements of cursor.description except the column names are set to None, so this tuple cannot be used to find the column types for a query result (unlike other DB-API compliant modules). Is the only way to get the types of the columns to use <code>pragma table_info(table_name).fetchall()</code> to get a description of the table, store it in memory, and then match the column names from cursor.description to that overall table description?</p>
4
2009-10-17T22:11:14Z
1,586,168
<p>I haven't tried this in Python, but you could try something like</p> <pre><code>SELECT * FROM sqlite_master WHERE type = 'table'; </code></pre> <p>which contains the DDL CREATE statement used to create the table. By parsing the DDL you can get the column type info, such as it is. Remember that SQLITE is rather vague and unrestrictive when it comes to column data types.</p>
1
2009-10-18T22:12:46Z
[ "python", "sqlite", "python-db-api" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,583,445
<p>Not sure whether it is any better than the versions you proposed, however...</p> <p>If predicate is guaranteed to return True/False only, then</p> <pre><code>sum(map(predicate, seq)) == 1 </code></pre> <p>will do (although it won't stop at the second element)</p>
2
2009-10-17T22:59:08Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,583,450
<p>Perhaps something like this is more to your taste?</p> <pre><code>def has_one(seq,predicate=bool): nwanted=1 n=0 for item in seq: if predicate(item): n+=1 if n&gt;nwanted: return False return n==nwanted </code></pre> <p>This is rather like the list comprehension example, but requires only one pass over one sequence. Compared to the second <code>has_one</code> function, and like the list comprehension code, it generalizes more easily to other counts. I've demonstrated this (hopefully without error...) by adding in a variable for the number of items wanted.</p>
3
2009-10-17T23:01:04Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,583,465
<p>How about calling <a href="http://docs.python.org/3.1/library/functions.html#any" rel="nofollow"><code>any</code></a> twice, on an iterator (Python 2.x and 3.x compatible)?</p> <pre><code>&gt;&gt;&gt; def has_one(seq, predicate=bool): ... seq = (predicate(e) for e in seq) ... return any(seq) and not any(seq) ... &gt;&gt;&gt; has_one([]) False &gt;&gt;&gt; has_one([1]) True &gt;&gt;&gt; has_one([0]) False &gt;&gt;&gt; has_one([1, 2]) False </code></pre> <p><code>any</code> will take at most <em>one</em> element which evaluates to <code>True</code> from the iterator. If it succeeds the first time and fails the second time, then only one element matches the predicate.</p> <p><strong>Edit:</strong> I see <a href="http://stackoverflow.com/users/19403/robert-rossney">Robert Rossney</a> suggests a generalized version, which checks whether exactly <em>n</em> elements match the predicate. Let me join in on the fun, using <a href="http://docs.python.org/3.1/library/functions.html#all" rel="nofollow"><code>all</code></a>:</p> <pre><code>&gt;&gt;&gt; def has_n(seq, n, predicate=bool): ... seq = (predicate(e) for e in seq) ... return all(any(seq) for _ in range(n)) and not any(seq) ... &gt;&gt;&gt; has_n(range(0), 3) False &gt;&gt;&gt; has_n(range(3), 3) False &gt;&gt;&gt; has_n(range(4), 3) True &gt;&gt;&gt; has_n(range(5), 3) False </code></pre>
10
2009-10-17T23:09:55Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,583,512
<p>I liked Stephan202's answer, but I like this one a little more, even though it's two lines instead of one. I like it because it's just as crazy but a tiny bit more explicit about how its craziness works:</p> <pre><code>def has_one(seq): g = (x for x in seq) return any(g) and not any(g) </code></pre> <p><strong>Edit:</strong></p> <p>Here's a more generalized version that supports a predicate:</p> <pre><code>def has_exactly(seq, count, predicate = bool): g = (predicate(x) for x in seq) while(count &gt; 0): if not any(g): return False count -= 1 if count == 0: return not any(g) </code></pre>
3
2009-10-17T23:37:36Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,609,321
<p>How about ...</p> <pre><code>import functools import operator def exactly_one(seq): """ Handy for ensuring that exactly one of a bunch of options has been set. &gt;&gt;&gt; exactly_one((3, None, 'frotz', None)) False &gt;&gt;&gt; exactly_one((None, None, 'frotz', None)) True """ return 1 == functools.reduce(operator.__add__, [1 for x in seq if x]) </code></pre>
1
2009-10-22T19:02:25Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,792,927
<p>Here's modified <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202's answer</a>:</p> <pre><code>from itertools import imap, repeat def exactly_n_is_true(iterable, n, predicate=None): it = iter(iterable) if predicate is None else imap(predicate, iterable) return all(any(it) for _ in repeat(None, n)) and not any(it) </code></pre> <p>Differences:</p> <ol> <li><p><code>predicate()</code> is None by default. The meaning is the same as for built-in <code>filter()</code> and stdlib's <code>itertools.ifilter()</code> functions.</p></li> <li><p>More explicit function and parameters names (this is subjective).</p></li> <li><p><code>repeat()</code> allows large <code>n</code> to be used.</p></li> </ol> <p>Example:</p> <pre><code>if exactly_n_is_true(seq, 1, predicate): # predicate() is true for exactly one item from the seq </code></pre>
0
2009-11-24T21:08:06Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
1,793,199
<p>Look, Ma! No rtfm("itertools"), no dependency on predicate() returning a boolean, minimum evaluation, just works!</p> <pre><code>Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam &gt;&gt;&gt; def count_in_bounds(seq, predicate=lambda x: x, low=1, high=1): ... count = 0 ... for item in seq: ... if predicate(item): ... count = count + 1 ... if count &gt; high: ... return 0 ... return count &gt;= low ... &gt;&gt;&gt; seq1 = [0, 0, 1, 0, 1, 0, 1, 0, 0, 0] &gt;&gt;&gt; count_in_bounds(seq1) 0 &gt;&gt;&gt; count_in_bounds(seq1, low=3, high=3) 1 &gt;&gt;&gt; count_in_bounds(seq1, low=3, high=4) 1 &gt;&gt;&gt; count_in_bounds(seq1, low=4, high=4) 0 &gt;&gt;&gt; count_in_bounds(seq1, low=0, high=3) 1 &gt;&gt;&gt; count_in_bounds(seq1, low=3, high=3) 1 &gt;&gt;&gt; </code></pre>
1
2009-11-24T21:56:20Z
[ "python", "idioms" ]
Idiomatic Python has_one
1,583,364
<p>I just invented a stupid little helper function:</p> <pre><code>def has_one(seq, predicate=bool): """Return whether there is exactly one item in `seq` that matches `predicate`, with a minimum of evaluation (short-circuit). """ iterator = (item for item in seq if predicate(item)) try: iterator.next() except StopIteration: # No items match predicate. return False try: iterator.next() except StopIteration: # Exactly one item matches predicate. return True return False # More than one item matches the predicate. </code></pre> <p>Because the most readable/idiomatic inline thing I could come up with was:</p> <pre><code>[predicate(item) for item in seq].count(True) == 1 </code></pre> <p>... which is fine in my case because I know seq is small, but it just feels weird. <strong>Is there an idiom I’m forgetting here that prevents me from having to break out this helper?</strong></p> <h2>Clarification</h2> <p>Looking back on it, this was kind of a crappily posed question, though we got some excellent answers! I was looking for either:</p> <ul> <li>An obvious and readable inline idiom or stdlib function, eager evaluation being acceptable in this case.</li> <li>A more obvious and readable helper function -- since it's breaking out a whole other function, only the minimum amount of evaluation seems acceptable.</li> </ul> <p><a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583465#1583465">@Stephan202</a> came up with a really cool idiom for the helper function and <a href="http://stackoverflow.com/questions/1583364/idiomatic-python-hasone/1583445#1583445">@Martin v. Löwis</a> came up with a more simple inline idiom under the assumption that the predicate returns a bool. Thanks @ everybody for your help!</p>
3
2009-10-17T22:23:15Z
14,392,813
<p><a href="http://stackoverflow.com/a/1583450/239657">This</a> and <a href="http://stackoverflow.com/a/1793199/239657">this</a> straightforward counting-loop solutions are definitely clearest.</p> <p>For the sport of it, here is a variation on the <code>any(g) and not any(g)</code> theme that looks less magic on the surface - but it's actually similarly fragile when one comes to debug/modify it (you can't exchange the order, you have to understand how the short-circuiting <code>and</code> hands off a single iterator between two short-circuiting consumers...).</p> <pre><code>def cumulative_sums(values): s = 0 for v in values: s += v yield s def count_in_bounds(iterable, start=1, stop=2): counter = cumulative_sums(bool(x) for x in iterable) return (start in counter) and (stop not in counter) </code></pre> <p>It's trivial to also take a predicate instead of <code>bool</code> but I think it's better to follow <code>any()</code> and <code>all()</code> in leaving that to the caller - it's easy to pass a generator expression if needed.</p> <p>Taking arbitrary [start, stop) is a nice bonus, but it's not as generic as I'd like. It's tempting to pass <code>stop=None</code> to emulate e.g. <code>any()</code>, which works, but always consumes all input; the proper emulation is kinda awkward:</p> <pre><code>def any(iterable): return not count_in_bounds(iterable, 0, 1) def all(iterable): return count_in_bounds((not x for x in iterable), 0, 1) </code></pre> <p>Taking a variable number of bounds and specifying which should return True/False would get out of hand.<br> Perhaps a simple saturating counter is the best primitive:</p> <pre><code>def count_true(iterable, stop_at=float('inf')): c = 0 for x in iterable: c += bool(x) if c &gt;= stop_at: break return c def any(iterable): return count_true(iterable, 1) &gt;= 1 def exactly_one(iterable): return count_true(iterable, 2) == 1 def weird(iterable): return count_true(iterable, 10) in {2, 3, 5, 7} </code></pre> <p><code>all()</code> still requires negating the inputs, or a matching <code>count_false()</code> helper. </p>
0
2013-01-18T05:17:22Z
[ "python", "idioms" ]
Apparently my app. runs but I don't see anything
1,583,437
<p>I'm learning python and Qt to create graphical desktop apps. I designed the UI with Qt Designer and converted the .ui to .py using pyuic, according to the tutorial I'm following, I should be able to run my app. but when I do it, a terminal window opens and it says:</p> <pre><code>cd '/Users/andresacevedo/' &amp;&amp; '/opt/local/bin/python2.6' '/Users/andresacevedo/aj.pyw' &amp;&amp; echo Exit status: $? &amp;&amp; exit 1 Exit status: 0 logout [Process completed] </code></pre> <p>Does it means that the app. exited without errors? then why I don't see the UI that I designed?</p> <p>P.S. I'm using OS X Snow leopard</p> <p>Thanks,</p> <p><hr /></p> <p>Edit (This is the source code of my app.)</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'principal.ui' # # Created: Sat Oct 17 15:07:17 2009 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(379, 330) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 379, 22)) self.menubar.setObjectName("menubar") self.menuMenu_1 = QtGui.QMenu(self.menubar) self.menuMenu_1.setObjectName("menuMenu_1") MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionOpcion_1 = QtGui.QAction(MainWindow) self.actionOpcion_1.setObjectName("actionOpcion_1") self.menuMenu_1.addAction(self.actionOpcion_1) self.menubar.addAction(self.menuMenu_1.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.menuMenu_1.setTitle(QtGui.QApplication.translate("MainWindow", "Menu 1", None, QtGui.QApplication.UnicodeUTF8)) self.actionOpcion_1.setText(QtGui.QApplication.translate("MainWindow", "Opcion 1", None, QtGui.QApplication.UnicodeUTF8)) </code></pre>
0
2009-10-17T22:54:49Z
1,583,612
<p>The problem is that your python code is merely defining a class, but has no main program which invokes the class or causes QT to pop up a window. </p> <p>It seems a little unusual that your Ui_MainWindow class isn't actually a subclass of QMainWindow; it isn't a widget itself, but it merely configures the MainWindow which gets passed to it. But I think that can still work, with something like the (untested) code below.</p> <pre><code>import sys from PyQt4 import Qt # (define class Ui_MainWindow here...) if __name__=="__main__": app=Qt.QApplication(sys.argv) mywin = Qt.QMainWindow() myui = Ui_MainWindow(mywin) myui.setupUI(mywin) app.connect(app, Qt.SIGNAL("lastWindowClosed()"), app, Qt.SLOT("quit()")) mywin.show() app.exec_() </code></pre>
1
2009-10-18T00:41:15Z
[ "python", "osx", "pyqt" ]
Apparently my app. runs but I don't see anything
1,583,437
<p>I'm learning python and Qt to create graphical desktop apps. I designed the UI with Qt Designer and converted the .ui to .py using pyuic, according to the tutorial I'm following, I should be able to run my app. but when I do it, a terminal window opens and it says:</p> <pre><code>cd '/Users/andresacevedo/' &amp;&amp; '/opt/local/bin/python2.6' '/Users/andresacevedo/aj.pyw' &amp;&amp; echo Exit status: $? &amp;&amp; exit 1 Exit status: 0 logout [Process completed] </code></pre> <p>Does it means that the app. exited without errors? then why I don't see the UI that I designed?</p> <p>P.S. I'm using OS X Snow leopard</p> <p>Thanks,</p> <p><hr /></p> <p>Edit (This is the source code of my app.)</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'principal.ui' # # Created: Sat Oct 17 15:07:17 2009 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(379, 330) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 379, 22)) self.menubar.setObjectName("menubar") self.menuMenu_1 = QtGui.QMenu(self.menubar) self.menuMenu_1.setObjectName("menuMenu_1") MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionOpcion_1 = QtGui.QAction(MainWindow) self.actionOpcion_1.setObjectName("actionOpcion_1") self.menuMenu_1.addAction(self.actionOpcion_1) self.menubar.addAction(self.menuMenu_1.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.menuMenu_1.setTitle(QtGui.QApplication.translate("MainWindow", "Menu 1", None, QtGui.QApplication.UnicodeUTF8)) self.actionOpcion_1.setText(QtGui.QApplication.translate("MainWindow", "Opcion 1", None, QtGui.QApplication.UnicodeUTF8)) </code></pre>
0
2009-10-17T22:54:49Z
1,584,143
<p>I'm doing very newbie questions, well because I'm a pyqt newbie... what was happening was that I called pyuic without the -x attribute, so the code just creates the UI but not the code for running it, anyway your help was very valuable.</p>
1
2009-10-18T06:02:17Z
[ "python", "osx", "pyqt" ]
Apparently my app. runs but I don't see anything
1,583,437
<p>I'm learning python and Qt to create graphical desktop apps. I designed the UI with Qt Designer and converted the .ui to .py using pyuic, according to the tutorial I'm following, I should be able to run my app. but when I do it, a terminal window opens and it says:</p> <pre><code>cd '/Users/andresacevedo/' &amp;&amp; '/opt/local/bin/python2.6' '/Users/andresacevedo/aj.pyw' &amp;&amp; echo Exit status: $? &amp;&amp; exit 1 Exit status: 0 logout [Process completed] </code></pre> <p>Does it means that the app. exited without errors? then why I don't see the UI that I designed?</p> <p>P.S. I'm using OS X Snow leopard</p> <p>Thanks,</p> <p><hr /></p> <p>Edit (This is the source code of my app.)</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'principal.ui' # # Created: Sat Oct 17 15:07:17 2009 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(379, 330) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 379, 22)) self.menubar.setObjectName("menubar") self.menuMenu_1 = QtGui.QMenu(self.menubar) self.menuMenu_1.setObjectName("menuMenu_1") MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionOpcion_1 = QtGui.QAction(MainWindow) self.actionOpcion_1.setObjectName("actionOpcion_1") self.menuMenu_1.addAction(self.actionOpcion_1) self.menubar.addAction(self.menuMenu_1.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.menuMenu_1.setTitle(QtGui.QApplication.translate("MainWindow", "Menu 1", None, QtGui.QApplication.UnicodeUTF8)) self.actionOpcion_1.setText(QtGui.QApplication.translate("MainWindow", "Opcion 1", None, QtGui.QApplication.UnicodeUTF8)) </code></pre>
0
2009-10-17T22:54:49Z
1,584,433
<p>The code you get from Qt Designer is only a class with set of widgets. It is not an application. See the <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#using-qt-designer" rel="nofollow">PyQt manual</a> for info how to use the Designer code in your applications. I'd suggest to read some Qt tutorial first, write some "hello world" application first, and only then write applications that use Designer forms.</p>
0
2009-10-18T09:08:14Z
[ "python", "osx", "pyqt" ]
Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code
1,583,595
<p>In the past, I created a Django wiki, and it was fairly straightforward to make a Page table for the current wiki entries, and then to store old revisions into a Revision table.</p> <p>More recently, I decided to set up a website on Google App Engine, and I used some wiki code that another programmer wrote. Because he created his Page model in sort of a complicated way (complicated to me at least) using Entities, I am unsure about how to create the Revision table and integrate it with his Page model.</p> <p>Here is the relevant code. Could someone help me write the Revision model, and integrate saving the revisions with the Save method of the Page model?</p> <pre><code>class Page(object): def __init__(self, name, entity=None): self.name = name self.entity = entity if entity: self.content = entity['content'] if entity.has_key('user'): self.user = entity['user'] else: self.user = None self.created = entity['created'] self.modified = entity['modified'] else: # New pages should start out with a simple title to get the user going now = datetime.datetime.now() self.content = '&lt;h1&gt;' + cgi.escape(name) + '&lt;/h1&gt;' self.user = None self.created = now self.modified = now def save(self): """Creates or edits this page in the datastore.""" now = datetime.datetime.now() if self.entity: entity = self.entity else: entity = datastore.Entity('Page') entity['name'] = self.name entity['created'] = now entity['content'] = datastore_types.Text(self.content) entity['modified'] = now if users.GetCurrentUser(): entity['user'] = users.GetCurrentUser() elif entity.has_key('user'): del entity['user'] datastore.Put(entity) </code></pre> <p>By the way, this code comes from: <a href="http://code.google.com/p/google-app-engine-samples/downloads/list" rel="nofollow">http://code.google.com/p/google-app-engine-samples/downloads/list</a></p> <p>I'm pretty inexperienced with GAE Django models, and mine tend to be very simple. For example, here's my model for a blog Article:</p> <pre><code>class Article(db.Model): author = db.UserProperty() title = db.StringProperty(required=True) text = db.TextProperty(required=True) tags = db.StringProperty(required=True) date_created = db.DateProperty(auto_now_add=True) </code></pre>
0
2009-10-18T00:29:40Z
1,585,411
<p>The code in your first snippet is not a model - it's a custom class that uses the low-level datastore module. If you want to extend it, I would recommend throwing it out and replacing it with actual models, along similar lines to the Article model you demonstrated in your second snippet.</p> <p>Also, they're App Engine models, not Django models - Django models don't work on App Engine.</p>
1
2009-10-18T16:51:43Z
[ "python", "django", "google-app-engine", "django-models" ]
Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code
1,583,595
<p>In the past, I created a Django wiki, and it was fairly straightforward to make a Page table for the current wiki entries, and then to store old revisions into a Revision table.</p> <p>More recently, I decided to set up a website on Google App Engine, and I used some wiki code that another programmer wrote. Because he created his Page model in sort of a complicated way (complicated to me at least) using Entities, I am unsure about how to create the Revision table and integrate it with his Page model.</p> <p>Here is the relevant code. Could someone help me write the Revision model, and integrate saving the revisions with the Save method of the Page model?</p> <pre><code>class Page(object): def __init__(self, name, entity=None): self.name = name self.entity = entity if entity: self.content = entity['content'] if entity.has_key('user'): self.user = entity['user'] else: self.user = None self.created = entity['created'] self.modified = entity['modified'] else: # New pages should start out with a simple title to get the user going now = datetime.datetime.now() self.content = '&lt;h1&gt;' + cgi.escape(name) + '&lt;/h1&gt;' self.user = None self.created = now self.modified = now def save(self): """Creates or edits this page in the datastore.""" now = datetime.datetime.now() if self.entity: entity = self.entity else: entity = datastore.Entity('Page') entity['name'] = self.name entity['created'] = now entity['content'] = datastore_types.Text(self.content) entity['modified'] = now if users.GetCurrentUser(): entity['user'] = users.GetCurrentUser() elif entity.has_key('user'): del entity['user'] datastore.Put(entity) </code></pre> <p>By the way, this code comes from: <a href="http://code.google.com/p/google-app-engine-samples/downloads/list" rel="nofollow">http://code.google.com/p/google-app-engine-samples/downloads/list</a></p> <p>I'm pretty inexperienced with GAE Django models, and mine tend to be very simple. For example, here's my model for a blog Article:</p> <pre><code>class Article(db.Model): author = db.UserProperty() title = db.StringProperty(required=True) text = db.TextProperty(required=True) tags = db.StringProperty(required=True) date_created = db.DateProperty(auto_now_add=True) </code></pre>
0
2009-10-18T00:29:40Z
1,585,978
<p>I created this model (which mimics the Page class):</p> <pre><code>class Revision (db.Model): name = db.StringProperty(required=True) created = db.DateTimeProperty(required=True) modified = db.DateTimeProperty(auto_now_add=True) content = db.TextProperty(required=True) user = db.UserProperty() </code></pre> <p>In the Save() method of the Page class, I added this code to save a Revision, before I updated the fields with the new data:</p> <pre><code>r = Revision(name = self.name, content = self.content, created = self.created, modified = self.modified, user = self.user) r.put() </code></pre> <p>I have the wiki set up now to accept a GET parameter to specify which revision you want to see or edit. When the user wants a revision, I fetch the Page from the database, and replace the Page's Content with the Revision's Content:</p> <pre><code>page = models.Page.load(title) if request.GET.get('rev'): query = db.Query(models.Revision) query.filter('name =', title).order('created') rev = request.GET.get('rev') rev_page = query.fetch(1, int(rev)) page.content = rev_page.content </code></pre>
0
2009-10-18T20:40:32Z
[ "python", "django", "google-app-engine", "django-models" ]
What does "lambda" mean in Python, and what's the simplest way to use it?
1,583,617
<p>Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.</p>
10
2009-10-18T00:44:25Z
1,583,629
<p>I do not know which book you are using, but <a href="http://www.diveintopython.org/power%5Fof%5Fintrospection/lambda%5Ffunctions.html" rel="nofollow"><em>Dive into Python</em> has a section</a> which I think is informative.</p>
3
2009-10-18T00:50:07Z
[ "python", "lambda" ]
What does "lambda" mean in Python, and what's the simplest way to use it?
1,583,617
<p>Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.</p>
10
2009-10-18T00:44:25Z
1,583,630
<p>Lambda, which originated from <a href="http://en.wikipedia.org/wiki/Lambda%5Fcalculus">Lambda Calculus</a> and (AFAIK) was first implemented in <a href="http://en.wikipedia.org/wiki/Lisp%5F%28programming%5Flanguage%29">Lisp</a>, is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:</p> <pre><code>&gt;&gt;&gt; addTwo = lambda x: x+2 &gt;&gt;&gt; addTwo(2) 4 </code></pre> <p>This assigns <code>addTwo</code> to the anonymous function, which accepts 1 argument x, and in the function body it adds 2 to x, it returns the last value of the last expression in the function body so there's no <code>return</code> keyword.</p> <p>The code above is roughly equivalent to:</p> <pre><code>&gt;&gt;&gt; def addTwo(x): ... return x+2 ... &gt;&gt;&gt; addTwo(2) 4 </code></pre> <p>Except you're not using a function definition, you're assigning an identifier to the lambda.</p> <p>The best place to use them is when you don't really want to define a function with a name, possibly because that function will only be used <em>one</em> time and not numerous times, in which case you would be better off with a function definition.</p> <p>Example of a hash tree using lambdas:</p> <pre><code>&gt;&gt;&gt; mapTree = { ... 'number': lambda x: x**x, ... 'string': lambda x: x[1:] ... } &gt;&gt;&gt; otype = 'number' &gt;&gt;&gt; mapTree[otype](2) 4 &gt;&gt;&gt; otype = 'string' &gt;&gt;&gt; mapTree[otype]('foo') 'oo' </code></pre> <p>In this example I don't really want to define a name to either of those functions because I'll only use them within the hash, therefore I'll use lambdas.</p>
26
2009-10-18T00:50:12Z
[ "python", "lambda" ]
What does "lambda" mean in Python, and what's the simplest way to use it?
1,583,617
<p>Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.</p>
10
2009-10-18T00:44:25Z
1,584,145
<p>Use of lambda is sort of a style thing. When you can get away with a very simple function, and usually where you are just storing it somewhere (in a list of functions perhaps, or in a GUI toolkit data structure, etc.) people feel lambda reduces clutter in their code.</p> <p>In Python it is only possible to make a lambda that returns a single expression, and the lambda cannot span multiple lines (unless you join the multiple lines by using the backslash-at-the-end-of-a-line trick). People have requested that Python add improvements for lambda, but it hasn't happened. As I understand it, the changes to make lambda able to write any function would significantly complicate the parsing code in Python. And, since we already have <code>def</code> to define a function, the gain is not considered worth the complication. So there are some cases where you might wish to use lambda where it is not possible. In that case, you can just use a <code>def</code>:</p> <pre><code>object1.register_callback_function(lambda x: x.foo() &gt; 3) def fn(x): if x.foo() &gt; 3: x.recalibrate() return x.value() &gt; 9 elif x.bar() &gt; 3: x.do_something_else() return x.other_value &lt; 0 else: x.whatever() return True object2.register_callback_function(fn) del(fn) </code></pre> <p>The first callback function was simple and a lambda sufficed. For the second one, it is simply not possible to use a lambda. We achieve the same effect by using <code>def</code> and making a function object that is bound to the name <code>fn</code>, and then passing <code>fn</code> to <code>register_callback_function()</code>. Then, just to show we can, we call <code>del()</code> on the name <code>fn</code> to unbind it. Now the name <code>fn</code> no longer is bound with any object, but <code>register_callback_function()</code> still has a reference to the function object so the function object lives on.</p>
2
2009-10-18T06:03:08Z
[ "python", "lambda" ]
Possible Data Schemes for Achievements on Google App Engine
1,583,808
<p>I'm building a flash game website using Google App Engine. I'm going to put achievements on it, and am scratching my head on how exactly to store this data. I have a (non-google) user model. I need to know how to store each kind of achievement (name, description, picture), as well as link them with users who earn them. Also, I need to keep track of when they earned it, as well as their current progress for those who don't have one yet.</p> <p>If anyone wants to give suggestions about detection or other achievement related task feel free.</p> <p><strong>EDIT:</strong></p> <p>Non-Google User Model:</p> <pre><code>class BeardUser(db.Model): email = db.StringProperty() username = db.StringProperty() password = db.StringProperty() settings = db.ReferenceProperty(UserSettings) is_admin = db.BooleanProperty() user_role = db.StringProperty(default="user") datetime = db.DateTimeProperty(auto_now_add=True) </code></pre>
1
2009-10-18T02:12:09Z
1,583,865
<p>Unless your users will be adding achievements dynamically (as in something like Kongregate where users can upload their own games, etc), your achievement list will be static. That means you can store the (name, description, picture) list in your main python file, or as an achievements module or something. You can reference the achievements in your dynamic data by name or id as specified in this list.</p> <p>To indicate whether a given user has gotten an achievement, a simple way is to add a ListProperty to your player model that will hold the achievements that the player has gotten. By default this will be indexed so you can query for which players have gotten which achievements, etc.</p> <p>If you also want to store what date/time the user has gotten the achievement, we're getting into an area where the built-in properties are less ideal. You could add another ListProperty with datetime properties corresponding to each achievement, but that's awkward: what we'd really like is a tuple or dict so that we can store the achievement id/name together with the time it was achieved, and make it easy to add additional properties related to each achievement in the future.</p> <p>My usual approach for cases like this is to dump my ideal data structure into a BlobProperty, but that has some disadvantages and you may prefer a different approach.</p> <p>Another approach is to have an achievement model separate from your user model, and a ListProperty full of referenceProperties to all the achievements that user has gotten. this has the advantage of letting you index everything very nicely but will be an additional API CPU cost at runtime especially if you have a lot of achievements to look up, and operations like deleting all a user's achievements will be very expensive compared to the above.</p>
2
2009-10-18T02:58:49Z
[ "python", "google-app-engine", "website", "achievements" ]
Possible Data Schemes for Achievements on Google App Engine
1,583,808
<p>I'm building a flash game website using Google App Engine. I'm going to put achievements on it, and am scratching my head on how exactly to store this data. I have a (non-google) user model. I need to know how to store each kind of achievement (name, description, picture), as well as link them with users who earn them. Also, I need to keep track of when they earned it, as well as their current progress for those who don't have one yet.</p> <p>If anyone wants to give suggestions about detection or other achievement related task feel free.</p> <p><strong>EDIT:</strong></p> <p>Non-Google User Model:</p> <pre><code>class BeardUser(db.Model): email = db.StringProperty() username = db.StringProperty() password = db.StringProperty() settings = db.ReferenceProperty(UserSettings) is_admin = db.BooleanProperty() user_role = db.StringProperty(default="user") datetime = db.DateTimeProperty(auto_now_add=True) </code></pre>
1
2009-10-18T02:12:09Z
3,249,319
<p>Building on Brandon's answer here.</p> <p>If you can, it would be MUCH faster to define all the achievements in the Python files, so they are in-memory and require no database fetching. This is also simpler to implement.</p> <pre><code>class StaticAchievement(object): """ An achievement defined in a Python file. """ by_name = {} by_index = [] def __init__(self, name, description="", picture=None): if picture is None: picture = "static/default_achievement.png" StaticAchievement.by_name[name] = self StaticAchievement.by_index.append(self) self.index = len(StaticAchievement.by_index) # This automatically adds an entry to the StaticAchievement.by_name dict. # It also adds an entry to to the StaticAchievement.by_index list. StaticAchievement( name="tied your shoe", description="You successfully tied your shoes!", picture="static/shoes.png" ) </code></pre> <p>Then all you have to do is keep the ids for each player's achievements in a db.StringListProperty. When you have the player's object loaded, rendering the achievements requires no additional db lookups - you already have the ids, now you just have to look them up in StaticAchievement.all. This is simple to implement, and allows you to easily query which users have a given achievement, etc. Nothing else is required.</p> <p>If you want additional data associated with the user's possession of an achievement (e.g. the date at which it was acquired) then you have a choice of approaches:</p> <p><strong>1: Store it in another ListProperty of the same length.</strong> </p> <p>This retains the implementation simplicity and the indexability of the properties. However, this sort of solution is not to everyone's taste. If you need to make the use of this data less messy, just write a method on the player object like this:</p> <pre><code> def achievement_tuples(self): r = [] for i in range(0, len(self.achievements)): r.append( (self.achievements[i], self.achievement_dates[i]) ) return r </code></pre> <p>You could handle progress by maintaining a parallel ListProperty of integers, and incrementing those integers when the user makes progress.</p> <p>As long as you can understand how the data is represented, you can easily hide that representation behind whatever methods you want - allowing you to have both the interface you want and the performance and indexing characteristics you want. But if you don't really need the indexing and don't like the lists, see option #2.</p> <p><strong>2: Store the additional data in a BlobProperty.</strong></p> <p>This requires you to serialize and deserialize the data, and you give up the nice querying of the listproperties, but maybe you will be happier if you hate the concept of the parallel lists. This is what people tend to do when they really want the Python way of doing things, as distinct from the App Engine way.</p> <p><strong>3: Store the additional data in the db</strong> </p> <p>(e.g. a PlayersAchievement object containing both a StringProperty of the Achievement id, and a DateProperty, and a UserProperty; and on the player an achivements listproperty full of references to PlayersAchievement objects)</p> <p>Since we expect players to potentially get a large number of achievements, the overhead for this will get bad fast. Getting around it will get very complex very quickly: memcache, storing intermediate data like blobs of prerendered HTML or serialized lists of tuples, setting up tasks, etc. This is also the kind of stuff you will have to do if you want the achievement definitions themselves to be modifiable/stored in the DB.</p>
3
2010-07-14T18:41:34Z
[ "python", "google-app-engine", "website", "achievements" ]
activestate pythonwin missing import modules?
1,583,947
<p>I'm working my way through DiveIntoPython.com and I'm having trouble getting the import to work. I've installed ActiveState's Pythonwin on a windows xp prof environment. </p> <p>In the website, there is an exercise which involves 'import odbchelper' and odbchelper.<strong>name</strong></p> <p><a href="http://www.diveintopython.org/getting%5Fto%5Fknow%5Fpython/testing%5Fmodules.html" rel="nofollow">http://www.diveintopython.org/getting_to_know_python/testing_modules.html</a></p> <p>When I run it interactive, i get: </p> <pre><code>&gt;&gt;&gt; import odbchelper Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; ImportError: No module named odbchelper &gt;&gt;&gt; odbchelper.__name__ Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; NameError: name 'odbchelper' is not defined </code></pre> <p>I'm guessing either i don't have the pathing set correctly or the module does not exist referenced in one of the folders when I run 'sys.path'. Any ideas? </p> <p>thanks in advance</p>
1
2009-10-18T03:46:13Z
1,583,953
<p>This module doesn't come packaged with Python2.6 for sure (just tried on my machine). Have you tried googling where this module might be?</p> <p>Consider this <a href="http://ubuntuforums.org/showthread.php?t=487584" rel="nofollow">post</a>.</p>
1
2009-10-18T03:50:02Z
[ "python", "import" ]
activestate pythonwin missing import modules?
1,583,947
<p>I'm working my way through DiveIntoPython.com and I'm having trouble getting the import to work. I've installed ActiveState's Pythonwin on a windows xp prof environment. </p> <p>In the website, there is an exercise which involves 'import odbchelper' and odbchelper.<strong>name</strong></p> <p><a href="http://www.diveintopython.org/getting%5Fto%5Fknow%5Fpython/testing%5Fmodules.html" rel="nofollow">http://www.diveintopython.org/getting_to_know_python/testing_modules.html</a></p> <p>When I run it interactive, i get: </p> <pre><code>&gt;&gt;&gt; import odbchelper Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; ImportError: No module named odbchelper &gt;&gt;&gt; odbchelper.__name__ Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; NameError: name 'odbchelper' is not defined </code></pre> <p>I'm guessing either i don't have the pathing set correctly or the module does not exist referenced in one of the folders when I run 'sys.path'. Any ideas? </p> <p>thanks in advance</p>
1
2009-10-18T03:46:13Z
1,583,961
<p>figured it out.. </p> <p>found this: </p> <pre><code>http://www.faqs.org/docs/diveintopython/odbchelper_divein.html </code></pre> <p>downloaded the file and then put it into a folder. c:\temp\python\ in my case with the commands: </p> <pre><code>&gt;&gt; import sys &gt;&gt; sys.path.append('c:\\temp\\python\\') </code></pre>
1
2009-10-18T03:55:25Z
[ "python", "import" ]
Python xpath not working?
1,584,180
<p>Okay, this is starting to drive me a little bit nuts. I've tried several xml/xpath libraries for Python, and can't figure out a simple way to get a stinkin' "title" element.</p> <p>The latest attempt looks like this (using Amara):</p> <pre><code>def view(req, url): req.content_type = 'text/plain' doc = amara.parse(urlopen(url)) for node in doc.xml_xpath('//title'): req.write(str(node)+'\n') </code></pre> <p>But that prints out nothing. My XML looks like this: <a href="http://programanddesign.com/feed/atom/" rel="nofollow">http://programanddesign.com/feed/atom/</a></p> <p>If I try <code>//*</code> instead of <code>//title</code> it returns everything as expected. I know that the XML has <code>title</code>s in there, so what's the problem? Is it the namespace or something? If so, how can I fix it?</p> <p><hr /></p> <p>Can't seem to get it working with no prefix, but this does work: </p> <pre><code>def view(req, url): req.content_type = 'text/plain' doc = amara.parse(url, prefixes={'atom': 'http://www.w3.org/2005/Atom'}) req.write(str(doc.xml_xpath('//atom:title'))) </code></pre>
0
2009-10-18T06:35:28Z
1,584,194
<p>You probably just have to take into account the namespace of the document which you're dealing with.</p> <p>I'd suggest looking up how to deal with namespaces in Amara:</p> <p><a href="http://www.xml3k.org/Amara/Manual#namespaces" rel="nofollow">http://www.xml3k.org/Amara/Manual#namespaces</a></p> <p>Edit: Using your code snippet I made some edits. I don't know what version of Amara you're using but based on the docs I tried to accommodate it as much as possible:</p> <pre><code>def view(req, url): req.content_type = 'text/plain' ns = {u'f' : u'http://www.w3.org/2005/Atom', u't' : u'http://purl.org/syndication/thread/1.0'} doc = amara.parse(urlopen(url), prefixes=ns) req.write(str(doc.xml_xpath(u'f:title'))) </code></pre>
1
2009-10-18T06:46:57Z
[ "python", "xml", "xpath", "xml-namespaces", "amara" ]
Python xpath not working?
1,584,180
<p>Okay, this is starting to drive me a little bit nuts. I've tried several xml/xpath libraries for Python, and can't figure out a simple way to get a stinkin' "title" element.</p> <p>The latest attempt looks like this (using Amara):</p> <pre><code>def view(req, url): req.content_type = 'text/plain' doc = amara.parse(urlopen(url)) for node in doc.xml_xpath('//title'): req.write(str(node)+'\n') </code></pre> <p>But that prints out nothing. My XML looks like this: <a href="http://programanddesign.com/feed/atom/" rel="nofollow">http://programanddesign.com/feed/atom/</a></p> <p>If I try <code>//*</code> instead of <code>//title</code> it returns everything as expected. I know that the XML has <code>title</code>s in there, so what's the problem? Is it the namespace or something? If so, how can I fix it?</p> <p><hr /></p> <p>Can't seem to get it working with no prefix, but this does work: </p> <pre><code>def view(req, url): req.content_type = 'text/plain' doc = amara.parse(url, prefixes={'atom': 'http://www.w3.org/2005/Atom'}) req.write(str(doc.xml_xpath('//atom:title'))) </code></pre>
0
2009-10-18T06:35:28Z
1,584,226
<p>It is indeed the namespaces. It was a bit tricky to find in the lxml docs, but here's how you do it:</p> <pre><code>from lxml import etree doc = etree.parse(open('index.html')) doc.xpath('//default:title', namespaces={'default':'http://www.w3.org/2005/Atom'}) </code></pre> <p>You can also do this:</p> <pre><code>title_finder = etree.ETXPath('//{http://www.w3.org/2005/Atom}title') title_finder(doc) </code></pre> <p>And you'll get the titles back in both cases.</p>
1
2009-10-18T07:08:03Z
[ "python", "xml", "xpath", "xml-namespaces", "amara" ]
Unit testing a method called during initialization?
1,584,220
<p>I have a class like the following:</p> <pre><code>class Positive(object): def __init__(self, item): self._validate_item(item) self.item = item def _validate_item(self, item): if item &lt;= 0: raise ValueError("item should be positive.") </code></pre> <p>I'd like to write a unit test for <code>_validate_item()</code>, like the following:</p> <pre><code>class PositiveTests(unittest.TestCase): def test_validate_item_error(self): self.assertRaises( ValueError, Positive._validate_item, 0 ) </code></pre> <p>Unfortunately, this won't work because the unit test only passes 0 to the method, instead of a class instance (for the <code>self</code> parameter) and the 0. Is there any solution to this other than having to test this validation method indirectly via the <code>__init__()</code> of the class?</p>
1
2009-10-18T07:03:13Z
1,584,244
<p>You're not creating an instance of Positive. How about</p> <pre><code>Positive()._validate_item, 0 </code></pre>
1
2009-10-18T07:21:02Z
[ "python", "unit-testing", "oop", "testing" ]
Unit testing a method called during initialization?
1,584,220
<p>I have a class like the following:</p> <pre><code>class Positive(object): def __init__(self, item): self._validate_item(item) self.item = item def _validate_item(self, item): if item &lt;= 0: raise ValueError("item should be positive.") </code></pre> <p>I'd like to write a unit test for <code>_validate_item()</code>, like the following:</p> <pre><code>class PositiveTests(unittest.TestCase): def test_validate_item_error(self): self.assertRaises( ValueError, Positive._validate_item, 0 ) </code></pre> <p>Unfortunately, this won't work because the unit test only passes 0 to the method, instead of a class instance (for the <code>self</code> parameter) and the 0. Is there any solution to this other than having to test this validation method indirectly via the <code>__init__()</code> of the class?</p>
1
2009-10-18T07:03:13Z
1,584,246
<p>If you're not using self in the method's body, it's a hint that it might not need to be a class member. You can either move the _validate_item function into module scope:</p> <pre><code>def _validate_item(item): if item &lt;= 0: raise ValueError("item should be positive.") </code></pre> <p>Or if it really has to stay in the class, the mark the method static:</p> <pre><code>class Positive(object): def __init__(self, item): self._validate_item(item) self.item = item @staticmethod def _validate_item(item): if item &lt;= 0: raise ValueError("item should be positive.") </code></pre> <p>Your test should then work as written.</p>
7
2009-10-18T07:21:47Z
[ "python", "unit-testing", "oop", "testing" ]
Unit testing a method called during initialization?
1,584,220
<p>I have a class like the following:</p> <pre><code>class Positive(object): def __init__(self, item): self._validate_item(item) self.item = item def _validate_item(self, item): if item &lt;= 0: raise ValueError("item should be positive.") </code></pre> <p>I'd like to write a unit test for <code>_validate_item()</code>, like the following:</p> <pre><code>class PositiveTests(unittest.TestCase): def test_validate_item_error(self): self.assertRaises( ValueError, Positive._validate_item, 0 ) </code></pre> <p>Unfortunately, this won't work because the unit test only passes 0 to the method, instead of a class instance (for the <code>self</code> parameter) and the 0. Is there any solution to this other than having to test this validation method indirectly via the <code>__init__()</code> of the class?</p>
1
2009-10-18T07:03:13Z
1,584,352
<p>Well, _validate_item() is tested through the constructor. Invoking it with a null or negative value will raise the ValueError exception.</p> <p>Taking a step back, that's the goal no ? The "requirement" is that object shall not be created with a zero or negative value. </p> <p>Now this is a contrived example, so the above could not be applicable to the real class ; another possibility, to really have a test dedicated to the _validate_item() method, could be to create an object with a positive value, and then to invoke the validate_item() on it. </p>
1
2009-10-18T08:21:06Z
[ "python", "unit-testing", "oop", "testing" ]
google wave OnBlipSubmitted
1,584,406
<p>I'm trying to create a wave robot, and I have the basic stuff working. I'm trying to create a new blip with help text when someone types @help but for some reason it doesnt create it. I'm getting no errors in the log console, and I'm seeing the info log 'in @log'</p> <pre><code>def OnBlipSubmitted(properties, context): # Get the blip that was just submitted. blip = context.GetBlipById(properties['blipId']) text = blip.GetDocument().GetText() if text.startswith('@help') == True: logging.info('in @help') blip.CreateChild().GetDocument().SetText('help text') </code></pre>
1
2009-10-18T08:53:41Z
1,584,416
<p>Have you tried using <code>Append()</code> instead of <code>SetText()</code>? That's what I'd do in my C# API - I haven't used the Python API, but I'd imagine it's similar. Here's a sample from my demo robot:</p> <pre><code>protected override void OnBlipSubmitted(IEvent e) { if (e.Blip.Document.Text.Contains("robot")) { IBlip blip = e.Blip.CreateChild(); ITextView textView = blip.Document; textView.Append("Are you talking to me?"); } } </code></pre> <p>That works fine.</p> <p>EDIT: Here's the resulting JSON from the above code:</p> <pre><code>{ "javaClass": "com.google.wave.api.impl.OperationMessageBundle", "version": "173784133", "operations": { "javaClass": "java.util.ArrayList", "list": [ { "javaClass": "com.google.wave.api.impl.OperationImpl", "type": "BLIP_CREATE_CHILD", "waveId": "googlewave.com!w+PHAstGbKC", "waveletId": "googlewave.com!conv+root", "blipId": "b+Iw_Xw7FCC", "index": -1, "property": { "javaClass": "com.google.wave.api.impl.BlipData", "annotations": { "javaClass": "java.util.ArrayList", "list": [] }, "lastModifiedTime": -1, "contributors": { "javaClass": "java.util.ArrayList", "list": [] }, "waveId": "googlewave.com!w+PHAstGbKC", "waveletId": "googlewave.com!conv+root", "version": -1, "parentBlipId": null, "creator": null, "content": "\nAre you talking to me?", "blipId": "410621dc-d7a1-4be5-876c-0a9d313858bb", "elements": { "map": {}, "javaClass": "java.util.HashMap" }, "childBlipIds": { "javaClass": "java.util.ArrayList", "list": [] } } }, { "javaClass": "com.google.wave.api.impl.OperationImpl", "type": "DOCUMENT_APPEND", "waveId": "googlewave.com!w+PHAstGbKC", "waveletId": "googlewave.com!conv+root", "blipId": "410621dc-d7a1-4be5-876c-0a9d313858bb", "index": 0, "property": "Are you talking to me?" } ] } } </code></pre> <p>How does that compare with the JSON which comes out of your robot?</p>
0
2009-10-18T08:59:04Z
[ "python", "google-app-engine", "google-wave" ]
google wave OnBlipSubmitted
1,584,406
<p>I'm trying to create a wave robot, and I have the basic stuff working. I'm trying to create a new blip with help text when someone types @help but for some reason it doesnt create it. I'm getting no errors in the log console, and I'm seeing the info log 'in @log'</p> <pre><code>def OnBlipSubmitted(properties, context): # Get the blip that was just submitted. blip = context.GetBlipById(properties['blipId']) text = blip.GetDocument().GetText() if text.startswith('@help') == True: logging.info('in @help') blip.CreateChild().GetDocument().SetText('help text') </code></pre>
1
2009-10-18T08:53:41Z
1,585,179
<p>For some reason it just started working. I think the google wave is spotty.</p>
0
2009-10-18T15:35:07Z
[ "python", "google-app-engine", "google-wave" ]