title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Why does namespace after method call changes?
1,361,393
<p>I'm creating a class, but having some trouble with the namespacing in python.</p> <p>You can see the code below, and it mostly works ok, but after the call to <code>guiFrame._stateMachine()</code> the time module is somehow not defined anymore.</p> <p>If I re-import the time module in <code>_stateMachine()</code> it works. But why is the time module not in the namespace when I import it in the head?</p> <p>Am I missing something?</p> <p>The error message:</p> <pre><code> File "C:\Scripts\Python\GUI.py", line 106, in &lt;module&gt; guiFrame._stateMachine() File "C:\Scripts\Python\GUI.py", line 74, in _stateMachine self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localt f.load.cpuThreadsValue['10094'])) UnboundLocalError: local variable 'time' referenced before assignment </code></pre> <p>The code:</p> <pre><code>import os import cpu_load_internal import throughput_internal import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from Tkinter import * import tkMessageBox import time class GUIFramework(Frame): """This is the GUI""" def __init__(self,master=None): """Initialize yourself""" """Initialise the base class""" Frame.__init__(self,master) """Set the Window Title""" self.master.title("Type Some Text") """Display the main window with a little bit of padding""" self.grid(padx=10,pady=10) self.CreateWidgets() plt.figure(1) def _setup_parsing(self): self.load = cpu_load_internal.CPULoad('C:\Templogs') self.throughput = throughput_internal.MACThroughput('C:\Templogs') self.tempfile = open('output.txt','w') self.state = 0 def _parsing(self): self.load.read_lines() self.throughput.read_lines() self.cpuLoad.set(self.load.cpuThreadsValue['10094']) self.macThroughput.set(self.throughput.macULThroughput) def __change_state1(self): self.state = 2 def __change_state3(self): self.state = 3 def CreateWidgets(self): """Create all the widgets that we need""" """Create the Text""" self.cpuLoad = StringVar() self.lbText1 = Label(self, textvariable=self.cpuLoad) self.lbText1.grid(row=0, column=0) self.macThroughput = StringVar() self.lbText2 = Label(self, textvariable=self.macThroughput) self.lbText2.grid(row=0, column=1) self.butStart = Button(self, text = 'Start', command = self.__change_state1) self.butStart.grid(row=1, column=0) self.butStop = Button(self, text = 'Stop', command = self.__change_state3) self.butStop.grid(row=1, column=1) def _stateMachine(self): if (self.state == 2): print self.throughput.macULUpdate print self.load.cpuUpdate if self.load.cpuUpdate: self.load.cpuUpdate = 0 print 'cpuUMTS %s\n' % (self.load.cpuThreadsValue['10094']) self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localtime()), self.load.cpuThreadsValue['10094'])) if self.throughput.macULUpdate: self.throughput.macULUpdate = 0 print 'macUL %s %s\n' % (self.throughput.macULThroughput, self.throughput.macULThroughputUnit) self.tempfile.write('%s macUL %s %s\n' % (time.asctime(time.localtime()), self.throughput.macULThroughput, self.throughput.macULThroughputUnit)) if (self.state == 3): self.tempfile.seek(0) plt.plot([1,2,3],[1,4,6]) plt.savefig('test.png') self.state == 0 while 1: try: line = (self.tempfile.next()) except: break if 'cpuUMTS' in line: line.split time = 4 if __name__ == "__main__": guiFrame = GUIFramework() print dir(guiFrame) guiFrame._setup_parsing() guiFrame.state = 2 while(1): guiFrame._parsing() guiFrame._stateMachine() guiFrame.update() time.sleep(0.1) </code></pre>
2
2009-09-01T09:07:54Z
1,361,409
<p>Why do you assign to <code>time</code>? You can't use it as local variable, it will overshadow the module! If you look closely it complains that you use <code>time</code> before you assign to it -- since to use it as a local variable in <code>_stateMachine</code>.</p> <pre><code>time = 4 </code></pre>
7
2009-09-01T09:11:58Z
[ "python", "namespaces" ]
Why does namespace after method call changes?
1,361,393
<p>I'm creating a class, but having some trouble with the namespacing in python.</p> <p>You can see the code below, and it mostly works ok, but after the call to <code>guiFrame._stateMachine()</code> the time module is somehow not defined anymore.</p> <p>If I re-import the time module in <code>_stateMachine()</code> it works. But why is the time module not in the namespace when I import it in the head?</p> <p>Am I missing something?</p> <p>The error message:</p> <pre><code> File "C:\Scripts\Python\GUI.py", line 106, in &lt;module&gt; guiFrame._stateMachine() File "C:\Scripts\Python\GUI.py", line 74, in _stateMachine self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localt f.load.cpuThreadsValue['10094'])) UnboundLocalError: local variable 'time' referenced before assignment </code></pre> <p>The code:</p> <pre><code>import os import cpu_load_internal import throughput_internal import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from Tkinter import * import tkMessageBox import time class GUIFramework(Frame): """This is the GUI""" def __init__(self,master=None): """Initialize yourself""" """Initialise the base class""" Frame.__init__(self,master) """Set the Window Title""" self.master.title("Type Some Text") """Display the main window with a little bit of padding""" self.grid(padx=10,pady=10) self.CreateWidgets() plt.figure(1) def _setup_parsing(self): self.load = cpu_load_internal.CPULoad('C:\Templogs') self.throughput = throughput_internal.MACThroughput('C:\Templogs') self.tempfile = open('output.txt','w') self.state = 0 def _parsing(self): self.load.read_lines() self.throughput.read_lines() self.cpuLoad.set(self.load.cpuThreadsValue['10094']) self.macThroughput.set(self.throughput.macULThroughput) def __change_state1(self): self.state = 2 def __change_state3(self): self.state = 3 def CreateWidgets(self): """Create all the widgets that we need""" """Create the Text""" self.cpuLoad = StringVar() self.lbText1 = Label(self, textvariable=self.cpuLoad) self.lbText1.grid(row=0, column=0) self.macThroughput = StringVar() self.lbText2 = Label(self, textvariable=self.macThroughput) self.lbText2.grid(row=0, column=1) self.butStart = Button(self, text = 'Start', command = self.__change_state1) self.butStart.grid(row=1, column=0) self.butStop = Button(self, text = 'Stop', command = self.__change_state3) self.butStop.grid(row=1, column=1) def _stateMachine(self): if (self.state == 2): print self.throughput.macULUpdate print self.load.cpuUpdate if self.load.cpuUpdate: self.load.cpuUpdate = 0 print 'cpuUMTS %s\n' % (self.load.cpuThreadsValue['10094']) self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localtime()), self.load.cpuThreadsValue['10094'])) if self.throughput.macULUpdate: self.throughput.macULUpdate = 0 print 'macUL %s %s\n' % (self.throughput.macULThroughput, self.throughput.macULThroughputUnit) self.tempfile.write('%s macUL %s %s\n' % (time.asctime(time.localtime()), self.throughput.macULThroughput, self.throughput.macULThroughputUnit)) if (self.state == 3): self.tempfile.seek(0) plt.plot([1,2,3],[1,4,6]) plt.savefig('test.png') self.state == 0 while 1: try: line = (self.tempfile.next()) except: break if 'cpuUMTS' in line: line.split time = 4 if __name__ == "__main__": guiFrame = GUIFramework() print dir(guiFrame) guiFrame._setup_parsing() guiFrame.state = 2 while(1): guiFrame._parsing() guiFrame._stateMachine() guiFrame.update() time.sleep(0.1) </code></pre>
2
2009-09-01T09:07:54Z
1,361,411
<p>You seem to use time as a variable. What happens here:</p> <blockquote> <p>"C:\Scripts\Python\GUI.py", line 74</p> </blockquote>
2
2009-09-01T09:12:24Z
[ "python", "namespaces" ]
Why does namespace after method call changes?
1,361,393
<p>I'm creating a class, but having some trouble with the namespacing in python.</p> <p>You can see the code below, and it mostly works ok, but after the call to <code>guiFrame._stateMachine()</code> the time module is somehow not defined anymore.</p> <p>If I re-import the time module in <code>_stateMachine()</code> it works. But why is the time module not in the namespace when I import it in the head?</p> <p>Am I missing something?</p> <p>The error message:</p> <pre><code> File "C:\Scripts\Python\GUI.py", line 106, in &lt;module&gt; guiFrame._stateMachine() File "C:\Scripts\Python\GUI.py", line 74, in _stateMachine self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localt f.load.cpuThreadsValue['10094'])) UnboundLocalError: local variable 'time' referenced before assignment </code></pre> <p>The code:</p> <pre><code>import os import cpu_load_internal import throughput_internal import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from Tkinter import * import tkMessageBox import time class GUIFramework(Frame): """This is the GUI""" def __init__(self,master=None): """Initialize yourself""" """Initialise the base class""" Frame.__init__(self,master) """Set the Window Title""" self.master.title("Type Some Text") """Display the main window with a little bit of padding""" self.grid(padx=10,pady=10) self.CreateWidgets() plt.figure(1) def _setup_parsing(self): self.load = cpu_load_internal.CPULoad('C:\Templogs') self.throughput = throughput_internal.MACThroughput('C:\Templogs') self.tempfile = open('output.txt','w') self.state = 0 def _parsing(self): self.load.read_lines() self.throughput.read_lines() self.cpuLoad.set(self.load.cpuThreadsValue['10094']) self.macThroughput.set(self.throughput.macULThroughput) def __change_state1(self): self.state = 2 def __change_state3(self): self.state = 3 def CreateWidgets(self): """Create all the widgets that we need""" """Create the Text""" self.cpuLoad = StringVar() self.lbText1 = Label(self, textvariable=self.cpuLoad) self.lbText1.grid(row=0, column=0) self.macThroughput = StringVar() self.lbText2 = Label(self, textvariable=self.macThroughput) self.lbText2.grid(row=0, column=1) self.butStart = Button(self, text = 'Start', command = self.__change_state1) self.butStart.grid(row=1, column=0) self.butStop = Button(self, text = 'Stop', command = self.__change_state3) self.butStop.grid(row=1, column=1) def _stateMachine(self): if (self.state == 2): print self.throughput.macULUpdate print self.load.cpuUpdate if self.load.cpuUpdate: self.load.cpuUpdate = 0 print 'cpuUMTS %s\n' % (self.load.cpuThreadsValue['10094']) self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localtime()), self.load.cpuThreadsValue['10094'])) if self.throughput.macULUpdate: self.throughput.macULUpdate = 0 print 'macUL %s %s\n' % (self.throughput.macULThroughput, self.throughput.macULThroughputUnit) self.tempfile.write('%s macUL %s %s\n' % (time.asctime(time.localtime()), self.throughput.macULThroughput, self.throughput.macULThroughputUnit)) if (self.state == 3): self.tempfile.seek(0) plt.plot([1,2,3],[1,4,6]) plt.savefig('test.png') self.state == 0 while 1: try: line = (self.tempfile.next()) except: break if 'cpuUMTS' in line: line.split time = 4 if __name__ == "__main__": guiFrame = GUIFramework() print dir(guiFrame) guiFrame._setup_parsing() guiFrame.state = 2 while(1): guiFrame._parsing() guiFrame._stateMachine() guiFrame.update() time.sleep(0.1) </code></pre>
2
2009-09-01T09:07:54Z
1,361,424
<p>You try to assing to the variable <code>time</code> in this method:</p> <pre><code>time = 4 </code></pre> <p>Therefore the compiler assumes that time must be a local variable, which isn't true. And that is the reason why you get this error when you want to use the module <code>time</code>, even if you try to use the module before you assign to <code>time</code>.</p>
2
2009-09-01T09:14:57Z
[ "python", "namespaces" ]
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
<p>I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. </p> <pre><code>response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) </code></pre> <p>I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)</p> <p>I've already tried urllib.quote(), but it raises KeyError exception.</p> <p>Possibly I'm doing something wrong but maybe it's impossible.</p>
38
2009-09-01T10:00:31Z
1,361,646
<p>This is a FAQ.</p> <p>There is no interoperable way to do this. Some browsers implement proprietary extensions (IE, Chrome), other implement RFC 2231 (Firefox, Opera).</p> <p>See test cases at <a href="http://greenbytes.de/tech/tc2231/">http://greenbytes.de/tech/tc2231/</a>.</p> <p>Update: as of November 2012, all current desktop browsers support the encoding defined in RFC 6266 and RFC 5987 (Safari >= 6, IE >= 9, Chrome, Firefox, Opera, Konqueror).</p>
35
2009-09-01T10:11:28Z
[ "python", "django", "http", "http-headers", "escaping" ]
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
<p>I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. </p> <pre><code>response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) </code></pre> <p>I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)</p> <p>I've already tried urllib.quote(), but it raises KeyError exception.</p> <p>Possibly I'm doing something wrong but maybe it's impossible.</p>
38
2009-09-01T10:00:31Z
1,362,846
<p>Take a look at this snippets to encode non ascii filenames <a href="http://www.djangosnippets.org/snippets/1710/" rel="nofollow">http://www.djangosnippets.org/snippets/1710/</a></p>
1
2009-09-01T14:37:20Z
[ "python", "django", "http", "http-headers", "escaping" ]
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
<p>I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. </p> <pre><code>response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) </code></pre> <p>I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)</p> <p>I've already tried urllib.quote(), but it raises KeyError exception.</p> <p>Possibly I'm doing something wrong but maybe it's impossible.</p>
38
2009-09-01T10:00:31Z
1,365,186
<p>Don't send a filename in Content-Disposition. There is no way to make non-ASCII header parameters work cross-browser(*).</p> <p>Instead, send just “Content-Disposition: attachment”, and leave the filename as a URL-encoded UTF-8 string in the trailing (PATH_INFO) part of your URL, for the browser to pick up and use by default. UTF-8 URLs are handled much more reliably by browsers than anything to do with Content-Disposition.</p> <p>(*: actually, there's not even a current standard that says how it <em>should</em> be done as the relationships between RFCs 2616, 2231 and 2047 are pretty dysfunctional, something that Julian is trying to get cleared up at a spec level. Consistent browser support is in the distant future.)</p>
30
2009-09-01T23:41:27Z
[ "python", "django", "http", "http-headers", "escaping" ]
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
<p>I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. </p> <pre><code>response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) </code></pre> <p>I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)</p> <p>I've already tried urllib.quote(), but it raises KeyError exception.</p> <p>Possibly I'm doing something wrong but maybe it's impossible.</p>
38
2009-09-01T10:00:31Z
3,144,680
<p>A hack:</p> <pre><code>if (Request.UserAgent.Contains("IE")) { // IE will accept URL encoding, but spaces don't need to be, and since they're so common.. filename = filename.Replace("%", "%25").Replace(";", "%3B").Replace("#", "%23").Replace("&amp;", "%26"); } </code></pre>
0
2010-06-29T20:58:53Z
[ "python", "django", "http", "http-headers", "escaping" ]
How to encode UTF8 filename for HTTP headers? (Python, Django)
1,361,604
<p>I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII. </p> <pre><code>response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) </code></pre> <p>I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)</p> <p>I've already tried urllib.quote(), but it raises KeyError exception.</p> <p>Possibly I'm doing something wrong but maybe it's impossible.</p>
38
2009-09-01T10:00:31Z
8,996,249
<p>Note that in 2011, <a href="http://tools.ietf.org/html/rfc6266#appendix-D">RFC 6266</a> (especially Appendix D) weighed in on this issue and has specific recommendations to follow.</p> <p>Namely, you can issue a <code>filename</code> with only ASCII characters, followed by <code>filename*</code> with a RFC 5987-formatted filename for those agents that understand it. </p> <p>Typically this will look like <code>filename="my-resume.pdf"; filename*=UTF-8''My%20R%C3%A9sum%C3%A9.pdf</code>, where the Unicode filename ("My Résumé.pdf") is encoded into UTF-8 and then percent-encoded (note, do NOT use <code>+</code> for spaces).</p> <p>Please do actually read RFC 6266 and RFC 5987 (or use a robust and tested library that abstracts this for you), as my summary here is lacking in important detail.</p>
22
2012-01-25T00:13:54Z
[ "python", "django", "http", "http-headers", "escaping" ]
IMAP interface access to existing user messaging system in Python
1,361,671
<p>I am running a site where users can private message each other. As with any other such website, to read and mark their messages, users must log on to the site.</p> <p>I wish to expose an IMAP interface so that users may read their site messages using their standard email client. There would be few complications in such approach as what be userid to email-address mapping and what would happen if the user replies a mail but for the time being I'm little concerned about these issues.</p> <p>Is there any lightweight raw IMAP server in Python to which I could just add few rules or logic to expose an IMAP interface to user's messages?</p>
0
2009-09-01T10:18:14Z
1,361,689
<p><a href="http://twistedmatrix.com/trac/wiki/TwistedMail" rel="nofollow">Twisted Mail</a> project:</p> <blockquote> <p>Twisted Mail contains high-level, efficient protocol implementations for both clients and servers of SMTP, POP3, and <strong>IMAP4</strong>. Additionally, it contains an "out of the box" combination SMTP/POP3 virtual-hosting mail server. Also included is a read/write Maildir implementation and a basic Mail Exchange calculator (depends on Twisted Names). </p> </blockquote> <p>The examples for <code>IMAP4</code> contain only a client. Look into the <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/mail/imap4.py" rel="nofollow">source</a> for more information.</p>
1
2009-09-01T10:22:20Z
[ "python", "interface", "imap" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,361,750
<p>You could use:</p> <pre><code>-math.pow(3, float(1)/3) </code></pre> <p>Or more generally:</p> <pre><code>if x &gt; 0: return math.pow(x, float(1)/3) elif x &lt; 0: return -math.pow(abs(x), float(1)/3) else: return 0 </code></pre>
9
2009-09-01T10:42:37Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,361,761
<p>Primitive solution:</p> <pre><code>def cubic_root(nr): if nr&lt;0: return -math.pow(-nr, float(1)/3) else: return math.pow(nr, float(1)/3) </code></pre> <p>Probably massively non-pythonic, but it should work.</p>
0
2009-09-01T10:45:52Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,361,778
<pre><code>math.pow(abs(x),float(1)/3) * (1,-1)[x&lt;0] </code></pre>
10
2009-09-01T10:50:09Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,361,789
<p>Taking the earlier answers and making it into a one-liner:</p> <pre><code>import math def cubic_root(x): return math.copysign(math.pow(abs(x), 1.0/3.0), x) </code></pre>
8
2009-09-01T10:54:58Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,361,794
<p>You can also wrap the <code>libm</code> library that offers a <code>cbrt</code> (cube root) function:</p> <pre><code>from ctypes import * libm = cdll.LoadLibrary('libm.so.6') libm.cbrt.restype = c_double libm.cbrt.argtypes = [c_double] libm.cbrt(-8.0) </code></pre> <p>gives the expected</p> <pre><code>-2.0 </code></pre>
3
2009-09-01T10:56:29Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,361,834
<p>The cubic root of a negative number is just the negative of the cubic root of the absolute value of that number.</p> <p>i.e. x^(1/3) for x &lt; 0 is the same as (-1)*(|x|)^(1/3)</p> <p>Just make your number positive, and then perform cubic root.</p>
3
2009-09-01T11:04:54Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,362,288
<p>A simple use of <a href="http://en.wikipedia.org/wiki/De%5FMoivre%27s%5Fformula">De Moivre's formula</a>, is sufficient to show that the cube root of a value, regardless of sign, is a multi-valued function. That means, for any input value, there will be three solutions. Most of the solutions presented to far only return the principle root. A solution that returns all valid roots, and explicitly tests for non-complex special cases, is shown below.</p> <pre><code>import numpy import math def cuberoot( z ): z = complex(z) x = z.real y = z.imag mag = abs(z) arg = math.atan2(y,x) return [ mag**(1./3) * numpy.exp( 1j*(arg+2*n*math.pi)/3 ) for n in range(1,4) ] </code></pre> <p><strong>Edit:</strong> As requested, in cases where it is inappropriate to have dependency on numpy, the following code does the same thing.</p> <pre><code>def cuberoot( z ): z = complex(z) x = z.real y = z.imag mag = abs(z) arg = math.atan2(y,x) resMag = mag**(1./3) resArg = [ (arg+2*math.pi*n)/3. for n in range(1,4) ] return [ resMag*(math.cos(a) + math.sin(a)*1j) for a in resArg ] </code></pre>
17
2009-09-01T12:44:15Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
1,362,820
<p>You can get the complete (all n roots) and more general (any sign, any power) solution using:</p> <pre><code>import cmath x, t = -3., 3 # x**(1/t) a = cmath.exp((1./t)*cmath.log(x)) p = cmath.exp(1j*2*cmath.pi*(1./t)) r = [a*(p**i) for i in range(t)] </code></pre> <p>Explanation: a is using the equation x<sup>u</sup> = exp(u*log(x)). This solution will then be one of the roots, and to get the others, rotate it in the complex plane by a (full rotation)/t.</p>
8
2009-09-01T14:31:59Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
23,831,822
<p>You can use <code>cbrt</code> from <code>scipy.special</code>:</p> <pre><code>&gt;&gt;&gt; from scipy.special import cbrt &gt;&gt;&gt; cbrt(-3) -1.4422495703074083 </code></pre> <p>This also works for arrays.</p>
0
2014-05-23T14:27:38Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
30,122,775
<p>I just had a very similar problem and found the NumPy solution from <a href="http://scipy-user.10969.n7.nabble.com/numpy-array-root-operation-td1727.html" rel="nofollow">this forum post</a>.</p> <p>In a nushell, we can use of the NumPy <code>sign</code> and <code>absolute</code> methods to help us out. Here is an example that has worked for me:</p> <pre><code>import numpy as np x = np.array([-81,25]) print x #&gt;&gt;&gt; [-81 25] xRoot5 = np.sign(x) * np.absolute(x)**(1.0/5.0) print xRoot5 #&gt;&gt;&gt; [-2.40822469 1.90365394] print xRoot5**5 #&gt;&gt;&gt; [-81. 25.] </code></pre> <p>So going back to the original cube root problem:</p> <pre><code>import numpy as np y = -3. np.sign(y) * np.absolute(y)**(1./3.) #&gt;&gt;&gt; -1.4422495703074083 </code></pre> <p>I hope this helps.</p>
0
2015-05-08T11:31:17Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
32,223,710
<p>For an arithmetic, calculator-like answer in Python 3:</p> <pre><code>&gt;&gt;&gt; -3.0**(1/3) -1.4422495703074083 </code></pre> <p>or <code>-3.0**(1./3)</code> in Python 2.</p> <p>For the algebraic solution of <code>x**3 + (0*x**2 + 0*x) + 3 = 0</code> use numpy:</p> <pre><code>&gt;&gt;&gt; p = [1,0,0,3] &gt;&gt;&gt; numpy.roots(p) [-3.0+0.j 1.5+2.59807621j 1.5-2.59807621j] </code></pre>
0
2015-08-26T10:08:48Z
[ "python", "math" ]
Cubic root of the negative number on python
1,361,740
<p>Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?</p> <pre><code>&gt;&gt;&gt; math.pow(-3, float(1)/3) nan </code></pre> <p>it does not work. Cubic root of the negative number is negative number. Any solutions?</p>
11
2009-09-01T10:40:10Z
33,182,838
<p>this works with numpy array as well:</p> <pre><code>cbrt = lambda n: n/abs(n)*abs(n)**(1./3) </code></pre>
0
2015-10-17T04:45:48Z
[ "python", "math" ]
Can't use an inheriting Django model's Meta class to configure a field defined in an inherited abstract model
1,361,791
<p>I would like to use properties from an inheriting model's Meta class to configure a field defined in an abstract model higher up the inheritance tree:</p> <pre><code>class NamedModel(models.Model): class Meta: abstract = True verbose_name = 'object' name = models.CharField("Name", max_length=200, db_index=True, help_text="A meaningful name for this %s." % Meta.verbose_name) # see what I'm trying to do here? ) ... class OwnedModel(NamedModel): class Meta(NamedModel.Meta): verbose_name = 'owned object' </code></pre> <p>I would like the help text on the name field of OwnedModel forms to say 'A meaningful name for this owned object'. <strong>But it does not</strong>: the word 'owned' is missing, which would suggest that the verbose_name from the NamedModel.Meta is used when the model is set up, not OwnedModel.Meta.</p> <p>This isn't quite what I expect from an inheritance point of view: is there some way to get the field to be created whereby Meta.verbose_name refers to the value on the non-abstract model class, not the abstract one on which the field was defined?</p> <p>Or am I being daft?</p> <p>(This may seem like a trivial example, and it is: but it's just to illustrate the point of something more important and complex I am trying to do)</p> <p>Many thanks in advance.</p>
4
2009-09-01T10:55:43Z
1,362,316
<p>I think this happens because Meta.verbose_name is used and NamedModel.name is created when class NamedModel is parsed. So later, when class OwnedModel gets parsed, there is no chance to change anything.</p> <p>Maybe you can set the help_text property on OwnedModel.name later on, but this may change NamedModel.name also.</p> <p>In similar situations I have put the variable parts in class attribute of the model (not Meta) and then used the by run time methods/properties to generate the texts I need.</p>
1
2009-09-01T12:51:15Z
[ "python", "django", "inheritance", "django-models", "metaclass" ]
Can't use an inheriting Django model's Meta class to configure a field defined in an inherited abstract model
1,361,791
<p>I would like to use properties from an inheriting model's Meta class to configure a field defined in an abstract model higher up the inheritance tree:</p> <pre><code>class NamedModel(models.Model): class Meta: abstract = True verbose_name = 'object' name = models.CharField("Name", max_length=200, db_index=True, help_text="A meaningful name for this %s." % Meta.verbose_name) # see what I'm trying to do here? ) ... class OwnedModel(NamedModel): class Meta(NamedModel.Meta): verbose_name = 'owned object' </code></pre> <p>I would like the help text on the name field of OwnedModel forms to say 'A meaningful name for this owned object'. <strong>But it does not</strong>: the word 'owned' is missing, which would suggest that the verbose_name from the NamedModel.Meta is used when the model is set up, not OwnedModel.Meta.</p> <p>This isn't quite what I expect from an inheritance point of view: is there some way to get the field to be created whereby Meta.verbose_name refers to the value on the non-abstract model class, not the abstract one on which the field was defined?</p> <p>Or am I being daft?</p> <p>(This may seem like a trivial example, and it is: but it's just to illustrate the point of something more important and complex I am trying to do)</p> <p>Many thanks in advance.</p>
4
2009-09-01T10:55:43Z
1,363,176
<p>In fact I ended up doing the following. The base model gets given a dynamic_field_definition() class method, which can be used to patch up the fields, with the cls argument being the correct (inheriting) class. That means that that cls' Meta attributes are of that correct child, not the original base.</p> <p>I then wire up that method to get called on the class_prepared signal, so that you know everything's otherwise ready.</p> <pre><code>class NamedModel(models.Model): ... @classmethod def dynamic_field_definition(cls): pass def dynamic_field_definition(sender, **kwargs): if issubclass(sender, NamedModel): sender.dynamic_field_definition() class_prepared.connect(dynamic_field_definition) </code></pre> <p>Then the field properties that vary with model class are simply reconfigured by that class method (or more likely the method as overridden in derived classes).</p> <p>It's a slightly hacky way to bring a last little bit of OO-ness to Django models, but it works fine for my purpose.</p>
0
2009-09-01T15:40:27Z
[ "python", "django", "inheritance", "django-models", "metaclass" ]
Can't use an inheriting Django model's Meta class to configure a field defined in an inherited abstract model
1,361,791
<p>I would like to use properties from an inheriting model's Meta class to configure a field defined in an abstract model higher up the inheritance tree:</p> <pre><code>class NamedModel(models.Model): class Meta: abstract = True verbose_name = 'object' name = models.CharField("Name", max_length=200, db_index=True, help_text="A meaningful name for this %s." % Meta.verbose_name) # see what I'm trying to do here? ) ... class OwnedModel(NamedModel): class Meta(NamedModel.Meta): verbose_name = 'owned object' </code></pre> <p>I would like the help text on the name field of OwnedModel forms to say 'A meaningful name for this owned object'. <strong>But it does not</strong>: the word 'owned' is missing, which would suggest that the verbose_name from the NamedModel.Meta is used when the model is set up, not OwnedModel.Meta.</p> <p>This isn't quite what I expect from an inheritance point of view: is there some way to get the field to be created whereby Meta.verbose_name refers to the value on the non-abstract model class, not the abstract one on which the field was defined?</p> <p>Or am I being daft?</p> <p>(This may seem like a trivial example, and it is: but it's just to illustrate the point of something more important and complex I am trying to do)</p> <p>Many thanks in advance.</p>
4
2009-09-01T10:55:43Z
37,395,779
<p>Why don't you try to make a class.</p> <pre><code>class BaseNamedModelMeta: abstract = True verbose_name = "your text" </code></pre> <p>And then inherit and override whatever you want like this:</p> <pre><code>class OwnedModel(NamedModel): class Meta(BaseNamedModelMeta): verbose_name = 'owned object' </code></pre>
2
2016-05-23T16:10:51Z
[ "python", "django", "inheritance", "django-models", "metaclass" ]
How to unload a .NET assembly reference in IronPython
1,362,114
<p>After loading a reference to an assembly with something like:</p> <pre><code>import clr clr.AddRferenceToFileAndPath(r'C:\foo.dll') </code></pre> <p>How can I unload the assembly again?</p> <p>Why would anyone ever want to do this? Because I'm recompiling <code>foo.dll</code> and want to reload it, but the compiler is giving me a fuss, since IronPython is allready accessing <code>foo.dll</code>.</p>
5
2009-09-01T12:03:01Z
1,362,144
<p>.NET itself doesn't support unloading just a single assembly. Instead, you need to unload a whole <code>AppDomain</code>. I don't know exactly how IronPython works with <code>AppDomain</code>s, but that's the normal .NET way of doing things. (Load the assembly into a new <code>AppDomain</code>, use it, discard the <code>AppDomain</code>, create a new <code>AppDomain</code> with the new version of the file etc.)</p>
4
2009-09-01T12:10:50Z
[ "python", ".net", "ironpython", "python.net" ]
Django: how to retrieve an object selected by the ``object_detail`` generic view?
1,362,782
<p>Hi (sorry for my ugly english)</p> <p>I wonder if this is possible to retrieve an object which was selected with the object_detail generic view. For example :</p> <p>from django.views.generic.list_detail import object_detail</p> <pre><code>def my_view(request, slug) response = object_detail(request, MyModel.objects.all(), slug=slug, slug_field='slug', template_object_name='object') # Here I need my object in ``response`` to do something after. </code></pre> <p>I don't know where is the object</p>
1
2009-09-01T14:25:02Z
1,363,107
<p>You can't get the object this way, since <code>object_detail</code> simply returns a rendered response. If you need it, you'll just have to get it manually:</p> <pre><code>object = MyModel.objects.get(slug=slug) </code></pre>
2
2009-09-01T15:28:40Z
[ "python", "django", "view", "generics" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,032
<p>Figuring out what to make into a function and what to just include inline is something of an art. Many factors (performance, readability, maintainability) feed into the equation.</p> <p>I actually find your example kind of silly in many ways - a function that just returns it's argument? Unless it's an overload that's changing the rules, it's stupid. A function to square things? Again, why bother. Your function 'foo' should probably return a string, so that it can be used directly:</p> <pre><code>''.join(foo(x)," -- bar !! "]) </code></pre> <p>That's probably a more correct level of encapsulation in this example.</p> <p>As I say, it really depends on the circumstances. Unfortunately, this is the sort of thing that doesn't lend itself well to examples.</p>
0
2009-09-01T15:16:27Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,047
<p>I don't know how good python compilers are, but the answer to this question for many languages is that the compiler will optimize calls to small procedures / functions / methods by inlining them. In fact, in some language implementations you generally get better performance by NOT trying to "micro-optimize" the code yourself.</p>
2
2009-09-01T15:17:45Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,064
<p>Function call overheads are not big; you won't normally notice them. You only see them in this case because your actual code (x*x) is itself so completely trivial. In any real program that does real work, the amount of time spent in function-calling overhead will be negligably small.</p> <p>(Not that I'd really recommend using foo, identity and square in the example, in any case; they're so trivial it's just as readable to have them inline and they don't really encapsulate or abstract anything.)</p> <blockquote> <p>if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p> </blockquote> <p>Because programs are written for to be easy for <em>you</em> to read and maintain. You <em>could</em> replace constants with their literal values, but it'd make the program harder to work with, for a benefit that is so tiny you'll probably never even be able to measure it: the height of <a href="http://en.wikipedia.org/wiki/Optimization%5F%28computer%5Fscience%29#cite%5Fref-0" rel="nofollow">premature optimisation</a>.</p>
6
2009-09-01T15:20:03Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,071
<p>What you are talking about is the effect of inlining functions for gaining efficiency. </p> <p>It is certainly true in your Python example, that encapsulation hurts performance. But there are some counter example to it:</p> <ol> <li><p>In Java, defining getter&amp;setter instead of defining public member variables does not result in performance degradation as the JIT inline the getters&amp;setters.</p></li> <li><p>sometimes calling a function repetedly may be better than performing inlining as the code executed may then fit in the cache. Inlining may cause code explosion...</p></li> </ol>
1
2009-09-01T15:21:30Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,092
<p>IMO, this is related to <a href="http://stackoverflow.com/questions/94794/what-is-the-cost-of-a-function-call">Function Call Costs</a>. Which are negligible usually, but not zero. Splitting the code in a lot of very small functions may hurt. Especially in interpreted languages where full optimization is not available.</p> <p>Inlining functions may improve performance but it may also deteriorate. See, for example, <a href="http://yosefk.com/c++fqa/inline.html#fqa-9.3" rel="nofollow">C++ FQA Lite</a> for explanations (“Inlining can make code faster by eliminating function call overhead, or slower by generating too much code, causing instruction cache misses”). This is not C++ specific. Better leave optimizations for compiler/interpreter unless they are <em>really necessary</em>.</p> <p>By the way, I don't see a huge difference between two versions:</p> <pre><code>$ python bench.py fine-grained function decomposition: 5.46632194519 one-liner: 4.46827578545 $ python --version Python 2.5.2 </code></pre> <p>I think this result is acceptable. See bench.py in the <a href="http://pastebin.com/f7eb3be0" rel="nofollow">pastebin</a>.</p>
0
2009-09-01T15:26:20Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,108
<p>There is a performance hit for using functions, since there is the overhead of jumping to a new address, pushing registers on the stack, and returning at the end. This overhead is very small, however, and even in peformance critial systems worrying about such overhead is most likely premature optimization.</p> <p>Many languages avoid these issues in small frequenty called functions by using inlining, which is essentially what you do above.</p> <p>Python does not do inlining. The closest thing you can do is use macros to replace the function calls. </p> <p>This sort of performance issue is better served by another language, if you need the sort of speed gained by inlining (mostly marginal, and sometimes detremental) then you need to consider not using python for whatever you are working on. </p>
0
2009-09-01T15:28:42Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,118
<p>Encapsulation is about one thing and one thing only: Readability. If you're really so worried about performance that you're willing to start stripping out encapsulated logic, you may as well just start coding in assembly.</p> <p>Encapsulation also assists in debugging and feature adding. Consider the following: lets say you have a simple game and need to add code that depletes the players health under some circumstances. Easy, yes?</p> <pre><code>def DamagePlayer(dmg): player.health -= dmg; </code></pre> <p>This IS very trivial code, so it's very tempting to simply scatter "player.health -=" everywhere. But what if later you want to add a powerup that halves damage done to the player while active? If the logic is still encapsulated, it's easy:</p> <pre><code>def DamagePlayer(dmg): if player.hasCoolPowerUp: player.health -= dmg / 2 else player.health -= dmg </code></pre> <p>Now, consider if you had neglected to encapulate that bit of logic because of it's simplicity. Now you're looking at coding the same logic into 50 different places, at least one of which you are almost certain to forget, which leads to weird bugs like: "When player has powerup all damage is halved except when hit by AlienSheep enemies..."</p> <p>Do you want to have problems with Alien Sheep? I don't think so. :)</p> <p>In all seriousness, the point I'm trying to make is that encapsulation is a very good thing in the right circumstances. Of course, it's also easy to over-encapsulate, which can be just as problematic. Also, there are situations where the speed really truly does matter (though they are rare), and that extra few clock cycles is worth it. About the only way to find the right balance is practice. Don't shun encapsulation because it's slower, though. The benefits usually far outweigh the costs.</p>
2
2009-09-01T15:30:00Z
[ "python", "performance" ]
Encapsulation severely hurts performance?
1,362,997
<p>I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:</p> <pre><code>def make_legal_foo_string(x): return "This is a foo string: " + str(x) def sum_up_to(x): return x*(x+1)/2 def foo(x): return [make_legal_foo_string(x),sum_up_to(x),x+1] def bar(x): return ''.join([str(foo(x))," -- bar !! "]) </code></pre> <p>it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?</p>
3
2009-09-01T15:09:44Z
1,363,263
<p>There is a good technical reason why what you suggested is impossible. In Python, functions, constants, and everything else are <strong>accessible at runtime and can be changed at any time if necessary</strong>; they could also be changed by outside modules. This is an explicit promise of Python and one would need some <em>extremely</em> important reasons to break it.</p> <p>For example, here's the common logging idiom:</p> <pre><code># beginning of the file xxx.py log = lambda *x: None def something(): ... log(...) ... </code></pre> <p>(here <code>log</code> does nothing), and then at some other module or at the interactive prompt:</p> <pre><code>import xxx xxx.log = print xxx.something() </code></pre> <p>As you see, here <code>log</code> is modified by completely different module --- or by the user --- so that logging now works. That would be impossible if <code>log</code> was optimized away.</p> <p>Similarly, if <strong>an exception</strong> was to happen in <code>make_legal_foo_string</code> (this is possible, e.g. if <code>x.__str__()</code> is broken and returns <code>None</code>) you'd be hit with a source quote from a wrong line and even perhaps from a wrong file in your scenario. </p> <p>There are some tools that in fact apply some optimizations to Python code, but I don't think of the kind you suggested.</p>
0
2009-09-01T15:53:54Z
[ "python", "performance" ]
Pointers and arrays in Python ctypes
1,363,163
<p>I have a DLL containing a C function with a prototype like this:</p> <p><code>int c_read_block(uint32 addr, uint32 *buf, uint32 num);</code></p> <p>I want to call it from Python using ctypes. The function expects a pointer to a chunk of memory, into which it will write the results. I don't know how to construct and pass such a chunk of memory. The ctypes documentation isn't much help.</p> <p>Constructing an array and passing it "byref", like this:</p> <pre> cresult = (c_ulong * num)() err = self.c_read_block(addr, byref(cresult), num) </pre> <p>Gives this error message:</p> <p><code>ArgumentError: argument 3: &lt;type 'exceptions.TypeError'&gt;: expected LP_c_ulong instance instead of pointer to c_ulong_Array_2</code></p> <p>I guess that is because the Python ulong array is nothing like a c uint32 array. Should I use <code>create_char_string</code>. If so, how do I persuade Python to "cast" that buffer to an LP_c_ulong?</p>
26
2009-09-01T15:38:20Z
1,363,344
<p>You can cast with the <a href="http://docs.python.org/library/ctypes.html#type-conversions"><code>cast</code></a> function :)</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; x = (ctypes.c_ulong*5)() &gt;&gt;&gt; x &lt;__main__.c_ulong_Array_5 object at 0x00C2DB20&gt; &gt;&gt;&gt; ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong)) &lt;__main__.LP_c_ulong object at 0x0119FD00&gt; &gt;&gt;&gt; </code></pre>
43
2009-09-01T16:10:10Z
[ "python", "arrays", "pointers", "ctypes" ]
Pointers and arrays in Python ctypes
1,363,163
<p>I have a DLL containing a C function with a prototype like this:</p> <p><code>int c_read_block(uint32 addr, uint32 *buf, uint32 num);</code></p> <p>I want to call it from Python using ctypes. The function expects a pointer to a chunk of memory, into which it will write the results. I don't know how to construct and pass such a chunk of memory. The ctypes documentation isn't much help.</p> <p>Constructing an array and passing it "byref", like this:</p> <pre> cresult = (c_ulong * num)() err = self.c_read_block(addr, byref(cresult), num) </pre> <p>Gives this error message:</p> <p><code>ArgumentError: argument 3: &lt;type 'exceptions.TypeError'&gt;: expected LP_c_ulong instance instead of pointer to c_ulong_Array_2</code></p> <p>I guess that is because the Python ulong array is nothing like a c uint32 array. Should I use <code>create_char_string</code>. If so, how do I persuade Python to "cast" that buffer to an LP_c_ulong?</p>
26
2009-09-01T15:38:20Z
36,847,468
<p>There is a typo in the solution. In order to get a pointer to an array of ulongs you need to cast to a <code>POINTER(list of ulong)</code></p> <pre><code>In [33]: ptr = ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong*5)) In [34]: ptr Out[34]: &lt;__main__.LP_c_ulong_Array_5 at 0x23e2560&gt; </code></pre>
0
2016-04-25T17:41:09Z
[ "python", "arrays", "pointers", "ctypes" ]
calling vb dll in python
1,363,305
<p>So I have a function in vb that is converted to a dll that I want to use in python. However trying to use it, I get an error message this is the VB function</p> <pre><code>Function DISPLAYNAME(Name) MsgBox ("Hello " &amp; Name &amp; "!") End Function </code></pre> <p>and this is how I call it in python</p> <pre><code>from ctypes import * test = windll.TestDLL print test print test.DISPLAYNAME("one") </code></pre> <p>But I get errors so what is the right way of calling the dll</p> <pre><code>Traceback (most recent call last): File "C:\Test\testdll.py", line 4, in &lt;module&gt; print test.DISPLAYNAME("one") File "C:\Python26\lib\ctypes\__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "C:\Python26\lib\ctypes\__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'DISPLAYNAME' not found </code></pre> <p>I have been looking around online but no solution so far. Can't use cdll since this is for c progs.</p> <p>I have looked at some of the python and dll related questions but no solution so far works for my issue.</p>
3
2009-09-01T16:02:39Z
1,363,322
<p>I dunno the answer to your specific question, but if it's VB.NET, you can natively call it in <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a>.</p>
0
2009-09-01T16:06:37Z
[ "python", "vb.net", "dll", "vb6" ]
calling vb dll in python
1,363,305
<p>So I have a function in vb that is converted to a dll that I want to use in python. However trying to use it, I get an error message this is the VB function</p> <pre><code>Function DISPLAYNAME(Name) MsgBox ("Hello " &amp; Name &amp; "!") End Function </code></pre> <p>and this is how I call it in python</p> <pre><code>from ctypes import * test = windll.TestDLL print test print test.DISPLAYNAME("one") </code></pre> <p>But I get errors so what is the right way of calling the dll</p> <pre><code>Traceback (most recent call last): File "C:\Test\testdll.py", line 4, in &lt;module&gt; print test.DISPLAYNAME("one") File "C:\Python26\lib\ctypes\__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "C:\Python26\lib\ctypes\__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'DISPLAYNAME' not found </code></pre> <p>I have been looking around online but no solution so far. Can't use cdll since this is for c progs.</p> <p>I have looked at some of the python and dll related questions but no solution so far works for my issue.</p>
3
2009-09-01T16:02:39Z
1,363,333
<p>It might be a scoping issue, with out the Public access modifier, the function may not be visible to external callers. Try</p> <pre><code>Public Function DISPLAYNAME(Name) MsgBox ("Hello " &amp; Name &amp; "!") End Function </code></pre> <p>in your dll </p>
0
2009-09-01T16:08:19Z
[ "python", "vb.net", "dll", "vb6" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,461
<p>Although I don't get why this should be more efficient, I am pretty sure a for loop will give the best performance:</p> <pre><code>l = [start] for i in diff: l.append(l[-1] + i) </code></pre>
0
2009-09-01T16:35:16Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,463
<p>The following works for me:</p> <pre><code>orig = [start] for x in diff: orig.append(orig[-1] + x) </code></pre> <p>Using <code>map</code> will create an new array of the same size, filled with <code>None</code>. I also find a simple <code>for</code> loop more readable, and in this case as fast as you can get.</p>
6
2009-09-01T16:35:21Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,489
<p>Several of the other respondents have reasonable implementations of the algorithm you asked for, but I'm unclear on exactly what problem it is you're really trying to solve.</p> <p>Unless the numbers being stored are very large (i.e., overflow an integer and require bignums), your list of diffs won't gain you any efficiency -- an integer is an integer from the Python runtime POV, so your example "diff" list of <code>[-1, -1, 1, 2]</code> will consume just as much memory as the original list <code>[1005, 1004, 1003, 1004, 1006]</code>.</p>
2
2009-09-01T16:41:09Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,491
<p>For such large data structures numpy will work well. For this example, it's <strong>over 200x faster</strong> (see below), and a bit easier to code, basically just</p> <pre><code>add.accumulate(diff) </code></pre> <p>Comparison between numpy and direct list manipulation:</p> <pre><code>import numpy as nx import timeit N = 10000 diff_nx = nx.zeros(N, dtype=nx.int) diff_py = list(diff_nx) start = 1005 def f0(): orig = [start] for x in diff_py: orig.append(orig[-1] + x) def f1(): diff_nx[0] = start nx.add.accumulate(diff_nx) t = timeit.Timer("f0()", "from __main__ import f0, f1, diff_nx, diff_py, nx, start") print t.timeit(number=1000) t = timeit.Timer("f1()", "from __main__ import f0, f1, diff_nx, diff_py, nx, start") print t.timeit(number=1000) </code></pre> <p>gives</p> <pre><code>13.4044158459 # for list looping 0.0474112033844 # for numpy accumulate </code></pre> <p>Really, though, it seems better to reuse an established compression algorithm, like can easily be done with <a href="http://www.pytables.org/moin">PyTables</a>, rather than rolling your own like it seems that you're doing here.</p> <p>Also, here, I'm suggesting that you read in the data with room for the prepended start term, rather than rebuild the list with the prepended term, of course, so you don't have to do the copy.</p>
7
2009-09-01T16:41:17Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,493
<p>Perfect for generators:</p> <pre><code>def diff2abs( diffs, start ): yield start for diff in diffs: start += diff yield start start = 1005 diffs = [-1, -1, 1, 2] original_list = list( diff2abs( diffs, start )) </code></pre>
4
2009-09-01T16:41:40Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,494
<pre><code>class runningtotal: def __init__(self, start = 0): self.total = start def __call__(self, value): self.total += value return self.total </code></pre> <p>Now try:</p> <pre><code>&gt;&gt;&gt; map(runningtotal(start), [0,]+diff) [1005, 1004, 1003, 1004, 1006] </code></pre>
2
2009-09-01T16:41:43Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,512
<p>As mshsayem suggested, use list comprehensions - they are generally faster than for loops or map/lambdas (according do Mark Lutz's book Learning Python).</p> <p>If you really want to use an more FP-ish solution, the proper function would be "scan", wich [I believe] isn't implemented in Python so you would have to implement it yourself (which is not a hard task).</p> <p>"scan" is basically a reduce, but instead of reducing the list to a single value, it stores the result of each "iteration" in a new list.</p> <p>If you implemented it, you could do something like:</p> <pre><code>scan(lambda x,y: x+y, [start]++diff) </code></pre>
1
2009-09-01T16:46:16Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
1,363,614
<p>I don't know about your reasoning for storing the integers as diffs -- rcoder gave a good answer about why this generally is not more efficient than storing the integers themselves -- but if you don't need to have access to the entire list at once, it's more efficient memory-wise for you to use a generator. Since you say this is a "big list," you can save a lot of memory this way, instead of allocating the entire list at once. Here's a generator comprehension to get your list back:</p> <pre><code>start = 1005 def mod_start(x): global start start += x return start int_generator = (mod_start(i) for i in diffs) </code></pre> <p>You can then iterate over int_generator like you would any list, without having the entire list in memory at once. Note, however, that you cannot subscript or slice a generator, but you can use it in many useful situations.</p> <p>You can clean up the example so that the start variable does not need to be global. It just can't be local to the mod_start function.</p> <p><strong>Edit:</strong> You don't have to use the generator comprehension to get a generator. You can also use a generator function with the yield expression, like THC4k did. That avoids the start variable scope issue and is probably a little cleaner. You can also get a list from a generator at any time by passing it to the list() built-in function.</p>
0
2009-09-01T17:13:30Z
[ "python", "performance", "list", "lambda", "map-function" ]
Efficient way to use python's lambda, map
1,363,413
<p>I need to store a big list of integers in Bigtable(db). For efficiency I am storing them as diff between 2 consecutive items.</p> <p>for eg:</p> <pre> original_list = [1005, 1004, 1003, 1004, 1006] </pre> <p>Storing the above list(which actually contains more than 1000k items) as</p> <pre> start = 1005 diff = [-1, -1, 1, 2]</pre> <p>The closest I could manage is,</p> <pre> ltp = [start] map(lambda x: ltp.append(ltp[-1] + x), tick)</pre> <p>I am looking for an efficient way to convert it back into original list.</p>
3
2009-09-01T16:27:08Z
6,575,399
<p>No comment on the performance of this, but you can use reduce here.</p> <pre><code>start = 1005 diffs = [-1,-1,1,2] reduce(lambda undiffed_list, diff: undiffed_list + [undiffed_list[-1] + diff],diffs,[start]) </code></pre> <p>gets you what you want.</p>
0
2011-07-04T19:31:30Z
[ "python", "performance", "list", "lambda", "map-function" ]
appengine: NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query
1,363,531
<p>While using django.core.paginator import ObjectPaginator, I'm getting this error:</p> <blockquote> <p>NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query.</p> </blockquote> <p>The original query is written in this form:</p> <pre><code>query = models.Cdr.all() query.filter("var1 =", var1 ) query.filter("var2 =", var2) query.filter("var3 =", var3) </code></pre> <p>I get this exception when ObjectPaginator tries to count the number of elements, but only for some values of <em>var1</em>.</p> <p>Why would this query fail for some values of <em>var1</em>, while working with others?</p> <p>What would you recommend for this case?</p>
2
2009-09-01T16:50:26Z
1,363,737
<p>The general procedure recommended to fix <code>NeedIndexError</code> occurrences is <a href="http://groups.google.com/group/google-appengine/msg/36bf21bab219c376" rel="nofollow">this one</a>. I expect the composite index may not have been built on your development depending on the amount and structure of the data (which can change depending on <code>var1</code> value) but turns out to be needed (to avoid aborting the query for efficiency reasons, as the error msg hints and Nick confirms in this comment) when running on the actual store.</p>
2
2009-09-01T17:48:34Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
appengine: NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query
1,363,531
<p>While using django.core.paginator import ObjectPaginator, I'm getting this error:</p> <blockquote> <p>NeedIndexError: The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query.</p> </blockquote> <p>The original query is written in this form:</p> <pre><code>query = models.Cdr.all() query.filter("var1 =", var1 ) query.filter("var2 =", var2) query.filter("var3 =", var3) </code></pre> <p>I get this exception when ObjectPaginator tries to count the number of elements, but only for some values of <em>var1</em>.</p> <p>Why would this query fail for some values of <em>var1</em>, while working with others?</p> <p>What would you recommend for this case?</p>
2
2009-09-01T16:50:26Z
6,320,352
<p>I have run into this problem. The problem is not with your code but with GAE's indexing system itself. To fix it, you have to explicitly write the index in your index.yaml file. That worked for me, but I have <a href="http://stackoverflow.com/questions/3025018/appengine-backreferences-need-composite-index">read elsewhere</a> that explicitly defining your index may not always fix it. Regardless, I recommend that you <a href="http://code.google.com/p/googleappengine/issues/detail?id=5185" rel="nofollow">star the bug I opened</a>.</p> <p>GAE does not automatically build an index for queries that only have equality filters. Instead, it uses an algorithm Google calls "zigzag merge join" (Google it). It appears that this algorithm is breaking down in certain situations. It looks like team google <a href="http://groups.google.com/group/google-appengine/browse_thread/thread/94d7e74a2e882b4b" rel="nofollow">is working on</a> fixing this problem, but it still pops up in some situations.</p>
1
2011-06-12T05:34:19Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
python DST and GMT management into a scheduler
1,363,692
<p>I'm planning to write a sheduler app in python and I wouldn't be in trouble with DST and GMT handling.</p> <p>As example see also <a href="http://stackoverflow.com/questions/563053/scheduling-dst">PHP related question 563053</a>.</p> <p>Does anyone worked already on something similar? </p> <p>Does anyone already experienced with PyTZ - Python Time Zone Library?</p>
1
2009-09-01T17:37:03Z
1,363,716
<p>Sure, many of us have worked on calendars / schedulers and are familiar with pytz. What's your specific question, that's not already well answered in the SO question you point to and ITS answers / comments...?</p> <p><strong>Edit</strong>: so there are no special, particular pitfalls if you do things as recommended in the best answers to the other question. In particular, do standardize on UTC internally ("GMT" is an antediluvian term and concept) and convert to/from timzones (w/DST &amp;c) on I/O (just as you should standardize on Unicode internally and encode/decode to bytes, if you must, only on I/O!-).</p> <p>There's a simple and flexible module in the Python standard library called <a href="http://docs.python.org/library/sched.html" rel="nofollow">sched</a> which provides a configurable "event scheduler" and might be at the core of your app, with help from <a href="http://docs.python.org/library/calendar.html" rel="nofollow">calendar</a>, <a href="http://docs.python.org/library/datetime.html" rel="nofollow">datetime</a> etc. Some of the recipes in the "Time and Money" chapter of the Python Cookbook, 2nd ed, may help (it's widely available as online pirate copies, though as a co-author I don't necessarily LIKE that fact;-).</p> <p>It's hard to say much more without having any idea of what you're writing -- web service, web app, desktop app, or whatever else. Do you want to support <a href="http://en.wikipedia.org/wiki/VCal" rel="nofollow">vCal</a>, <a href="http://en.wikipedia.org/wiki/ICalendar" rel="nofollow">iCalendar</a>, <a href="http://en.wikipedia.org/wiki/VCalendar#vCalendar%5F1.0" rel="nofollow">vCalendar</a>, other forms of interop/sync/mashup and if so with what other apps, services and/or de facto standards? Etc, etc -- like all apps, it can grow and grow if it proves successful, of course;-).</p>
3
2009-09-01T17:43:26Z
[ "python", "time", "calendar", "timezone", "utc" ]
python DST and GMT management into a scheduler
1,363,692
<p>I'm planning to write a sheduler app in python and I wouldn't be in trouble with DST and GMT handling.</p> <p>As example see also <a href="http://stackoverflow.com/questions/563053/scheduling-dst">PHP related question 563053</a>.</p> <p>Does anyone worked already on something similar? </p> <p>Does anyone already experienced with PyTZ - Python Time Zone Library?</p>
1
2009-09-01T17:37:03Z
1,365,798
<p>pytz works great. Be sure to convert and store your times as UTC and use the pytz/datetime conversion routines to convert to local time. There's an example of usage and timezone conversion <a href="http://parand.com/say/index.php/2008/02/11/parsing-and-normalizing-dates-with-timezones-in-python/" rel="nofollow">here</a>, basically:</p> <pre><code>import datetime import pytz datetime.datetime(2008, 1, 31, 22, 56, 13, tzinfo=&lt;UTC&gt;) utcdate.astimezone(pytz.timezone('US/Pacific')) # result: # datetime.datetime(2008, 1, 31, 14, 56, 13, tzinfo=&lt;DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD&gt;) </code></pre>
3
2009-09-02T04:15:54Z
[ "python", "time", "calendar", "timezone", "utc" ]
Python singleton / object instantiation
1,363,839
<p>I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows:</p> <pre><code>_Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance = self else: self = __instance </code></pre> <p>This works in part but the self = __instance part seems to be failing. I've included some output from the interpretor to demonstrate (the code above is saved in singleton.py):</p> <pre><code>&gt;&gt;&gt; import singleton &gt;&gt;&gt; x = singleton.Singleton() &gt;&gt;&gt; x.name 'The one' &gt;&gt;&gt; singleton._Singleton__instance.name 'The one' &gt;&gt;&gt; y = singleton.Singleton() &gt;&gt;&gt; y.name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Singleton instance has no attribute 'name' &gt;&gt;&gt; type(y) &lt;type 'instance'&gt; &gt;&gt;&gt; dir(y) ['__doc__', '__init__', '__module__'] </code></pre> <p>Is it possible to do what i'm trying? If not is there another way of doing this?</p> <p>Any suggestions welcome.</p> <p>Cheers.</p>
5
2009-09-01T18:10:16Z
1,363,852
<p><strong>From <a href="http://en.wikipedia.org/wiki/Singleton%5Fpattern#Python" rel="nofollow">Singleton Pattern (Python)</a></strong>:</p> <pre><code>class Singleton(type): def __init__(self, name, bases, dict): super(Singleton, self).__init__(name, bases, dict) self.instance = None def __call__(self, *args, **kw): if self.instance is None: self.instance = super(Singleton, self).__call__(*args, **kw) return self.instance class MyClass(object): __metaclass__ = Singleton print MyClass() print MyClass() </code></pre>
4
2009-09-01T18:15:38Z
[ "python", "singleton" ]
Python singleton / object instantiation
1,363,839
<p>I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows:</p> <pre><code>_Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance = self else: self = __instance </code></pre> <p>This works in part but the self = __instance part seems to be failing. I've included some output from the interpretor to demonstrate (the code above is saved in singleton.py):</p> <pre><code>&gt;&gt;&gt; import singleton &gt;&gt;&gt; x = singleton.Singleton() &gt;&gt;&gt; x.name 'The one' &gt;&gt;&gt; singleton._Singleton__instance.name 'The one' &gt;&gt;&gt; y = singleton.Singleton() &gt;&gt;&gt; y.name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Singleton instance has no attribute 'name' &gt;&gt;&gt; type(y) &lt;type 'instance'&gt; &gt;&gt;&gt; dir(y) ['__doc__', '__init__', '__module__'] </code></pre> <p>Is it possible to do what i'm trying? If not is there another way of doing this?</p> <p>Any suggestions welcome.</p> <p>Cheers.</p>
5
2009-09-01T18:10:16Z
1,363,856
<p>This is about the most basic Singleton you can make. It uses a <a href="http://docs.python.org/library/functions.html#classmethod" rel="nofollow">class method</a> to check whether the singleton has been created and makes a new one if it hasn't. There are more advanced ways of going about this, such as overriding the <a href="http://docs.python.org/reference/datamodel.html#object.__new__" rel="nofollow"><code>__new__</code> method</a>.</p> <pre><code>class Singleton: instance = None @classmethod def get(cls): if cls.instance is None: cls.instance = cls() return cls.instance def __init__(self): self.x = 5 # or whatever you want to do sing = Singleton.get() print sing.x # prints 5 </code></pre> <p>As for why your code fails, there are several reasons. First, by the time <code>__init__</code> is called, a new object has already been created, defeating the purpose of the singleton pattern. Second, when you say <code>self = __instance</code>, that simply resets the local variable self; this would be akin to saying</p> <pre><code>def f(x): x = 7 # changes the value of our local variable y = 5 f(y) print y # this is still 5 </code></pre> <p>Since variables in Python are passed by value and not reference, you can't say <code>self = blah</code> and have it be meaningful in the way you want. The above Singleton class is more what you want, unless you want to get fancy and look into overriding the <code>__new__</code> operator.</p>
1
2009-09-01T18:16:04Z
[ "python", "singleton" ]
Python singleton / object instantiation
1,363,839
<p>I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows:</p> <pre><code>_Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance = self else: self = __instance </code></pre> <p>This works in part but the self = __instance part seems to be failing. I've included some output from the interpretor to demonstrate (the code above is saved in singleton.py):</p> <pre><code>&gt;&gt;&gt; import singleton &gt;&gt;&gt; x = singleton.Singleton() &gt;&gt;&gt; x.name 'The one' &gt;&gt;&gt; singleton._Singleton__instance.name 'The one' &gt;&gt;&gt; y = singleton.Singleton() &gt;&gt;&gt; y.name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Singleton instance has no attribute 'name' &gt;&gt;&gt; type(y) &lt;type 'instance'&gt; &gt;&gt;&gt; dir(y) ['__doc__', '__init__', '__module__'] </code></pre> <p>Is it possible to do what i'm trying? If not is there another way of doing this?</p> <p>Any suggestions welcome.</p> <p>Cheers.</p>
5
2009-09-01T18:10:16Z
1,363,857
<p>Assigning to an argument or any other local variable (barename) cannot ever, possibly have ANY effect outside the function; that applies to your <code>self = whatever</code> as it would to ANY other assignment to a (barename) argument or other local variable.</p> <p>Rather, override <code>__new__</code>:</p> <pre><code>class Singleton(object): __instance = None def __new__(cls): if cls.__instance == None: cls.__instance = object.__new__(cls) cls.__instance.name = "The one" return cls.__instance </code></pre> <p>I've done other enhancements here, such as uprooting the global, the old-style class, etc.</p> <p>MUCH better is to use <a href="http://www.aleax.it/5ep.html" rel="nofollow">Borg</a> (aka monostate) instead of your chosen Highlander (aka singleton), but that's a different issue from the one you're asking about;-).</p>
17
2009-09-01T18:16:39Z
[ "python", "singleton" ]
Python singleton / object instantiation
1,363,839
<p>I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows:</p> <pre><code>_Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance = self else: self = __instance </code></pre> <p>This works in part but the self = __instance part seems to be failing. I've included some output from the interpretor to demonstrate (the code above is saved in singleton.py):</p> <pre><code>&gt;&gt;&gt; import singleton &gt;&gt;&gt; x = singleton.Singleton() &gt;&gt;&gt; x.name 'The one' &gt;&gt;&gt; singleton._Singleton__instance.name 'The one' &gt;&gt;&gt; y = singleton.Singleton() &gt;&gt;&gt; y.name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Singleton instance has no attribute 'name' &gt;&gt;&gt; type(y) &lt;type 'instance'&gt; &gt;&gt;&gt; dir(y) ['__doc__', '__init__', '__module__'] </code></pre> <p>Is it possible to do what i'm trying? If not is there another way of doing this?</p> <p>Any suggestions welcome.</p> <p>Cheers.</p>
5
2009-09-01T18:10:16Z
1,363,858
<pre><code>self = _instance </code></pre> <p>This wont do what you are expecting it to do. Read about how Python treats names.</p>
0
2009-09-01T18:16:43Z
[ "python", "singleton" ]
Python singleton / object instantiation
1,363,839
<p>I'm learning Python and i've been trying to implement a Singleton-type class as a test. The code i have is as follows:</p> <pre><code>_Singleton__instance = None class Singleton: def __init__(self): global __instance if __instance == None: self.name = "The one" __instance = self else: self = __instance </code></pre> <p>This works in part but the self = __instance part seems to be failing. I've included some output from the interpretor to demonstrate (the code above is saved in singleton.py):</p> <pre><code>&gt;&gt;&gt; import singleton &gt;&gt;&gt; x = singleton.Singleton() &gt;&gt;&gt; x.name 'The one' &gt;&gt;&gt; singleton._Singleton__instance.name 'The one' &gt;&gt;&gt; y = singleton.Singleton() &gt;&gt;&gt; y.name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Singleton instance has no attribute 'name' &gt;&gt;&gt; type(y) &lt;type 'instance'&gt; &gt;&gt;&gt; dir(y) ['__doc__', '__init__', '__module__'] </code></pre> <p>Is it possible to do what i'm trying? If not is there another way of doing this?</p> <p>Any suggestions welcome.</p> <p>Cheers.</p>
5
2009-09-01T18:10:16Z
1,363,867
<p><a href="http://stackoverflow.com/questions/1296311/bruce-eckels-code-snippet-from-design-pattern-im-confused-on-how-it-works">http://stackoverflow.com/questions/1296311/bruce-eckels-code-snippet-from-design-pattern-im-confused-on-how-it-works</a></p> <pre><code>class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class MySingleton(Borg): def __init__(self, arg): Borg.__init__(self) self.val = arg def __str__(self): return self.val x = MySingleton('sausage') print x y = MySingleton('eggs') print y z = MySingleton('spam') print z print x print y print ´x´ print ´y´ print ´z´ output = ''' sausage eggs spam spam spam &lt;__main__. MySingleton instance at 0079EF2C&gt; &lt;__main__. MySingleton instance at 0079E10C&gt; &lt;__main__. MySingleton instance at 00798F9C&gt; ''' </code></pre>
6
2009-09-01T18:18:06Z
[ "python", "singleton" ]
Invoking a method on an object
1,364,117
<p>Given a PyObject* pointing to a python object, how do I invoke one of the object methods? The documentation never gives an example of this:</p> <pre><code>PyObject* obj = .... PyObject* args = Py_BuildValue("(s)", "An arg"); PyObject* method = PyWHATGOESHERE(obj, "foo"); PyObject* ret = PyWHATGOESHERE(obj, method, args); if (!ret) { // check error... } </code></pre> <p>This would be the equivalent of</p> <pre><code>&gt;&gt;&gt; ret = obj.foo("An arg") </code></pre>
5
2009-09-01T19:08:33Z
1,364,159
<pre><code>PyObject* obj = .... PyObject *ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg"); if (!ret) { // check error... } </code></pre> <p>Read up on the <a href="http://docs.python.org/c-api/index.html">Python C API documentation</a>. In this case, you want the <a href="http://docs.python.org/c-api/object.html">object protocol</a>.</p> <blockquote> <pre><code>PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...) </code></pre> <p>Return value: New reference.</p> <p>Call the method named method of object o with a variable number of C arguments. The C arguments are described by a <code>Py_BuildValue()</code> format string that should produce a tuple. The format may be <code>NULL</code>, indicating that no arguments are provided. Returns the result of the call on success, or <code>NULL</code> on failure. This is the equivalent of the Python expression <code>o.method(args)</code>. Note that if you only pass <code>PyObject * args</code>, <code>PyObject_CallMethodObjArgs()</code> is a faster alternative.</p> </blockquote> <p>And</p> <blockquote> <pre><code>PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) </code></pre> <p>Return value: New reference.</p> <p>Calls a method of the object <code>o</code>, where the name of the method is given as a Python string object in name. It is called with a variable number of <code>PyObject*</code> arguments. The arguments are provided as a variable number of parameters followed by <code>NULL</code>. Returns the result of the call on success, or <code>NULL</code> on failure.</p> </blockquote>
6
2009-09-01T19:14:33Z
[ "python", "c", "embedded-language" ]
Invoking a method on an object
1,364,117
<p>Given a PyObject* pointing to a python object, how do I invoke one of the object methods? The documentation never gives an example of this:</p> <pre><code>PyObject* obj = .... PyObject* args = Py_BuildValue("(s)", "An arg"); PyObject* method = PyWHATGOESHERE(obj, "foo"); PyObject* ret = PyWHATGOESHERE(obj, method, args); if (!ret) { // check error... } </code></pre> <p>This would be the equivalent of</p> <pre><code>&gt;&gt;&gt; ret = obj.foo("An arg") </code></pre>
5
2009-09-01T19:08:33Z
1,364,216
<p>Your example would be:</p> <pre><code>PyObject* ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg"); </code></pre>
2
2009-09-01T19:27:05Z
[ "python", "c", "embedded-language" ]
Stopping python using ctrl+c
1,364,173
<p>I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to <kbd>Ctrl</kbd><kbd>C</kbd> to stop the program. Is there any way around this?</p>
45
2009-09-01T19:17:13Z
1,364,179
<p>If it is running in the Python shell use <kbd>Ctrl</kbd> + <kbd>Z</kbd>, otherwise locate the <code>python</code> process and kill it.</p>
23
2009-09-01T19:18:43Z
[ "python" ]
Stopping python using ctrl+c
1,364,173
<p>I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to <kbd>Ctrl</kbd><kbd>C</kbd> to stop the program. Is there any way around this?</p>
45
2009-09-01T19:17:13Z
1,364,199
<p>The only sure way is to use <kbd>Ctrl</kbd><kbd>Break</kbd>. Stops every python script instantly!</p> <p>(Note that on some keyboards, "Break" is labeled as "Pause".)</p>
58
2009-09-01T19:21:49Z
[ "python" ]
Stopping python using ctrl+c
1,364,173
<p>I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to <kbd>Ctrl</kbd><kbd>C</kbd> to stop the program. Is there any way around this?</p>
45
2009-09-01T19:17:13Z
1,364,409
<p>Pressing <kbd>Ctrl</kbd> + <kbd>c</kbd> while a python program is running will cause python to raise a <a href="http://docs.python.org/library/exceptions.html#exceptions.KeyboardInterrupt">KeyboardInterupt</a> exception. It's likely that a program that makes lots of HTTP requests will have lots of exception handling code. If the except part of the try-except block doesn't specify which exceptions it should catch, it will catch all exceptions including the KeyboardInterupt that you just caused. A properly coded python program will make use of the <a href="http://docs.python.org/library/exceptions.html#exception-hierarchy">python exception hierarchy</a> and only catch exceptions that are derived from Exception.</p> <pre><code>#This is the wrong way to do things try: #Some stuff might raise an IO exception except: #Code that ignores errors #This is the right way to do things try: #Some stuff might raise an IO exception except Exception: #This won't catch KeyboardInterupt </code></pre> <p>If you can't change the code (or need to kill the program so that your changes will take effect) then you can try pressing <kbd>Ctrl</kbd> + <kbd>c</kbd> rapidly. The first of the KeyboardInterupt exceptions will knock your program out of the try block and hopefully one of the later KeyboardInterrupt exceptions will be raised when the program is outside of a try block.</p>
44
2009-09-01T20:12:04Z
[ "python" ]
Stopping python using ctrl+c
1,364,173
<p>I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to <kbd>Ctrl</kbd><kbd>C</kbd> to stop the program. Is there any way around this?</p>
45
2009-09-01T19:17:13Z
21,460,045
<p>The interrupt process is hardware and OS dependent. So you will have very different behavior depending on where you run your python script. For example, on Windows machines we have <kbd>Ctrl</kbd>+<kbd>C</kbd> (<code>SIGINT</code>) and <kbd>Ctrl</kbd>+<kbd>Break</kbd> (<code>SIGBREAK</code>). </p> <p>So while SIGINT is present on all systems and can be handled and caught, the SIGBREAK signal is Windows specific (and can be disabled in <em>CONFIG.SYS</em>) and is really handled by the BIOS as an interrupt vector <a href="http://en.wikipedia.org/wiki/BIOS_call">INT 1Bh</a>, which is why this key is much more powerful than any other. So if you're using some *nix flavored OS, you will get different results depending on the implementation, since that signal is not present there, but others are. In Linux you can check what signals are available to you by: </p> <pre><code>$ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGEMT 8) SIGFPE 9) SIGKILL 10) SIGBUS 11) SIGSEGV 12) SIGSYS 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGURG 17) SIGSTOP 18) SIGTSTP 19) SIGCONT 20) SIGCHLD 21) SIGTTIN 22) SIGTTOU 23) SIGIO 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGPWR 30) SIGUSR1 31) SIGUSR2 32) SIGRTMAX </code></pre> <p>So if you want to catch the <code>CTRL+BREAK</code> <a href="http://man7.org/linux/man-pages/man7/signal.7.html">signal</a> on a linux system you'll have to check to what <a href="http://en.wikipedia.org/wiki/Unix_signal">POSIX signal</a> they have mapped that key. Popular mappings are:</p> <pre><code>CTRL+\ = SIGQUIT CTRL+D = SIGQUIT CTRL+C = SIGINT CTRL+Z = SIGTSTOP CTRL+BREAK = SIGKILL or SIGTERM or SIGSTOP </code></pre> <p>In fact, many more functions are available under Linux, where the <kbd>SysRq</kbd> (System Request) key can take on <a href="http://en.wikipedia.org/wiki/Magic_SysRq_key">a life of its own</a>... </p>
14
2014-01-30T15:05:31Z
[ "python" ]
Python 3.1 inline division override
1,364,583
<p>I don't know if this is a bug in 3.1, but if I remember correctly "inline" division worked like this in pre-3k versions:</p> <pre><code>Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class A: ... def __init__(self, x): ... self.x = x ... def __idiv__(self, y): ... self.x /= y ... &gt;&gt;&gt; a = A(5) &gt;&gt;&gt; a /= 2 </code></pre> <p>However, 3.1 gives me this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for /=: 'A' and 'int' </code></pre> <p>... or am I missing something?</p>
3
2009-09-01T20:50:38Z
1,364,606
<p>Gaaah! Found <code>__floordiv__</code> and <code>__truediv__</code>. Sorry!</p> <p>If you'd like to tell me why 2to3 doesn't translate <code>__idiv__</code> into a <code>__truediv__</code> with a <code>__floordiv__(self, y): self.__truediv__(y)</code>, please go ahead!</p>
6
2009-09-01T20:54:39Z
[ "python", "python-3.x" ]
Python generating Python
1,364,640
<p>I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:</p> <pre><code># # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') </code></pre> <p>That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.</p>
8
2009-09-01T21:02:28Z
1,364,714
<p>This is pretty much the best way to generate Python <em>source</em> code. However, you can also generate Python executable code at runtime using the <a href="http://docs.python.org/3.1/library/ast.html" rel="nofollow"><code>ast</code></a> library. (I linked to the Python 3 version because it's more capable than the 2.x version.) You can build code using the abstract syntax tree, then pass it to <code>compile()</code> to compile it into executable code. Then you can use <code>eval</code> to run the code.</p> <p>I'm not sure whether there is a convenient way to save the compiled code for use later though (ie. in a <code>.pyc</code> file).</p>
3
2009-09-01T21:20:35Z
[ "code-generation", "python" ]
Python generating Python
1,364,640
<p>I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:</p> <pre><code># # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') </code></pre> <p>That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.</p>
8
2009-09-01T21:02:28Z
1,364,718
<p>We use Jinja2 to fill in a template. It's much simpler.</p> <p>The template looks a lot like Python code with a few <code>{{something}}</code> replacements in it.</p>
17
2009-09-01T21:21:48Z
[ "code-generation", "python" ]
Python generating Python
1,364,640
<p>I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:</p> <pre><code># # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') </code></pre> <p>That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.</p>
8
2009-09-01T21:02:28Z
1,364,802
<p>From what I understand you are trying to do, I would consider using reflection to dynamically examine a class at runtime and generate output based on that. There is a good tutorial on reflection (A.K.A. introspection) at <a href="http://diveintopython3.ep.io/" rel="nofollow">http://diveintopython3.ep.io/</a>.</p> <p>You can use the <code>dir()</code> function to get a list of names of the attributes of a given object. The doc string of an object is accessible via the <code>__doc__</code> attribute. That is, if you want to look at the doc string of a function or class you can do the following:</p> <pre><code>&gt;&gt;&gt; def foo(): ... """A doc string comment.""" ... pass ... &gt;&gt;&gt; print foo.__doc__ A doc string comment. </code></pre>
0
2009-09-01T21:46:47Z
[ "code-generation", "python" ]
Python generating Python
1,364,640
<p>I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:</p> <pre><code># # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') </code></pre> <p>That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.</p>
8
2009-09-01T21:02:28Z
1,365,122
<p>I'm not sure whether this is especially Pythonic, but you could use operator overloading:</p> <pre><code>class CodeGenerator: def __init__(self, indentation='\t'): self.indentation = indentation self.level = 0 self.code = '' def indent(self): self.level += 1 def dedent(self): if self.level &gt; 0: self.level -= 1 def __add__(self, value): temp = CodeGenerator(indentation=self.indentation) temp.level = self.level temp.code = str(self) + ''.join([self.indentation for i in range(0, self.level)]) + str(value) return temp def __str__(self): return str(self.code) a = CodeGenerator() a += 'for a in range(1, 3):\n' a.indent() a += 'for b in range(4, 6):\n' a.indent() a += 'print(a * b)\n' a.dedent() a += '# pointless comment\n' print(a) </code></pre> <p>This is, of course, far more expensive to implement than your example, and I would be wary of too much meta-programming, but it was a fun exercise. You can extend or use this as you see fit; how about:</p> <ul> <li>adding a write method and redirecting stdout to an object of this to print straight to a script file</li> <li>inheriting from it to customise output</li> <li>adding attribute getters and setters</li> </ul> <p>Would be great to hear about whatever you go with :)</p>
0
2009-09-01T23:15:49Z
[ "code-generation", "python" ]
Python generating Python
1,364,640
<p>I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:</p> <pre><code># # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') </code></pre> <p>That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.</p>
8
2009-09-01T21:02:28Z
1,365,182
<p>Just read your comment to wintermute - ie:</p> <blockquote> <p>What I have is a bunch of planets that I want to store each as their own text files. I'm not particularly attached to storing them as python source code, but I am attached to making them human-readable.</p> </blockquote> <p>If that's the case, then it seems like you shouldn't need subclasses but should be able to use the same class and distinguish the planets via data alone. And in that case, why not just write the data to files and, when you need the planet objects in your program, read in the data to initialize the objects?</p> <p>If you needed to do stuff like overriding methods, I could see writing out code - but shouldn't you just be able to have the same methods for all planets, just using different variables?</p> <p>The advantage of just writing out the data (it can include label type info for readability that you'd skip when you read it in) is that non-Python programmers won't get distracted when reading them, you could use the same files with some other language if necessary, etc.</p>
7
2009-09-01T23:39:09Z
[ "code-generation", "python" ]
Python generating Python
1,364,640
<p>I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:</p> <pre><code># # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') </code></pre> <p>That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.</p>
8
2009-09-01T21:02:28Z
28,443,506
<p>I'd recommend using <a href="https://github.com/audreyr/cookiecutter" rel="nofollow">cookiecutter</a> for generating code.</p>
3
2015-02-10T22:58:04Z
[ "code-generation", "python" ]
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
<p>How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.</p>
14
2009-09-01T21:26:11Z
1,364,875
<p>You can check if <code>os.environ['HTTP_HOST'].endswith('.appspot.com')</code> -- if so, then you're serving from <code>something.appspot.com</code> and can send a redirect, or otherwise alter your behavior as desired.</p> <p>You could deploy this check-and-redirect-if-needed (or other behavior alteration of your choice) in any of various ways (decorators, WSGI middleware, inheritance from an intermediate base class of yours that subclasses <code>webapp.RequestHandler</code> [[or whatever other base handler class you're currently using]] and method names different than get and post in your application-level handler classes, and others yet) but I think that the key idea here is that <code>os.environ</code> is set by the app engine framework according to CGI standards and so you can rely on those standards (similarly WSGI builds its own environment based on the values it picks up from os.environ).</p>
15
2009-09-01T22:02:16Z
[ "python", "google-app-engine", "redirect" ]
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
<p>How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.</p>
14
2009-09-01T21:26:11Z
1,404,772
<pre><code>def redirect_from_appspot(wsgi_app): def redirect_if_needed(env, start_response): if env["HTTP_HOST"].startswith('my_app_name.appspot.com'): import webob, urlparse request = webob.Request(env) scheme, netloc, path, query, fragment = urlparse.urlsplit(request.url) url = urlparse.urlunsplit([scheme, 'www.my_domain.com', path, query, fragment]) start_response('301 Moved Permanently', [('Location', url)]) return ["301 Moved Peramanently", "Click Here" % url] else: return wsgi_app(env, start_response) return redirect_if_needed </code></pre>
3
2009-09-10T11:36:06Z
[ "python", "google-app-engine", "redirect" ]
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
<p>How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.</p>
14
2009-09-01T21:26:11Z
1,980,033
<p>The code posted above has two problems - it tries to redirect secure traffic (which isn't supported on custom domains), and also your cron jobs will fail when Google call them on your appspot domain and you serve up a 301.</p> <p>I posted a slightly modified version to my blog: <a href="http://blog.dantup.com/2009/12/redirecting-requests-from-appid-appspot-com-to-a-custom-domain">http://blog.dantup.com/2009/12/redirecting-requests-from-appid-appspot-com-to-a-custom-domain</a></p> <p>I've included the code below for convenience.</p> <pre><code>from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app def run_app(url_mapping): application = webapp.WSGIApplication(url_mapping, debug=True) application = redirect_from_appspot(application) run_wsgi_app(application) def redirect_from_appspot(wsgi_app): """Handle redirect to my domain if called from appspot (and not SSL)""" from_server = "dantup-blog.appspot.com" to_server = "blog.dantup.com" def redirect_if_needed(env, start_response): # If we're calling on the appspot address, and we're not SSL (SSL only works on appspot) if env["HTTP_HOST"].endswith(from_server) and env["HTTPS"] == "off": # Parse the URL import webob, urlparse request = webob.Request(env) scheme, netloc, path, query, fragment = urlparse.urlsplit(request.url) url = urlparse.urlunsplit([scheme, to_server, path, query, fragment]) # Exclude /admin calls, since they're used by Cron, TaskQueues and will fail if they return a redirect if not path.startswith('/admin'): # Send redirect start_response("301 Moved Permanently", [("Location", url)]) return ["301 Moved Peramanently", "Click Here %s" % url] # Else, we return normally return wsgi_app(env, start_response) return redirect_if_needed </code></pre>
7
2009-12-30T12:45:25Z
[ "python", "google-app-engine", "redirect" ]
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
<p>How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.</p>
14
2009-09-01T21:26:11Z
23,743,686
<p>In case you are using <a href="https://webapp-improved.appspot.com/" rel="nofollow">webapp2</a>, a slightly easier (depending on your use case) solution is possible using its <code>DomainRoute</code>.</p> <p>If this is your URL map:</p> <pre><code>url_map = [ ('/', HomeHandler), ('/about', AboutHandler), ('/admin/(.+)', AdminHandler), MailForwardHandler.mapping(), ] application = webapp2.WSGIApplication(url_map, debug=True) </code></pre> <p>and the admin and mail should <em>not</em> redirect, then add the redirect routes as follows:</p> <pre><code>from webapp2_extras import routes url_map = [ routes.DomainRoute('appid.appspot.com', [ routes.RedirectRoute('/', redirect_to='http://app.com', schemes=['http']), routes.RedirectRoute('/about', redirect_to='http://app.com/about', schemes=['http']), ], ('/', HomeHandler), ('/about', AboutHandler), ('/admin/(.+)', AdminHandler), MailForwardHandler.mapping(), ] application = webapp2.WSGIApplication(url_map, debug=True) </code></pre> <p>This will, as specified, only redirect http, <em>not</em> https. It uses a permanent redirect (301), as desired.</p> <p>You can also pass a function to <code>redirect_to</code>, <a href="https://webapp-improved.appspot.com/api/webapp2_extras/routes.html#webapp2_extras.routes.RedirectRoute" rel="nofollow">as described in the documentation</a>, which should make it easier when you have lots of rules.</p>
0
2014-05-19T17:25:03Z
[ "python", "google-app-engine", "redirect" ]
Block requests from *.appspot.com and force custom domain in Google App Engine
1,364,733
<p>How can I prevent a user from accessing my app at example.appspot.com and force them to access it at example.com? I already have example.com working, but I don't want users to be able to access the appspot domain. I'm using python.</p>
14
2009-09-01T21:26:11Z
24,758,934
<p>You can redirect it to your custom domain (here <code>example.com</code>) by overriding the <code>initialize</code> method in your <code>webapp2.RequestHandler</code> base class the following way :</p> <pre><code>def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) if self.request.host.endswith('appspot.com'): self.request.host = 'example.com' self.redirect(self.request.url, permanent=True) </code></pre>
1
2014-07-15T13:03:06Z
[ "python", "google-app-engine", "redirect" ]
How to connect to a GObject signal in python, without it keeping a reference to the connecter?
1,364,923
<p>The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:</p> <pre><code>class ClipboardMonitor (object): def __init__(self): clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD) clip.connect("owner-change", self._clipboard_changed) </code></pre> <p>The problem is now that, <strong>no instance of ClipboardMonitor will ever die</strong>. The gtk clipboard is an application-wide object, and connecting to it keeps a reference to the object, since we use the callback <code>self._clipboard_changed</code>.</p> <p>I'm debating how to work around this using weak references (weakref module), but I have yet to come up with a plan. Anyone have an idea how to pass a callback to the signal registration, and have it behave like a weak reference (if the signal callback is called when the ClipboardMonitor instance is out of scope, it should be a no-op).</p> <p>Addition: <strong>Phrased independently of GObject or GTK+:</strong></p> <p>How do you provide a callback method to an opaque object, with weakref semantics? If the connecting object goes out of scope, it should be deleted and the callback should act as a no-op; the connectee should not hold a reference to the connector.</p> <p>To clarify: I explicitly want to avoid having to call a "destructor/finalizer" method</p>
2
2009-09-01T22:16:52Z
1,364,959
<p>The standard way is to disconnect the signal. This however needs to have a destructor-like method in your class, called explicitly by code which maintains your object. This is necessary, because otherwise you'll get circular dependency.</p> <pre><code>class ClipboardMonitor(object): [...] def __init__(self): self.clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD) self.signal_id = self.clip.connect("owner-change", self._clipboard_changed) def close(self): self.clip.disconnect(self.signal_id) </code></pre> <p>As you pointed out, you need weakrefs if you want to avoid explicite destroying. I would write a weak callback factory, like:</p> <pre><code>import weakref class CallbackWrapper(object): def __init__(self, sender, callback): self.weak_obj = weakref.ref(callback.im_self) self.weak_fun = weakref.ref(callback.im_func) self.sender = sender self.handle = None def __call__(self, *things): obj = self.weak_obj() fun = self.weak_fun() if obj is not None and fun is not None: return fun(obj, *things) elif self.handle is not None: self.sender.disconnect(self.handle) self.handle = None self.sender = None def weak_connect(sender, signal, callback): wrapper = CallbackWrapper(sender, callback) wrapper.handle = sender.connect(signal, wrapper) return wrapper </code></pre> <p>(this is a proof of concept code, works for me -- you should probably adapt this piece to your needs). Few notes:</p> <ul> <li>I am storing callback object and function separatelly. You cannot simply make a weakref of a bound method, because bound methods are very temporary objects. Actually <code>weakref.ref(obj.method)</code> will destroy the bound method object instantly after creating a weakref. I didn't checked it it is needed to store a weakref to the function too... I guess if your code is static, you probably can avoid that.</li> <li>The object wrapper will remove itself from the signal sender when it notices that the weak reference ceased to exist. This is also necessary to destroy the circular dependence between the CallbackWrapper and the signal sender object.</li> </ul>
6
2009-09-01T22:27:56Z
[ "python", "pygtk", "pygobject" ]
How to connect to a GObject signal in python, without it keeping a reference to the connecter?
1,364,923
<p>The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:</p> <pre><code>class ClipboardMonitor (object): def __init__(self): clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD) clip.connect("owner-change", self._clipboard_changed) </code></pre> <p>The problem is now that, <strong>no instance of ClipboardMonitor will ever die</strong>. The gtk clipboard is an application-wide object, and connecting to it keeps a reference to the object, since we use the callback <code>self._clipboard_changed</code>.</p> <p>I'm debating how to work around this using weak references (weakref module), but I have yet to come up with a plan. Anyone have an idea how to pass a callback to the signal registration, and have it behave like a weak reference (if the signal callback is called when the ClipboardMonitor instance is out of scope, it should be a no-op).</p> <p>Addition: <strong>Phrased independently of GObject or GTK+:</strong></p> <p>How do you provide a callback method to an opaque object, with weakref semantics? If the connecting object goes out of scope, it should be deleted and the callback should act as a no-op; the connectee should not hold a reference to the connector.</p> <p>To clarify: I explicitly want to avoid having to call a "destructor/finalizer" method</p>
2
2009-09-01T22:16:52Z
1,365,131
<p>(This answer tracks my progress)</p> <p>This second version will disconnect as well; I have a convenience function for gobjects, but I actually need this class for a more general case -- both for D-Bus signal callbacks and GObject callbacks.</p> <p>Anyway, what can one call the <code>WeakCallback</code> implementation style? It is a very clean encapsulation of the weak callback, but with the gobject/dbus specialization unnoticeably tacked on. Beats writing two subclasses for those two cases.</p> <pre><code>import weakref class WeakCallback (object): """A Weak Callback object that will keep a reference to the connecting object with weakref semantics. This allows to connect to gobject signals without it keeping the connecting object alive forever. Will use @gobject_token or @dbus_token if set as follows: sender.disconnect(gobject_token) dbus_token.remove() """ def __init__(self, obj, attr): """Create a new Weak Callback calling the method @obj.@attr""" self.wref = weakref.ref(obj) self.callback_attr = attr self.gobject_token = None self.dbus_token = None def __call__(self, *args, **kwargs): obj = self.wref() if obj: attr = getattr(obj, self.callback_attr) attr(*args, **kwargs) elif self.gobject_token: sender = args[0] sender.disconnect(self.gobject_token) self.gobject_token = None elif self.dbus_token: self.dbus_token.remove() self.dbus_token = None def gobject_connect_weakly(sender, signal, connector, attr, *user_args): """Connect weakly to GObject @sender's @signal, with a callback in @connector named @attr. """ wc = WeakCallback(connector, attr) wc.gobject_token = sender.connect(signal, wc, *user_args) </code></pre>
0
2009-09-01T23:20:06Z
[ "python", "pygtk", "pygobject" ]
How to connect to a GObject signal in python, without it keeping a reference to the connecter?
1,364,923
<p>The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:</p> <pre><code>class ClipboardMonitor (object): def __init__(self): clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD) clip.connect("owner-change", self._clipboard_changed) </code></pre> <p>The problem is now that, <strong>no instance of ClipboardMonitor will ever die</strong>. The gtk clipboard is an application-wide object, and connecting to it keeps a reference to the object, since we use the callback <code>self._clipboard_changed</code>.</p> <p>I'm debating how to work around this using weak references (weakref module), but I have yet to come up with a plan. Anyone have an idea how to pass a callback to the signal registration, and have it behave like a weak reference (if the signal callback is called when the ClipboardMonitor instance is out of scope, it should be a no-op).</p> <p>Addition: <strong>Phrased independently of GObject or GTK+:</strong></p> <p>How do you provide a callback method to an opaque object, with weakref semantics? If the connecting object goes out of scope, it should be deleted and the callback should act as a no-op; the connectee should not hold a reference to the connector.</p> <p>To clarify: I explicitly want to avoid having to call a "destructor/finalizer" method</p>
2
2009-09-01T22:16:52Z
1,726,152
<p>not actually tried it yet, but:</p> <pre><code>class WeakCallback(object): """ Used to wrap bound methods without keeping a ref to the underlying object. You can also pass in user_data and user_kwargs in the same way as with rpartial. Note that refs will be kept to everything you pass in other than the callback, which will have a weakref kept to it. """ def __init__(self, callback, *user_data, **user_kwargs): self.im_self = weakref.proxy(callback.im_self, self._invalidated) self.im_func = weakref.proxy(callback.im_func) self.user_data = user_data self.user_kwargs = user_kwargs def __call__(self, *args, **kwargs): kwargs.update(self.user_kwargs) args += self.user_data self.im_func(self.im_self, *args, **kwargs) def _invalidated(self, im_self): """Called by the weakref.proxy object.""" cb = getattr(self, 'cancel_callback', None) if cb is not None: cb() def add_cancel_function(self, cancel_callback): """ A ref will be kept to cancel_callback. It will be called back without any args when the underlying object dies. You can wrap it in WeakCallback if you want, but that's a bit too self-referrential for me to do by default. Also, that would stop you being able to use a lambda as the cancel_callback. """ self.cancel_callback = cancel_callback def weak_connect(sender, signal, callback): """ API-compatible with the function described in http://stackoverflow.com/questions/1364923/. Mostly used as an example. """ cb = WeakCallback(callback) handle = sender.connect(signal, cb) cb.add_cancel_function(WeakCallback(sender.disconnect, handle)) </code></pre>
0
2009-11-12T23:30:29Z
[ "python", "pygtk", "pygobject" ]
Python on Snow Leopard, how to open >255 sockets?
1,364,955
<p>Consider this code:</p> <pre><code>import socket store = [] scount = 0 while True: scount+=1 print "Creating socket %d" % (scount) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) store.append(s) </code></pre> <p>Gives the following result:</p> <pre><code>Creating socket 1 Creating socket 2 ... Creating socket 253 Creating socket 254 Traceback (most recent call last): File "test_sockets.py", line 9, in &lt;module&gt; File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/socket.py", line 159, in __init__ socket.error: (24, 'Too many open files') </code></pre> <p>Checking sysctl for the allowed number of open files gives:</p> <pre><code>$ sysctl -A |grep maxfiles kern.maxfiles = 12288 kern.maxfilesperproc = 10240 kern.maxfiles: 12288 kern.maxfilesperproc: 10240 </code></pre> <p>Which is way more than the 253 sockets I could successfully open...</p> <p>Could someone please help me in getting this number up to over 500? I am trying to simulate a peer to peer network using real sockets (requirement), with only 50 simulated nodes and 5 outgoing and 5 incoming connections each, would give the number of 500 needed sockets.</p> <p>By the way, running this same code under Linux gives me about 1020 sockets, which is more the way I like it.</p>
4
2009-09-01T22:27:06Z
1,364,989
<p>Did you install XCode and the developer tools off the Snow Leopard install disk? I'm able to open way more ports than you're able to:</p> <pre><code>Creating socket 1 Creating socket 2 ... Creating socket 7161 Creating socket 7162 Creating socket 7163 Creating socket 7164 Creating socket 7165 Creating socket 7166 Traceback (most recent call last): File "socket-test.py", line 7, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/socket.py", line 159, in __init__ socket.error: (24, 'Too many open files') </code></pre> <p><code>sysctl</code> shows me a lot more info then your output shows (even with the grep) but the four lines you have match mine exactly, so all I can think of is needing something from the dev tools on the disk.</p>
1
2009-09-01T22:36:14Z
[ "python", "sockets", "osx" ]
Python on Snow Leopard, how to open >255 sockets?
1,364,955
<p>Consider this code:</p> <pre><code>import socket store = [] scount = 0 while True: scount+=1 print "Creating socket %d" % (scount) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) store.append(s) </code></pre> <p>Gives the following result:</p> <pre><code>Creating socket 1 Creating socket 2 ... Creating socket 253 Creating socket 254 Traceback (most recent call last): File "test_sockets.py", line 9, in &lt;module&gt; File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/socket.py", line 159, in __init__ socket.error: (24, 'Too many open files') </code></pre> <p>Checking sysctl for the allowed number of open files gives:</p> <pre><code>$ sysctl -A |grep maxfiles kern.maxfiles = 12288 kern.maxfilesperproc = 10240 kern.maxfiles: 12288 kern.maxfilesperproc: 10240 </code></pre> <p>Which is way more than the 253 sockets I could successfully open...</p> <p>Could someone please help me in getting this number up to over 500? I am trying to simulate a peer to peer network using real sockets (requirement), with only 50 simulated nodes and 5 outgoing and 5 incoming connections each, would give the number of 500 needed sockets.</p> <p>By the way, running this same code under Linux gives me about 1020 sockets, which is more the way I like it.</p>
4
2009-09-01T22:27:06Z
1,365,014
<p>You can increase available sockets with <code>ulimit</code>. Looks like 1200 is the max for non-root users in bash. I can get up to 10240 with zsh.</p> <pre><code>$ ulimit -n 1200 $ python sockets .... Creating socket 1197 Creating socket 1198 Traceback (most recent call last): File "sockets", line 7, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 182, in __init__ socket.error: [Errno 24] Too many open files </code></pre>
16
2009-09-01T22:44:06Z
[ "python", "sockets", "osx" ]
Python packages depending on libxml2 and libxslt
1,365,075
<p>Apart from <code>lxml</code>, is anyone aware of Python packages that depend on libxml2 and libxslt?</p>
0
2009-09-01T23:01:34Z
1,365,180
<p>See e.g. the list <a href="http://www.xmlsoft.org/XSLT/python.html" rel="nofollow">here</a> -- not exhaustive, as the page itself says, but a start.</p>
1
2009-09-01T23:38:41Z
[ "python", "dependencies", "lxml", "libxml2", "libxslt" ]
virtualenv in PowerShell?
1,365,081
<p>Hi fellow pythonistas, there seems to be a problem when <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> is used in PowerShell.</p> <p>When I try to activate my environment in PowerShell like..</p> <p>&gt; env/scripts/activate</p> <p>.. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .)</p> <p>I guess the problem is that PowerShell spawns a new cmd. process just for running the activate.bat thus rendering the changes activate.bat does to the shell dead after it completes. </p> <p>Do you have any workarounds for the issue? (I'm sticking with cmd.exe for now)</p>
11
2009-09-01T23:03:59Z
1,365,119
<p><a href="http://www.leeholmes.com/blog/NothingSolvesEverythingPowerShellAndOtherTechnologies.aspx">Here</a>'s a post which contains a Powershell script which allows you to run batch files that persistently modify their environment variables. The script propagates any environment variable changes back to the calling PowerShell environment.</p>
8
2009-09-01T23:15:02Z
[ "python", "powershell", "virtualenv" ]
virtualenv in PowerShell?
1,365,081
<p>Hi fellow pythonistas, there seems to be a problem when <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> is used in PowerShell.</p> <p>When I try to activate my environment in PowerShell like..</p> <p>&gt; env/scripts/activate</p> <p>.. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .)</p> <p>I guess the problem is that PowerShell spawns a new cmd. process just for running the activate.bat thus rendering the changes activate.bat does to the shell dead after it completes. </p> <p>Do you have any workarounds for the issue? (I'm sticking with cmd.exe for now)</p>
11
2009-09-01T23:03:59Z
3,927,458
<p>A quick work-around would be to invoke cmd and then run your activate.bat from within the cmd session. For example:</p> <pre><code>PS C:\my_cool_env\Scripts&gt; cmd Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\my_cool_env\Scripts&gt;activate.bat (my_cool_env) C:\my_cool_env\Scripts&gt; </code></pre>
2
2010-10-13T19:52:47Z
[ "python", "powershell", "virtualenv" ]
virtualenv in PowerShell?
1,365,081
<p>Hi fellow pythonistas, there seems to be a problem when <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> is used in PowerShell.</p> <p>When I try to activate my environment in PowerShell like..</p> <p>&gt; env/scripts/activate</p> <p>.. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .)</p> <p>I guess the problem is that PowerShell spawns a new cmd. process just for running the activate.bat thus rendering the changes activate.bat does to the shell dead after it completes. </p> <p>Do you have any workarounds for the issue? (I'm sticking with cmd.exe for now)</p>
11
2009-09-01T23:03:59Z
10,030,999
<p><strong><a href="http://pypi.python.org/pypi/virtualenv">The latest version of virtualenv</a> supports PowerShell out-of-the-box</strong>.</p> <p>Just make sure you run:</p> <pre><code>Scripts\activate.ps1 </code></pre> <p>instead of</p> <pre><code>Scripts\activate </code></pre> <p>The latter will execute <code>activate.bat</code>, which doesn't work on PowerShell.</p>
26
2012-04-05T14:56:40Z
[ "python", "powershell", "virtualenv" ]
virtualenv in PowerShell?
1,365,081
<p>Hi fellow pythonistas, there seems to be a problem when <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> is used in PowerShell.</p> <p>When I try to activate my environment in PowerShell like..</p> <p>&gt; env/scripts/activate</p> <p>.. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .)</p> <p>I guess the problem is that PowerShell spawns a new cmd. process just for running the activate.bat thus rendering the changes activate.bat does to the shell dead after it completes. </p> <p>Do you have any workarounds for the issue? (I'm sticking with cmd.exe for now)</p>
11
2009-09-01T23:03:59Z
29,918,484
<p>try this: <code>. .\env\Scripts\activate.ps1</code> watch dots and spaces</p>
-1
2015-04-28T11:41:41Z
[ "python", "powershell", "virtualenv" ]
virtualenv in PowerShell?
1,365,081
<p>Hi fellow pythonistas, there seems to be a problem when <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> is used in PowerShell.</p> <p>When I try to activate my environment in PowerShell like..</p> <p>&gt; env/scripts/activate</p> <p>.. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .)</p> <p>I guess the problem is that PowerShell spawns a new cmd. process just for running the activate.bat thus rendering the changes activate.bat does to the shell dead after it completes. </p> <p>Do you have any workarounds for the issue? (I'm sticking with cmd.exe for now)</p>
11
2009-09-01T23:03:59Z
34,651,375
<p>This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:</p> <p><i>set-executionpolicy remotesigned </i></p> <p>for more: <a href="http://www.faqforge.com/windows/windows-powershell-running-scripts-is-disabled-on-this-system/" rel="nofollow">http://www.faqforge.com/windows/windows-powershell-running-scripts-is-disabled-on-this-system/</a></p>
1
2016-01-07T09:21:17Z
[ "python", "powershell", "virtualenv" ]
Is storing user configuration settings on database OK?
1,365,164
<p>I'm building a fairly large enterprise application made in python that on its first version will require network connection.</p> <p>I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder.</p> <p>Some of the advantages I've thought of are:</p> <ul> <li>the user can change computers keeping all its settings</li> <li>settings can be backed up along with the rest of the systems data (not a big concern)</li> </ul> <p>What would be some of the caveats of this approach?</p>
2
2009-09-01T23:32:52Z
1,365,175
<p>One caveat might depend on where the user is using the application from. For example, if they use two computers with different screen resolutions, and 'selected zoom/text size' is one of the things you associate with the user, it might not always be suitable. It depends what kind of settings you intend to allow the user to customize. My workplace still has some users trapped on tiny LCD screens with a max res of 800x600, and we have to account for those when developing.</p>
5
2009-09-01T23:36:38Z
[ "python", "database", "settings", "code-smell" ]
Is storing user configuration settings on database OK?
1,365,164
<p>I'm building a fairly large enterprise application made in python that on its first version will require network connection.</p> <p>I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder.</p> <p>Some of the advantages I've thought of are:</p> <ul> <li>the user can change computers keeping all its settings</li> <li>settings can be backed up along with the rest of the systems data (not a big concern)</li> </ul> <p>What would be some of the caveats of this approach?</p>
2
2009-09-01T23:32:52Z
1,365,176
<p>Do you need the database to run any part of the application? If that's the case there are no reasons <strong>not</strong> to store the config inside the DB. You already mentioned the benefits and there are no downsides.</p>
3
2009-09-01T23:36:46Z
[ "python", "database", "settings", "code-smell" ]
Is storing user configuration settings on database OK?
1,365,164
<p>I'm building a fairly large enterprise application made in python that on its first version will require network connection.</p> <p>I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder.</p> <p>Some of the advantages I've thought of are:</p> <ul> <li>the user can change computers keeping all its settings</li> <li>settings can be backed up along with the rest of the systems data (not a big concern)</li> </ul> <p>What would be some of the caveats of this approach?</p>
2
2009-09-01T23:32:52Z
1,365,178
<p>This is pretty standard. Go for it.</p> <p>The caveat is that when you take the database down for maintenance, no one can use the app because their profile is inaccessible. You can either solve that by making a 100%-on db solution, or, more easily, through some form of caching of profiles locally (an "offline" mode of operations). That would allow your app to function whether the user or the db are off the network.</p>
8
2009-09-01T23:38:23Z
[ "python", "database", "settings", "code-smell" ]
Is storing user configuration settings on database OK?
1,365,164
<p>I'm building a fairly large enterprise application made in python that on its first version will require network connection.</p> <p>I've been thinking in keeping some user settings stored on the database, instead of a file in the users home folder.</p> <p>Some of the advantages I've thought of are:</p> <ul> <li>the user can change computers keeping all its settings</li> <li>settings can be backed up along with the rest of the systems data (not a big concern)</li> </ul> <p>What would be some of the caveats of this approach?</p>
2
2009-09-01T23:32:52Z
1,365,183
<p>It's perfectly reasonable to keep user settings in the database, as long as the settings pertain to the application independent of user location. One possible advantage of a file in the user's home folder is that users can send settings to one another. You may of course regard this as an advantage or a disadvantage :-)</p>
3
2009-09-01T23:39:42Z
[ "python", "database", "settings", "code-smell" ]
How to deal with user authentication and wrongful modification in scripting languages?
1,365,254
<p>I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory).</p> <p>Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project.</p> <p>The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because "compiling" with <code>py2exe</code> is the closest I can get to obfuscation of the code on Windows. </p> <p>I'm not really trying to <em>hide</em> the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app.</p> <p>One of the ways I've thought to avoid this is making a <code>C</code> module for the authentication, but I would rather not have to do that.</p> <p>Of course this question is changing now and is not just "Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?", but "How do you harden an scripting (Python) against wrongful modification?"</p>
2
2009-09-02T00:03:32Z
1,365,394
<p>Possibly:</p> <ol> <li>The user enters their credentials into the desktop client.</li> <li>The client says to the server: "Hi, my name username and my password is password".</li> <li>The server checks these.</li> <li>The server says to the client: "Hi, username. Here is your secret token: ..."</li> <li>Subsequently the client uses the secret token together with the username to "sign" communications with the server.</li> </ol>
1
2009-09-02T00:53:33Z
[ "python", "security", "design-patterns", "authentication", "cracking" ]
How to deal with user authentication and wrongful modification in scripting languages?
1,365,254
<p>I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory).</p> <p>Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project.</p> <p>The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because "compiling" with <code>py2exe</code> is the closest I can get to obfuscation of the code on Windows. </p> <p>I'm not really trying to <em>hide</em> the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app.</p> <p>One of the ways I've thought to avoid this is making a <code>C</code> module for the authentication, but I would rather not have to do that.</p> <p>Of course this question is changing now and is not just "Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?", but "How do you harden an scripting (Python) against wrongful modification?"</p>
2
2009-09-02T00:03:32Z
1,365,422
<p>How malicious are your users? Really.</p> <p>Exactly how malicious?</p> <p>If your users are evil sociopaths and can't be trusted with a desktop solution, then <strong>don't build a desktop solution</strong>. Build a web site.</p> <p>If your users are ordinary users, they'll screw the environment up by installing viruses, malware and keyloggers from porn sites before they try to (a) learn Python (b) learn how your security works and (c) make a sincere effort at breaking it.</p> <p>If you actually have desktop security issues (i.e., public safety, military, etc.) then rethink using the desktop.</p> <p>Otherwise, relax, do the right thing, and don't worry about "scripting".</p> <p>C++ programs are easier to hack because people are lazy and permit SQL injection. </p>
3
2009-09-02T01:07:36Z
[ "python", "security", "design-patterns", "authentication", "cracking" ]
On localhost, how to pick a free port number?
1,365,265
<p>I try to play with inter process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally, server is able to launch slaves in a separate process and listens on some port and the slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using python, if that cuts the choices down.... Thanks!</p>
91
2009-09-02T00:07:14Z
1,365,281
<p>Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with <code>getsockname()</code> right after <code>bind()</code>.</p>
28
2009-09-02T00:12:53Z
[ "python", "sockets", "ipc", "port" ]
On localhost, how to pick a free port number?
1,365,265
<p>I try to play with inter process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally, server is able to launch slaves in a separate process and listens on some port and the slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using python, if that cuts the choices down.... Thanks!</p>
91
2009-09-02T00:07:14Z
1,365,283
<p>You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and <em>CATCH EXCEPTIONS</em>. That is how you will know if a port is unusable (used by another process, in other words) on your computer. </p> <p>However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails.</p> <p>Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data.</p> <p>I presume you will be using UDP for this?</p>
2
2009-09-02T00:13:25Z
[ "python", "sockets", "ipc", "port" ]
On localhost, how to pick a free port number?
1,365,265
<p>I try to play with inter process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally, server is able to launch slaves in a separate process and listens on some port and the slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using python, if that cuts the choices down.... Thanks!</p>
91
2009-09-02T00:07:14Z
1,365,284
<p>Do not bind to a specific port, or bind to port 0, e.g. <code>sock.bind(('', 0))</code>. The OS will then pick an available port for you. You can get the port that was chosen using <code>sock.getsockname()[1]</code>, and pass it on to the slaves so that they can connect back.</p>
143
2009-09-02T00:14:14Z
[ "python", "sockets", "ipc", "port" ]
What's a server equivalent of django.test.client to test external URL fetch?
1,365,279
<p>I'd like to make sure a given view in my test is fetching an external URL properly. It uses urllib2 (but this shouldn't matter, since it's blackbox testing). Perhaps a temporary local server of some kind? Is there an app that does this already? (My Googling has failed me.)</p>
0
2009-09-02T00:12:35Z
1,365,296
<p>Your module under test presumably imports urllib2. You can monkey-patch the module in your test harness to point to your own fake urllib2 - for instance, this needn't be a module, it could be a class instance which has an urlopen method which checks that the correct url is called and returns a suitable response.</p> <p><strong>Update:</strong> Here's a skeleton of the approach. Let's assume your module under test is called <code>mymodule</code>. In your test module (or a separate utility module), you could have:</p> <pre><code>import urllib2 # the real urllib2 class Urllib2Simulator: # This is a sort of Mock #In practice, you could supply additional parameters to this to tell it #how to behave when e.g. urlopen is classed def __init__(self): self.urls_opened = [] def urlopen(self, url, data=None): # this method simulates urlopen self.urls_opened.append((url, data)) # remember what was opened #Now, you can either delegate to the real urllib2 (simplest) #Or completely simulate what it does (that's more work) #Let's keep it simple for this answer. #Our class instance will be acting a bit like a proxy. return urllib2.urlopen(url, data) #similarly define any other urllib2 functions that mymodule calls </code></pre> <p>and then, in your test code:</p> <pre><code>class MyModuleTest(unittest.TestCase): def test_url_retrieval(self): # use whatever name is best real_urllib2 = mymodule.urllib2 #remember it so we can restore it simulator = Urllib2Simulator() mymodule.urllib2 = simulator # the monkey-patch is here # here, invoke your mymodule functionality which is supposed to # retrieve URLs using urllib2.urlopen mymodule.do_something_which_fetches_urls() #restore the previous binding to urllib2 mymodule.urllib2 = real_urllib2 # restored - back to normal #Now, check that simulator.urls_opened contains the correct values </code></pre> <p>I've used this technique with some success. (It's particularly useful when you want to simulate time passing.) In a unit-test scenario it's less work than setting up a real server. For integration testing I'd probably use a real server, as S. Lott's answer suggests. But this approach allows you to easily simulate different conditions, without having a whole server-based test framework (for example, you can set things up so that the server appears to return particular errors, to test how your code would handle them, or configurable delays in responding, so you can test timeouts, or malformed responses, etc.)</p>
3
2009-09-02T00:19:06Z
[ "python", "django", "testing" ]
What's a server equivalent of django.test.client to test external URL fetch?
1,365,279
<p>I'd like to make sure a given view in my test is fetching an external URL properly. It uses urllib2 (but this shouldn't matter, since it's blackbox testing). Perhaps a temporary local server of some kind? Is there an app that does this already? (My Googling has failed me.)</p>
0
2009-09-02T00:12:35Z
1,365,434
<p>You can use <a href="http://docs.python.org/library/simplehttpserver.html" rel="nofollow">SimpleHTTPServer</a> to rig up a fake web server for testing.</p> <p>We use the WSGI reference implementation, <a href="http://docs.python.org/library/wsgiref.html" rel="nofollow">wsgiref</a>, to rig up a fake web server for testing, also. We like wsgiref because it's a very clean way to create an extensible mock web server. Further, we have status and shutdown WSGI applications that we use to make sure that everything happened properly from the web site's point of view.</p>
2
2009-09-02T01:12:34Z
[ "python", "django", "testing" ]
What's a server equivalent of django.test.client to test external URL fetch?
1,365,279
<p>I'd like to make sure a given view in my test is fetching an external URL properly. It uses urllib2 (but this shouldn't matter, since it's blackbox testing). Perhaps a temporary local server of some kind? Is there an app that does this already? (My Googling has failed me.)</p>
0
2009-09-02T00:12:35Z
36,316,530
<p>I'm a huge fan of <a href="https://github.com/kevin1024/vcrpy" rel="nofollow">vcrpy</a> (<a href="https://pypi.python.org/pypi/vcrpy" rel="nofollow">PyPI</a>) when testing external URLs. It can record HTTP interactions to a file and play them back when the test is run later. The easiest way to use it is a decorator on the test function, and the cassettes (recorded request/responses) are in YAML by default and easy to edit. From their README:</p> <blockquote> <p>VCR.py simplifies and speeds up tests that make HTTP requests. The first time you run code that is inside a VCR.py context manager or decorated function, VCR.py records all HTTP interactions that take place through the libraries it supports and serializes and writes them to a flat file (in yaml format by default). This flat file is called a cassette. When the relevant piece of code is executed again, VCR.py will read the serialized requests and responses from the aforementioned cassette file, and intercept any HTTP requests that it recognizes from the original test run and return the responses that corresponded to those requests.</p> </blockquote> <p>Example (also from the docs):</p> <pre><code>@vcr.use_cassette('fixtures/vcr_cassettes/synopsis.yaml') def test_iana(): response = urllib2.urlopen('http://www.iana.org/domains/reserved').read() assert 'Example domains' in response </code></pre>
0
2016-03-30T18:12:23Z
[ "python", "django", "testing" ]
Center Google Map Based on geocoded IP
1,365,722
<p>Basically whenever someones opens up my (Google) map I want it default to their approximate location.</p> <p>Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?</p>
5
2009-09-02T03:38:31Z
1,365,734
<p>Check out <a href="http://www.ipinfodb.com/" rel="nofollow">http://www.ipinfodb.com/</a>. You can get a latitude and longitude value by passing their services an IP address. I did something recently where I created a simple service that grabbed the current IP address and then passed it to the service ("api/location/city" is just a service that curls the ipinfodb service). Using jquery:</p> <pre><code>$.get("api/location/city", null, function(data, textStatus) { if (data != null) { if (data.Status == "OK") { var lat = parseFloat(data.Latitude); var lng = parseFloat(data.Longitude); $.setCenter(lat, lng, $.settings.defaultCityZoom); manager = new MarkerManager(map, {trackMarkers : true }); var e = $.createUserMarker(map.getCenter()); e.bindInfoWindowHtml($("#marker-content-event").html()); var m = []; m.push(e); // map.addOverlay(e); manager.addMarkers(m, 10); manager.refresh(); } else { $.setCenter($.settings.defaultLat, $.settings.defaultLng, $.settings.defaultZoom); } } }, "json"); </code></pre> <p>The key here is this line:</p> <pre><code>$.setCenter(lat, lng, $.settings.defaultCityZoom); </code></pre> <p>Just setting the center to the lat/lng of the result of the service call.</p>
3
2009-09-02T03:44:27Z
[ "javascript", "python", "django", "google-maps" ]
Center Google Map Based on geocoded IP
1,365,722
<p>Basically whenever someones opens up my (Google) map I want it default to their approximate location.</p> <p>Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?</p>
5
2009-09-02T03:38:31Z
1,365,739
<p>Per <a href="http://code.google.com/apis/maps/documentation/introduction.html#Initializing%5Fthe%5FMap" rel="nofollow">the docs</a>, just <code>map.setCenter(new GLatLng(37.4419, -122.1419), 13);</code> or whatever other coordinates. Doing it in the page's Javascript is normally preferred.</p> <p>If you mean translating an IP to lat and long, I don't think the Google API supports that, but there are other web services that do, such as <a href="http://www.maxmind.com/app/ip-location" rel="nofollow">maxmind</a>, <a href="http://www.hostip.info/" rel="nofollow">hostip</a>, and many, many others. I don't know which one(s) to recommend -- try out a few, would be my suggestion!</p>
0
2009-09-02T03:46:37Z
[ "javascript", "python", "django", "google-maps" ]
Center Google Map Based on geocoded IP
1,365,722
<p>Basically whenever someones opens up my (Google) map I want it default to their approximate location.</p> <p>Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?</p>
5
2009-09-02T03:38:31Z
1,365,757
<p>If the user uses FireFox 3.5/google gears, you can retrieve the lat and lng from the browser itself. You'll find details on another <a href="http://stackoverflow.com/questions/1177726/where-is-a-sample-of-some-javascript-code-for-location-aware-browsing-in-firefox">stackoverflow post here</a></p>
0
2009-09-02T03:54:22Z
[ "javascript", "python", "django", "google-maps" ]