title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
PYTHON: Update MULTIPLE COLUMNS with python variables | 1,081,750 | <p>I'm trying to write a valid mysql statement that would allow me to update multiple columns in one record with values provided as python variables.</p>
<p>My statement would look like this:</p>
<pre><code>db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
cursor = db.cursor()
sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
cursor.execute(sql_update)
cursor.close ()
db.commit()
db.close()
</code></pre>
<p>While trying to execute the query I keep receiving information that there is an error in my SQL syntax. I can't locate it though.
Please, maybe someone can point me my mistake or show me how it should be written?</p>
| 0 | 2009-07-04T07:42:43Z | 1,081,794 | <p>Maybe it's about apostrophes around string/VARCHAR values:</p>
<pre><code>sql_update = "UPDATE table_name SET field1='%s', field2='%s', field3='%s', field4='%s', field5='%s', field6='%s', field7='%s', field8='%s', field9='%s', field10='%s' WHERE id='%s'" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
</code></pre>
| 0 | 2009-07-04T08:23:55Z | [
"python",
"mysql",
"variables"
] |
PYTHON: Update MULTIPLE COLUMNS with python variables | 1,081,750 | <p>I'm trying to write a valid mysql statement that would allow me to update multiple columns in one record with values provided as python variables.</p>
<p>My statement would look like this:</p>
<pre><code>db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
cursor = db.cursor()
sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
cursor.execute(sql_update)
cursor.close ()
db.commit()
db.close()
</code></pre>
<p>While trying to execute the query I keep receiving information that there is an error in my SQL syntax. I can't locate it though.
Please, maybe someone can point me my mistake or show me how it should be written?</p>
| 0 | 2009-07-04T07:42:43Z | 35,963,084 | <p>I did it as:</p>
<pre><code> def bscaSoporte(self, denom_sop):
soporte = (denom_sop,) #Para que tome la variable, lista
sql= 'SELECT * FROM SOPORTE_ID WHERE denom_sop LIKE ?'
self.cursor1.execute(sql, soporte)
return self.cursor1.fetchall()
def updSoporte(self, lstNuevosVal):
#busca soporte, SOLO HAY UNO que cumpla
denom_sop = lstNuevosVal.pop(0)
print(lstNuevosVal)
encontrado = self.bscaSoporte(denom_sop)
soporte = (denom_sop,) #Para que tome la variable, lista
if encontrado != None:
sqlupdate =('UPDATE SOPORTE_ID SET dst_pln_eje = ?, geom_Z_eje = ?, \
geom_Y_0_grd = ?, dst_hta_eje = ?, geom_Z_0_grd = ?, \
descrip = ? WHERE denom_sop LIKE ?')
#añado denom_soporte al final de la lista
lstNuevosVal.append(denom_sop)
self.cursor1.execute(sqlupdate, (lstNuevosVal))
self.conexion.commit()
</code></pre>
<p><code>lstNuevosVal</code> has all parameters to replace in <code>sql</code> command. The value of <code>lstNuevosVal</code> is </p>
<pre><code>['Soporte 1', '6.35', '7.36', '8.37', '9.38', '10.39', 'Soporte 306048\nCabeza 3072589\nMáquina: Deco20\n\n']
</code></pre>
| 0 | 2016-03-12T20:44:47Z | [
"python",
"mysql",
"variables"
] |
Yahoo Chat in Python | 1,082,078 | <p>I'm wondering how the best way to build a way to interface with Yahoo Chat is. I haven't found anything that looks incredibly easy to do yet. One thought it to build it all from scratch, the other thought would be to grab the code from open source software. I could use something like zinc, however, this maybe more complex than it needs to be. Another option would be to find a library that supports it, however, I haven't seen one. What are your thoughts on how to proceed and what would be the best way? I'm not necessarily looking for the fastest way as this is a bit of a learning project for me.</p>
| 1 | 2009-07-04T12:03:15Z | 1,082,094 | <p><a href="https://github.com/fahhem/python-purple" rel="nofollow">Python-purple</a> is a python API for accessing libpurple, the Pidgin backend. It will give you access to all the IM networks which Pidgin supports, including Y!Messenger, MSN Messenger, Jabber/GTalk/XMPP, and more...</p>
| 4 | 2009-07-04T12:12:11Z | [
"python",
"networking"
] |
2D vector projection in Python | 1,082,187 | <p>The code below projects the blue vector, AC, onto the red vector, AB, the resulting projected vector, AD, is drawn as purple. This is intended as my own implementation of <a href="http://demonstrations.wolfram.com/VectorProjections/" rel="nofollow">this Wolfram demonstration</a>.</p>
<p>Something is wrong however and I can really figure out what. Should be either that the projection formula itself is wrong or that I mistake some local coordinates with world coordinates. Any help is appreciated.</p>
<p>This code is trimmed but can still be executed without problems, assuming you have pygame:</p>
<pre><code>import pygame
from pygame.locals import *
def vadd(a,b):
return (a[0]+b[0],a[1]+b[1])
def vsub(a,b):
return (a[0]-b[0],a[1]-b[1])
def project(a, b):
""" project a onto b
formula: b(dot(a,b)/(|b|^2))
"""
abdot = (a[0]*b[0])+(a[1]*b[1])
blensq = (b[0]*b[0])+(b[1]*b[1])
temp = float(abdot)/float(blensq)
c = (b[0]*temp,b[1]*temp)
print a,b,abdot,blensq,temp,c
return c
pygame.init()
screen = pygame.display.set_mode((150, 150))
running = True
A = (75.0,75.0)
B = (100.0,50.0)
C = (90,70)
AB = vsub(B,A)
AC = vsub(C,A)
D = project(AC,AB)
AD = vsub(D,A)
while running:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
running = False
pygame.draw.line(screen, (255,0,0), A, B)
pygame.draw.line(screen, (0,0,255), A, C)
pygame.draw.line(screen, (255,0,255), A, D)
pygame.display.flip()
</code></pre>
| 2 | 2009-07-04T13:13:45Z | 1,082,203 | <p>Shouldn't this</p>
<pre><code>D = project(AC,AB)
AD = vsub(D,A)
</code></pre>
<p>be</p>
<pre><code>AD = project(AC,AB)
D = vadd(A,AD)
</code></pre>
<p>Unfortunately, I can't test it, but that's the only thing that looks wrong to me.</p>
| 6 | 2009-07-04T13:24:12Z | [
"python",
"math",
"2d",
"projection"
] |
Automatically pressing a "submit" button using python | 1,082,361 | <p>The bus company I use runs an awful website (<a href="http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=he&state=" rel="nofollow">Hebrew</a>,<a href="http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=en&state=" rel="nofollow">English</a>) which making a simple "From A to B timetable today" query a nightmare. I suspect they are trying to encourage the usage of the costly SMS query system.</p>
<p>I'm trying to harvest the entire timetable from the site, by submitting the query for every possible point to every possible point, which would sum to about 10k queries. The query result appears in a popup window. I'm quite new to web programming, but familiar with the basic aspects of python.</p>
<ol>
<li>What's the most elegant way to parse the page, select a value fro a drop-down menu, and press "submit" using a script?</li>
<li>How do I give the program the contents of the new pop-up as input?</li>
</ol>
<p>Thanks!</p>
| 1 | 2009-07-04T15:00:38Z | 1,082,380 | <p><a href="http://twill.idyll.org/">Twill</a> is a simple scripting language for Web browsing. It happens to sport a <a href="http://twill.idyll.org/python-api.html">python api</a>.</p>
<blockquote>
<p>twill is essentially a thin shell around the mechanize package. All twill commands are implemented in the commands.py file, and pyparsing does the work of parsing the input and converting it into Python commands (see parse.py). Interactive shell work and readline support is implemented via the cmd module (from the standard Python library).</p>
</blockquote>
<p>An example of "pressing" submit from the above linked doc:</p>
<pre><code>from twill.commands import go, showforms, formclear, fv, submit
go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()
formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()
submit('0')
</code></pre>
| 10 | 2009-07-04T15:14:08Z | [
"python",
"scripting",
"form-submit",
"data-harvest"
] |
Automatically pressing a "submit" button using python | 1,082,361 | <p>The bus company I use runs an awful website (<a href="http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=he&state=" rel="nofollow">Hebrew</a>,<a href="http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=en&state=" rel="nofollow">English</a>) which making a simple "From A to B timetable today" query a nightmare. I suspect they are trying to encourage the usage of the costly SMS query system.</p>
<p>I'm trying to harvest the entire timetable from the site, by submitting the query for every possible point to every possible point, which would sum to about 10k queries. The query result appears in a popup window. I'm quite new to web programming, but familiar with the basic aspects of python.</p>
<ol>
<li>What's the most elegant way to parse the page, select a value fro a drop-down menu, and press "submit" using a script?</li>
<li>How do I give the program the contents of the new pop-up as input?</li>
</ol>
<p>Thanks!</p>
| 1 | 2009-07-04T15:00:38Z | 1,082,396 | <p>I would suggest you use <a href="http://wwwsearch.sourceforge.net/mechanize/">mechanize</a>. Here's a code snippet from their page that shows how to submit a form :</p>
<pre><code>
import re
from mechanize import Browser
br = Browser()
br.open("http://www.example.com/")
# follow second link with element text matching regular expression
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
assert br.viewing_html()
print br.title()
print response1.geturl()
print response1.info() # headers
print response1.read() # body
response1.close() # (shown for clarity; in fact Browser does this for you)
br.select_form(name="order")
# Browser passes through unknown attributes (including methods)
# to the selected HTMLForm (from ClientForm).
br["cheeses"] = ["mozzarella", "caerphilly"] # (the method here is __setitem__)
response2 = br.submit() # submit current form
# print currently selected form (don't call .submit() on this, use br.submit())
print br.form
</code></pre>
| 10 | 2009-07-04T15:22:14Z | [
"python",
"scripting",
"form-submit",
"data-harvest"
] |
Automatically pressing a "submit" button using python | 1,082,361 | <p>The bus company I use runs an awful website (<a href="http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=he&state=" rel="nofollow">Hebrew</a>,<a href="http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=en&state=" rel="nofollow">English</a>) which making a simple "From A to B timetable today" query a nightmare. I suspect they are trying to encourage the usage of the costly SMS query system.</p>
<p>I'm trying to harvest the entire timetable from the site, by submitting the query for every possible point to every possible point, which would sum to about 10k queries. The query result appears in a popup window. I'm quite new to web programming, but familiar with the basic aspects of python.</p>
<ol>
<li>What's the most elegant way to parse the page, select a value fro a drop-down menu, and press "submit" using a script?</li>
<li>How do I give the program the contents of the new pop-up as input?</li>
</ol>
<p>Thanks!</p>
| 1 | 2009-07-04T15:00:38Z | 1,082,412 | <p>You very rarely want to actually "press the submit button", rather than making GET or POST requests to the handler resource directly. Look at the HTML where the form is, and see what parameters its submitting to what URL, and if it is GET or POST method. You can form these requests with urllib(2) easily enough.</p>
| 7 | 2009-07-04T15:30:05Z | [
"python",
"scripting",
"form-submit",
"data-harvest"
] |
Sort a list of strings based on regular expression match or something similar | 1,082,413 | <p>I have a text file that looks a bit like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
random text random text, %C can be anything blabla blabla
</code></pre>
<p>When I <code>readlines()</code> it in, it becomes a list of sentences. Now I want this list to be sorted by the letter after the <code>%</code>. So basically, when the sort is applied to the above, it should look like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, %C can be anything blabla blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
</code></pre>
<p>Is there a good way to do this, or will I have to break each string in to tubles, and then move the letters to a specific column, and then sort using <code>key=operator.itemgetter(col)</code>?</p>
<p>Thank you</p>
| 4 | 2009-07-04T15:30:10Z | 1,082,431 | <pre><code>In [1]: def grp(pat, txt):
...: r = re.search(pat, txt)
...: return r.group(0) if r else '&'
In [2]: y
Out[2]:
['random text random text, can be anything blabla %A blabla',
'random text random text, can be anything blabla %D blabla',
'random text random text, can be anything blabla blabla %F',
'random text random text, can be anything blabla blabla',
'random text random text, %C can be anything blabla blabla']
In [3]: y.sort(key=lambda l: grp("%\w", l))
In [4]: y
Out[4]:
['random text random text, can be anything blabla %A blabla',
'random text random text, %C can be anything blabla blabla',
'random text random text, can be anything blabla %D blabla',
'random text random text, can be anything blabla blabla %F',
'random text random text, can be anything blabla blabla']
</code></pre>
| 5 | 2009-07-04T15:38:59Z | [
"python",
"sorting"
] |
Sort a list of strings based on regular expression match or something similar | 1,082,413 | <p>I have a text file that looks a bit like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
random text random text, %C can be anything blabla blabla
</code></pre>
<p>When I <code>readlines()</code> it in, it becomes a list of sentences. Now I want this list to be sorted by the letter after the <code>%</code>. So basically, when the sort is applied to the above, it should look like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, %C can be anything blabla blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
</code></pre>
<p>Is there a good way to do this, or will I have to break each string in to tubles, and then move the letters to a specific column, and then sort using <code>key=operator.itemgetter(col)</code>?</p>
<p>Thank you</p>
| 4 | 2009-07-04T15:30:10Z | 1,082,434 | <p>You could use a custom <code>key</code> function to compare the strings. Using the <code>lambda</code> syntax you can write that inline, like so:</p>
<pre><code>strings.sort(key=lambda str: re.sub(".*%", "", str));
</code></pre>
<p>The <code>re.sub(".*%", "", str)</code> call effectively removes anything before the first percent sign so if the string has a percent sign it'll compare what comes after it, otherwise it'll compare the entire string.</p>
<p>Pedantically speaking, this doesn't just use the letter following the percent sign, it also uses everything after. If you want to use the letter and <em>only</em> the letter try this slightly longer line:</p>
<pre><code>strings.sort(key=lambda str: re.sub(".*%(.).*", "\\1", str));
</code></pre>
| 1 | 2009-07-04T15:40:10Z | [
"python",
"sorting"
] |
Sort a list of strings based on regular expression match or something similar | 1,082,413 | <p>I have a text file that looks a bit like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
random text random text, %C can be anything blabla blabla
</code></pre>
<p>When I <code>readlines()</code> it in, it becomes a list of sentences. Now I want this list to be sorted by the letter after the <code>%</code>. So basically, when the sort is applied to the above, it should look like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, %C can be anything blabla blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
</code></pre>
<p>Is there a good way to do this, or will I have to break each string in to tubles, and then move the letters to a specific column, and then sort using <code>key=operator.itemgetter(col)</code>?</p>
<p>Thank you</p>
| 4 | 2009-07-04T15:30:10Z | 1,082,435 | <p>what about this? hope this helps.</p>
<pre><code>def k(line):
v = line.partition("%")[2]
v = v[0] if v else 'z' # here z stands for the max value
return v
print ''.join(sorted(open('data.txt', 'rb'), key = k))
</code></pre>
| 3 | 2009-07-04T15:40:29Z | [
"python",
"sorting"
] |
Sort a list of strings based on regular expression match or something similar | 1,082,413 | <p>I have a text file that looks a bit like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
random text random text, %C can be anything blabla blabla
</code></pre>
<p>When I <code>readlines()</code> it in, it becomes a list of sentences. Now I want this list to be sorted by the letter after the <code>%</code>. So basically, when the sort is applied to the above, it should look like:</p>
<pre><code>random text random text, can be anything blabla %A blabla
random text random text, %C can be anything blabla blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
</code></pre>
<p>Is there a good way to do this, or will I have to break each string in to tubles, and then move the letters to a specific column, and then sort using <code>key=operator.itemgetter(col)</code>?</p>
<p>Thank you</p>
| 4 | 2009-07-04T15:30:10Z | 1,082,447 | <p>Here is a quick-and-dirty approach. Without knowing more about the requirements of your sort, I can't know if this satisfies your need. </p>
<p>Assume that your list is held in '<code>listoflines</code>':</p>
<pre><code>listoflines.sort( key=lambda x: x[x.find('%'):] )
</code></pre>
<p>Note that this will sort all lines without a '%' character by their final character.</p>
| 1 | 2009-07-04T15:45:16Z | [
"python",
"sorting"
] |
Running both python 2.6 and 3.1 on the same machine | 1,082,692 | <p>I'm currently toying with python at home and I'm planning to switch to python 3.1. The fact is that I have some script that use python 2.6 and I can't convert them since they use some module that aren't available for python 3.1 atm. So I'm considering installing python 3.1 along my python 2.6. I only found people on internet that achieve that by compiling python from source and use <code>make altinstall</code> instead of the classic <code>make install</code>. Anyway, I think compiling from source is a bit complicated. I thought running two different version of a program is easy on linux (I run fedora 11 for the record). Any hint?</p>
<p>Thanks for reading.</p>
| 1 | 2009-07-04T18:02:49Z | 1,082,698 | <p>You're not supposed to need to run them together.</p>
<p>2.6 already has all of the 3.0 features. You can enable those features with <code>from __future__ import</code> statements.</p>
<p>It's much simpler run 2.6 (with some <code>from __future__ import</code>) until everything you need is in 3.x, then switch.</p>
| 1 | 2009-07-04T18:08:12Z | [
"python",
"linux",
"python-3.x"
] |
Running both python 2.6 and 3.1 on the same machine | 1,082,692 | <p>I'm currently toying with python at home and I'm planning to switch to python 3.1. The fact is that I have some script that use python 2.6 and I can't convert them since they use some module that aren't available for python 3.1 atm. So I'm considering installing python 3.1 along my python 2.6. I only found people on internet that achieve that by compiling python from source and use <code>make altinstall</code> instead of the classic <code>make install</code>. Anyway, I think compiling from source is a bit complicated. I thought running two different version of a program is easy on linux (I run fedora 11 for the record). Any hint?</p>
<p>Thanks for reading.</p>
| 1 | 2009-07-04T18:02:49Z | 1,082,730 | <p>Download the python version you want to have as an alternative, untar it, and when you configure it, use --prefix=/my/alt/dir</p>
<p>Cheers</p>
<pre><code>Nik
</code></pre>
| 2 | 2009-07-04T18:21:09Z | [
"python",
"linux",
"python-3.x"
] |
Running both python 2.6 and 3.1 on the same machine | 1,082,692 | <p>I'm currently toying with python at home and I'm planning to switch to python 3.1. The fact is that I have some script that use python 2.6 and I can't convert them since they use some module that aren't available for python 3.1 atm. So I'm considering installing python 3.1 along my python 2.6. I only found people on internet that achieve that by compiling python from source and use <code>make altinstall</code> instead of the classic <code>make install</code>. Anyway, I think compiling from source is a bit complicated. I thought running two different version of a program is easy on linux (I run fedora 11 for the record). Any hint?</p>
<p>Thanks for reading.</p>
| 1 | 2009-07-04T18:02:49Z | 1,103,293 | <p>On my Linux system (Ubuntu Jaunty), I have Python 2.5, 2.6 and 3.0 installed, just by installing the binary (deb) packages <strong>'python2.5'</strong>, <strong>'python2.6'</strong> and <strong>'python3.0'</strong> using apt-get. Perhaps Fedora packages them and names them as RPMs in a similar way.</p>
<p>I can run the one I need from the command line just by typing e.g. <strong><code>python2.6</code></strong>. So I can also specify the one I want at the top of my script by putting e.g.:</p>
<pre><code>#!/usr/bin/python2.6
</code></pre>
| 3 | 2009-07-09T11:29:16Z | [
"python",
"linux",
"python-3.x"
] |
Running both python 2.6 and 3.1 on the same machine | 1,082,692 | <p>I'm currently toying with python at home and I'm planning to switch to python 3.1. The fact is that I have some script that use python 2.6 and I can't convert them since they use some module that aren't available for python 3.1 atm. So I'm considering installing python 3.1 along my python 2.6. I only found people on internet that achieve that by compiling python from source and use <code>make altinstall</code> instead of the classic <code>make install</code>. Anyway, I think compiling from source is a bit complicated. I thought running two different version of a program is easy on linux (I run fedora 11 for the record). Any hint?</p>
<p>Thanks for reading.</p>
| 1 | 2009-07-04T18:02:49Z | 1,103,562 | <p>Why do you need to use <code>make install</code> at all? After having done <code>make</code> to compile python 3.x, just move the python folder somewhere, and create a symlink to the python executable in your <code>~/bin</code> directory. Add that directory to your path if it isn't already, and you'll have a working python development version ready to be used. As long as the symlink itself is not named python (I've named mine <code>py</code>), you'll never experience any clashes.</p>
<p>An added benefit is that if you want to change to a new release of python 3.x, for example if you're following the beta releases, you simply download, compile and replace the folder with the new one.</p>
<p>It's slightly messy, but the messiness is confined to one directory, and I find it much more convenient than thinking about altinstalls and the like.</p>
| 0 | 2009-07-09T12:33:52Z | [
"python",
"linux",
"python-3.x"
] |
How do you subclass the file type in Python? | 1,082,801 | <p>I'm trying to subclass the built-in <code>file</code> class in Python to add some extra features to <code>stdin</code> and <code>stdout</code>. Here's the code I have so far:</p>
<pre><code>class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message printed.
"""
def __init__(self, file1, file2):
"""Initializes the TeeWithTimestamp"""
self.file1 = file1
self.file2 = file2
self.at_start_of_line = True
def write(self, text):
"""Writes text to both files, prefixed with a timestamp"""
if len(text):
# Add timestamp if at the start of a line; also add [STDERR]
# for stderr
if self.at_start_of_line:
now = datetime.datetime.now()
prefix = now.strftime('[%H:%M:%S] ')
if self.file1 == sys.__stderr__:
prefix += '[STDERR] '
text = prefix + text
self.file1.write(text)
self.file2.write(text)
self.at_start_of_line = (text[-1] == '\n')
</code></pre>
<p>The purpose is to add a timestamp to the beginning of each message, and to log everything to a log file. However, the problem I run into is that if I do this:</p>
<pre><code># log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
</code></pre>
<p>Then when I try to do <code>print 'foo'</code>, I get a <code>ValueError: I/O operation on closed file</code>. I can't meaningfully call <code>file.__init__()</code> in my <code>__init__()</code>, since I don't want to open a new file, and I can't assign <code>self.closed = False</code> either, since it's a read-only attribute.</p>
<p>How can I modify this so that I can do <code>print 'foo'</code>, and so that it supports all of the standard <code>file</code> attributes and methods?</p>
| 13 | 2009-07-04T19:07:22Z | 1,082,817 | <p>Calling <code>file.__init__</code> is quite feasible (e.g., on '/dev/null') but no real use because your attempted override of <code>write</code> doesn't "take" for the purposes of <code>print</code> statements -- the latter internally calls the real <code>file.write</code> when it sees that <code>sys.stdout</code> is an actual instance of <code>file</code> (and by inheriting you've made it so).</p>
<p><code>print</code> doesn't really need any other method except <code>write</code>, so making your class inherit from <code>object</code> instead of <code>file</code> will work.</p>
<p>If you need other file methods (i.e., <code>print</code> is not all you're doing), you're best advised to implement them yourself.</p>
| 12 | 2009-07-04T19:17:03Z | [
"python",
"file",
"subclass"
] |
How do you subclass the file type in Python? | 1,082,801 | <p>I'm trying to subclass the built-in <code>file</code> class in Python to add some extra features to <code>stdin</code> and <code>stdout</code>. Here's the code I have so far:</p>
<pre><code>class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message printed.
"""
def __init__(self, file1, file2):
"""Initializes the TeeWithTimestamp"""
self.file1 = file1
self.file2 = file2
self.at_start_of_line = True
def write(self, text):
"""Writes text to both files, prefixed with a timestamp"""
if len(text):
# Add timestamp if at the start of a line; also add [STDERR]
# for stderr
if self.at_start_of_line:
now = datetime.datetime.now()
prefix = now.strftime('[%H:%M:%S] ')
if self.file1 == sys.__stderr__:
prefix += '[STDERR] '
text = prefix + text
self.file1.write(text)
self.file2.write(text)
self.at_start_of_line = (text[-1] == '\n')
</code></pre>
<p>The purpose is to add a timestamp to the beginning of each message, and to log everything to a log file. However, the problem I run into is that if I do this:</p>
<pre><code># log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
</code></pre>
<p>Then when I try to do <code>print 'foo'</code>, I get a <code>ValueError: I/O operation on closed file</code>. I can't meaningfully call <code>file.__init__()</code> in my <code>__init__()</code>, since I don't want to open a new file, and I can't assign <code>self.closed = False</code> either, since it's a read-only attribute.</p>
<p>How can I modify this so that I can do <code>print 'foo'</code>, and so that it supports all of the standard <code>file</code> attributes and methods?</p>
| 13 | 2009-07-04T19:07:22Z | 2,484,093 | <p>You can as well avoid using <code>super</code> :</p>
<pre><code>class SuperFile(file):
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
</code></pre>
<p>You'll be able to write with it.</p>
| 2 | 2010-03-20T17:55:21Z | [
"python",
"file",
"subclass"
] |
Apache: VirtualHost with [PHP|Python|Ruby] support | 1,082,906 | <p>I am experimenting with several languages (Python, Ruby...), and I would like to know if there is a way <strong>to optimize</strong> my Apache Server to load
<strong>certain</strong> modules <strong>only</strong> in <strong>certain</strong> VirtualHost, for instance: </p>
<pre><code>http://myapp1 <- just with Ruby support
http://myapp2 <- just with Python support
http://myapp3 <- just with Php support
...
</code></pre>
<p>Thanks.</p>
| 1 | 2009-07-04T20:17:33Z | 1,082,924 | <p>I dont think thats possible as,</p>
<ol>
<li>The same thread/forked process might be serving pages from different Virtualhosts. So if it has loaded only python, what happens when it needs to serve ruby?</li>
<li>For reason 1, certain directives are web server only, and not virtualhost specific. MaxRequestsPerChild, LoadModule etc are such.</li>
</ol>
| 0 | 2009-07-04T20:27:21Z | [
"php",
"python",
"ruby",
"apache",
"virtualhost"
] |
Apache: VirtualHost with [PHP|Python|Ruby] support | 1,082,906 | <p>I am experimenting with several languages (Python, Ruby...), and I would like to know if there is a way <strong>to optimize</strong> my Apache Server to load
<strong>certain</strong> modules <strong>only</strong> in <strong>certain</strong> VirtualHost, for instance: </p>
<pre><code>http://myapp1 <- just with Ruby support
http://myapp2 <- just with Python support
http://myapp3 <- just with Php support
...
</code></pre>
<p>Thanks.</p>
| 1 | 2009-07-04T20:17:33Z | 1,082,975 | <p>Each Apache worker loads every module, so it's not possible to do within Apache itself.</p>
<p>What you need to do is move your language modules to processes external to Apache workers.</p>
<p>This is done for your languages with the following modules:</p>
<ul>
<li><strong>PHP</strong>: <a href="http://www.fastcgi.com/mod%5Ffastcgi/docs/mod%5Ffastcgi.html" rel="nofollow">mod_fastcgi</a>. More info: <a href="http://www.seaoffire.net/fcgi-faq.html" rel="nofollow">Apache+Chroot+FastCGI</a>.</li>
<li><strong>Python</strong>: <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> in <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess" rel="nofollow">daemon mode</a>.</li>
<li><strong>Ruby</strong>: <a href="http://www.modrails.com/" rel="nofollow">passenger/mod_rack</a></li>
</ul>
| 3 | 2009-07-04T21:12:49Z | [
"php",
"python",
"ruby",
"apache",
"virtualhost"
] |
Apache: VirtualHost with [PHP|Python|Ruby] support | 1,082,906 | <p>I am experimenting with several languages (Python, Ruby...), and I would like to know if there is a way <strong>to optimize</strong> my Apache Server to load
<strong>certain</strong> modules <strong>only</strong> in <strong>certain</strong> VirtualHost, for instance: </p>
<pre><code>http://myapp1 <- just with Ruby support
http://myapp2 <- just with Python support
http://myapp3 <- just with Php support
...
</code></pre>
<p>Thanks.</p>
| 1 | 2009-07-04T20:17:33Z | 1,136,664 | <p>I think the only way is to have a "proxy" web server that dispatches requests to the real servers ...</p>
<p>The proxy server has a list of domain names -> Server Side language, and does nothing else but transparently redirecting to the correct real server</p>
<p>There are N real server, each one with a specific configuration and a single language supported and loaded ... each server will listen on a different port of course and eventually only on the loopback device</p>
<p>Apache mod_proxy should do the job</p>
<p>My 2 cents</p>
| 0 | 2009-07-16T10:18:36Z | [
"php",
"python",
"ruby",
"apache",
"virtualhost"
] |
Apache: VirtualHost with [PHP|Python|Ruby] support | 1,082,906 | <p>I am experimenting with several languages (Python, Ruby...), and I would like to know if there is a way <strong>to optimize</strong> my Apache Server to load
<strong>certain</strong> modules <strong>only</strong> in <strong>certain</strong> VirtualHost, for instance: </p>
<pre><code>http://myapp1 <- just with Ruby support
http://myapp2 <- just with Python support
http://myapp3 <- just with Php support
...
</code></pre>
<p>Thanks.</p>
| 1 | 2009-07-04T20:17:33Z | 1,448,734 | <p>My Idea is several apache processes (each one with different config) listening on different addresses and/or ports and a http proxy (squid or apache) in the front redirecting to respective server. This has a possible added advantage of caching.</p>
| 0 | 2009-09-19T15:10:38Z | [
"php",
"python",
"ruby",
"apache",
"virtualhost"
] |
Want to write an eBook collection manager in Python. What do I need to learn? | 1,083,071 | <p>I have been teaching myself the rudiments of Python and have reached a stage where I would like to tackle a project of increasing complexity in order to "scratch an itch".</p>
<p>I have a large eBook collection (several gigabytes, organized in folders according to topic, mostly .pdf files with the occasional .djvu, .html, and .chm). I have tried a number of eBook manager apps and have found all of them lacking in key areas, or simply unavailable for Linux. </p>
<p>Therefore, I would like to write an eBook manager application in Python that can perform the following tasks:</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
<li>Link from entry in database to actual eBook file; open file from application.</li>
<li>Rename, relocate, and delete files from application.</li>
<li>Select default application to open arbitrary file types.</li>
<li>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</li>
<li>Allow the creation of reading lists.</li>
<li>Allow tags, notes, ratings.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
<li>Display cover as image (Ã la Beagle).</li>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>So, my questions are:</p>
<ol>
<li><p>How would you go about tackling this project? </p></li>
<li><p>Which libraries would I have to learn in order to achieve the desired functionality?</p></li>
<li><p>What other resources (tutorials, source code, etc.) do you recommend?</p></li>
</ol>
<p>Thank you in advance!</p>
| 7 | 2009-07-04T22:18:13Z | 1,083,082 | <p>for your 'basic' needs no additional library is needed. the plain standard python library is sufficient. for your optional needs I was looking for answers too</p>
| 0 | 2009-07-04T22:29:25Z | [
"python"
] |
Want to write an eBook collection manager in Python. What do I need to learn? | 1,083,071 | <p>I have been teaching myself the rudiments of Python and have reached a stage where I would like to tackle a project of increasing complexity in order to "scratch an itch".</p>
<p>I have a large eBook collection (several gigabytes, organized in folders according to topic, mostly .pdf files with the occasional .djvu, .html, and .chm). I have tried a number of eBook manager apps and have found all of them lacking in key areas, or simply unavailable for Linux. </p>
<p>Therefore, I would like to write an eBook manager application in Python that can perform the following tasks:</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
<li>Link from entry in database to actual eBook file; open file from application.</li>
<li>Rename, relocate, and delete files from application.</li>
<li>Select default application to open arbitrary file types.</li>
<li>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</li>
<li>Allow the creation of reading lists.</li>
<li>Allow tags, notes, ratings.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
<li>Display cover as image (Ã la Beagle).</li>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>So, my questions are:</p>
<ol>
<li><p>How would you go about tackling this project? </p></li>
<li><p>Which libraries would I have to learn in order to achieve the desired functionality?</p></li>
<li><p>What other resources (tutorials, source code, etc.) do you recommend?</p></li>
</ol>
<p>Thank you in advance!</p>
| 7 | 2009-07-04T22:18:13Z | 1,083,112 | <p>For the UI, I would suggest wxPython. Tkinter is more used, but I find it horrible. PyGTK and PyQt probably are good options too.
Here are two good tutorials:<br />
<a href="http://zetcode.com/wxpython/" rel="nofollow">http://zetcode.com/wxpython/</a><br />
<a href="http://wiki.wxpython.org/AnotherTutorial" rel="nofollow">http://wiki.wxpython.org/AnotherTutorial</a><br />
There is also a very good book, âwxPython in actionâ.</p>
<p>It's probably a good idea to store your objects in a relational database.
Python ships with the sqlite3 module, which will probably be sufficient and allows to easily experiment on the shell.
This SQL tutorial seems good: <a href="http://en.wikibooks.org/wiki/Structured%5FQuery%5FLanguage" rel="nofollow">http://en.wikibooks.org/wiki/Structured_Query_Language</a>.<br />
If you find yourself spending too much time on storing and retrieving the objects, you'll probably want to use a framework like SQLAlchemy which automates the process.</p>
<p>Once you have learned SQL, it's possible that you won't be sure how to map objects to tables (it isn't as easy as it may look). I don't know any resource about that, though.</p>
<p>And don't forget to think about the design before coding. :-) I would also suggest learning how to write unit tests.</p>
| 3 | 2009-07-04T22:44:49Z | [
"python"
] |
Want to write an eBook collection manager in Python. What do I need to learn? | 1,083,071 | <p>I have been teaching myself the rudiments of Python and have reached a stage where I would like to tackle a project of increasing complexity in order to "scratch an itch".</p>
<p>I have a large eBook collection (several gigabytes, organized in folders according to topic, mostly .pdf files with the occasional .djvu, .html, and .chm). I have tried a number of eBook manager apps and have found all of them lacking in key areas, or simply unavailable for Linux. </p>
<p>Therefore, I would like to write an eBook manager application in Python that can perform the following tasks:</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
<li>Link from entry in database to actual eBook file; open file from application.</li>
<li>Rename, relocate, and delete files from application.</li>
<li>Select default application to open arbitrary file types.</li>
<li>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</li>
<li>Allow the creation of reading lists.</li>
<li>Allow tags, notes, ratings.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
<li>Display cover as image (Ã la Beagle).</li>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>So, my questions are:</p>
<ol>
<li><p>How would you go about tackling this project? </p></li>
<li><p>Which libraries would I have to learn in order to achieve the desired functionality?</p></li>
<li><p>What other resources (tutorials, source code, etc.) do you recommend?</p></li>
</ol>
<p>Thank you in advance!</p>
| 7 | 2009-07-04T22:18:13Z | 1,083,140 | <p>Look at <a href="http://couchdb.apache.org" rel="nofollow">CouchDB</a> instead of traditional relational database models. It's document-centric, so it's a good fit for something like an e-book organizer. There are great python libs for it, but CouchDB speaks HTTP and JSON, so it's pretty trivial to query/connect, etc. </p>
<p>A great solution would be to use the built-in functionality for attachments to actually store the PDFs themselves, and then dynamically assign meta-data as desired. The CouchDB query process uses a two-pass Map/Reduce rather than looping through the data so much faster than traditional relational databases that might have multiple tables and joins between them.</p>
<p>Worth a gander.</p>
| 3 | 2009-07-04T23:03:31Z | [
"python"
] |
Want to write an eBook collection manager in Python. What do I need to learn? | 1,083,071 | <p>I have been teaching myself the rudiments of Python and have reached a stage where I would like to tackle a project of increasing complexity in order to "scratch an itch".</p>
<p>I have a large eBook collection (several gigabytes, organized in folders according to topic, mostly .pdf files with the occasional .djvu, .html, and .chm). I have tried a number of eBook manager apps and have found all of them lacking in key areas, or simply unavailable for Linux. </p>
<p>Therefore, I would like to write an eBook manager application in Python that can perform the following tasks:</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
<li>Link from entry in database to actual eBook file; open file from application.</li>
<li>Rename, relocate, and delete files from application.</li>
<li>Select default application to open arbitrary file types.</li>
<li>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</li>
<li>Allow the creation of reading lists.</li>
<li>Allow tags, notes, ratings.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
<li>Display cover as image (Ã la Beagle).</li>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>So, my questions are:</p>
<ol>
<li><p>How would you go about tackling this project? </p></li>
<li><p>Which libraries would I have to learn in order to achieve the desired functionality?</p></li>
<li><p>What other resources (tutorials, source code, etc.) do you recommend?</p></li>
</ol>
<p>Thank you in advance!</p>
| 7 | 2009-07-04T22:18:13Z | 1,083,166 | <p>Firstly, I'm no pro; take everything I say with a pinch of salt.</p>
<p>The biggest decision I can see you're likely to need to take is the nature of the database.
I'd be tempted to state that the project is sufficiently ambitious that you might well want to look into something SQL-shaped for the database.</p>
<p>Get to know and love the Global Module Index (1) (for your version of Python). It has probably got 99% of everything you ever need - but at the same time, a speculative search for specific bibliophile modules might be of use.</p>
<p>Also, this is a big project. Have an idea how the whole thing sits together, but focus on smaller, manageable chunks first.</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
</ul>
<p>You'll want to look at <code>os.walk</code> (2). Use the <code>os</code> module to maintain cross-platform compatibility if this interests you.</p>
<ul>
<li>Link from entry in database to actual eBook file; open file from application.</li>
</ul>
<p>I would assume that this would be done by referring to the path to the eBook; <code>os.system</code> (3) will allow you to launch the relevant reader.</p>
<ul>
<li>Rename, relocate, and delete files from application.</li>
</ul>
<p>The <code>os</code> module remains your friend.</p>
<ul>
<li><p>Select default application to open arbitrary file types.
In windows, you can run <code>start</code> <i><code>filename</code></i><code>.pdf</code> to use Windows' inbuilt default applications, or simply have a lookup based on file type. (You probably want to use a dictionary (4) for this.)</p></li>
<li><p>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</p></li>
</ul>
<p>Not sure what processing you're wanting: <code>urllib</code> (5) lets you grab HTML in a convienient fashion, but [<code>HTMLParser</code>] may help extract the information you're interested in from the website.</p>
<ul>
<li>Allow the creation of reading lists.</li>
</ul>
<p>Not sure what you're doing here. I'm guessing this would mean creating a list of eBooks and is therefore a database issue. You might want to consider how you are referring to these books: by file name? ISBN? Your own unique IDs? Amazon URLs?</p>
<ul>
<li>Allow tags, notes, ratings.
These are probably elements of your database.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
</ul>
<p>If you've got the metadata, should just be a case of concatenating the relevant strings.</p>
<ul>
<li>Display cover as image (Ã la Beagle).</li>
</ul>
<p>You might want to build a whole GUI in wxPython (6) or similar. This is a significant task.</p>
<ul>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>Might be near impossible for DRM-encumbered forms; you might also need to write different handlers for each format (although some will have modules available, I am sure.)</p>
<p>(1): docs.python.org/modindex.html</p>
<p>(2): docs.python.org/library/os.html#os.walk</p>
<p>(3): docs.python.org/library/os.html#os.system</p>
<p>(4): docs.python.org/tutorial/datastructures.html#dictionaries</p>
<p>(5): docs.python.org/library/urllib.html</p>
<p>(6): www.wxpython.org/</p>
| 5 | 2009-07-04T23:23:55Z | [
"python"
] |
Want to write an eBook collection manager in Python. What do I need to learn? | 1,083,071 | <p>I have been teaching myself the rudiments of Python and have reached a stage where I would like to tackle a project of increasing complexity in order to "scratch an itch".</p>
<p>I have a large eBook collection (several gigabytes, organized in folders according to topic, mostly .pdf files with the occasional .djvu, .html, and .chm). I have tried a number of eBook manager apps and have found all of them lacking in key areas, or simply unavailable for Linux. </p>
<p>Therefore, I would like to write an eBook manager application in Python that can perform the following tasks:</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
<li>Link from entry in database to actual eBook file; open file from application.</li>
<li>Rename, relocate, and delete files from application.</li>
<li>Select default application to open arbitrary file types.</li>
<li>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</li>
<li>Allow the creation of reading lists.</li>
<li>Allow tags, notes, ratings.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
<li>Display cover as image (Ã la Beagle).</li>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>So, my questions are:</p>
<ol>
<li><p>How would you go about tackling this project? </p></li>
<li><p>Which libraries would I have to learn in order to achieve the desired functionality?</p></li>
<li><p>What other resources (tutorials, source code, etc.) do you recommend?</p></li>
</ol>
<p>Thank you in advance!</p>
| 7 | 2009-07-04T22:18:13Z | 1,083,928 | <p><strong>"How would you go about tackling this project?"</strong></p>
<p>Slowly.</p>
<p>First, define your use cases. You have a list of features, but no user interaction even hinted at. Define what interactions you will make with your application and what value the application creates for you. This can be hard.</p>
<p>Then, prioritize those use cases. This is important.</p>
<p>Don't fetishize over the final technology stack. Picking too much technology creates all new problems. Once you've mastered the problem domain, you can add technologies.</p>
<p>Also, don't spend too much time on a GUI. GUI's are hard -- remarkably hard -- and it helps to have everything else understood before starting down the road of GUI development. Learning Python, learning to build GUI's and learning to catalog eBooks is too much.</p>
<p>Pick one use case. Just one. Build a small command-line application that does just this.</p>
<p>Then move to the next use case. You may want to build a separate command-line application, or extend the previous one.</p>
<p>Eventually, you'll have a clunky command-line collection of tools that actually works, doing the various things you need it to do.</p>
<p>Now, you can tackle the GUI.</p>
| 3 | 2009-07-05T11:56:04Z | [
"python"
] |
Want to write an eBook collection manager in Python. What do I need to learn? | 1,083,071 | <p>I have been teaching myself the rudiments of Python and have reached a stage where I would like to tackle a project of increasing complexity in order to "scratch an itch".</p>
<p>I have a large eBook collection (several gigabytes, organized in folders according to topic, mostly .pdf files with the occasional .djvu, .html, and .chm). I have tried a number of eBook manager apps and have found all of them lacking in key areas, or simply unavailable for Linux. </p>
<p>Therefore, I would like to write an eBook manager application in Python that can perform the following tasks:</p>
<ul>
<li>Recursively import all files in a directory and its sub-folders into application's database.</li>
<li>Link from entry in database to actual eBook file; open file from application.</li>
<li>Rename, relocate, and delete files from application.</li>
<li>Select default application to open arbitrary file types.</li>
<li>Fetch metadata in bulk from Amazon.com, the Library of Congress, or other repositories.</li>
<li>Allow the creation of reading lists.</li>
<li>Allow tags, notes, ratings.</li>
</ul>
<p>Optional, but would be nice:</p>
<ul>
<li>Create BibTex references from arbitrarily selected items.</li>
<li>Display cover as image (Ã la Beagle).</li>
<li>Text snippets (also à la Beagle).</li>
</ul>
<p>So, my questions are:</p>
<ol>
<li><p>How would you go about tackling this project? </p></li>
<li><p>Which libraries would I have to learn in order to achieve the desired functionality?</p></li>
<li><p>What other resources (tutorials, source code, etc.) do you recommend?</p></li>
</ol>
<p>Thank you in advance!</p>
| 7 | 2009-07-04T22:18:13Z | 10,569,373 | <p>Why would you write one if Calibre does that already. It's build based on a modular design and it allows Python based plugins . </p>
<p>Write a plugin instead to solve your specific need instead of reinventing the wheel :)</p>
| 0 | 2012-05-13T04:45:24Z | [
"python"
] |
Does creating separate functions instead of one big one slow processing time? | 1,083,105 | <p>I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache. </p>
<pre><code>def generate_random_string():
# return a random 6-digit long string
def check_and_store_to_memcache():
randomstring = generate_random_string()
#check against memcache
#if ok, then store key value with another value
#if not ok, run generate_random_string() again and check again.
</code></pre>
<p>Does creating two functions instead of just one big one affect performance? I prefer two, as it better matches how I think, but don't mind combining them if that's "best practice".</p>
<p>Thanks!</p>
| 7 | 2009-07-04T22:41:12Z | 1,083,121 | <p>Focus on being able to read and easily understand your code.</p>
<p>Once you've done this, if you have a performance problem, then look into what might be causing it.</p>
<p>Most languages, python included, tend to have fairly low overhead for making method calls. Putting this code into a single function is not going to (dramatically) change the performance metrics - I'd guess that your random number generation will probably be the bulk of the time, not having 2 functions. </p>
<p>That being said, splitting functions does have a (very, very minor) impact on performance. However, I'd think of it this way - it may take you from going 80 mph on the highway to 79.99mph (which you'll never really notice). The important things to watch for are avoiding stoplights and traffic jams, since they're going to make you have to stop altogether...</p>
| 27 | 2009-07-04T22:47:33Z | [
"python",
"google-app-engine",
"function",
"performance"
] |
Does creating separate functions instead of one big one slow processing time? | 1,083,105 | <p>I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache. </p>
<pre><code>def generate_random_string():
# return a random 6-digit long string
def check_and_store_to_memcache():
randomstring = generate_random_string()
#check against memcache
#if ok, then store key value with another value
#if not ok, run generate_random_string() again and check again.
</code></pre>
<p>Does creating two functions instead of just one big one affect performance? I prefer two, as it better matches how I think, but don't mind combining them if that's "best practice".</p>
<p>Thanks!</p>
| 7 | 2009-07-04T22:41:12Z | 1,085,124 | <p>Reed is right. For the change you're considering, the cost of a function call is a small number of cycles, and you'd have to be doing it 10^8 or so times per second before you'd notice.</p>
<p>However, I would caution that often people go to the other extreme, and then it is <em>as if</em> function calls were costly. I've seen this in over-designed systems where there were many layers of abstraction.</p>
<p>What happens is there is some human psychology that says if something is easy to call, then it is fast. This leads to writing more function calls than strictly necessary, and when this occurs over multiple layers of abstraction, the wastage can be exponential.</p>
<p>Following Reed's driving example, a function call can be like a detour, and if the detour contains detours, and if those also contain detours, soon there is tremendous time being wasted, for no <em>obvious</em> reason, because each function call looks innocent.</p>
| 4 | 2009-07-06T02:02:39Z | [
"python",
"google-app-engine",
"function",
"performance"
] |
Does creating separate functions instead of one big one slow processing time? | 1,083,105 | <p>I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache. </p>
<pre><code>def generate_random_string():
# return a random 6-digit long string
def check_and_store_to_memcache():
randomstring = generate_random_string()
#check against memcache
#if ok, then store key value with another value
#if not ok, run generate_random_string() again and check again.
</code></pre>
<p>Does creating two functions instead of just one big one affect performance? I prefer two, as it better matches how I think, but don't mind combining them if that's "best practice".</p>
<p>Thanks!</p>
| 7 | 2009-07-04T22:41:12Z | 1,085,128 | <p>In almost all cases, "inlining" functions to increase speed is like getting a hair cut to lose weight.</p>
| 13 | 2009-07-06T02:06:33Z | [
"python",
"google-app-engine",
"function",
"performance"
] |
Does creating separate functions instead of one big one slow processing time? | 1,083,105 | <p>I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache. </p>
<pre><code>def generate_random_string():
# return a random 6-digit long string
def check_and_store_to_memcache():
randomstring = generate_random_string()
#check against memcache
#if ok, then store key value with another value
#if not ok, run generate_random_string() again and check again.
</code></pre>
<p>Does creating two functions instead of just one big one affect performance? I prefer two, as it better matches how I think, but don't mind combining them if that's "best practice".</p>
<p>Thanks!</p>
| 7 | 2009-07-04T22:41:12Z | 1,085,147 | <p>Like others have said, I wouldn't worry about it in this particular scenario. The very small overhead involved in function calls would pale in comparison to what is done inside each function. And as long as these functions don't get called in rapid succession, it probably wouldn't matter much anyway.</p>
<p>It is a good question though. In some cases it's best not to break code into multiple functions. For example, when working with math intensive tasks with nested loops it's best to make as few function calls as possible in the inner loop. That's because the simple math operations themselves are very cheap, and next to that the function-call-overhead can cause a noticeable performance penalty.</p>
<p>Years ago I discovered the hypot (hypotenuse) function in the math library I was using in a VC++ app was very slow. It seemed ridiculous to me because it's such a simple set of functionality -- return sqrt(a * a + b * b) -- how hard is that? So I wrote my own and managed to improve performance 16X over. Then I added the "inline" keyword to the function and made it 3X faster than that (about 50X faster at this point). Then I took the code out of the function and put it in my loop itself and saw yet another small performance increase. So... yeah, those are the types of scenarios where you can see a difference.</p>
| 2 | 2009-07-06T02:19:24Z | [
"python",
"google-app-engine",
"function",
"performance"
] |
What is the Pythonic way to write this loop? | 1,083,115 | <pre><code>for jr in json_reports:
jr['time_created'] = str(jr['time_created'])
</code></pre>
| 1 | 2009-07-04T22:46:04Z | 1,083,128 | <p>Looks to me that you're already there</p>
| 10 | 2009-07-04T22:51:49Z | [
"python"
] |
What is the Pythonic way to write this loop? | 1,083,115 | <pre><code>for jr in json_reports:
jr['time_created'] = str(jr['time_created'])
</code></pre>
| 1 | 2009-07-04T22:46:04Z | 1,083,130 | <p>That would be the pythonic way to write the loop if you need to assign it to the same list.</p>
<p>If you just want to pull out strings of all <code>time_created</code> indices in each element of <code>json_reports</code>, you can use a list comprehension:</p>
<pre><code>strings = [str(i['time_created']) for i in json_reports]
</code></pre>
| 5 | 2009-07-04T22:53:51Z | [
"python"
] |
Play mp3 using Python, PyQt, and Phonon | 1,083,118 | <p>I been trying all day to figure out the Qt's Phonon library with Python. </p>
<p>My long term goal is to see if I could get it to play a mms:// stream, but since I can't find an implementation of this done anywhere, I will figure that part out myself. (figured I'd put it out there if anyone knew more about this specifically, if not no big deal.)</p>
<p>Anyway, I figured I'd work backwards from a working example I found online. This launches a file browser and will play the mp3 file specified. I wanted to strip out the file browser stuff and get it down to the essentials of executing the script and having it play an Mp3 file with a hardcoded path.</p>
<p>I'm assuming my problem is a misunderstanding of setCurrentSource() and specifying the data types. (see: <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/phonon-mediasource.html#fileName">http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/phonon-mediasource.html#fileName</a>)</p>
<p>I'm keeping my question kind of broad because ANY help with understanding Phonon would be greatly appreciated. </p>
<pre><code>import sys
from PyQt4.QtGui import QApplication, QMainWindow, QDirModel, QColumnView
from PyQt4.QtGui import QFrame
from PyQt4.QtCore import SIGNAL
from PyQt4.phonon import Phonon
class MainWindow(QMainWindow):
m_model = QDirModel()
def __init__(self):
QMainWindow.__init__(self)
self.m_fileView = QColumnView(self)
self.m_media = None
self.setCentralWidget(self.m_fileView)
self.m_fileView.setModel(self.m_model)
self.m_fileView.setFrameStyle(QFrame.NoFrame)
self.connect(self.m_fileView,
SIGNAL("updatePreviewWidget(const QModelIndex &)"), self.play)
def play(self, index):
self.delayedInit()
self.m_media.setCurrentSource(
Phonon.MediaSource(self.m_model.filePath(index)))
self.m_media.play()
def delayedInit(self):
if not self.m_media:
self.m_media = Phonon.MediaObject(self)
audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
Phonon.createPath(self.m_media, audioOutput)
def main():
app = QApplication(sys.argv)
QApplication.setApplicationName("Phonon Tutorial 2 (Python)")
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 7 | 2009-07-04T22:47:08Z | 1,116,179 | <p>Phonon supports different audio file formats on different platforms, using the system's own support for media formats, so it could be that your system doesn't provide libraries for playing MP3 files. Certainly, MP3 is not supported out of the box on some Linux distributions. If you are using Linux, please take a look at the following page for information about enabling MP3 support:</p>
<p><a href="http://doc.qt.io/qt-4.8/phonon-overview.html#linux" rel="nofollow">http://doc.qt.io/qt-4.8/phonon-overview.html#linux</a></p>
<p>Another way to diagnose problems with Phonon's media formats is to run the Capabilities example provided with Qt:</p>
<p><a href="http://doc.qt.io/qt-4.8///qt-phonon-capabilities-example.html" rel="nofollow">http://doc.qt.io/qt-4.8///qt-phonon-capabilities-example.html</a></p>
<p>This should tell you which media formats are supported by your system.</p>
| 2 | 2009-07-12T15:03:54Z | [
"python",
"pyqt",
"media",
"phonon"
] |
Play mp3 using Python, PyQt, and Phonon | 1,083,118 | <p>I been trying all day to figure out the Qt's Phonon library with Python. </p>
<p>My long term goal is to see if I could get it to play a mms:// stream, but since I can't find an implementation of this done anywhere, I will figure that part out myself. (figured I'd put it out there if anyone knew more about this specifically, if not no big deal.)</p>
<p>Anyway, I figured I'd work backwards from a working example I found online. This launches a file browser and will play the mp3 file specified. I wanted to strip out the file browser stuff and get it down to the essentials of executing the script and having it play an Mp3 file with a hardcoded path.</p>
<p>I'm assuming my problem is a misunderstanding of setCurrentSource() and specifying the data types. (see: <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/phonon-mediasource.html#fileName">http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/phonon-mediasource.html#fileName</a>)</p>
<p>I'm keeping my question kind of broad because ANY help with understanding Phonon would be greatly appreciated. </p>
<pre><code>import sys
from PyQt4.QtGui import QApplication, QMainWindow, QDirModel, QColumnView
from PyQt4.QtGui import QFrame
from PyQt4.QtCore import SIGNAL
from PyQt4.phonon import Phonon
class MainWindow(QMainWindow):
m_model = QDirModel()
def __init__(self):
QMainWindow.__init__(self)
self.m_fileView = QColumnView(self)
self.m_media = None
self.setCentralWidget(self.m_fileView)
self.m_fileView.setModel(self.m_model)
self.m_fileView.setFrameStyle(QFrame.NoFrame)
self.connect(self.m_fileView,
SIGNAL("updatePreviewWidget(const QModelIndex &)"), self.play)
def play(self, index):
self.delayedInit()
self.m_media.setCurrentSource(
Phonon.MediaSource(self.m_model.filePath(index)))
self.m_media.play()
def delayedInit(self):
if not self.m_media:
self.m_media = Phonon.MediaObject(self)
audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
Phonon.createPath(self.m_media, audioOutput)
def main():
app = QApplication(sys.argv)
QApplication.setApplicationName("Phonon Tutorial 2 (Python)")
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 7 | 2009-07-04T22:47:08Z | 2,563,460 | <p>In <code>delayedInit</code> method; create <code>MediaObject</code> like following:</p>
<pre><code>def delayedInit(self):
if not self.m_media:
self.m_media = Phonon.createPlayer(Phonon.MusicCategory)
</code></pre>
| 1 | 2010-04-01T20:30:20Z | [
"python",
"pyqt",
"media",
"phonon"
] |
How would you adblock using Python? | 1,083,170 | <p>I'm slowly building a <a href="http://github.com/regomodo/qtBrowser/tree/master" rel="nofollow">web browser</a> in PyQt4 and like the speed i'm getting out of it. However, I want to combine easylist.txt with it. I believe adblock uses this to block http requests by the browser.</p>
<p>How would you go about it using python/PyQt4?</p>
<p>[edit1]
Ok. I think i've setup Privoxy. I haven't setup any additional filters and it seems to work. The PyQt4 i've tried to use looks like this</p>
<p><code>self.proxyIP = "127.0.0.1"<br />
self.proxyPORT= 8118<br />
proxy = QNetworkProxy()<br />
proxy.setType(QNetworkProxy.HttpProxy)<br />
proxy.setHostName(self.proxyIP)<br />
proxy.setPort(self.proxyPORT)<br />
QNetworkProxy.setApplicationProxy(proxy) </code></p>
<p>However, this does absolutely nothing and I cannot make sense of the docs and can not find any examples.</p>
<p>[edit2] I've just noticed that i'f I change self.proxyIP to my actual local IP rather than 127.0.0.1 the page doesn't load. So something is happening.</p>
| 4 | 2009-07-04T23:29:48Z | 1,085,037 | <p>Is this question about web filtering?</p>
<p>Then try use some of external web-proxy, for sample Privoxy (<a href="http://en.wikipedia.org/wiki/Privoxy" rel="nofollow">http://en.wikipedia.org/wiki/Privoxy</a>).</p>
| 0 | 2009-07-05T23:14:43Z | [
"python",
"pyqt4",
"adblock"
] |
How would you adblock using Python? | 1,083,170 | <p>I'm slowly building a <a href="http://github.com/regomodo/qtBrowser/tree/master" rel="nofollow">web browser</a> in PyQt4 and like the speed i'm getting out of it. However, I want to combine easylist.txt with it. I believe adblock uses this to block http requests by the browser.</p>
<p>How would you go about it using python/PyQt4?</p>
<p>[edit1]
Ok. I think i've setup Privoxy. I haven't setup any additional filters and it seems to work. The PyQt4 i've tried to use looks like this</p>
<p><code>self.proxyIP = "127.0.0.1"<br />
self.proxyPORT= 8118<br />
proxy = QNetworkProxy()<br />
proxy.setType(QNetworkProxy.HttpProxy)<br />
proxy.setHostName(self.proxyIP)<br />
proxy.setPort(self.proxyPORT)<br />
QNetworkProxy.setApplicationProxy(proxy) </code></p>
<p>However, this does absolutely nothing and I cannot make sense of the docs and can not find any examples.</p>
<p>[edit2] I've just noticed that i'f I change self.proxyIP to my actual local IP rather than 127.0.0.1 the page doesn't load. So something is happening.</p>
| 4 | 2009-07-04T23:29:48Z | 1,085,057 | <p>The easylist.txt file is simply plain text, as demonstrated here: <a href="http://adblockplus.mozdev.org/easylist/easylist.txt" rel="nofollow">http://adblockplus.mozdev.org/easylist/easylist.txt</a></p>
<p>lines beginning with [ and also ! appear to be comments, so it is simply a case of sorting through the file, and searching for the correct things in the url/request depending upon the starting character of the line in the easylist.txt file.</p>
| 0 | 2009-07-05T23:25:22Z | [
"python",
"pyqt4",
"adblock"
] |
How would you adblock using Python? | 1,083,170 | <p>I'm slowly building a <a href="http://github.com/regomodo/qtBrowser/tree/master" rel="nofollow">web browser</a> in PyQt4 and like the speed i'm getting out of it. However, I want to combine easylist.txt with it. I believe adblock uses this to block http requests by the browser.</p>
<p>How would you go about it using python/PyQt4?</p>
<p>[edit1]
Ok. I think i've setup Privoxy. I haven't setup any additional filters and it seems to work. The PyQt4 i've tried to use looks like this</p>
<p><code>self.proxyIP = "127.0.0.1"<br />
self.proxyPORT= 8118<br />
proxy = QNetworkProxy()<br />
proxy.setType(QNetworkProxy.HttpProxy)<br />
proxy.setHostName(self.proxyIP)<br />
proxy.setPort(self.proxyPORT)<br />
QNetworkProxy.setApplicationProxy(proxy) </code></p>
<p>However, this does absolutely nothing and I cannot make sense of the docs and can not find any examples.</p>
<p>[edit2] I've just noticed that i'f I change self.proxyIP to my actual local IP rather than 127.0.0.1 the page doesn't load. So something is happening.</p>
| 4 | 2009-07-04T23:29:48Z | 1,490,881 | <p>Privoxy is solid. If you want it to be completely API based though, check out the <a href="http://bcws.brightcloud.com" rel="nofollow">BrightCloud web filtering API</a> as well.</p>
| 0 | 2009-09-29T06:24:36Z | [
"python",
"pyqt4",
"adblock"
] |
How would you adblock using Python? | 1,083,170 | <p>I'm slowly building a <a href="http://github.com/regomodo/qtBrowser/tree/master" rel="nofollow">web browser</a> in PyQt4 and like the speed i'm getting out of it. However, I want to combine easylist.txt with it. I believe adblock uses this to block http requests by the browser.</p>
<p>How would you go about it using python/PyQt4?</p>
<p>[edit1]
Ok. I think i've setup Privoxy. I haven't setup any additional filters and it seems to work. The PyQt4 i've tried to use looks like this</p>
<p><code>self.proxyIP = "127.0.0.1"<br />
self.proxyPORT= 8118<br />
proxy = QNetworkProxy()<br />
proxy.setType(QNetworkProxy.HttpProxy)<br />
proxy.setHostName(self.proxyIP)<br />
proxy.setPort(self.proxyPORT)<br />
QNetworkProxy.setApplicationProxy(proxy) </code></p>
<p>However, this does absolutely nothing and I cannot make sense of the docs and can not find any examples.</p>
<p>[edit2] I've just noticed that i'f I change self.proxyIP to my actual local IP rather than 127.0.0.1 the page doesn't load. So something is happening.</p>
| 4 | 2009-07-04T23:29:48Z | 18,323,507 | <p>I know this is an old question, but I thought I'd try giving an answer for anyone who happens to stumble upon it. You could create a subclass of QNetworkAccessManager and combine it with <a href="https://github.com/atereshkin/abpy" rel="nofollow">https://github.com/atereshkin/abpy</a>. Something kind of like this:</p>
<pre><code>from PyQt4.QtNetwork import QNetworkAccessManager
from abpy import Filter
adblockFilter = Filter(file("easylist.txt"))
class MyNetworkAccessManager(QNetworkAccessManager):
def createRequest(self, op, request, device=None):
url = request.url().toString()
doFilter = adblockFilter.match(url)
if doFilter:
return QNetworkAccessManager.createRequest(self, self.GetOperation, QNetworkRequest(QUrl()))
else:
QNetworkAccessManager.createRequest(self, op, request, device)
myNetworkAccessManager = MyNetworkAccessManager()
</code></pre>
<p>After that, set the following on all your QWebView instances, or make a subclass of QWebView:</p>
<pre><code>QWebView.page().setNetworkAccessManager(myNetworkAccessManager)
</code></pre>
<p>Hope this helps!</p>
| 4 | 2013-08-19T21:33:28Z | [
"python",
"pyqt4",
"adblock"
] |
Running JSON through Python's eval()? | 1,083,250 | <p>Best practices aside, is there a compelling reason <strong>not</strong> to do this?</p>
<p>I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confidence that the JSON data is both benign (as there's little point in distrusting Google) and valid.</p>
<p>My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the <code>"\/"</code> escape sequence â which GC doesn't appear to generate.</p>
<p>So, as I'm working with Python 2.4 (i.e. no <code>json</code> module), <code>eval()</code> is looking <em>really</em> tempting.</p>
<p><strong>Edit:</strong> For the record, I am very much <strong>not</strong> asking if this is a good idea. I'm <em>quite</em> aware that it isn't, and I very much doubt I'll ever use this technique for any future projects even if I end up using it for this one. I just wanted to make sure that I know what kind of trouble I'll run into if I do. :-)</p>
| 17 | 2009-07-05T00:35:10Z | 1,083,262 | <p>The point of best practices is that in most cases, it's a bad idea to disregard them. If I were you, I'd use a parser to parse JSON into Python. Try out <a href="http://undefined.org/python/#simplejson" rel="nofollow">simplejson</a>, it was very straightforward for parsing JSON when I last tried it and it claims to be compatible with Python 2.4. </p>
<p>I disagree that there's little point in distrusting Google. I wouldn't distrust them, but I'd verify the data you get from them. The reason that I'd actually use a JSON parser is right in your question:</p>
<blockquote>
<p>My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the "\/" escape sequence â which GC doesn't appear to generate.</p>
</blockquote>
<p>What makes you think that Google Code will never generate an escape sequence like that? </p>
<p>Parsing is a solved problem if you use the right tools. If you try to take shortcuts like this, you'll eventually get bitten by incorrect assumptions, or you'll do something like trying to hack together a parser with regex's and boolean logic when a parser already exists for your language of choice.</p>
| 10 | 2009-07-05T00:40:58Z | [
"python",
"json"
] |
Running JSON through Python's eval()? | 1,083,250 | <p>Best practices aside, is there a compelling reason <strong>not</strong> to do this?</p>
<p>I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confidence that the JSON data is both benign (as there's little point in distrusting Google) and valid.</p>
<p>My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the <code>"\/"</code> escape sequence â which GC doesn't appear to generate.</p>
<p>So, as I'm working with Python 2.4 (i.e. no <code>json</code> module), <code>eval()</code> is looking <em>really</em> tempting.</p>
<p><strong>Edit:</strong> For the record, I am very much <strong>not</strong> asking if this is a good idea. I'm <em>quite</em> aware that it isn't, and I very much doubt I'll ever use this technique for any future projects even if I end up using it for this one. I just wanted to make sure that I know what kind of trouble I'll run into if I do. :-)</p>
| 17 | 2009-07-05T00:35:10Z | 1,083,302 | <p>If you're comfortable with your script working fine for a while, and then randomly failing on some obscure edge case, I would go with eval.</p>
<p>If it's important that your code be robust, I would take the time to add simplejson. You don't need the C portion for speedups, so it really shouldn't be hard to dump a few .py files into a directory somewhere.</p>
<p>As an example of something that might bite you, JSON uses Unicode and simplejson returns Unicode, whereas eval returns str:</p>
<pre><code>>>> simplejson.loads('{"a":1, "b":2}')
{u'a': 1, u'b': 2}
>>> eval('{"a":1, "b":2}')
{'a': 1, 'b': 2}
</code></pre>
<p>Edit: a better example of where eval() behaves differently:</p>
<pre><code>>>> simplejson.loads('{"X": "\uabcd"}')
{u'X': u'\uabcd'}
>>> eval('{"X": "\uabcd"}')
{'X': '\\uabcd'}
>>> simplejson.loads('{"X": "\uabcd"}') == eval('{"X": "\uabcd"}')
False
</code></pre>
<p>Edit 2: saw yet another problem today pointed out by SilentGhost: eval doesn't handle true -> True, false -> False, null -> None correctly.</p>
<pre><code>>>> simplejson.loads('[false, true, null]')
[False, True, None]
>>> eval('[false, true, null]')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'false' is not defined
>>>
</code></pre>
| 24 | 2009-07-05T01:28:43Z | [
"python",
"json"
] |
Running JSON through Python's eval()? | 1,083,250 | <p>Best practices aside, is there a compelling reason <strong>not</strong> to do this?</p>
<p>I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confidence that the JSON data is both benign (as there's little point in distrusting Google) and valid.</p>
<p>My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the <code>"\/"</code> escape sequence â which GC doesn't appear to generate.</p>
<p>So, as I'm working with Python 2.4 (i.e. no <code>json</code> module), <code>eval()</code> is looking <em>really</em> tempting.</p>
<p><strong>Edit:</strong> For the record, I am very much <strong>not</strong> asking if this is a good idea. I'm <em>quite</em> aware that it isn't, and I very much doubt I'll ever use this technique for any future projects even if I end up using it for this one. I just wanted to make sure that I know what kind of trouble I'll run into if I do. :-)</p>
| 17 | 2009-07-05T00:35:10Z | 1,083,318 | <p><code>eval</code>ing JSON is a bit like trying to run XML through a C++ compiler. </p>
<p><code>eval</code> is meant to evaluate Python code. Although there are some syntactical similarities, <strong>JSON isn't Python code</strong>. Heck, not only is it not <em>Python</em> code, it's not code to begin with. Therefore, even if you can get away with it for your use-case, I'd argue that it's a bad idea conceptually. Python is an apple, JSON is orange-flavored soda.</p>
| -2 | 2009-07-05T01:40:50Z | [
"python",
"json"
] |
Running JSON through Python's eval()? | 1,083,250 | <p>Best practices aside, is there a compelling reason <strong>not</strong> to do this?</p>
<p>I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confidence that the JSON data is both benign (as there's little point in distrusting Google) and valid.</p>
<p>My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the <code>"\/"</code> escape sequence â which GC doesn't appear to generate.</p>
<p>So, as I'm working with Python 2.4 (i.e. no <code>json</code> module), <code>eval()</code> is looking <em>really</em> tempting.</p>
<p><strong>Edit:</strong> For the record, I am very much <strong>not</strong> asking if this is a good idea. I'm <em>quite</em> aware that it isn't, and I very much doubt I'll ever use this technique for any future projects even if I end up using it for this one. I just wanted to make sure that I know what kind of trouble I'll run into if I do. :-)</p>
| 17 | 2009-07-05T00:35:10Z | 28,351,359 | <p>One major difference is that a boolean in JSON is <code>true</code>|<code>false</code>, but Python uses <code>True</code>|<code>False</code>.</p>
<p>The most important reason not to do this can be generalized: <code>eval</code> should never be used to interpret external input since this allows for arbitrary code execution.</p>
| 0 | 2015-02-05T18:26:45Z | [
"python",
"json"
] |
Missing datetime.timedelta.to_seconds() -> float in Python? | 1,083,402 | <p>I understand that seconds and microseconds are probably represented separately in <code>datetime.timedelta</code> for efficiency reasons, but I just wrote this simple function:</p>
<pre><code>def to_seconds_float(timedelta):
"""Calculate floating point representation of combined
seconds/microseconds attributes in :param:`timedelta`.
:raise ValueError: If :param:`timedelta.days` is truthy.
>>> to_seconds_float(datetime.timedelta(seconds=1, milliseconds=500))
1.5
>>> too_big = datetime.timedelta(days=1, seconds=12)
>>> to_seconds_float(too_big) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ('Must not have days', datetime.timedelta(1, 12))
"""
if timedelta.days:
raise ValueError('Must not have days', timedelta)
return timedelta.seconds + timedelta.microseconds / 1E6
</code></pre>
<p>This is useful for things like passing a value to <code>time.sleep</code> or <code>select.select</code>. <strong>Why isn't something like this part of the <code>datetime.timedelta</code> interface?</strong> I may be missing some corner case. Time representation seems to have so many non-obvious corner cases...</p>
<p>I rejected days right out to have a reasonable shot at some precision (I'm too lazy to actually work out the math ATM, so this seems like a reasonable compromise ;-).</p>
| 9 | 2009-07-05T03:28:02Z | 1,083,408 | <p>A Python float has about 15 significant digits, so with seconds being up to 86400 (5 digits to the left of the decimal point) and microseconds needing 6 digits, you could well include the days (up to several years' worth) without loss of precision.</p>
<p>A good mantra is "pi seconds is a nanocentury" -- about 3.14E9 seconds per 100 years, i.e. 3E7 per year, so 3E13 microseconds per year. The mantra is good because it's memorable, even though it does require you to do a little mental arithmetic afterwards (but, like spinach, it's GOOD for you -- keeps you nimble and alert!-).</p>
<p>The design philosophy of <code>datetime</code> is somewhat minimalist, so it's not surprising it omits many possible helper methods that boil down to simple arithmetic expressions.</p>
| 12 | 2009-07-05T03:35:44Z | [
"python",
"datetime",
"timedelta"
] |
Missing datetime.timedelta.to_seconds() -> float in Python? | 1,083,402 | <p>I understand that seconds and microseconds are probably represented separately in <code>datetime.timedelta</code> for efficiency reasons, but I just wrote this simple function:</p>
<pre><code>def to_seconds_float(timedelta):
"""Calculate floating point representation of combined
seconds/microseconds attributes in :param:`timedelta`.
:raise ValueError: If :param:`timedelta.days` is truthy.
>>> to_seconds_float(datetime.timedelta(seconds=1, milliseconds=500))
1.5
>>> too_big = datetime.timedelta(days=1, seconds=12)
>>> to_seconds_float(too_big) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: ('Must not have days', datetime.timedelta(1, 12))
"""
if timedelta.days:
raise ValueError('Must not have days', timedelta)
return timedelta.seconds + timedelta.microseconds / 1E6
</code></pre>
<p>This is useful for things like passing a value to <code>time.sleep</code> or <code>select.select</code>. <strong>Why isn't something like this part of the <code>datetime.timedelta</code> interface?</strong> I may be missing some corner case. Time representation seems to have so many non-obvious corner cases...</p>
<p>I rejected days right out to have a reasonable shot at some precision (I'm too lazy to actually work out the math ATM, so this seems like a reasonable compromise ;-).</p>
| 9 | 2009-07-05T03:28:02Z | 1,083,613 | <p>Your concern for precision is misplaced. Here's a simple two-liner to calculate roughly how many YEARS you can squeeze into what's left of the 53 bits of precsion in an IEEE754 64-bit float:</p>
<pre><code>>>> import math
>>> 10 ** (math.log10(2 ** 53) - math.log10(60 * 60 * 24) - 6) / 365.25
285.42092094268787
>>>
</code></pre>
<p>Watch out for round-off; add the smallest non-zero numbers first:</p>
<pre><code>return timedelta.seconds + timedelta.microseconds / 1E6 + timedelta.days * 86400
</code></pre>
| 3 | 2009-07-05T07:17:38Z | [
"python",
"datetime",
"timedelta"
] |
Get brief human-readable info about XRI OpenID with Python? | 1,083,435 | <p>I'd like to be able to tell to the site visitor that comes with his/her OpenID: <strong>you are using your XYZ id for the first time on mysite - please create your sceen name</strong>, where XYZ is a nice token that makes sense. For example - XYZ could be the provider name.</p>
<p>I'd like to find a solution that works for OpenID as defined in the standard - i.e. work for <strong>XRI</strong> type of ID - extensible resource identifier.</p>
<p>urlparse (as suggested by RichieHindle) works for url-type openid, but does not work in general, e.g. for <strong>i-name</strong> IDs like "=somename". There are many other forms of valid OpenID string that don't even closely look like url.</p>
<p>Thanks.</p>
| 0 | 2009-07-05T04:11:45Z | 1,083,594 | <p>Since OpenIDs are URLs, this might be the cleanest way in the absence of built-in support in Janrain:</p>
<pre><code>from urlparse import urlparse
openid_str = "http://myprovider/myname" # str(openid_obj)
parts = urlparse(openid_str)
provider_name = parts[1]
print (provider_name) # Prints myprovider
</code></pre>
| 3 | 2009-07-05T06:53:12Z | [
"python",
"openid",
"janrain",
"xri"
] |
How to handle back and forward buttons in the hildon.Seekbar? | 1,083,905 | <p>The <a href="http://maemo.org/development/documentation/apis/3-x/python-maemo-3.x/pyhildon%5Fseekbar/" rel="nofollow">hildon.Seekbar</a> widget consists of a scale widget and two buttons. What signals does the widget send when the buttons are clicked or how could I find out? Is there a way to monitor <strong>all</strong> signals/events that a widget sends in PyGTK?</p>
| 2 | 2009-07-05T11:40:35Z | 1,086,608 | <p>The documentation you linked to shows this:</p>
<pre><code>seekbar.connect("value-changed", control_changed, label)
seekbar.connect("notify::fraction", fraction_changed, label)
</code></pre>
<p>So it seems it has (at least) two signals called "value-changed" and "notify::fraction". It also shows an inheritance diagram that tells you that the Seekbar inherits the standard GTK+ <a href="http://library.gnome.org/devel/gtk/stable/GtkScale.html" rel="nofollow">Scale</a> widget, which is where the first signal comes from (by further inheritance).</p>
<p>Not sure where the "notify::fraction" signal comes from, though.</p>
| 1 | 2009-07-06T11:57:06Z | [
"python",
"gtk",
"pygtk",
"maemo",
"seekbar"
] |
How to handle back and forward buttons in the hildon.Seekbar? | 1,083,905 | <p>The <a href="http://maemo.org/development/documentation/apis/3-x/python-maemo-3.x/pyhildon%5Fseekbar/" rel="nofollow">hildon.Seekbar</a> widget consists of a scale widget and two buttons. What signals does the widget send when the buttons are clicked or how could I find out? Is there a way to monitor <strong>all</strong> signals/events that a widget sends in PyGTK?</p>
| 2 | 2009-07-05T11:40:35Z | 1,915,536 | <p>gobjects have a way of notifying about property changes and it does this with signals. So connecting to notify::property gets you changes to property.</p>
| 0 | 2009-12-16T15:51:16Z | [
"python",
"gtk",
"pygtk",
"maemo",
"seekbar"
] |
using registered com object dll from .NET | 1,083,913 | <p>I implemented a python com server and generate an executable and dll using py2exe tool.
then I used regsvr32.exe to register the dll.I got a message that the registration was successful. Then I tried to add reference to that dll in .NET. I browsed to the dll location and select it, but I got an error message box that says: A reference to the dll could not be added, please make sure that the file is accessible and that it is a valid assembly or COM component.The code of the server and setup script is added below.
I want to mention that I can run the server as a python script and consume it from .net using late binding.
Is there something I'm missing or doing wrong? I would appreciate any help.</p>
<p>thanks,
Sarah</p>
<h1>hello.py</h1>
<pre><code>import pythoncom
import sys
class HelloWorld:
#pythoncom.frozen = 1
if hasattr(sys, 'importers'):
_reg_class_spec_ = "__main__.HelloWorld"
_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
_reg_clsid_ = pythoncom.CreateGuid()
_reg_desc_ = "Python Test COM Server"
_reg_progid_ = "Python.TestServer"
_public_methods_ = ['Hello']
_public_attrs_ = ['softspace', 'noCalls']
_readonly_attrs_ = ['noCalls']
def __init__(self):
self.softspace = 1
self.noCalls = 0
def Hello(self, who):
self.noCalls = self.noCalls + 1
# insert "softspace" number of spaces
print "Hello" + " " * self.softspace + str(who)
return "Hello" + " " * self.softspace + str(who)
if __name__=='__main__':
import sys
if hasattr(sys, 'importers'):
# running as packed executable.
if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]:
# --register and --unregister work as usual
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
else:
# start the server.
from win32com.server import localserver
localserver.main()
else:
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
</code></pre>
<h1>setup.py</h1>
<pre><code>from distutils.core import setup
import py2exe
setup(com_server = ["hello"])
</code></pre>
| 2 | 2009-07-05T11:48:47Z | 1,083,993 | <p>If you want to use a registered <strong>Com</strong> object, you need to find it on the Com tab in the <a href="http://msdn.microsoft.com/en-us/library/wkze6zky.aspx" rel="nofollow">Add Reference</a> dialog box. You do not navigate to the dll.</p>
| 0 | 2009-07-05T12:38:44Z | [
".net",
"python",
"com",
"py2exe"
] |
using registered com object dll from .NET | 1,083,913 | <p>I implemented a python com server and generate an executable and dll using py2exe tool.
then I used regsvr32.exe to register the dll.I got a message that the registration was successful. Then I tried to add reference to that dll in .NET. I browsed to the dll location and select it, but I got an error message box that says: A reference to the dll could not be added, please make sure that the file is accessible and that it is a valid assembly or COM component.The code of the server and setup script is added below.
I want to mention that I can run the server as a python script and consume it from .net using late binding.
Is there something I'm missing or doing wrong? I would appreciate any help.</p>
<p>thanks,
Sarah</p>
<h1>hello.py</h1>
<pre><code>import pythoncom
import sys
class HelloWorld:
#pythoncom.frozen = 1
if hasattr(sys, 'importers'):
_reg_class_spec_ = "__main__.HelloWorld"
_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
_reg_clsid_ = pythoncom.CreateGuid()
_reg_desc_ = "Python Test COM Server"
_reg_progid_ = "Python.TestServer"
_public_methods_ = ['Hello']
_public_attrs_ = ['softspace', 'noCalls']
_readonly_attrs_ = ['noCalls']
def __init__(self):
self.softspace = 1
self.noCalls = 0
def Hello(self, who):
self.noCalls = self.noCalls + 1
# insert "softspace" number of spaces
print "Hello" + " " * self.softspace + str(who)
return "Hello" + " " * self.softspace + str(who)
if __name__=='__main__':
import sys
if hasattr(sys, 'importers'):
# running as packed executable.
if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]:
# --register and --unregister work as usual
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
else:
# start the server.
from win32com.server import localserver
localserver.main()
else:
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
</code></pre>
<h1>setup.py</h1>
<pre><code>from distutils.core import setup
import py2exe
setup(com_server = ["hello"])
</code></pre>
| 2 | 2009-07-05T11:48:47Z | 1,084,886 | <p>The line:</p>
<pre><code>_reg_clsid_ = pythoncom.CreateGuid()
</code></pre>
<p>creates a new GUID everytime this file is called. You can create a GUID on the command line:</p>
<pre><code>C:\>python -c "import pythoncom; print pythoncom.CreateGuid()"
{C86B66C2-408E-46EA-845E-71626F94D965}
</code></pre>
<p>and then change your line:</p>
<pre><code>_reg_clsid_ = "{C86B66C2-408E-46EA-845E-71626F94D965}"
</code></pre>
<p>After making this change, I was able to run your code and test it with the following VBScript:</p>
<pre><code>Set obj = CreateObject("Python.TestServer")
MsgBox obj.Hello("foo")
</code></pre>
<p>I don't have MSVC handy to see if this fixes the "add reference" problem.</p>
| 2 | 2009-07-05T21:45:35Z | [
".net",
"python",
"com",
"py2exe"
] |
using registered com object dll from .NET | 1,083,913 | <p>I implemented a python com server and generate an executable and dll using py2exe tool.
then I used regsvr32.exe to register the dll.I got a message that the registration was successful. Then I tried to add reference to that dll in .NET. I browsed to the dll location and select it, but I got an error message box that says: A reference to the dll could not be added, please make sure that the file is accessible and that it is a valid assembly or COM component.The code of the server and setup script is added below.
I want to mention that I can run the server as a python script and consume it from .net using late binding.
Is there something I'm missing or doing wrong? I would appreciate any help.</p>
<p>thanks,
Sarah</p>
<h1>hello.py</h1>
<pre><code>import pythoncom
import sys
class HelloWorld:
#pythoncom.frozen = 1
if hasattr(sys, 'importers'):
_reg_class_spec_ = "__main__.HelloWorld"
_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
_reg_clsid_ = pythoncom.CreateGuid()
_reg_desc_ = "Python Test COM Server"
_reg_progid_ = "Python.TestServer"
_public_methods_ = ['Hello']
_public_attrs_ = ['softspace', 'noCalls']
_readonly_attrs_ = ['noCalls']
def __init__(self):
self.softspace = 1
self.noCalls = 0
def Hello(self, who):
self.noCalls = self.noCalls + 1
# insert "softspace" number of spaces
print "Hello" + " " * self.softspace + str(who)
return "Hello" + " " * self.softspace + str(who)
if __name__=='__main__':
import sys
if hasattr(sys, 'importers'):
# running as packed executable.
if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]:
# --register and --unregister work as usual
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
else:
# start the server.
from win32com.server import localserver
localserver.main()
else:
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
</code></pre>
<h1>setup.py</h1>
<pre><code>from distutils.core import setup
import py2exe
setup(com_server = ["hello"])
</code></pre>
| 2 | 2009-07-05T11:48:47Z | 1,152,106 | <p>I will answer my question to help any one may have similar questions. I hope that would help.
I can not find my server on the COM tab because, .NET (& Visual-Studio) need COM servers with TLB. But Python's COM servers have no TLB.
So to use the server from .NET by (C# and Late binding). The following code shows how to make this:</p>
<p>// the C# code</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Type pythonServer;
object pythonObject;
pythonServer = Type.GetTypeFromProgID("PythonDemos.Utilities");
pythonObject = Activator.CreateInstance(pythonServer);
}
}
} `
</code></pre>
| 2 | 2009-07-20T07:25:19Z | [
".net",
"python",
"com",
"py2exe"
] |
Best way to programatically create image | 1,083,943 | <p>I'm looking for a way to create a graphics file (I don't really mind the file type, as they are easily converted).</p>
<p>The input would be the desired resolution, and a list of pixels and colors (x, y, RGB color).</p>
<p>Is there a convenient python library for that? What are the pros\cons\pitfalls?</p>
<p>Udi</p>
| 2 | 2009-07-05T12:03:30Z | 1,083,946 | <p><a href="http://www.pythonware.com/products/pil/">PIL</a> is the canonical Python Imaging Library.</p>
<p>Pros: Everybody wanting to do what you're doing uses PIL. 8-)</p>
<p>Cons: None springs to mind.</p>
| 5 | 2009-07-05T12:04:48Z | [
"python",
"graphics",
"python-imaging-library"
] |
Best way to programatically create image | 1,083,943 | <p>I'm looking for a way to create a graphics file (I don't really mind the file type, as they are easily converted).</p>
<p>The input would be the desired resolution, and a list of pixels and colors (x, y, RGB color).</p>
<p>Is there a convenient python library for that? What are the pros\cons\pitfalls?</p>
<p>Udi</p>
| 2 | 2009-07-05T12:03:30Z | 1,084,405 | <p>Alternatively, you can try <a href="http://www.imagemagick.org/script/api.php#python" rel="nofollow">ImageMagick</a>.
Last time I checked, PIL didn't work on Python 3, which is potentially a con. (I don't know about ImageMagick's API.) I believe an updated version of PIL is expected in the year.</p>
| 0 | 2009-07-05T16:41:22Z | [
"python",
"graphics",
"python-imaging-library"
] |
How to get an xpathContext from an xmlNode in python | 1,084,058 | <p>big fan of xpath on .net, and sax in python, but first time using xpath in python.</p>
<p>I have a small script, that uses xpath to select some nodes from a doc, iterates through them, and then ideally uses xpath again to get the relevant data from them. However I can't get that last bit, once I have the xmlNode I cannot get a context from it.</p>
<pre><code>import libxml2
import urllib
doc = libxml2.parseDoc(
urllib.urlopen('http://somemagicwebservice.com/').read())
ctxt = doc.xpathNewContext()
listitems = ctxt.xpathEval('//List/ListItem')
for item in listitems:
itemctxt = item.xpathNewContext()
title = itemctxt.xpathEval('//ItemAttributes/Title')
asin = itemctxt.xpathEval('//Item/ASIN')
itemctxc.xpathFreeContext()
ctxt.xpathFreeContext()
doc.freeDoc()
</code></pre>
<p>However the <code>itemctxt = item.xpathNewContext()</code> bit fails with </p>
<pre><code>itemctxt = item.xpathNewContext()
AttributeError: xmlNode instance has no attribute 'xpathNewContext'
</code></pre>
<p>Any ideas how to use xpath on a xmlNode? I can't find any good online info.
Thanks</p>
| 2 | 2009-07-05T13:27:21Z | 1,084,119 | <p>I don't think an XPathContext makes sense on an element? Try creating a new XPathContext, and setting it's node to the current element.</p>
<p>That said, I haven't used libxml2 directly, so it's a bit of a wild guess. I typically uses lxml, that exposes an ElementTree API around libxml2 and libxslt. It's much easier to use, and does indeed allow xpath() on elements. Of course, if you already have a lot of code using libxml2 you probably don't want to switch, but in that case you might want to take a look at lxmls source to see how it does it.</p>
<p><a href="http://codespeak.net/svn/lxml/trunk/src/lxml/xpath.pxi" rel="nofollow">http://codespeak.net/svn/lxml/trunk/src/lxml/xpath.pxi</a></p>
<p><a href="http://codespeak.net/svn/lxml/trunk/src/lxml/_elementpath.py" rel="nofollow">http://codespeak.net/svn/lxml/trunk/src/lxml/_elementpath.py</a></p>
<p>Seems good starting places.</p>
| 2 | 2009-07-05T14:06:19Z | [
"python",
"xpath",
"xmlnode"
] |
How to get an xpathContext from an xmlNode in python | 1,084,058 | <p>big fan of xpath on .net, and sax in python, but first time using xpath in python.</p>
<p>I have a small script, that uses xpath to select some nodes from a doc, iterates through them, and then ideally uses xpath again to get the relevant data from them. However I can't get that last bit, once I have the xmlNode I cannot get a context from it.</p>
<pre><code>import libxml2
import urllib
doc = libxml2.parseDoc(
urllib.urlopen('http://somemagicwebservice.com/').read())
ctxt = doc.xpathNewContext()
listitems = ctxt.xpathEval('//List/ListItem')
for item in listitems:
itemctxt = item.xpathNewContext()
title = itemctxt.xpathEval('//ItemAttributes/Title')
asin = itemctxt.xpathEval('//Item/ASIN')
itemctxc.xpathFreeContext()
ctxt.xpathFreeContext()
doc.freeDoc()
</code></pre>
<p>However the <code>itemctxt = item.xpathNewContext()</code> bit fails with </p>
<pre><code>itemctxt = item.xpathNewContext()
AttributeError: xmlNode instance has no attribute 'xpathNewContext'
</code></pre>
<p>Any ideas how to use xpath on a xmlNode? I can't find any good online info.
Thanks</p>
| 2 | 2009-07-05T13:27:21Z | 32,629,090 | <p><a href="http://stackoverflow.com/a/3379708/288875">http://stackoverflow.com/a/3379708/288875</a> suggests to call <code>setContextNode(..)</code> on a newly created context:</p>
<pre><code>itemctxt = doc.xpathNewContext()
for item in listitems:
itemctxt.setContextNode(item)
title = itemctxt.xpathEval('.//ItemAttributes/Title')
...
itemctxt.xpathFreeContext()
</code></pre>
<p>In the version of python libxml (2.9.1) which I'm currently using it turns out that one can even call:</p>
<pre><code>item.xpathEval('.//ItemAttributes/Title')
</code></pre>
<p>Note that you'll have to add a dot at the beginning of the xpath expressions <code>.//</code> (instead of <code>//</code>), otherwise you'll get search results relative to the document root.</p>
| 1 | 2015-09-17T11:20:23Z | [
"python",
"xpath",
"xmlnode"
] |
Make your program USE a gui | 1,084,514 | <p>I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen.</p>
<p>I used <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much with it :P </p>
<p>So... I need to:</p>
<ul>
<li>Take screenshots, then I will compare them to make the program "understand", but it needs to "see"</li>
<li>Use the mouse: move, click and release, it's simple, isn't it?</li>
<li>Using the keyboard: pressing some keys, or key combinations, including special keys like <kbd>Alt</kbd>,<kbd>Ctrl</kbd> etc...</li>
</ul>
<p>How can I do that in python?<br/>
Does it works in both linux and windows? (this could be really really cool, but it is not necessary)</p>
| 2 | 2009-07-05T17:52:25Z | 1,084,677 | <p>You can use <a href="http://www.tizmoi.net/watsup/intro.html" rel="nofollow">WATSUP</a> under Windows.</p>
| 2 | 2009-07-05T19:32:24Z | [
"python",
"user-interface",
"remote-control"
] |
Make your program USE a gui | 1,084,514 | <p>I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen.</p>
<p>I used <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much with it :P </p>
<p>So... I need to:</p>
<ul>
<li>Take screenshots, then I will compare them to make the program "understand", but it needs to "see"</li>
<li>Use the mouse: move, click and release, it's simple, isn't it?</li>
<li>Using the keyboard: pressing some keys, or key combinations, including special keys like <kbd>Alt</kbd>,<kbd>Ctrl</kbd> etc...</li>
</ul>
<p>How can I do that in python?<br/>
Does it works in both linux and windows? (this could be really really cool, but it is not necessary)</p>
| 2 | 2009-07-05T17:52:25Z | 1,084,773 | <p>I've used the Windows (only) <a href="http://msdn.microsoft.com/en-us/library/ms646310%28VS.85%29.aspx" rel="nofollow">Input API</a> to write a VNC-like remote-control application in the past. It lets you fake keyboard and mouse input nicely at a system level (ie not just posting events to a single application).</p>
<p>If you're trying to do any sort of automated testing of whole systems at the GUI level, <a href="http://www.usenix.org/event/usenix05/tech/freenix/full%5Fpapers/zeldovich/zeldovich%5Fhtml/index.html" rel="nofollow">this excellent USENIX paper</a> describing automated responsiveness testing is a must-read.</p>
| 0 | 2009-07-05T20:34:32Z | [
"python",
"user-interface",
"remote-control"
] |
Make your program USE a gui | 1,084,514 | <p>I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen.</p>
<p>I used <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much with it :P </p>
<p>So... I need to:</p>
<ul>
<li>Take screenshots, then I will compare them to make the program "understand", but it needs to "see"</li>
<li>Use the mouse: move, click and release, it's simple, isn't it?</li>
<li>Using the keyboard: pressing some keys, or key combinations, including special keys like <kbd>Alt</kbd>,<kbd>Ctrl</kbd> etc...</li>
</ul>
<p>How can I do that in python?<br/>
Does it works in both linux and windows? (this could be really really cool, but it is not necessary)</p>
| 2 | 2009-07-05T17:52:25Z | 1,085,111 | <p>If you are comfortable with pascal, a really powerful keyboard/mouse/screen-reading program is SCAR: <a href="http://freddy1990.com/index.php?page=product&name=scar" rel="nofollow">http://freddy1990.com/index.php?page=product&name=scar</a> It can do OCR, bitmap finding, color finding, etc. It's often used for automating online games, but it can be used for any situation where you want to simulate a human reading the screen and giving input.</p>
| 1 | 2009-07-06T01:55:26Z | [
"python",
"user-interface",
"remote-control"
] |
Make your program USE a gui | 1,084,514 | <p>I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen.</p>
<p>I used <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much with it :P </p>
<p>So... I need to:</p>
<ul>
<li>Take screenshots, then I will compare them to make the program "understand", but it needs to "see"</li>
<li>Use the mouse: move, click and release, it's simple, isn't it?</li>
<li>Using the keyboard: pressing some keys, or key combinations, including special keys like <kbd>Alt</kbd>,<kbd>Ctrl</kbd> etc...</li>
</ul>
<p>How can I do that in python?<br/>
Does it works in both linux and windows? (this could be really really cool, but it is not necessary)</p>
| 2 | 2009-07-05T17:52:25Z | 1,085,936 | <p>I've had some luck with similar tasks using <a href="http://pywinauto.openqa.org/" rel="nofollow">PyWinAuto</a>.</p>
<blockquote>
<p>pywinauto is a set of python modules
to automate the Microsoft Windows GUI.
At it's simplest it allows you to send
mouse and keyboard actions to windows
dialogs and controls.</p>
</blockquote>
<p>It also has some support for capturing images of dialogs and such using the Python Imaging Library <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>.</p>
| 2 | 2009-07-06T08:14:54Z | [
"python",
"user-interface",
"remote-control"
] |
Make your program USE a gui | 1,084,514 | <p>I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen.</p>
<p>I used <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much with it :P </p>
<p>So... I need to:</p>
<ul>
<li>Take screenshots, then I will compare them to make the program "understand", but it needs to "see"</li>
<li>Use the mouse: move, click and release, it's simple, isn't it?</li>
<li>Using the keyboard: pressing some keys, or key combinations, including special keys like <kbd>Alt</kbd>,<kbd>Ctrl</kbd> etc...</li>
</ul>
<p>How can I do that in python?<br/>
Does it works in both linux and windows? (this could be really really cool, but it is not necessary)</p>
| 2 | 2009-07-05T17:52:25Z | 1,092,401 | <p>AutoIt is completely capable of doing everything you mentioned. When I'm wanting to do some automation but use the features of Python, I find it easiest to use <a href="http://www.google.com/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.autoitscript.com%2Fautoit3%2Fdownloads.shtml&ei=Yk9TSsOsDYnWNfza6fQI&usg=AFQjCNEBCnVe6pRuxIzX%5FUE4U%5F3O8SVYOg&sig2=t4kpjNbgspeikHz2SBkIGg" rel="nofollow">AutoItX</a> which is a DLL/COM control.</p>
<p>Taken from <a href="http://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python/155587#155587">this answer</a> of mine:</p>
<pre><code>import win32com.client
oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" )
oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title
width = oAutoItX.WinGetClientSizeWidth("Firefox")
height = oAutoItX.WinGetClientSizeHeight("Firefox")
print width, height
</code></pre>
| 2 | 2009-07-07T13:39:50Z | [
"python",
"user-interface",
"remote-control"
] |
Getting a dict out of a method? | 1,084,566 | <p>I'm trying to get a <code>dict</code> out of a method, so far I'm able to get the method name, and its arguments (using the inspect module), the problem I'm facing is that I'd like to have the default arguments too (or the argument type).</p>
<p>This is basically my unit test:</p>
<pre><code>class Test:
def method1(anon_type, array=[], string="string", integer=12, obj=None):
pass
target = {"method1": [
{"anon": "None"},
{"array": "[]"},
{"string": "str"},
{"integer": "int"},
{"obj": "None"}]
}
method1_dict = get_method_dict(Test().method1)
self.assertEqual(target, method1_dict)
</code></pre>
<p>Here, I try to use <em>inspect</em> to get the method:</p>
<pre><code>>>> import inspect
>>> class Class:
... def method(self, string='str', integer=12):
... pass
...
>>> m_desc = inspect.getargspec(Class().method)
>>> m_desc
ArgSpec(args=['self', 'string', 'integer'], varargs=None, keywords=None, defaults=('str', 12))
>>>
</code></pre>
<p>but my problem is with the <em>default args</em>, as you see here:</p>
<pre><code>>>> class Class:
... def method(self, no_def_args, string='str', integer=12):
... pass
...
>>> m_desc = inspect.getargspec(Class().method)
>>> m_desc
ArgSpec(args=['self', 'no_def_args', 'string', 'integer'], varargs=None, keywords=None, defaults=('str', 12))
</code></pre>
<p>As you see the <code>no_def_args</code> is not in the defaults, so it's a problem to try to match the argument with their default arguments.</p>
| 1 | 2009-07-05T18:17:23Z | 1,084,599 | <p>what exactly is the problem? all arguments are ordered, keyword arguments should be the last in definition. do you know how to slice a list?</p>
| 2 | 2009-07-05T18:33:38Z | [
"python"
] |
Getting a dict out of a method? | 1,084,566 | <p>I'm trying to get a <code>dict</code> out of a method, so far I'm able to get the method name, and its arguments (using the inspect module), the problem I'm facing is that I'd like to have the default arguments too (or the argument type).</p>
<p>This is basically my unit test:</p>
<pre><code>class Test:
def method1(anon_type, array=[], string="string", integer=12, obj=None):
pass
target = {"method1": [
{"anon": "None"},
{"array": "[]"},
{"string": "str"},
{"integer": "int"},
{"obj": "None"}]
}
method1_dict = get_method_dict(Test().method1)
self.assertEqual(target, method1_dict)
</code></pre>
<p>Here, I try to use <em>inspect</em> to get the method:</p>
<pre><code>>>> import inspect
>>> class Class:
... def method(self, string='str', integer=12):
... pass
...
>>> m_desc = inspect.getargspec(Class().method)
>>> m_desc
ArgSpec(args=['self', 'string', 'integer'], varargs=None, keywords=None, defaults=('str', 12))
>>>
</code></pre>
<p>but my problem is with the <em>default args</em>, as you see here:</p>
<pre><code>>>> class Class:
... def method(self, no_def_args, string='str', integer=12):
... pass
...
>>> m_desc = inspect.getargspec(Class().method)
>>> m_desc
ArgSpec(args=['self', 'no_def_args', 'string', 'integer'], varargs=None, keywords=None, defaults=('str', 12))
</code></pre>
<p>As you see the <code>no_def_args</code> is not in the defaults, so it's a problem to try to match the argument with their default arguments.</p>
| 1 | 2009-07-05T18:17:23Z | 1,084,624 | <p>Here is what I usually do:</p>
<pre><code>import inspect, itertools
args, varargs, keywords, defaults = inspect.getargspec(method1)
print dict(itertools.izip_longest(args[::-1], defaults[::-1], fillvalue=None))
</code></pre>
<p>--></p>
<pre><code>{'integer': 12, 'array': [], 'anon_type': None, 'obj': None, 'string': 'string'}
</code></pre>
<p>This will only work on python2.6</p>
| 1 | 2009-07-05T18:50:01Z | [
"python"
] |
Django Database Caching | 1,084,569 | <p>I'm working on a small project, and I wanted to provide multiple caching options to the end user. I figured with Django it's pretty simplistic to swap memcached for database or file based caching. My memcached implementation works like a champ without any issues. I placed time stamps on my pages, and curl consistently shows the older timestamps in locations where I want caching to work properly. However, when I switch over to the database caching, I don't get any entries in the database, and caching blatantly doesn't work. </p>
<p>From what I see in the documentation all that should be necessary is to change the backend from:</p>
<pre><code>CACHE_BACKEND = 'memcached://localhost:11211'
</code></pre>
<p>To:</p>
<pre><code>CACHE_BACKEND = 'db://cache_table'
</code></pre>
<p>The table exists after running the required manage.py (createcachetable) line, and I can view it just fine. I'm currently in testing, so I am using sqlite3, but that shouldn't matter as far as I can tell. I can confirm that the table is completely empty, and hasn't been written to at any point. Also, as I stated previously, my timestamps are 'wrong' as well, giving me more evidence that something isn't quite right. </p>
<p>Any thoughts? I'm using sqlite3, Django 1.0.2, python 2.6, serving via Apache currently on an Ubuntu Jaunty machine. I'm sure I'm just glossing over something simple. Thanks for any help provided.</p>
| 3 | 2009-07-05T18:19:09Z | 1,084,583 | <p>According to the documentation you're supposed to create the table not by using syncdb but with the following:</p>
<pre><code>python manage.py createcachetable cache_table
</code></pre>
<p>If you haven't done that, try and see if it doesn't work.</p>
| 7 | 2009-07-05T18:30:48Z | [
"python",
"django",
"django-cache"
] |
Python: deep appending to dictionary? - in a single expression | 1,084,678 | <p>How do I, in a <strong>single expression</strong>, get a dictionary
where one key-value pair has been added to a sub-dictionary
in some input dictionary? The input dictionary should be left unchanged. It
can be assumed the sub-dictionary does exist and that the new key-value pair is not already in the sub-dictionary.</p>
<p><strong>Update 2</strong> (see below for definition of "SOsurvivalConditions", etc.):</p>
<p>The most concise way is:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>Update 1</strong> :</p>
<p>This meets the given requirements and does not have the
side-effect of modifying the input dictionary:</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
<p>However the more concise (but statement only) way can
be adapted with a helper function, e.g.:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr>
<p>The Example:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>'firstCondition' in SOsurvivalConditions now has two key-value pairs.
A new key-value pair, ('synonym', 'A modern form of RTFM is: Google It.'),
needs to be appended and the result should be available in a single expression.</p>
<p>This works (one line, but broken into several here):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>and returns:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>However there is a lot of redundancy in this
expression - all keys are repeated. And 'firstCondition' appears two times. Is there a more
elegant way?</p>
<p>(The names and the content of the datastructures here are made up, but represent a real problem I encountered today. Python version: 2.6.2.).</p>
| 8 | 2009-07-05T19:33:01Z | 1,084,688 | <pre><code>SOsurvivalConditions['firstCondition']['synonym'] = 'A modern form of RTFM is: Google It.'
</code></pre>
| 5 | 2009-07-05T19:39:11Z | [
"python"
] |
Python: deep appending to dictionary? - in a single expression | 1,084,678 | <p>How do I, in a <strong>single expression</strong>, get a dictionary
where one key-value pair has been added to a sub-dictionary
in some input dictionary? The input dictionary should be left unchanged. It
can be assumed the sub-dictionary does exist and that the new key-value pair is not already in the sub-dictionary.</p>
<p><strong>Update 2</strong> (see below for definition of "SOsurvivalConditions", etc.):</p>
<p>The most concise way is:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>Update 1</strong> :</p>
<p>This meets the given requirements and does not have the
side-effect of modifying the input dictionary:</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
<p>However the more concise (but statement only) way can
be adapted with a helper function, e.g.:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr>
<p>The Example:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>'firstCondition' in SOsurvivalConditions now has two key-value pairs.
A new key-value pair, ('synonym', 'A modern form of RTFM is: Google It.'),
needs to be appended and the result should be available in a single expression.</p>
<p>This works (one line, but broken into several here):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>and returns:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>However there is a lot of redundancy in this
expression - all keys are repeated. And 'firstCondition' appears two times. Is there a more
elegant way?</p>
<p>(The names and the content of the datastructures here are made up, but represent a real problem I encountered today. Python version: 2.6.2.).</p>
| 8 | 2009-07-05T19:33:01Z | 1,084,691 | <p>Are you looking for <code>dict.update</code> (documentation <a href="http://docs.python.org/library/stdtypes.html#dict.update" rel="nofollow">here</a>)?</p>
<pre><code>SOsurvivalConditions['firstCondition'].update({'synonym': 'A modern form of RTFM is: Google It.'})
</code></pre>
<p>is what, I think, you want.</p>
| 2 | 2009-07-05T19:39:54Z | [
"python"
] |
Python: deep appending to dictionary? - in a single expression | 1,084,678 | <p>How do I, in a <strong>single expression</strong>, get a dictionary
where one key-value pair has been added to a sub-dictionary
in some input dictionary? The input dictionary should be left unchanged. It
can be assumed the sub-dictionary does exist and that the new key-value pair is not already in the sub-dictionary.</p>
<p><strong>Update 2</strong> (see below for definition of "SOsurvivalConditions", etc.):</p>
<p>The most concise way is:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>Update 1</strong> :</p>
<p>This meets the given requirements and does not have the
side-effect of modifying the input dictionary:</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
<p>However the more concise (but statement only) way can
be adapted with a helper function, e.g.:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr>
<p>The Example:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>'firstCondition' in SOsurvivalConditions now has two key-value pairs.
A new key-value pair, ('synonym', 'A modern form of RTFM is: Google It.'),
needs to be appended and the result should be available in a single expression.</p>
<p>This works (one line, but broken into several here):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>and returns:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>However there is a lot of redundancy in this
expression - all keys are repeated. And 'firstCondition' appears two times. Is there a more
elegant way?</p>
<p>(The names and the content of the datastructures here are made up, but represent a real problem I encountered today. Python version: 2.6.2.).</p>
| 8 | 2009-07-05T19:33:01Z | 1,084,736 | <p>This works, but it's not pretty, and I think you are probably going too far with your lambda/oneliner/whatever you are trying to do :)</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
| 1 | 2009-07-05T20:11:19Z | [
"python"
] |
Python: deep appending to dictionary? - in a single expression | 1,084,678 | <p>How do I, in a <strong>single expression</strong>, get a dictionary
where one key-value pair has been added to a sub-dictionary
in some input dictionary? The input dictionary should be left unchanged. It
can be assumed the sub-dictionary does exist and that the new key-value pair is not already in the sub-dictionary.</p>
<p><strong>Update 2</strong> (see below for definition of "SOsurvivalConditions", etc.):</p>
<p>The most concise way is:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>Update 1</strong> :</p>
<p>This meets the given requirements and does not have the
side-effect of modifying the input dictionary:</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
<p>However the more concise (but statement only) way can
be adapted with a helper function, e.g.:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr>
<p>The Example:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>'firstCondition' in SOsurvivalConditions now has two key-value pairs.
A new key-value pair, ('synonym', 'A modern form of RTFM is: Google It.'),
needs to be appended and the result should be available in a single expression.</p>
<p>This works (one line, but broken into several here):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>and returns:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>However there is a lot of redundancy in this
expression - all keys are repeated. And 'firstCondition' appears two times. Is there a more
elegant way?</p>
<p>(The names and the content of the datastructures here are made up, but represent a real problem I encountered today. Python version: 2.6.2.).</p>
| 8 | 2009-07-05T19:33:01Z | 1,084,946 | <p>Here's one that does meet your peculiar specs (to within the ambiguity with which you've specified them):</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p>This does modify the initial data structures (rather than creating new ones, as @truppo's answer does), and is also an expression returning the overall dictionary (rather than being a statement, like @Evan's answer, or returning None, like @Seth's).</p>
<p>Of course many variants are possible (if you want the new entry to override an existing one with the same key 'synonym', rather than leave any such existing entry alone, you could use <code>__setitem__</code> instead of <code>setdefault</code>, for example -- it's hard to guess what you want to happen in such corner cases, as your initial specs are so desperately ambiguous and there's no "real use case" context given to help disambiguate them).</p>
<p><strong>Edit</strong>: with use case now clarified in comments (no changing the original data structures, and an expression is indeed needed, but a helper function would be OK) here's what I would suggest:</p>
<pre><code>def addSubEntry(mainDict, outerKey, innerKey, innerValue):
# copy inner and outer dicts to avoid altering initial data
result = dict(mainDict)
inner = dict(result.get(outerKey, {}))
inner[innerKey] = innerValue
result[outerKey] = inner
return result
</code></pre>
<p>and as the desired expression, use:</p>
<pre><code>addSubEntry(SOsurvivalConditions, 'firstCondition', 'synonym', 'A modern form of RTFM is: Google It.')
</code></pre>
<p>Several variants are possible depending on the exact behavior desired in corner cases. This version adds a new dictionary (with just the given inner key-value pair) if there was previously no entry with the given outer-key; if there <em>was</em> such a previous entry, it tries to make it into a dict (even if it was, say, a list of key-value tuples), raising an exception if that's just unfeasible. A stricter version (demanding that the inner entry already existed and was a dict or dict-like object, raising exception instead) might instead use</p>
<pre><code>inner = result[outerKey].copy()
</code></pre>
<p>as the second statement in the body.</p>
| 3 | 2009-07-05T22:21:17Z | [
"python"
] |
Python: deep appending to dictionary? - in a single expression | 1,084,678 | <p>How do I, in a <strong>single expression</strong>, get a dictionary
where one key-value pair has been added to a sub-dictionary
in some input dictionary? The input dictionary should be left unchanged. It
can be assumed the sub-dictionary does exist and that the new key-value pair is not already in the sub-dictionary.</p>
<p><strong>Update 2</strong> (see below for definition of "SOsurvivalConditions", etc.):</p>
<p>The most concise way is:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>Update 1</strong> :</p>
<p>This meets the given requirements and does not have the
side-effect of modifying the input dictionary:</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
<p>However the more concise (but statement only) way can
be adapted with a helper function, e.g.:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr>
<p>The Example:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>'firstCondition' in SOsurvivalConditions now has two key-value pairs.
A new key-value pair, ('synonym', 'A modern form of RTFM is: Google It.'),
needs to be appended and the result should be available in a single expression.</p>
<p>This works (one line, but broken into several here):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>and returns:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>However there is a lot of redundancy in this
expression - all keys are repeated. And 'firstCondition' appears two times. Is there a more
elegant way?</p>
<p>(The names and the content of the datastructures here are made up, but represent a real problem I encountered today. Python version: 2.6.2.).</p>
| 8 | 2009-07-05T19:33:01Z | 38,981,453 | <p>Python 3 is your friend:</p>
<pre><code>{**SOsurvivalConditions, 'firstCondition': {**SOsurvivalConditions['firstCondition'], 'synonym': 'A modern form of RTFM is: Google It.'}}
</code></pre>
<p>A single line expression that returns a dictionary with the additional subitem without modifying the original dictionary nor subdictionary.</p>
| 1 | 2016-08-16T17:54:37Z | [
"python"
] |
Python: deep appending to dictionary? - in a single expression | 1,084,678 | <p>How do I, in a <strong>single expression</strong>, get a dictionary
where one key-value pair has been added to a sub-dictionary
in some input dictionary? The input dictionary should be left unchanged. It
can be assumed the sub-dictionary does exist and that the new key-value pair is not already in the sub-dictionary.</p>
<p><strong>Update 2</strong> (see below for definition of "SOsurvivalConditions", etc.):</p>
<p>The most concise way is:</p>
<pre><code>(SOsurvivalConditions['firstCondition'].setdefault('synonym', 'A modern form of RTFM is: Google It.'), SOsurvivalConditions)[-1]
</code></pre>
<p><strong>Update 1</strong> :</p>
<p>This meets the given requirements and does not have the
side-effect of modifying the input dictionary:</p>
<pre><code>dict((k,dict(v, synonym='A modern form of RTFM is: Google It.') if k == "firstCondition" else v) for k,v in SOsurvivalConditions.iteritems())
</code></pre>
<p>However the more concise (but statement only) way can
be adapted with a helper function, e.g.:</p>
<pre><code>import copy
def dictDeepAdd(inputDict, dictKey, newKey, newValue):
"""
Adds new key-value pair to a sub-dictionary and
returns a new version of inputDict.
dictKey is the key in inputDict for which a new
key-value pair is added.
Side-effect: none (does not change inputDict).
"""
toReturn = copy.deepcopy(inputDict)
toReturn[dictKey][newKey] = newValue
return toReturn
dictDeepAdd(
SOsurvivalConditions,
'firstCondition',
'synonym',
'A modern form of RTFM is: Google It.'
)
</code></pre>
<hr>
<p>The Example:</p>
<pre><code>goodStyle = \
{
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
}
SOsurvivalConditions = \
{
'moodImperative' : 'be happy',
'firstCondition' : goodStyle,
}
</code></pre>
<p>'firstCondition' in SOsurvivalConditions now has two key-value pairs.
A new key-value pair, ('synonym', 'A modern form of RTFM is: Google It.'),
needs to be appended and the result should be available in a single expression.</p>
<p>This works (one line, but broken into several here):</p>
<pre><code>{
'moodImperative': SOsurvivalConditions['moodImperative'],
'firstCondition' :
dict(
SOsurvivalConditions['firstCondition'],
synonym = 'A modern form of RTFM is: Google It.'
)
}
</code></pre>
<p>and returns:</p>
<pre><code>{'moodImperative': 'be happy',
'firstCondition':
{'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
}
}
</code></pre>
<p>However there is a lot of redundancy in this
expression - all keys are repeated. And 'firstCondition' appears two times. Is there a more
elegant way?</p>
<p>(The names and the content of the datastructures here are made up, but represent a real problem I encountered today. Python version: 2.6.2.).</p>
| 8 | 2009-07-05T19:33:01Z | 38,982,579 | <p>I believe this meets your requirements:</p>
<pre><code>{k: dict(v, **{'synonym': 'A modern form of RTFM is: Google It.'}) if k == 'firstCondition' else v for k, v in SOsurvivalConditions.iteritems()}
</code></pre>
<p>This will produce a new dictionary that takes the inner dictionary of the original under <code>firstCondition</code> and creates a new dictionary from it with the new item included. One caveat is that if there are other mutable structures in the original dictionary as a value, this will copy over the references to the new dictionary. That didn't seem to be the case in your problem though, and you can easily modify it to also produce copies of those mutable structures.</p>
<p>Here's an affirmation that this works:</p>
<pre><code>SOsurvivalConditions = {
'moodImperative' : 'be happy',
'firstCondition' : {
'answer': 'RTFM responses are not acceptable on Stack Overflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM' : 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
},
}
target_dict = {
'moodImperative': 'be happy',
'firstCondition': {
'answer': 'RTFM responses are not acceptable on StackOverflow - Joel Spolsky has repeatedly said so in the Stack Overflow podcasts.',
'RTFM': 'RTFM is, in the less offensive version, an abbreviation for Read The Fine Manual.',
'synonym': 'A modern form of RTFM is: Google It.'
},
}
new_dict = {k: dict(v, **{'synonym': 'A modern form of RTFM is: Google It.'}) if k == 'firstCondition' else v for k, v in SOsurvivalConditions.iteritems()}
assert(SOsurvivalConditions['firstCondition'].get('synonym') is None) # asserts original dict didn't change
assert(new_dict == target_dict) # asserts target dictionary is produced
</code></pre>
| 1 | 2016-08-16T19:02:06Z | [
"python"
] |
How do I store desktop application data in a cross platform way for python? | 1,084,697 | <p>I have a python desktop application that needs to store user data. On Windows, this is usually in <code>%USERPROFILE%\Application Data\AppName\</code>, on OSX it's usually <code>~/Library/Application Support/AppName/</code>, and on other *nixes it's usually <code>~/.appname/</code>.</p>
<p>There exists a function in the standard library, <code>os.path.expanduser</code> that will get me a user's home directory, but I know that on Windows, at least, "Application Data" is localized into the user's language. That might be true for OSX as well.</p>
<p>What is the correct way to get this location?</p>
<p><strong>UPDATE:</strong>
Some further research indicates that the correct way to get this on OSX is by using the function NSSearchPathDirectory, but that's Cocoa, so it means calling the PyObjC bridge...</p>
| 37 | 2009-07-05T19:45:44Z | 1,084,700 | <p>Well, for Windows APPDATA (environmental variable) points to a user's "Application Data" folder. Not sure about OSX, though.</p>
<p>The correct way, in my opinion, is to do it on a per-platform basis.</p>
| 1 | 2009-07-05T19:50:27Z | [
"python",
"desktop-application",
"application-settings"
] |
How do I store desktop application data in a cross platform way for python? | 1,084,697 | <p>I have a python desktop application that needs to store user data. On Windows, this is usually in <code>%USERPROFILE%\Application Data\AppName\</code>, on OSX it's usually <code>~/Library/Application Support/AppName/</code>, and on other *nixes it's usually <code>~/.appname/</code>.</p>
<p>There exists a function in the standard library, <code>os.path.expanduser</code> that will get me a user's home directory, but I know that on Windows, at least, "Application Data" is localized into the user's language. That might be true for OSX as well.</p>
<p>What is the correct way to get this location?</p>
<p><strong>UPDATE:</strong>
Some further research indicates that the correct way to get this on OSX is by using the function NSSearchPathDirectory, but that's Cocoa, so it means calling the PyObjC bridge...</p>
| 37 | 2009-07-05T19:45:44Z | 1,088,459 | <p>Well, I hate to have been the one to answer my own question, but no one else seems to know. I'm leaving the answer for posterity.</p>
<pre><code>APPNAME = "MyApp"
import sys
from os import path, environ
if sys.platform == 'darwin':
from AppKit import NSSearchPathForDirectoriesInDomains
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
# NSApplicationSupportDirectory = 14
# NSUserDomainMask = 1
# True for expanding the tilde into a fully qualified path
appdata = path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME)
elif sys.platform == 'win32':
appdata = path.join(environ['APPDATA'], APPNAME)
else:
appdata = path.expanduser(path.join("~", "." + APPNAME))
</code></pre>
| 37 | 2009-07-06T18:14:36Z | [
"python",
"desktop-application",
"application-settings"
] |
How do I store desktop application data in a cross platform way for python? | 1,084,697 | <p>I have a python desktop application that needs to store user data. On Windows, this is usually in <code>%USERPROFILE%\Application Data\AppName\</code>, on OSX it's usually <code>~/Library/Application Support/AppName/</code>, and on other *nixes it's usually <code>~/.appname/</code>.</p>
<p>There exists a function in the standard library, <code>os.path.expanduser</code> that will get me a user's home directory, but I know that on Windows, at least, "Application Data" is localized into the user's language. That might be true for OSX as well.</p>
<p>What is the correct way to get this location?</p>
<p><strong>UPDATE:</strong>
Some further research indicates that the correct way to get this on OSX is by using the function NSSearchPathDirectory, but that's Cocoa, so it means calling the PyObjC bridge...</p>
| 37 | 2009-07-05T19:45:44Z | 14,026,484 | <p>You can try to use <a href="http://qt-project.org/doc/qt-5/qsettings.html" rel="nofollow"><code>QSettings</code></a> from Qt. You can obtain the path to your MyCompany/MyApp.ini file this way:</p>
<pre><code>from PySide.QtCore import QSettings, QCoreApplication
QSettings.setDefaultFormat(QSettings.IniFormat)
QCoreApplication.setOrganizationName("MyCompany")
QCoreApplication.setApplicationName("MyApp")
settings = QSettings()
print(settings.fileName())
</code></pre>
<p>Alternatively, without changing any global state:</p>
<pre><code>QSettings(
QSettings.IniFormat, QSettings.UserScope,
"MyCompany", "MyApp"
).fileName()
</code></pre>
<p>On Win7 you get something like:</p>
<pre>C:\Users\MyUser\AppData\Roaming\MyCompany\MyApp.ini</pre>
<p>On Linux (may vary):</p>
<pre>/home/myuser/.config/MyCompany/MyApp.ini</pre>
<p>I don't know the possible results for OSX (but I'd like to).</p>
<p><code>QSettings</code> functionallity seem to be nice until you want to use <code>registerFormat</code>, which is not available in PySide, so there is no easy way to use YAML or JSON writers for settings.</p>
| 4 | 2012-12-24T23:30:42Z | [
"python",
"desktop-application",
"application-settings"
] |
How do I store desktop application data in a cross platform way for python? | 1,084,697 | <p>I have a python desktop application that needs to store user data. On Windows, this is usually in <code>%USERPROFILE%\Application Data\AppName\</code>, on OSX it's usually <code>~/Library/Application Support/AppName/</code>, and on other *nixes it's usually <code>~/.appname/</code>.</p>
<p>There exists a function in the standard library, <code>os.path.expanduser</code> that will get me a user's home directory, but I know that on Windows, at least, "Application Data" is localized into the user's language. That might be true for OSX as well.</p>
<p>What is the correct way to get this location?</p>
<p><strong>UPDATE:</strong>
Some further research indicates that the correct way to get this on OSX is by using the function NSSearchPathDirectory, but that's Cocoa, so it means calling the PyObjC bridge...</p>
| 37 | 2009-07-05T19:45:44Z | 33,735,209 | <p>a small module that does exactly that:</p>
<p><a href="https://pypi.python.org/pypi/appdirs/1.4.0" rel="nofollow">https://pypi.python.org/pypi/appdirs/1.4.0</a></p>
| 4 | 2015-11-16T12:18:36Z | [
"python",
"desktop-application",
"application-settings"
] |
C++ or Python as a starting point into GUI programming? | 1,084,935 | <p>I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use with Qt).
In my school we learned the basics with Turbo Pascal, VB and a voluntary C course, though right now i only know a hint of all the things i learned back then.</p>
<p>Can you recommend me a way and a site or book (or two) that would bring me on that path (a perfect one would be one that teaches the language with help of the toolkit)?</p>
<p>Thank you in advance.</p>
| 7 | 2009-07-05T22:13:19Z | 1,084,948 | <p>I have read <a href="http://www.qtrac.eu/pyqtbook.html" rel="nofollow">Rapid GUI Programming with Python and Qt: The Definitive Guide to PyQt Programming by Mark Summerfield</a> , it's cool.
for C++ : C++ GUI Programming with Qt 4 (2nd Edition)
just my two cents. </p>
| 4 | 2009-07-05T22:21:41Z | [
"c++",
"python",
"qt"
] |
C++ or Python as a starting point into GUI programming? | 1,084,935 | <p>I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use with Qt).
In my school we learned the basics with Turbo Pascal, VB and a voluntary C course, though right now i only know a hint of all the things i learned back then.</p>
<p>Can you recommend me a way and a site or book (or two) that would bring me on that path (a perfect one would be one that teaches the language with help of the toolkit)?</p>
<p>Thank you in advance.</p>
| 7 | 2009-07-05T22:13:19Z | 1,084,952 | <p><a href="http://wiki.python.org/moin/PyQt" rel="nofollow">http://wiki.python.org/moin/PyQt</a><br />
You can use PyQT for Qt in Python. They have recommendations for tutorials and references on there.</p>
<p>Google "How to learn Qt" and "Learning C++".
There are some decent sources on there.</p>
| 4 | 2009-07-05T22:24:41Z | [
"c++",
"python",
"qt"
] |
C++ or Python as a starting point into GUI programming? | 1,084,935 | <p>I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use with Qt).
In my school we learned the basics with Turbo Pascal, VB and a voluntary C course, though right now i only know a hint of all the things i learned back then.</p>
<p>Can you recommend me a way and a site or book (or two) that would bring me on that path (a perfect one would be one that teaches the language with help of the toolkit)?</p>
<p>Thank you in advance.</p>
| 7 | 2009-07-05T22:13:19Z | 1,084,958 | <p>Being an expert in both C++ and Python, my mantra has long been "Python where I can, C++ where I must": Python is faster (in term of programmer productivity and development cycle) and easier, C++ can give that extra bit of power when I have to get close to the hardware or be extremely careful about every byte or machine cycle I spend. In your situation, I would recommend Python (and the many excellent books and URLs already recommended in other answers).</p>
| 22 | 2009-07-05T22:30:35Z | [
"c++",
"python",
"qt"
] |
C++ or Python as a starting point into GUI programming? | 1,084,935 | <p>I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use with Qt).
In my school we learned the basics with Turbo Pascal, VB and a voluntary C course, though right now i only know a hint of all the things i learned back then.</p>
<p>Can you recommend me a way and a site or book (or two) that would bring me on that path (a perfect one would be one that teaches the language with help of the toolkit)?</p>
<p>Thank you in advance.</p>
| 7 | 2009-07-05T22:13:19Z | 1,084,964 | <p>How about Ruby? You can write Qt apps in Ruby allegedly (<a href="http://rubyforge.org/projects/korundum" rel="nofollow">http://rubyforge.org/projects/korundum</a>), and it gives you a good excuse to look at the very excellent "Why's Poignant Guide..." (<a href="http://poignantguide.net" rel="nofollow">http://poignantguide.net</a>) which is how Monty Python would have introduced programming....</p>
<p>(Actually thinking about learning python myself, so feel free to ignore my advice (but visit Why's site anyway))</p>
| -1 | 2009-07-05T22:31:24Z | [
"c++",
"python",
"qt"
] |
Python: How can I import all variables? | 1,084,977 | <p>I'm new to Python and programming in general (a couple of weeks at most).</p>
<p>Concerning Python and using modules, I realise that functions can imported using <code>from a import *</code>.</p>
<p>So instead of typing</p>
<pre><code>a.sayHi()
a.sayBye()
</code></pre>
<p>I can say</p>
<pre><code>sayHi()
sayBye()
</code></pre>
<p>which I find simplifies things a great deal. Now, say I have a bunch of <em>variables</em> that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use <code>import a</code> and then be required to prefix all my variables with <code>a.</code>.</p>
<p>The following situation would by ideal:</p>
<p>a.py</p>
<pre><code>name = "Michael"
age = 15
</code></pre>
<p>b.py</p>
<pre><code>some_function
if name == "Michael":
if age == 15:
print("Simple!")
</code></pre>
<p>Output:</p>
<pre><code>Simple!
</code></pre>
| 18 | 2009-07-05T22:41:16Z | 1,084,984 | <p>You gave the solution yourself: <code>from a import *</code> will work just fine. Python does not differentiate between functions and variables in this respect.</p>
<pre><code>>>> from a import *
>>> if name == "Michael" and age == 15:
... print('Simple!')
...
Simple!
</code></pre>
| 40 | 2009-07-05T22:45:25Z | [
"python",
"variables",
"import",
"module"
] |
Python: How can I import all variables? | 1,084,977 | <p>I'm new to Python and programming in general (a couple of weeks at most).</p>
<p>Concerning Python and using modules, I realise that functions can imported using <code>from a import *</code>.</p>
<p>So instead of typing</p>
<pre><code>a.sayHi()
a.sayBye()
</code></pre>
<p>I can say</p>
<pre><code>sayHi()
sayBye()
</code></pre>
<p>which I find simplifies things a great deal. Now, say I have a bunch of <em>variables</em> that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use <code>import a</code> and then be required to prefix all my variables with <code>a.</code>.</p>
<p>The following situation would by ideal:</p>
<p>a.py</p>
<pre><code>name = "Michael"
age = 15
</code></pre>
<p>b.py</p>
<pre><code>some_function
if name == "Michael":
if age == 15:
print("Simple!")
</code></pre>
<p>Output:</p>
<pre><code>Simple!
</code></pre>
| 18 | 2009-07-05T22:41:16Z | 1,084,996 | <p>You didn't say this directly, but I'm assuming you're having trouble with manipulating these global variables.</p>
<p>If you manipulate global variables from inside a function, you must declare them global</p>
<pre><code>a = 10
def x():
global a
a = 15
print a
x()
print a
</code></pre>
<p>If you don't do that, then <code>a = 15</code> will just create a local variable and assign it 15, while the global a stays 10</p>
| 7 | 2009-07-05T22:51:08Z | [
"python",
"variables",
"import",
"module"
] |
Python: How can I import all variables? | 1,084,977 | <p>I'm new to Python and programming in general (a couple of weeks at most).</p>
<p>Concerning Python and using modules, I realise that functions can imported using <code>from a import *</code>.</p>
<p>So instead of typing</p>
<pre><code>a.sayHi()
a.sayBye()
</code></pre>
<p>I can say</p>
<pre><code>sayHi()
sayBye()
</code></pre>
<p>which I find simplifies things a great deal. Now, say I have a bunch of <em>variables</em> that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use <code>import a</code> and then be required to prefix all my variables with <code>a.</code>.</p>
<p>The following situation would by ideal:</p>
<p>a.py</p>
<pre><code>name = "Michael"
age = 15
</code></pre>
<p>b.py</p>
<pre><code>some_function
if name == "Michael":
if age == 15:
print("Simple!")
</code></pre>
<p>Output:</p>
<pre><code>Simple!
</code></pre>
| 18 | 2009-07-05T22:41:16Z | 1,086,390 | <p>Just for some context, most linters will flag <code>from module import *</code> with a warning, because it's prone to namespace collisions that will cause headaches down the road.</p>
<p>Nobody has noted yet that, as an alternative, you can use the</p>
<pre><code>from a import name, age
</code></pre>
<p>form and then use <code>name</code> and <code>age</code> directly (without the <code>a.</code> prefix). The <code>from [module] import [identifiers]</code> form is more future proof because you can easily see when one import will be overriding another.</p>
<p>Also note that "variables" aren't different from functions in Python in terms of how they're addressed -- every identifier like <code>name</code> or <code>sayBye</code> is pointing at some kind of object. The identifier <code>name</code> is pointing at a string object, <code>sayBye</code> is pointing at a function object, and <code>age</code> is pointing at an integer object. When you tell Python:</p>
<pre><code>from a import name, age
</code></pre>
<p>you're saying "take those objects pointed at by <code>name</code> and <code>age</code> within module <code>a</code> and point at them in the current scope with the same identifiers".</p>
<p>Similarly, if you want to point at them with different identifiers on import, you can use the</p>
<pre><code>from a import sayBye as bidFarewell
</code></pre>
<p>form. The same function object gets pointed at, except in the current scope the identifier pointing at it is <code>bidFarewell</code> whereas in module <code>a</code> the identifier pointing at it is <code>sayBye</code>.</p>
| 21 | 2009-07-06T10:33:08Z | [
"python",
"variables",
"import",
"module"
] |
Python: How can I import all variables? | 1,084,977 | <p>I'm new to Python and programming in general (a couple of weeks at most).</p>
<p>Concerning Python and using modules, I realise that functions can imported using <code>from a import *</code>.</p>
<p>So instead of typing</p>
<pre><code>a.sayHi()
a.sayBye()
</code></pre>
<p>I can say</p>
<pre><code>sayHi()
sayBye()
</code></pre>
<p>which I find simplifies things a great deal. Now, say I have a bunch of <em>variables</em> that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use <code>import a</code> and then be required to prefix all my variables with <code>a.</code>.</p>
<p>The following situation would by ideal:</p>
<p>a.py</p>
<pre><code>name = "Michael"
age = 15
</code></pre>
<p>b.py</p>
<pre><code>some_function
if name == "Michael":
if age == 15:
print("Simple!")
</code></pre>
<p>Output:</p>
<pre><code>Simple!
</code></pre>
| 18 | 2009-07-05T22:41:16Z | 1,086,705 | <p>Like others have said,</p>
<pre><code>from module import *
</code></pre>
<p>will also import the modules variables.</p>
<p>However, you need to understand that you are <em>not</em> importing variables, just references to objects. Assigning something else to the imported names in the importing module <strong>won't</strong> affect the other modules.</p>
<p>Example: assume you have a module <code>module.py</code> containing the following code:</p>
<pre><code>a= 1
b= 2
</code></pre>
<p>Then you have two other modules, <code>mod1.py</code> and <code>mod2.py</code> which both do the following:</p>
<pre><code>from module import *
</code></pre>
<p>In each module, two names, <code>a</code> and <code>b</code> are created, pointing to the objects <code>1</code> and <code>2</code>, respectively.</p>
<p>Now, if somewhere in <code>mod1.py</code> you assign something else to the global name <code>a</code>:</p>
<pre><code>a= 3
</code></pre>
<p>the name <code>a</code> in <code>module.py</code> and the name <code>a</code> in <code>mod2.py</code> will still point to the object <code>1</code>.</p>
<p>So <code>from module import *</code> will work if you want read-only globals, but it won't work if you want read-write globals. If the latter, you're better off just importing <code>import module</code> and then either getting the value (<code>module.a</code>) or setting the value (<code>module.a= â¦</code>) prefixed by the module.</p>
| 11 | 2009-07-06T12:28:24Z | [
"python",
"variables",
"import",
"module"
] |
How do I use TLS with asyncore? | 1,085,050 | <p>An asyncore-based XMPP client opens a normal TCP connection to an XMPP server. The server indicates it requires an encrypted connection. The client is now expected to start a TLS handshake so that subsequent requests can be encrypted.</p>
<p><a href="http://trevp.net/tlslite/readme.txt" rel="nofollow">tlslite</a> integrates with asyncore, but the sample code is for a server (?) and I don't understand what it's doing. </p>
<p>I'm on Python 2.5. How can I get the TLS magic working?</p>
<p><hr /></p>
<p>Here's what ended up working for me:</p>
<pre><code>from tlslite.api import *
def handshakeTls(self):
"""
Encrypt the socket using the tlslite module
"""
self.logger.info("activating TLS encrpytion")
self.socket = TLSConnection(self.socket)
self.socket.handshakeClientCert()
</code></pre>
| 3 | 2009-07-05T23:23:06Z | 1,085,246 | <p>I've followed what I believe are all the steps tlslite documents to make an asyncore client work -- I can't actually get it to work since the only asyncore client I have at hand to tweak for the purpose is the example in the Python docs, which is an HTTP 1.0 client, and I believe that because of this I'm trying to set up an HTTPS connection in a very half-baked way. And I have no asyncore XMPP client, nor any XMPP server requesting TLS, to get anywhere close to your situation. Nevertheless I decided to share the fruits of my work anyway because (even though some step may be missing) it does seem to be a bit better than what you previously had -- I <em>think</em> I'm showing all the needed steps in the <code>__init__</code>. BTW, I copied the pem files from the tlslite/test directory.</p>
<pre><code>import asyncore, socket
from tlslite.api import *
s = open("./clientX509Cert.pem").read()
x509 = X509()
x509.parse(s)
certChain = X509CertChain([x509])
s = open("./clientX509Key.pem").read()
privateKey = parsePEMKey(s, private=True)
class http_client(TLSAsyncDispatcherMixIn, asyncore.dispatcher):
ac_in_buffer_size = 16384
def __init__(self, host, path):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect( (host, 80) )
TLSAsyncDispatcherMixIn.__init__(self, self.socket)
self.tlsConnection.ignoreAbruptClose = True
handshaker = self.tlsConnection.handshakeClientCert(
certChain=certChain,
privateKey=privateKey,
async=True)
self.setHandshakeOp(handshaker)
self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path
def handle_connect(self):
pass
def handle_close(self):
self.close()
def handle_read(self):
print self.recv(8192)
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
c = http_client('www.readyhosting.com', '/')
asyncore.loop()
</code></pre>
<p>This is a mix of the asyncore example http client in the Python docs, plus what I've gleaned from the tlslite docs and have been able to reverse engineer from their sources. Hope this (even though incomplete/not working) can at least advance you in your quest...</p>
<p>Personally, in your shoes, I'd consider switching from asyncore to <a href="http://python.net/crew/mwh/apidocs/twisted.words.protocols.jabber.xmlstream.TLSInitiatingInitializer.html" rel="nofollow">twisted</a> -- asyncore is old and rusty, Twisted already integrates a lot of juicy, useful bits (the URL I gave is to a bit in the docs that already does integrate TLS and XMPP for you...).</p>
| 2 | 2009-07-06T03:05:37Z | [
"python",
"ssl"
] |
How do I use TLS with asyncore? | 1,085,050 | <p>An asyncore-based XMPP client opens a normal TCP connection to an XMPP server. The server indicates it requires an encrypted connection. The client is now expected to start a TLS handshake so that subsequent requests can be encrypted.</p>
<p><a href="http://trevp.net/tlslite/readme.txt" rel="nofollow">tlslite</a> integrates with asyncore, but the sample code is for a server (?) and I don't understand what it's doing. </p>
<p>I'm on Python 2.5. How can I get the TLS magic working?</p>
<p><hr /></p>
<p>Here's what ended up working for me:</p>
<pre><code>from tlslite.api import *
def handshakeTls(self):
"""
Encrypt the socket using the tlslite module
"""
self.logger.info("activating TLS encrpytion")
self.socket = TLSConnection(self.socket)
self.socket.handshakeClientCert()
</code></pre>
| 3 | 2009-07-05T23:23:06Z | 1,085,862 | <p>Definitely check out twisted and wokkel. I've been building tons of xmpp bots and components with it and it's a dream.</p>
| 4 | 2009-07-06T07:54:16Z | [
"python",
"ssl"
] |
Problem with printing contents of a list | 1,085,051 | <p>I'm having a somewhat odd problem with Python(2.6.2) <del>that I've come to the conclusion is a bug in the Vista port (I cant replicate it in XP or Linux).</del></p>
<p>I have a list of users, encrypted passwords, and their host that I am storing in a larger list (it's acting as a sort of database).</p>
<p>This all works fine and dandy, except for that there is an inconsistency in how a single user's data is stored and how the group is stored.</p>
<p>created by the 'create_user' method</p>
<blockquote>
<p>['localhost', 'demo', 'demouserpasswordhash']</p>
</blockquote>
<p>created by the 'create_database' method</p>
<blockquote>
<p>['\xff\xfel\x00o\x00c\x00a\x00l\x00h\x00o\x00s\x00t\x00', '\x00d\x00e\x00m\x00o\x00', '\x00d\x00e\x00m\x00o\x00u\x00s\x00e\x00r\x00p\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00h\x00a\x00s\x00h\x00\r\x00\n']</p>
</blockquote>
<p>I don't understand why it's doing this, given how simple the code for it is:</p>
<pre><code># ----- base functions
def create_user ( user_data ):
return user_data.split(":")
def show_user ( user_data ):
print "Host: ", user_data[0]
print "Username: ", user_data[1]
print "Password: ", user_data[2]
print
def create_database ( user_list ):
database = []
for user in user_list:
database.append( create_user( user ) )
return database
def show_database( database ):
for row in database:
show_user( row )
# ----- test area
users = open( "users.txt" )
test_user = create_user( "localhost:demo:demouserpasswordhash" )
db = create_database( users )
print db[0]
print test_user
# -----
</code></pre>
<p>Anyone have any similar experiences with this or is it just me?</p>
| 1 | 2009-07-05T23:23:50Z | 1,085,059 | <p>Your file users.txt is in UTF-16, but you're opening it as ASCII.</p>
<p>Either change it to ASCII, or open it like this:</p>
<pre><code>import codecs
users = codecs.open( "users-16.txt", "r", "utf-16" )
</code></pre>
| 6 | 2009-07-05T23:25:26Z | [
"python"
] |
Problem with printing contents of a list | 1,085,051 | <p>I'm having a somewhat odd problem with Python(2.6.2) <del>that I've come to the conclusion is a bug in the Vista port (I cant replicate it in XP or Linux).</del></p>
<p>I have a list of users, encrypted passwords, and their host that I am storing in a larger list (it's acting as a sort of database).</p>
<p>This all works fine and dandy, except for that there is an inconsistency in how a single user's data is stored and how the group is stored.</p>
<p>created by the 'create_user' method</p>
<blockquote>
<p>['localhost', 'demo', 'demouserpasswordhash']</p>
</blockquote>
<p>created by the 'create_database' method</p>
<blockquote>
<p>['\xff\xfel\x00o\x00c\x00a\x00l\x00h\x00o\x00s\x00t\x00', '\x00d\x00e\x00m\x00o\x00', '\x00d\x00e\x00m\x00o\x00u\x00s\x00e\x00r\x00p\x00a\x00s\x00s\x00w\x00o\x00r\x00d\x00h\x00a\x00s\x00h\x00\r\x00\n']</p>
</blockquote>
<p>I don't understand why it's doing this, given how simple the code for it is:</p>
<pre><code># ----- base functions
def create_user ( user_data ):
return user_data.split(":")
def show_user ( user_data ):
print "Host: ", user_data[0]
print "Username: ", user_data[1]
print "Password: ", user_data[2]
print
def create_database ( user_list ):
database = []
for user in user_list:
database.append( create_user( user ) )
return database
def show_database( database ):
for row in database:
show_user( row )
# ----- test area
users = open( "users.txt" )
test_user = create_user( "localhost:demo:demouserpasswordhash" )
db = create_database( users )
print db[0]
print test_user
# -----
</code></pre>
<p>Anyone have any similar experiences with this or is it just me?</p>
| 1 | 2009-07-05T23:23:50Z | 1,085,066 | <p>Try replacing</p>
<pre><code>create_user( user )
</code></pre>
<p>with</p>
<pre><code>create_user( user.decode("utf16") )
</code></pre>
| 1 | 2009-07-05T23:28:28Z | [
"python"
] |
Real-time intercepting of stdout from another process in Python | 1,085,071 | <p>I'd like to run a system process, intercept the output, and modify it real-time, line by line, in a Python script.</p>
<p>My best attempt, which waits for the process to complete before printing, is:</p>
<pre><code>#!/usr/bin/env python
import subprocess
cmd = "waitsome.py"
proc = subprocess.Popen(cmd, shell=True, bufsize=256, stdout=subprocess.PIPE)
for line in proc.stdout:
print ">>> " + line.rstrip()
</code></pre>
<p>The script <code>waitsome.py</code> simply prints a line every half a second:</p>
<pre><code>#!/usr/bin/env python
import time
from sys import stdout
print "Starting"
for i in range(0,20):
time.sleep(0.5)
print "Hello, iteration", i
stdout.flush()
</code></pre>
<p>Is there an easy solution to get <code>subprocess</code> to allow iterating over the output in real time? Do I have to use threads?</p>
<p>Once upon a time, I scripted in Perl, and this was a piece of cake:</p>
<pre><code>open(CMD, "waitsome.py |");
while (<CMD>) {
print ">>> $_";
}
close(CMD);
</code></pre>
| 3 | 2009-07-05T23:31:08Z | 1,085,100 | <p>Looping over a file unavoidably buffers things in pretty large chunks -- a known issue with all Python 2.* implementations. It works as you intend in Python 3.1, with the final loop being slightly different:</p>
<pre><code>for line in proc.stdout:
print(">>> " + str(line.rstrip()))
</code></pre>
<p>If upgrading to Python 3.1 is impractical (and I know it will often be!), go the other way and write the loop in an old-fashioned manner -- the following version of the loop does work as you intend in Python 2.*:</p>
<pre><code>while True:
line = proc.stdout.readline()
if not line:
break
print ">>> " + line.rstrip()
</code></pre>
| 12 | 2009-07-06T01:51:07Z | [
"python",
"perl",
"process"
] |
Python sqlachemy - how to make table partitions? | 1,085,304 | <p>I am not very familiar with databases, and so I do not know how to partition a table using sqlachemy...</p>
<p>Your help would be greatly appreciated.</p>
| 0 | 2009-07-06T03:33:04Z | 1,085,318 | <p>It's quite an advanced subject for somebody not familiar with databases, but try Essential SQLAlchemy (you can read the key parts on <a href="http://books.google.com/books?id=septpU7dELIC&pg=PR5&lpg=PR5&dq=sqlalchemy+partition+table&source=bl&ots=0zv-uP1ckD&sig=gnaIpZPQA05lT6-FwL-BIFd-5Kg&hl=en&ei=NXFRSoGYIobatgPv6dG9Bw&sa=X&oi=book%5Fresult&ct=result&resnum=5" rel="nofollow">Google Book Search</a> -- p 122 to 124; the example on p. 125-126 is not freely readable online, so you'd have to purchase the book or read it on commercial services such as O'Reilly's <a href="http://my.safaribooksonline.com/" rel="nofollow">Safari</a> -- maybe on a free trial -- if you want to read the example).</p>
<p>Perhaps you can get better answers if you mention whether you're talking about vertical or horizontal partitioning, why you need partitioning, and what underlying database engines you are considering for the purpose.</p>
| 3 | 2009-07-06T03:41:36Z | [
"python",
"sqlalchemy"
] |
Python sqlachemy - how to make table partitions? | 1,085,304 | <p>I am not very familiar with databases, and so I do not know how to partition a table using sqlachemy...</p>
<p>Your help would be greatly appreciated.</p>
| 0 | 2009-07-06T03:33:04Z | 1,086,985 | <p>There are two kinds of partitioning: Vertical Partitioning and Horizontal Partitioning.</p>
<p>From the <a href="http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#partitioning-strategies" rel="nofollow">docs</a>:</p>
<blockquote>
<h1>Vertical Partitioning</h1>
<p>Vertical partitioning places different
kinds of objects, or different tables,
across multiple databases:</p>
<pre><code>engine1 = create_engine('postgres://db1')
engine2 = create_engine('postgres://db2')
Session = sessionmaker(twophase=True)
# bind User operations to engine 1, Account operations to engine 2
Session.configure(binds={User:engine1, Account:engine2})
session = Session()
</code></pre>
<h1>Horizontal Partitioning</h1>
<p>Horizontal partitioning partitions the
rows of a single table (or a set of
tables) across multiple databases.</p>
<p>See the âshardingâ example in
<a href="http://docs.sqlalchemy.org/en/rel_0_9/orm/examples.html#examples-sharding" rel="nofollow"><code>attribute_shard.py</code></a></p>
</blockquote>
<p>Just ask if you need more information on those, preferably providing more information about what you want to do.</p>
| 4 | 2009-07-06T13:32:30Z | [
"python",
"sqlalchemy"
] |
Python sqlachemy - how to make table partitions? | 1,085,304 | <p>I am not very familiar with databases, and so I do not know how to partition a table using sqlachemy...</p>
<p>Your help would be greatly appreciated.</p>
| 0 | 2009-07-06T03:33:04Z | 1,087,081 | <p>Automatic partitioning is a very database engine specific concept and SQLAlchemy doesn't provide any generic tools to manage partitioning. Mostly because it wouldn't provide anything really useful while being another API to learn. If you want to do database level partitioning then do the CREATE TABLE statements using custom Oracle DDL statements (see Oracle documentation how to create partitioned tables and migrate data to them). You can use a partitioned table in SQLAlchemy just like you would use a normal table, you just need the table declaration so that SQLAlchemy knows what to query. You can reflect the definition from the database, or just duplicate the table declaration in SQLAlchemy code.</p>
<p>Very large datasets are usually time-based, with older data becoming read-only or read-mostly and queries usually only look at data from a time interval. If that describes your data, you should probably partition your data using the date field.</p>
<p>There's also application level partitioning, or sharding, where you use your application to split data across different database instances. This isn't all that popular in the Oracle world due to the exorbitant pricing models. If you do want to use sharding, then look at SQLAlchemy documentation and examples for that, for how SQLAlchemy can support you in that, but be aware that application level sharding will affect how you need to build your application code.</p>
| 2 | 2009-07-06T13:48:20Z | [
"python",
"sqlalchemy"
] |
game design - handling bonuses / duck typing - python | 1,085,532 | <p>I am currently faced with a design problem in my game design, not terrible but it bothers me enough so I want to ask others opinions :-)</p>
<p>I am currently experimenting with pygame, I have developed a little space shooter and now I would like to handle some bonuses.</p>
<p>Right now I have an abstract class Bonus from which derive all the bonuses currently implemented: a "health bonus" which gives back some health to the player, a "death bonus" which drops the player's health to 1.</p>
<p>In my game loop here is what I do (roughly):</p>
<pre><code>def testCollisionBonusBolt():
#bolts are sprites fired by the player that allow him to get the bonuses
collisions = pygame.sprite.groupcollide(bonusesGroup, boltsGroup, True, True)
for col in collisions:
player.bonuses.append(col)
</code></pre>
<p>And right after I tell the player to use the bonuses</p>
<pre><code>class Player:
...
def useBonuses(self):
for bonus in self.bonuses:
bonus.use(self)
</code></pre>
<p>Until now everything is OK, but I would like to add a "bomb bonus" which when shooted by the player explodes and kills the enemies on his surroundings.</p>
<p>This "bonus" implements the "use(target)" method of my abstract class Bonus as the others to, but I feel kind of bad adding such a bonus to the list of the player's bonuses as there should be no relation between them!</p>
<p>The concept behind a bonus is that this is "something that does something to something", previously the targets where my player class but now it is not as clear...
Of course instead of calling player.useBonuses() after detecting which bonuses where shooted I could test the type (using isinstance) for example of the bonuses but after all the discussions I've read about duck-typing and why it's the pythonic way I am wondering how can I manage my bonus problem?</p>
<p>Thanks for reading this far, hope you guys can help me out!</p>
<p>regards</p>
| 4 | 2009-07-06T05:18:18Z | 1,085,541 | <p>If you don't want a certain <code>col</code> to go in <code>player.bonuses</code> but elsewhere, make a <code>toplayer</code> method in the abstract class <code>Bonus</code> with the default implementation:</p>
<pre><code>def toplayer(self, player):
player.bonuses.append(self)
</code></pre>
<p>and override it in the <code>bomb bonus</code> class. (You don't have to inherit, as you mention, but there's no trouble in so doing if it gets you some easy functionality reuse.)</p>
<p>So for example a player could have an attribute <code>bomb</code>, normally <code>None</code>, and the <code>bomb bonus</code> class could do:</p>
<pre><code>def toplayer(self, player):
player.bomb = self
</code></pre>
<p>And when the time comes to act on all the bonus accrued, it could start with</p>
<pre><code>if player.bomb is not None:
player.bomb.explode(player.position)
</code></pre>
<p>or the like.</p>
| 1 | 2009-07-06T05:24:22Z | [
"python",
"pygame",
"duck-typing"
] |
game design - handling bonuses / duck typing - python | 1,085,532 | <p>I am currently faced with a design problem in my game design, not terrible but it bothers me enough so I want to ask others opinions :-)</p>
<p>I am currently experimenting with pygame, I have developed a little space shooter and now I would like to handle some bonuses.</p>
<p>Right now I have an abstract class Bonus from which derive all the bonuses currently implemented: a "health bonus" which gives back some health to the player, a "death bonus" which drops the player's health to 1.</p>
<p>In my game loop here is what I do (roughly):</p>
<pre><code>def testCollisionBonusBolt():
#bolts are sprites fired by the player that allow him to get the bonuses
collisions = pygame.sprite.groupcollide(bonusesGroup, boltsGroup, True, True)
for col in collisions:
player.bonuses.append(col)
</code></pre>
<p>And right after I tell the player to use the bonuses</p>
<pre><code>class Player:
...
def useBonuses(self):
for bonus in self.bonuses:
bonus.use(self)
</code></pre>
<p>Until now everything is OK, but I would like to add a "bomb bonus" which when shooted by the player explodes and kills the enemies on his surroundings.</p>
<p>This "bonus" implements the "use(target)" method of my abstract class Bonus as the others to, but I feel kind of bad adding such a bonus to the list of the player's bonuses as there should be no relation between them!</p>
<p>The concept behind a bonus is that this is "something that does something to something", previously the targets where my player class but now it is not as clear...
Of course instead of calling player.useBonuses() after detecting which bonuses where shooted I could test the type (using isinstance) for example of the bonuses but after all the discussions I've read about duck-typing and why it's the pythonic way I am wondering how can I manage my bonus problem?</p>
<p>Thanks for reading this far, hope you guys can help me out!</p>
<p>regards</p>
| 4 | 2009-07-06T05:18:18Z | 1,085,545 | <p>I don't write in python but here's my recommendation: Load up your player with each type of weapon he can get (even ones through bonuses) and set the ammo on the ones that he gets through bonuses to 0. Then when your player picks up a "bomb bonus" (or whatever) add one ammo to the bomb weapon on the player. That ought to work nicely.</p>
| 1 | 2009-07-06T05:25:37Z | [
"python",
"pygame",
"duck-typing"
] |
game design - handling bonuses / duck typing - python | 1,085,532 | <p>I am currently faced with a design problem in my game design, not terrible but it bothers me enough so I want to ask others opinions :-)</p>
<p>I am currently experimenting with pygame, I have developed a little space shooter and now I would like to handle some bonuses.</p>
<p>Right now I have an abstract class Bonus from which derive all the bonuses currently implemented: a "health bonus" which gives back some health to the player, a "death bonus" which drops the player's health to 1.</p>
<p>In my game loop here is what I do (roughly):</p>
<pre><code>def testCollisionBonusBolt():
#bolts are sprites fired by the player that allow him to get the bonuses
collisions = pygame.sprite.groupcollide(bonusesGroup, boltsGroup, True, True)
for col in collisions:
player.bonuses.append(col)
</code></pre>
<p>And right after I tell the player to use the bonuses</p>
<pre><code>class Player:
...
def useBonuses(self):
for bonus in self.bonuses:
bonus.use(self)
</code></pre>
<p>Until now everything is OK, but I would like to add a "bomb bonus" which when shooted by the player explodes and kills the enemies on his surroundings.</p>
<p>This "bonus" implements the "use(target)" method of my abstract class Bonus as the others to, but I feel kind of bad adding such a bonus to the list of the player's bonuses as there should be no relation between them!</p>
<p>The concept behind a bonus is that this is "something that does something to something", previously the targets where my player class but now it is not as clear...
Of course instead of calling player.useBonuses() after detecting which bonuses where shooted I could test the type (using isinstance) for example of the bonuses but after all the discussions I've read about duck-typing and why it's the pythonic way I am wondering how can I manage my bonus problem?</p>
<p>Thanks for reading this far, hope you guys can help me out!</p>
<p>regards</p>
| 4 | 2009-07-06T05:18:18Z | 1,085,567 | <p>I think you're on the right track - I would say the "Bomb Bonus" is still related to the player object because it affects the enemies around the player. You just need to implement the "Bomb Bonus"'s <code>use()</code> method like this:</p>
<pre><code>class BombBonus(Bonus):
def use(self, player):
assert isinstance(player, Player)
# TODO: find all enemies that are close to the player - assuming you
# have all enemy objects in a list call 'enemies'
global enemies
for enemy in enemies:
if distance(player.position, enemy.position) < 400:
# if the distance between player and an enemy is less than 400
# (change this value to your liking), destroy that enemy.
enemy.explode()
</code></pre>
<p>You'll need to work out your own implementation of <code>distance()</code>.</p>
<p>Developing a game without a detailed plan means that you're often going to have new ideas which <em>almost</em> fit your existing objects, and you will need to choose whether to expand your existing classes with new features to support your new idea, or create a new set of classes because you think the new idea is too different. There's no right and wrong here, just make sure your ideas stay organized in a way that makes sense to you.</p>
| 0 | 2009-07-06T05:37:29Z | [
"python",
"pygame",
"duck-typing"
] |
game design - handling bonuses / duck typing - python | 1,085,532 | <p>I am currently faced with a design problem in my game design, not terrible but it bothers me enough so I want to ask others opinions :-)</p>
<p>I am currently experimenting with pygame, I have developed a little space shooter and now I would like to handle some bonuses.</p>
<p>Right now I have an abstract class Bonus from which derive all the bonuses currently implemented: a "health bonus" which gives back some health to the player, a "death bonus" which drops the player's health to 1.</p>
<p>In my game loop here is what I do (roughly):</p>
<pre><code>def testCollisionBonusBolt():
#bolts are sprites fired by the player that allow him to get the bonuses
collisions = pygame.sprite.groupcollide(bonusesGroup, boltsGroup, True, True)
for col in collisions:
player.bonuses.append(col)
</code></pre>
<p>And right after I tell the player to use the bonuses</p>
<pre><code>class Player:
...
def useBonuses(self):
for bonus in self.bonuses:
bonus.use(self)
</code></pre>
<p>Until now everything is OK, but I would like to add a "bomb bonus" which when shooted by the player explodes and kills the enemies on his surroundings.</p>
<p>This "bonus" implements the "use(target)" method of my abstract class Bonus as the others to, but I feel kind of bad adding such a bonus to the list of the player's bonuses as there should be no relation between them!</p>
<p>The concept behind a bonus is that this is "something that does something to something", previously the targets where my player class but now it is not as clear...
Of course instead of calling player.useBonuses() after detecting which bonuses where shooted I could test the type (using isinstance) for example of the bonuses but after all the discussions I've read about duck-typing and why it's the pythonic way I am wondering how can I manage my bonus problem?</p>
<p>Thanks for reading this far, hope you guys can help me out!</p>
<p>regards</p>
| 4 | 2009-07-06T05:18:18Z | 1,846,212 | <p>I had a bonus system in an asteroid clone I wrote a few years ago. It lives (as much as a dead project can live) on <a href="http://bitbucket.org/mizipzor/pyroids/" rel="nofollow">Bitbucket</a> now. I dont think its as flexible as you seem to be aiming for. But small <a href="http://bitbucket.org/mizipzor/pyroids/src/tip/entity.py#cl-451" rel="nofollow">"bonus" entities</a> spawns and move around, if they <a href="http://bitbucket.org/mizipzor/pyroids/src/tip/entity.py#cl-472" rel="nofollow">collide with an asteroid</a>, the bonus is removed and missed by the player. If the <a href="http://bitbucket.org/mizipzor/pyroids/src/tip/entity.py#cl-366" rel="nofollow">player collides with it</a>, bonus points are awarded.</p>
| 0 | 2009-12-04T10:51:18Z | [
"python",
"pygame",
"duck-typing"
] |
How to check available Python libraries on Google App Engine & add more | 1,085,538 | <p>How to check available Python libraries on Google App Engine & add more?</p>
<p>Is SQLite available or we must use GQL with their database system only?</p>
<p>Thank you in advance.</p>
| 1 | 2009-07-06T05:23:58Z | 1,085,550 | <p>Afaik, you can only use the GAE specific database.</p>
| 1 | 2009-07-06T05:28:36Z | [
"python",
"google-app-engine",
"sqlite"
] |
How to check available Python libraries on Google App Engine & add more | 1,085,538 | <p>How to check available Python libraries on Google App Engine & add more?</p>
<p>Is SQLite available or we must use GQL with their database system only?</p>
<p>Thank you in advance.</p>
| 1 | 2009-07-06T05:23:58Z | 1,085,554 | <p>SQLite is there (but since you cannot write to files, you must use it in a read-only way, or on a <code>:memory:</code> database).</p>
<p>App engine <a href="http://code.google.com/appengine/docs/python/runtime.html#Pure%5FPython" rel="nofollow">docs</a> do a good job at documenting what's there. You can add any other pure-python library, typically as a zipfile of <code>.py</code> (NOT <code>.pyc</code>) files to upload in the main directory of your app (you can directly import from inside the zipfile, of course).</p>
<p>A few more pure-Python third-party libraries included with app engine are listed and documented <a href="http://code.google.com/appengine/docs/python/tools/libraries.html" rel="nofollow">here</a> -- the paragraph on zipimport at this URL has a bit more details on the ways and limitations of using zipfiles to add more third-party pure-Python libs to your app.</p>
| 4 | 2009-07-06T05:30:18Z | [
"python",
"google-app-engine",
"sqlite"
] |
What's the simplest way to put a python script into the system tray (Windows) | 1,085,694 | <p>What's the simplest way to put a python script into the system tray?</p>
<p>My target platform is Windows. I don't want to see the 'cmd.exe' window.</p>
| 31 | 2009-07-06T06:38:43Z | 1,085,718 | <p>Those are two questions, actually:</p>
<ol>
<li>Adding a tray icon can be done with Win32 API. Example: <a href="http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html">SysTrayIcon.py</a></li>
<li>Hiding the <code>cmd.exe</code> window is as easy as using <code>pythonw.exe</code> instead of <code>python.exe</code> to run your scripts.</li>
</ol>
| 44 | 2009-07-06T06:49:41Z | [
"python",
"system-tray"
] |
Does sphinx run on Jython? | 1,085,791 | <p>I'm still looking for a usable documentation tool chain. Working in the Java environment but also a Python user, I wondered if <a href="http://sphinx.pocoo.org/">Sphinx</a> would run on <a href="http://www.jython.org/">Jython</a> 2.5?</p>
| 6 | 2009-07-06T07:20:24Z | 1,085,966 | <p>I think the easiest thing to do is to try it ? I can't find anything that says it won't.</p>
| 1 | 2009-07-06T08:22:25Z | [
"java",
"python",
"documentation",
"jython"
] |
Does sphinx run on Jython? | 1,085,791 | <p>I'm still looking for a usable documentation tool chain. Working in the Java environment but also a Python user, I wondered if <a href="http://sphinx.pocoo.org/">Sphinx</a> would run on <a href="http://www.jython.org/">Jython</a> 2.5?</p>
| 6 | 2009-07-06T07:20:24Z | 1,086,231 | <p>There are many <a href="http://jython.sourceforge.net/docs/differences.html" rel="nofollow">differences between CPython and Jython</a>, so I'd recommend you to run Sphinx unit tests on Jython to see picture.</p>
<p>Good luck!</p>
| 1 | 2009-07-06T09:39:36Z | [
"java",
"python",
"documentation",
"jython"
] |
Does sphinx run on Jython? | 1,085,791 | <p>I'm still looking for a usable documentation tool chain. Working in the Java environment but also a Python user, I wondered if <a href="http://sphinx.pocoo.org/">Sphinx</a> would run on <a href="http://www.jython.org/">Jython</a> 2.5?</p>
| 6 | 2009-07-06T07:20:24Z | 1,486,504 | <p>Running Jython 2.5.1 with Sphinx in an Ant-script shows an error:</p>
<pre><code> [exec] Making output directory...
[exec] Running Sphinx v0.6.3
[exec] Exception occurred:
[exec] File "C:\jython\jython2.5.1\Lib\site-packages\sphinx-0.6.3-py2.5.egg\sphinx\highlighting.py", line 15, in <module>
[exec] import parser
[exec] ImportError: No module named parser
[exec] The full traceback has been saved in ....\sphinx-err-o_qfvt.log, if you want to report the issue to the author.
[exec] Please also report this if it was a user error, so that a better error message can be provided next time.
[exec] Send reports to sphinx-dev@googlegroups.com. Thanks!
[exec] Build finished. The HTML pages are in _build/html.
[exec] Result: 1
</code></pre>
<p>uncommented the import parser in <code>highlighting.py</code> :</p>
<pre><code> [exec] Running Sphinx v0.6.3
[exec] loading pickled environment... done
[exec] building [html]: targets for 1 source files that are out of date
[exec] updating environment: 0 added, 0 changed, 0 removed
[exec] looking for now-outdated files... none found
[exec] preparing documents... done
[exec] writing output... [100%] index
[exec] writing additional files... genindex search
[exec] copying static files... done
[exec] dumping search index... done
[exec] dumping object inventory... done
[exec] build succeeded.
[exec] Build finished. The HTML pages are in _build/html.
[exec] Result: 1
</code></pre>
| 3 | 2009-09-28T11:08:38Z | [
"java",
"python",
"documentation",
"jython"
] |
Does sphinx run on Jython? | 1,085,791 | <p>I'm still looking for a usable documentation tool chain. Working in the Java environment but also a Python user, I wondered if <a href="http://sphinx.pocoo.org/">Sphinx</a> would run on <a href="http://www.jython.org/">Jython</a> 2.5?</p>
| 6 | 2009-07-06T07:20:24Z | 1,487,066 | <p>to run sphinx on jython i had to do some changes:</p>
<ol>
<li><p>in the highlighting.py file:</p>
<p>uncomment <code>import parser</code> [line 15?]</p>
<p>uncomment the use of parser in PygmentsBridge.try_parse
(<code>whole try / except</code> ) [line 159 - 164?]</p>
<p>add an <code>return True</code> to PygmentsBridge.try_parse</p>
<p>(try_parse is now useless ?!)</p></li>
<li><p>in the <code>util/__init__.py</code> adding <code>err.errno == 0</code> in <code>ensuredir</code> (win32 only)</p>
<p>if not err.errno == 17 and not err.errno == 0:</p></li>
</ol>
<p><hr /></p>
<p>opened an issue:</p>
<p><a href="http://bitbucket.org/birkenfeld/sphinx/issue/265/sphinx-doesnt-run-with-jython251" rel="nofollow">http://bitbucket.org/birkenfeld/sphinx/issue/265/sphinx-doesnt-run-with-jython251</a></p>
| 3 | 2009-09-28T13:34:40Z | [
"java",
"python",
"documentation",
"jython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.