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 |
|---|---|---|---|---|---|---|---|---|---|
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 1,413,575 | <p>Why not just display it in the user's web browser?</p>
| 7 | 2009-09-11T22:36:26Z | [
"python",
"image"
] |
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 1,413,639 | <p>Or simply execute the image through the shell, as in </p>
<pre><code>import subprocess
subprocess.call([ fname ], shell=True)
</code></pre>
<p>and whatever program is installed to handle images will be launched.</p>
| 4 | 2009-09-11T22:53:41Z | [
"python",
"image"
] |
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 1,413,693 | <p>Since you are probably running Windows (from looking at your tags), this would be the easiest way to open and show an image file from the console without installing extra stuff like PIL.</p>
<pre><code>import os
os.system('start pic.png')
</code></pre>
| 4 | 2009-09-11T23:21:46Z | [
"python",
"image"
] |
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 13,843,577 | <p>In Xterm-compatible terminals, you can show the image directly in the terminal. See <a href="http://stackoverflow.com/a/13843534/309483">my answer to "PPM image to ASCII art in Python"</a></p>
<p><img src="http://i.stack.imgur.com/3mwxc.png" alt="ImageMagick's "logo:" image in Xterm (show picture in new tab for full size viewing)"></p>
| 4 | 2012-12-12T15:54:58Z | [
"python",
"image"
] |
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 37,520,984 | <h2>In a new window using Pillow/PIL</h2>
<p>Install <a href="https://pypi.python.org/pypi/Pillow/2.7.0" rel="nofollow">Pillow</a> (or PIL), e.g.:</p>
<pre><code>$ pip install pillow
</code></pre>
<p>Now you can</p>
<pre><code>from PIL import Image
with Image.open('path/to/file.jpg') as img:
img.show()
</code></pre>
<h2>Using native apps</h2>
<p>Other common alternatives include running <code>xdg-open</code> or starting the browser with the image path:</p>
<pre><code>import webbrowser
webbrowser.open('path/to/file.jpg')
</code></pre>
<h2>Inline a Linux console</h2>
<p>If you really want to show the image inline in the console and not as a new window, you may do that but only in a <a href="https://en.wikipedia.org/wiki/Linux_console" rel="nofollow">Linux console</a> using <a href="http://www.nongnu.org/fbi-improved/" rel="nofollow"><code>fbi</code></a> see <a href="https://askubuntu.com/questions/97542/how-do-i-make-my-terminal-display-graphical-pictures">ask Ubuntu</a> or else use ASCII-art like <a href="http://manpages.ubuntu.com/manpages/wily/man1/cacaview.1.html" rel="nofollow">CACA</a>.</p>
| 1 | 2016-05-30T08:27:31Z | [
"python",
"image"
] |
Python with matplotlib - reusing drawing functions | 1,413,681 | <p>I have a follow up question to this <a href="http://stackoverflow.com/questions/1401102/python-with-matplotlib-drawing-multiple-figures-in-parallel/1401686#1401686">question</a>.</p>
<p>Is it possible to streamline the figure generation by having multiple python scripts that work on different parts of the figure?</p>
<p>For example, if I have the following functions: </p>
<blockquote>
<p>FunctionA: Draw a histogram of something<br>
FunctionB: Draw a box with a text in it<br>
FunctionC: Draw a plot of something C<br>
FunctionD: Draw a plot of something D </p>
</blockquote>
<p>How do I go about reusing the above functions in different scripts? If I wanted, for instance, to create a figure with a histogram with a plot of something C, I would somehow call FunctionA and FunctionC from my script. Or, if I wanted a figure with the two plots, I'd call FunctionC and FunctionD.</p>
<p>I'm not sure if I'm explaining myself clearly, but another way of asking this question is this: how do I pass a figure object to a function and then have the function draw something to the passed figure object and then return it back to the main script to add other things like the title or something?</p>
| 11 | 2009-09-11T23:15:09Z | 1,413,865 | <p>Okey, I've figured out how to do this. It was a lot simpler than what I had imagined. It just required a bit of reading <a href="http://matplotlib.sourceforge.net/users/artists.html" rel="nofollow">here</a> with the <a href="http://matplotlib.sourceforge.net/api/figure%5Fapi.html#matplotlib.figure.Figure" rel="nofollow">figure</a> and <a href="http://matplotlib.sourceforge.net/api/axes%5Fapi.html#matplotlib.axes.Axes" rel="nofollow">axes</a> classes.</p>
<p>In your main script:</p>
<pre><code>import pylab as plt
import DrawFns
fig = plt.figure()
(do something with fig)
DrawFns.WriteText(fig, 'Testing')
plt.show()
</code></pre>
<p>In your DrawFns.py: </p>
<pre><code>def WriteText(_fig, _text):
[indent]_fig.text(0, 0, _text)
</code></pre>
<p>And that's it! And I can add more functions in DrawFns.py and call them from any script as long as they are included with <code>import</code> call. :D</p>
| 0 | 2009-09-12T00:34:45Z | [
"python",
"matplotlib"
] |
Python with matplotlib - reusing drawing functions | 1,413,681 | <p>I have a follow up question to this <a href="http://stackoverflow.com/questions/1401102/python-with-matplotlib-drawing-multiple-figures-in-parallel/1401686#1401686">question</a>.</p>
<p>Is it possible to streamline the figure generation by having multiple python scripts that work on different parts of the figure?</p>
<p>For example, if I have the following functions: </p>
<blockquote>
<p>FunctionA: Draw a histogram of something<br>
FunctionB: Draw a box with a text in it<br>
FunctionC: Draw a plot of something C<br>
FunctionD: Draw a plot of something D </p>
</blockquote>
<p>How do I go about reusing the above functions in different scripts? If I wanted, for instance, to create a figure with a histogram with a plot of something C, I would somehow call FunctionA and FunctionC from my script. Or, if I wanted a figure with the two plots, I'd call FunctionC and FunctionD.</p>
<p>I'm not sure if I'm explaining myself clearly, but another way of asking this question is this: how do I pass a figure object to a function and then have the function draw something to the passed figure object and then return it back to the main script to add other things like the title or something?</p>
| 11 | 2009-09-11T23:15:09Z | 1,413,894 | <p>Here you want to use the <a href="http://matplotlib.sourceforge.net/users/artists.html">Artist objects</a>, and pass them as needed to the functions:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def myhist(ax, color):
ax.hist(np.log(np.arange(1, 10, .1)), facecolor=color)
def say_something(ax, words):
t = ax.text(.2, 20., words)
make_a_dim_yellow_bbox(t)
def make_a_dim_yellow_bbox(txt):
txt.set_bbox(dict(facecolor='yellow', alpha=.2))
fig = plt.figure()
ax0 = fig.add_subplot(1,2,1)
ax1 = fig.add_subplot(1,2,2)
myhist(ax0, 'blue')
myhist(ax1, 'green')
say_something(ax0, 'this is the blue plot')
say_something(ax1, 'this is the green plot')
plt.show()
</code></pre>
<p><img src="http://i28.tinypic.com/2i6f7f5.png" alt="alt text" /></p>
| 8 | 2009-09-12T00:54:29Z | [
"python",
"matplotlib"
] |
Python Unicode and MIMEE | 1,413,735 | <p>Can someone who is way smarter than I tell me what I'm doing wrong.. Shouldn't this simply process...</p>
<pre><code># encoding: utf-8
from email.MIMEText import MIMEText
msg = MIMEText("hi")
msg.set_charset('utf-8')
print msg.as_string()
a = 'Ho\xcc\x82tel Ste\xcc\x81phane '
b = unicode(a, "utf-8")
print b
msg = MIMEText(b)
msg.set_charset('utf-8')
print msg.as_string()
</code></pre>
<p>I'm stumped...</p>
| 0 | 2009-09-11T23:36:14Z | 1,413,879 | <p>Assuming Python 2.* (alas, you don't tell us whether you're on Python 3, but as you're using <code>print</code> as a statement it looks like you aren't): <code>MIMEText" takes a string -- a plain string, NOT a Unicode object. So, use </code>b.encode('utf-8')<code> as the argument if what you start with is a Unicode object </code>b`.</p>
| 2 | 2009-09-12T00:44:29Z | [
"python",
"email",
"unicode"
] |
python serialize string | 1,413,763 | <p>I am needing to unserialize a string into an array in python just like php and then serialize it back.</p>
| 0 | 2009-09-11T23:49:42Z | 1,413,783 | <p>Take a look at the <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle module</a>. It is probably what you're looking for. </p>
<pre><code>import pickle
# Unserialize the string to an array
my_array = pickle.loads(serialized_data)
# Serialized back
serialized_data = pickle.dumps(my_array)
</code></pre>
| 0 | 2009-09-11T23:57:40Z | [
"python",
"serialization"
] |
python serialize string | 1,413,763 | <p>I am needing to unserialize a string into an array in python just like php and then serialize it back.</p>
| 0 | 2009-09-11T23:49:42Z | 1,413,872 | <p>What "serialized" the data in question into the string in the first place? Do you really mean an <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a> (and if so, of what simple type?), or do you actually mean a <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange" rel="nofollow">list</a> (and if so, what are the list's items supposed to be?)... etc, etc...</p>
<p>From the OP's comments it looks like he has <code>zin</code>, a <code>tuple</code>, and is trying to treat it as if it was, instead, a <code>str</code> into which data was serialized by pickling. So he's trying to unserialize the tuple via <code>pickle.loads</code>, and obviously that can't work -- <code>pickle.loads</code> wants an <code>str</code> (that's what the <code>s</code> MEANS), <strong>NOT</strong> a tuple -- it can't work with a tuple, it has even no idea of what to DO with a tuple.</p>
<p>Of course, neither do we, having been given zero indication about where that tuple comes from, why is it supposed to be a string instead, etc, etc. The OP should edit his answer to show more code (how is <code>zin</code> procured or fetched) and especially the code where <code>zin</code> is supposed to be PRODUCED (via <code>pickle.dumps</code>, I imagine) and how the communication from the producer to this would-be consumer is happening (or failing to happen;-).</p>
| 0 | 2009-09-12T00:38:51Z | [
"python",
"serialization"
] |
python serialize string | 1,413,763 | <p>I am needing to unserialize a string into an array in python just like php and then serialize it back.</p>
| 0 | 2009-09-11T23:49:42Z | 1,413,949 | <p>A string is already a sequence type in Python. You can iterate over the string one character at a time like this:</p>
<pre><code>for char in somestring:
do_something(char)
</code></pre>
<p>The question is... what did you want to do with it? Maybe we can give more details with a more detailed question.</p>
| 0 | 2009-09-12T01:17:29Z | [
"python",
"serialization"
] |
python serialize string | 1,413,763 | <p>I am needing to unserialize a string into an array in python just like php and then serialize it back.</p>
| 0 | 2009-09-11T23:49:42Z | 1,413,993 | <p>If you mean PHP's explode, try this</p>
<pre><code>>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']
>>> ''.join(['f', 'o', 'o', 'b', 'a', 'r'])
'foobar'
</code></pre>
| 1 | 2009-09-12T01:43:16Z | [
"python",
"serialization"
] |
Expected LP_c_double instance instead of c_double_Array - python ctypes error | 1,413,851 | <p>I have a function in a DLL that I have to wrap with python code. The function is expecting a pointer to an array of doubles. This is the error I'm getting:</p>
<pre><code>Traceback (most recent call last):
File "C:\....\.FROGmoduleTEST.py", line 243, in <module>
FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptrfdP)
ArgumentError: argument 1: <type 'exceptions.TypeError'>: expected LP_c_double instance instead of c_double_Array_0_Array_2
</code></pre>
<p>I tried casting it like so:</p>
<pre><code>ptrpulse = cast(ptrpulse, ctypes.LP_c_double)
</code></pre>
<p>but I get:</p>
<pre><code>NameError: name 'LP_c_double' is not defined
</code></pre>
<p>Any help or direction is greatly appreciated.
Thanks all!</p>
| 1 | 2009-09-12T00:28:09Z | 1,413,936 | <p>Are you writing the wrapper in Python yourself? The error saying "expected LP_c_double instance" means it's expecting a pointer to a single double, not an array as you've suggested. </p>
<pre><code>>>> ctypes.POINTER(ctypes.c_double * 10)()
<__main__.LP_c_double_Array_10 object at 0xb7eb24f4>
>>> ctypes.POINTER(ctypes.c_double * 20)()
<__main__.LP_c_double_Array_20 object at 0xb7d3a194>
>>> ctypes.POINTER(ctypes.c_double)()
<__main__.LP_c_double object at 0xb7eb24f4>
</code></pre>
<p>Either you need to fix your <a href="http://docs.python.org/library/ctypes.html#ctypes.%5FFuncPtr.argtypes" rel="nofollow">argtypes</a> to correctly expect a pointer to an array of doubles, or you need to pass in a pointer to a single double like the function currently expects.</p>
| 0 | 2009-09-12T01:11:29Z | [
"python",
"types",
"ctypes"
] |
Expected LP_c_double instance instead of c_double_Array - python ctypes error | 1,413,851 | <p>I have a function in a DLL that I have to wrap with python code. The function is expecting a pointer to an array of doubles. This is the error I'm getting:</p>
<pre><code>Traceback (most recent call last):
File "C:\....\.FROGmoduleTEST.py", line 243, in <module>
FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptrfdP)
ArgumentError: argument 1: <type 'exceptions.TypeError'>: expected LP_c_double instance instead of c_double_Array_0_Array_2
</code></pre>
<p>I tried casting it like so:</p>
<pre><code>ptrpulse = cast(ptrpulse, ctypes.LP_c_double)
</code></pre>
<p>but I get:</p>
<pre><code>NameError: name 'LP_c_double' is not defined
</code></pre>
<p>Any help or direction is greatly appreciated.
Thanks all!</p>
| 1 | 2009-09-12T00:28:09Z | 1,414,227 | <p>LP_c_double is created dynamically by ctypes when you create a pointer to a double. i.e.</p>
<pre><code>LP_c_double = POINTER(c_double)
</code></pre>
<p>At this point, you've created a C <em>type</em>. You can now create instances of these pointers.</p>
<pre><code>my_pointer_one = LP_c_double()
</code></pre>
<p>But here's the kicker. Your function isn't expecting a pointer to a double. It's expecting an array of doubles. In C, an array of type X is represented by a pointer (of type X) to the first element in that array.</p>
<p>In other words, to create a pointer to a double suitable for passing to your function, you actually need to allocate an array of doubles of some finite size (the documentation for ReturnPulse should indicate how much to allocate), and then pass that element directly (do not cast, do not de-reference).</p>
<p>i.e.</p>
<pre><code>size = GetSize()
# create the array type
array_of_size_doubles = c_double*size
# allocate several instances of that type
ptrpulse = array_of_size_doubles()
ptrtdl = array_of_size_doubles()
ptrtdP = array_of_size_doubles()
ptrfdl = array_of_size_doubles()
ptrfdP = array_of_size_doubles()
ReturnPulse(ptrpulse, ptrtdl, ptrtdP, ptrfdl, ptrfdP)
</code></pre>
<p>Now the five arrays should be populated with the values <em>returned</em> by ReturnPulse.</p>
| 2 | 2009-09-12T03:52:04Z | [
"python",
"types",
"ctypes"
] |
help with python forking child server for doing ajax push, long polling | 1,414,098 | <p>Alright, I only know some basic python but if I can get help with this then I am considering making it open source.</p>
<p>What I am trying to do:
- (Done) Ajax send for init content
- Python server recv command "init" to send most recent content
- (Done) Ajax recv content and then immediately calls back to python server
- Python server recv command "wait", sets up child, and waits for command "new" from ajax
- (Done) Ajax sends "new" command
- Python server wakes up all waiting children and sends newest content
- (Done) Ajax sends "wait", and so forth</p>
<p>I have already written the Python Server part in php but it uses 100% CPU so I knew I had to use forking socket daemon to be able to have multi processes sitting there waiting. Now, I could write this with PHP but the extensions it needs have to be manually installed which can be a problem with asking host to install it on shared accounts and so forth. So I turned to Python which would also give more flexability and run faster. Plus more people could user it.</p>
<p>So, if anyone could help with this, or give some direction, that would be great.</p>
<p>I am working on the code myself just just do not know it well enough. I can add the if statements in for the different commands and add in mysql connection myself. If I end up having any problems, I will ask here. I love this site.</p>
| 0 | 2009-09-12T02:41:33Z | 1,414,153 | <p>Look at <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a>.</p>
<p>Read all of these related questions on StackOverflow: <a href="http://stackoverflow.com/search?q=%5Bpython%5D+web+subprocess">http://stackoverflow.com/search?q=%5Bpython%5D+web+subprocess</a></p>
| 1 | 2009-09-12T03:12:16Z | [
"python",
"sockets",
"long-polling",
"fork"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 1,414,147 | <p>Make sure your EMAIL_HOST and EMAIL_PORT are set up right in settings.py (these refer to your SMTP server). It might be assuming that you have an SMTP server running on localhost.</p>
<p>To test this locally, run Python's built-in test SMTP server:</p>
<pre><code>python -m smtpd -n -c DebuggingServer localhost:1025
</code></pre>
<p>Then set these values in your settings.py</p>
<pre><code>EMAIL_HOST='localhost'
EMAIL_PORT=1025
</code></pre>
<p>Trigger a 500 error, and you should see the e-mail appear in the python smtpd terminal window.</p>
| 12 | 2009-09-12T03:06:46Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 1,414,348 | <p>Try this</p>
<pre><code># ./manage shell
>>> from django.core.mail import send_mail
>>> send_mail('Subject here', 'Here is the message.', 'from@example.com',['to@example.com'], fail_silently=False)
</code></pre>
<p>With a to@example.com that you actually get email at.</p>
| 1 | 2009-09-12T05:09:25Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 1,414,408 | <p>My web hosting provider - Webfaction - only allows emails to be sent From an email that has been explicitly created in the administrator panel. Creating one fixed the problem.</p>
| 6 | 2009-09-12T05:52:17Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 1,414,460 | <p>While likely not ideal, I have found using Gmail as the SMTP host works just fine. There is a useful guide at <a href="http://nathanostgard.com/archives/2007/7/2/gmail%5Fand%5Fdjango/" rel="nofollow">nathanostgard.com</a>. </p>
<p>Feel free to post your relevant settings.py sections (including EMAIL_*, SERVER_EMAIL, ADMINS (just take out your real email), MANAGERS, and DEBUG) if you want an extra set of eyes to check for typos!</p>
| 0 | 2009-09-12T06:25:34Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 1,794,213 | <p>Make sure you have DEBUG = False</p>
| 2 | 2009-11-25T02:04:24Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 6,551,508 | <p>In my case the cause was missing <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-SERVER_EMAIL">SERVER_EMAIL</a> setting.</p>
<p>The default for <a href="https://docs.djangoproject.com/en/dev/ref/settings/#server-email"><code>SERVER_EMAIL</code></a> is <code>root@localhost</code>. But many of email servers including
my email provider do not accept emails from such suspicious addresses. They silently drop the emails.</p>
<p>Changing the sender email address to <code>django@my-domain.com</code> solved the problem. In <code>settings.py</code>:</p>
<pre><code>SERVER_EMAIL = 'django@my-domain.com'
</code></pre>
| 69 | 2011-07-01T17:54:58Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 8,446,164 | <p>Although it's been a while, here's my response, so that other people can benefit in the future.</p>
<p>In my case, what was preventing emails to be sent to the ADMINS list, when an error occured, was an application specific setting. I was using django-piston, which provides the setting attributes PISTON_EMAIL_ERRORS and PISTON_DISPLAY_ERRORS. Setting these accordingly, enabled the application server to notify my by mail, whenever piston would crash.</p>
| 1 | 2011-12-09T13:29:09Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 9,541,647 | <p>I had the same situation. I created a new project and app and it worked, so I knew it was my code. I tracked it down to the LOGGING dictionary in settings.py. I had made some changes a few weeks back for logging with Sentry, but for some reason the error just started today. I changed back to the original and got it working:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
</code></pre>
<p>Then, I made some changes slowly and got it working with Sentry and emailing the ADMINS as well.</p>
| 21 | 2012-03-02T23:08:40Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 16,166,097 | <p>If, for some reason, you set DEBUG_PROPAGATE_EXCEPTIONS to True (it's False by default), email to admin will not work.</p>
| 1 | 2013-04-23T09:45:04Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 18,136,491 | <p>Another possibility for error is trouble with your ADMINS setting. The following setting will cause the sending of mail to admins to fail quietly:</p>
<pre><code>ADMINS = (
('your name', 'me@mydomain.com')
)
</code></pre>
<p>What's wrong with that? Well ADMINS needs to be a tuple of tuples, so the above needs to be formatted as</p>
<pre><code>ADMINS = (
('your name', 'me@mydomain.com'),
)
</code></pre>
<p>Note the trailing comma. Without the failing comma, the 'to' address on the email will be incorrectly formatted (and then probably discarded silently by your SMTP server).</p>
| 31 | 2013-08-08T21:30:20Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 20,324,455 | <p>Sorry if it is too naive, but in my case the emails were sent but were going directly to the SPAM folder. Before trying more complicated things check your SPAM folder first.</p>
| 2 | 2013-12-02T09:08:02Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 25,344,287 | <p>For what it's worth I had this issue and none of these suggestions worked for me. It turns out that my problem was that <code>SERVER_EMAIL</code> was set to an address that the server (Webfaction) didn't recognise. If this site were hosted <em>on</em> Webfaction (as my other sites are), this wouldn't be a problem, but as this was on a different server, the Webfaction servers not only check the authentication of the email being sent, but also the <code>From:</code> value as well.</p>
| 0 | 2014-08-16T21:44:03Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 28,100,754 | <p>Another thing worth noting here is that settings <code>handler500</code> might bypass the mechanism that sends errors on a 500 if the response from the view doesn't have a status code of 500.
If you have a <code>handler500</code> set, then in that view respond with something like this.</p>
<pre><code>t = loader.get_template('500.html')
response = HttpResponseServerError(
t.render(RequestContext(request, {'custom_context_var':
'IT BROKE OMG FIRE EVERYONE'})))
response.status_code = 500
return response
</code></pre>
| 2 | 2015-01-22T23:48:59Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 29,504,810 | <p>In my case, it's the <code>include_html</code> in <code>mail_admins</code>.</p>
<p>When I set <code>include_html</code> to <code>True</code>,the email server reject to send my email because it think that my emails are spam.</p>
<p>Everything works just fine when I set <code>include_html</code> to <code>False</code>.</p>
| 0 | 2015-04-08T02:22:56Z | [
"python",
"django"
] |
Django not sending emails to admins | 1,414,130 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/howto/error-reporting/">documentation</a>, if <code>DEBUG</code> is set to <code>False</code> and something is provided under the <code>ADMINS</code> setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?</p>
| 47 | 2009-09-12T02:57:59Z | 29,805,903 | <p>... and then there's the facepalm error, when you've used this in development to prevent emails from going out, and then accidentally copy the setting to production:</p>
<pre><code># Print emails to console
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
</code></pre>
<p>(of course you don't see them being printed to console when using a wsgi server). Removing the setting from production fixed this for me.</p>
| 0 | 2015-04-22T18:23:19Z | [
"python",
"django"
] |
Should I use pgreloaded? Or subversion of pygame? | 1,414,258 | <p>I'm using pygame with python 2.6 right now, But I want to use python 3.1.1 instead. The normal pygame only works with 2.x, but the subversion ones work with 3.x I think. But what about pgreloaded? Is that useable yet? The normal pygame actually works with 3.1 too, but not for os x (at least there isn't a download). Does anyone actually use pgreloaded or subversion pygames? So anyway, should I use pygame subversion, pgreloaded, or stick with the current pygame? I don't really care about being compatible with other things or distribution.</p>
<p>Thanks!</p>
<p>EDIT: Ok, I got rid of python 2.6, installed 3.1, used svn command to get pygame, tried running python3 setup.py, didn't work, changed raw_input in setup.py to input(), worked, now my pygames (that were so simple that they work the same under 2.6 and 3.1) run with python 3.1. :) I didn't get pgreloaded because there's no documentation for it.</p>
| 3 | 2009-09-12T04:16:37Z | 1,416,509 | <p>Just stick with Python 2.6.</p>
| 1 | 2009-09-13T00:06:58Z | [
"python",
"python-3.x",
"pygame"
] |
Should I use pgreloaded? Or subversion of pygame? | 1,414,258 | <p>I'm using pygame with python 2.6 right now, But I want to use python 3.1.1 instead. The normal pygame only works with 2.x, but the subversion ones work with 3.x I think. But what about pgreloaded? Is that useable yet? The normal pygame actually works with 3.1 too, but not for os x (at least there isn't a download). Does anyone actually use pgreloaded or subversion pygames? So anyway, should I use pygame subversion, pgreloaded, or stick with the current pygame? I don't really care about being compatible with other things or distribution.</p>
<p>Thanks!</p>
<p>EDIT: Ok, I got rid of python 2.6, installed 3.1, used svn command to get pygame, tried running python3 setup.py, didn't work, changed raw_input in setup.py to input(), worked, now my pygames (that were so simple that they work the same under 2.6 and 3.1) run with python 3.1. :) I didn't get pgreloaded because there's no documentation for it.</p>
| 3 | 2009-09-12T04:16:37Z | 1,656,917 | <p>pgreloaded has documentation - there is even an own package at <a href="http://code.google.com/p/pygame/downloads/list" rel="nofollow">http://code.google.com/p/pygame/downloads/list</a>.</p>
| 1 | 2009-11-01T11:20:29Z | [
"python",
"python-3.x",
"pygame"
] |
Should I use pgreloaded? Or subversion of pygame? | 1,414,258 | <p>I'm using pygame with python 2.6 right now, But I want to use python 3.1.1 instead. The normal pygame only works with 2.x, but the subversion ones work with 3.x I think. But what about pgreloaded? Is that useable yet? The normal pygame actually works with 3.1 too, but not for os x (at least there isn't a download). Does anyone actually use pgreloaded or subversion pygames? So anyway, should I use pygame subversion, pgreloaded, or stick with the current pygame? I don't really care about being compatible with other things or distribution.</p>
<p>Thanks!</p>
<p>EDIT: Ok, I got rid of python 2.6, installed 3.1, used svn command to get pygame, tried running python3 setup.py, didn't work, changed raw_input in setup.py to input(), worked, now my pygames (that were so simple that they work the same under 2.6 and 3.1) run with python 3.1. :) I didn't get pgreloaded because there's no documentation for it.</p>
| 3 | 2009-09-12T04:16:37Z | 1,913,924 | <p>Or consider using Pyglet (<a href="http://pyglet.org/" rel="nofollow">http://pyglet.org/</a>), which is a thin wrapper around openGL, esp. made for games. It works pretty well, documentation is reasonable, but it of course lacks the massive userbase that Pygame has. It is more mature than PGreloaded imho. </p>
| 0 | 2009-12-16T11:01:56Z | [
"python",
"python-3.x",
"pygame"
] |
Should I use pgreloaded? Or subversion of pygame? | 1,414,258 | <p>I'm using pygame with python 2.6 right now, But I want to use python 3.1.1 instead. The normal pygame only works with 2.x, but the subversion ones work with 3.x I think. But what about pgreloaded? Is that useable yet? The normal pygame actually works with 3.1 too, but not for os x (at least there isn't a download). Does anyone actually use pgreloaded or subversion pygames? So anyway, should I use pygame subversion, pgreloaded, or stick with the current pygame? I don't really care about being compatible with other things or distribution.</p>
<p>Thanks!</p>
<p>EDIT: Ok, I got rid of python 2.6, installed 3.1, used svn command to get pygame, tried running python3 setup.py, didn't work, changed raw_input in setup.py to input(), worked, now my pygames (that were so simple that they work the same under 2.6 and 3.1) run with python 3.1. :) I didn't get pgreloaded because there's no documentation for it.</p>
| 3 | 2009-09-12T04:16:37Z | 5,506,950 | <p>I think JD's link to pgreloaded doc is out of date, try this one:
<a href="http://wiki.pgreloaded.googlecode.com/hg/documentation/index.html" rel="nofollow">http://wiki.pgreloaded.googlecode.com/hg/documentation/index.html</a></p>
| 1 | 2011-03-31T22:10:43Z | [
"python",
"python-3.x",
"pygame"
] |
Local functions in Python | 1,414,304 | <p>In the following Python code, I get an <code>UnboundLocalError</code>. As I understand it, local functions share the local variables of the containing function, but this hardly seems to be the case here. I recognise that <code>a</code> is an immutable value in this context, but that should not be a problem.</p>
<pre><code>def outer():
a = 0
def inner():
a += 1
inner()
outer()
</code></pre>
<p>It would seem that the inner function has received copies of all the references in the parent function, as I do not get the <code>UnboundLocalError</code> exception if the value of <code>a</code> is wrapped in a non-immutable type.</p>
<p>Is someone able to clarify the behaviour here, and point me to the appropriate Python documentation on this?</p>
| 26 | 2009-09-12T04:45:08Z | 1,414,320 | <p>I believe you're correct in seeing this as a "mutability" problem. While the code you posted does throw an "UnboundLocalError", the following code does not:</p>
<pre><code>def outer():
a = 0
def inner():
print a
inner()
outer()
</code></pre>
<p>Python doesn't allow you to reassign the value of a variable from an outer scope in an inner scope (unless you're using the keyword "global", which doesn't apply in this case).</p>
<p>Check out the bottom section of the "classes" documentation in this Python 2.6.2 documentation:</p>
<blockquote>
<h2><a href="https://docs.python.org/2.6/tutorial/classes.html#python-scopes-and-namespaces" rel="nofollow">9.2. Python Scopes and Namespaces</a></h2>
<p>[…] If a name is declared global, then all references and assignments go
directly to the middle scope containing the moduleâs global names.
Otherwise, all variables found outside of the innermost scope are
read-only (an attempt to write to such a variable will simply create a
new local variable in the innermost scope, leaving the identically
named outer variable unchanged).</p>
</blockquote>
<p>Your "UnboundLocalError" is because your function is actually declaring a new variable called "a" and then immediately trying to do a "+=" operation on it, but this fails because "a" does not have a value yet. (View the "a+=1" as "a = a+1" and you can see the problem if "a" is undefined).</p>
<p>In general, if you're going to want to modify "a", the way people usually get around it is to use a mutable type to pass "a" around (such as a list or a dictionary). You can modify "a" via the contents of the mutable type (as you probably noticed in your testing with this setup).</p>
<p>Hope that helps!</p>
| 26 | 2009-09-12T04:54:30Z | [
"python",
"function",
"binding",
"model",
"local"
] |
Local functions in Python | 1,414,304 | <p>In the following Python code, I get an <code>UnboundLocalError</code>. As I understand it, local functions share the local variables of the containing function, but this hardly seems to be the case here. I recognise that <code>a</code> is an immutable value in this context, but that should not be a problem.</p>
<pre><code>def outer():
a = 0
def inner():
a += 1
inner()
outer()
</code></pre>
<p>It would seem that the inner function has received copies of all the references in the parent function, as I do not get the <code>UnboundLocalError</code> exception if the value of <code>a</code> is wrapped in a non-immutable type.</p>
<p>Is someone able to clarify the behaviour here, and point me to the appropriate Python documentation on this?</p>
| 26 | 2009-09-12T04:45:08Z | 1,414,323 | <p>Try binding the variable as an argument. </p>
<pre><code>def outer():
a = 0
def inner(a=a):
a += 1
inner()
outer()
</code></pre>
<p>I'll try and dig up the appropriate documents.</p>
<p><strong>edit</strong></p>
<p>Since you want the inner function to have a side effect on the outer scope, then you need to use a mutable datatype like a list. Integers and strings are immutable.</p>
<pre><code>def outer():
a = [0]
def inner():
a[0] += 1
inner()
print a[0]
outer()
</code></pre>
| 8 | 2009-09-12T04:55:11Z | [
"python",
"function",
"binding",
"model",
"local"
] |
Local functions in Python | 1,414,304 | <p>In the following Python code, I get an <code>UnboundLocalError</code>. As I understand it, local functions share the local variables of the containing function, but this hardly seems to be the case here. I recognise that <code>a</code> is an immutable value in this context, but that should not be a problem.</p>
<pre><code>def outer():
a = 0
def inner():
a += 1
inner()
outer()
</code></pre>
<p>It would seem that the inner function has received copies of all the references in the parent function, as I do not get the <code>UnboundLocalError</code> exception if the value of <code>a</code> is wrapped in a non-immutable type.</p>
<p>Is someone able to clarify the behaviour here, and point me to the appropriate Python documentation on this?</p>
| 26 | 2009-09-12T04:45:08Z | 15,334,246 | <p>You should specify your variable as nonlocal to preserve it's state in closure, so definition should be like this</p>
<pre><code>def outer():
a = 0
def inner():
nonlocal a
a += 1
inner()
</code></pre>
| 5 | 2013-03-11T08:41:38Z | [
"python",
"function",
"binding",
"model",
"local"
] |
Python recursive program to prime factorize a number | 1,414,581 | <p>I wrote the following program to prime factorize a number:</p>
<pre><code>import math
def prime_factorize(x,li=[]):
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else: #This else belongs to for
li.append(x)
print li #First print statement; This is what is returned
return li
prime_factorize(x/i,li)
if __name__=='__main__':
print prime_factorize(300) #Second print statement, WTF. why is this None
</code></pre>
<p>Following is the output I get:</p>
<pre><code> [2, 2, 3, 5, 5]
None
</code></pre>
<p>Altho', the returned value is printed properly, the after returned value seems to be printing none, all the time. What am I missing?</p>
<p>Also, how can I improve the program (continuing to use the recursion)</p>
| 2 | 2009-09-12T07:50:42Z | 1,414,600 | <p>Your prime_factorize function doesn't have a return statement in the recursive case -- you want to invoke "return prime_factorize(x/i,li)" on its last line. Try it with a prime number (so the recursive call isn't needed) to see that it works in that case.</p>
<p>Also you probably want to make the signature something like:</p>
<pre><code>def prime_factorize(x,li=None):
if li is None: li = []
</code></pre>
<p>otherwise you get wrong results when calling it two or more times:</p>
<pre><code>>>> prime_factorize(10)
[2, 5]
>>> prime_factorize(4)
[2, 5, 2, 2]
>>> prime_factorize(19)
[2, 5, 2, 2, 19]
</code></pre>
| 9 | 2009-09-12T08:05:27Z | [
"python",
"algorithm",
"recursion",
"primes",
"prime-factoring"
] |
Python recursive program to prime factorize a number | 1,414,581 | <p>I wrote the following program to prime factorize a number:</p>
<pre><code>import math
def prime_factorize(x,li=[]):
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else: #This else belongs to for
li.append(x)
print li #First print statement; This is what is returned
return li
prime_factorize(x/i,li)
if __name__=='__main__':
print prime_factorize(300) #Second print statement, WTF. why is this None
</code></pre>
<p>Following is the output I get:</p>
<pre><code> [2, 2, 3, 5, 5]
None
</code></pre>
<p>Altho', the returned value is printed properly, the after returned value seems to be printing none, all the time. What am I missing?</p>
<p>Also, how can I improve the program (continuing to use the recursion)</p>
| 2 | 2009-09-12T07:50:42Z | 1,415,182 | <p>A more functional-style version.</p>
<pre><code>def prime_factorize( number ):
def recurse( factors, x, n ):
if x<2: return factors # 0,1 dont have prime factors
if n > 1+x**0.5: # reached the upper limit
factors.append( x ) # the only prime left is x itself
return factors
if x%n==0: # x is a factor
factors.append( n )
return recurse( factors, x/n, n )
else:
return recurse( factors, x, n+1 )
return recurse( [], number, 2)
for num, factors in ((n, prime_factorize( n )) for n in range(1,50000)):
assert (num==reduce(lambda x,y:x*y, factors, 1)), (num, factors)
#print num, ":", factors
</code></pre>
| 2 | 2009-09-12T13:59:57Z | [
"python",
"algorithm",
"recursion",
"primes",
"prime-factoring"
] |
Python recursive program to prime factorize a number | 1,414,581 | <p>I wrote the following program to prime factorize a number:</p>
<pre><code>import math
def prime_factorize(x,li=[]):
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else: #This else belongs to for
li.append(x)
print li #First print statement; This is what is returned
return li
prime_factorize(x/i,li)
if __name__=='__main__':
print prime_factorize(300) #Second print statement, WTF. why is this None
</code></pre>
<p>Following is the output I get:</p>
<pre><code> [2, 2, 3, 5, 5]
None
</code></pre>
<p>Altho', the returned value is printed properly, the after returned value seems to be printing none, all the time. What am I missing?</p>
<p>Also, how can I improve the program (continuing to use the recursion)</p>
| 2 | 2009-09-12T07:50:42Z | 1,415,324 | <p>@Anthony's correctly answered your original question about <code>print</code>. However, in the spirit of the several tips that were also offered, here's a simple refactorization using tail recursion removal:</p>
<pre><code>def prime_factorize(x):
li = []
while x >= 2:
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else:
li.append(x)
return li
x //= i
</code></pre>
<p>This doesn't address the crucial performance issues (big-O behavior is the same as for your original solution) -- but since Python itself doesn't do tail-recursion optimization, it's important to learn to do it manually.</p>
<p>"Change the [non-base-case] recursive steps <code>'return thisfun(newargs)'</code> into <code>args=newargs; continue</code> and put the whole body into a <code>while True:</code> loop" is the basic idea of tail-recursion optimization. Here I've also made li a non-arg (no reason for it to be an arg), put a condition on the <code>while</code>, and avoided the <code>continue</code> since the recursive step was at the end of the body anyway.</p>
<p>This formulation would be a good basis from which to apply further optimizing refactorings (sqrt avoidance, memoization, ...) to reach towards better performance.</p>
| 3 | 2009-09-12T15:04:33Z | [
"python",
"algorithm",
"recursion",
"primes",
"prime-factoring"
] |
Python recursive program to prime factorize a number | 1,414,581 | <p>I wrote the following program to prime factorize a number:</p>
<pre><code>import math
def prime_factorize(x,li=[]):
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else: #This else belongs to for
li.append(x)
print li #First print statement; This is what is returned
return li
prime_factorize(x/i,li)
if __name__=='__main__':
print prime_factorize(300) #Second print statement, WTF. why is this None
</code></pre>
<p>Following is the output I get:</p>
<pre><code> [2, 2, 3, 5, 5]
None
</code></pre>
<p>Altho', the returned value is printed properly, the after returned value seems to be printing none, all the time. What am I missing?</p>
<p>Also, how can I improve the program (continuing to use the recursion)</p>
| 2 | 2009-09-12T07:50:42Z | 6,992,179 | <pre><code>def primeFactorization(n):
""" Return the prime factors of the given number. """
factors = []
lastresult = n
while 1:
if lastresult == 1:
break
c = 2
while 1:
if lastresult % c == 0:
break
c += 1
factors.append(c)
lastresult /= c
return factors
</code></pre>
<p>is it fine.</p>
| 0 | 2011-08-09T06:24:34Z | [
"python",
"algorithm",
"recursion",
"primes",
"prime-factoring"
] |
Python recursive program to prime factorize a number | 1,414,581 | <p>I wrote the following program to prime factorize a number:</p>
<pre><code>import math
def prime_factorize(x,li=[]):
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else: #This else belongs to for
li.append(x)
print li #First print statement; This is what is returned
return li
prime_factorize(x/i,li)
if __name__=='__main__':
print prime_factorize(300) #Second print statement, WTF. why is this None
</code></pre>
<p>Following is the output I get:</p>
<pre><code> [2, 2, 3, 5, 5]
None
</code></pre>
<p>Altho', the returned value is printed properly, the after returned value seems to be printing none, all the time. What am I missing?</p>
<p>Also, how can I improve the program (continuing to use the recursion)</p>
| 2 | 2009-09-12T07:50:42Z | 13,167,918 | <p>If you want to do it completely recursive, I'd recommend this code, it does return the correct answer and the way it works is pretty clear.
If you want to make the program as efficient as possible I'd recommend you to stick to one of your previous methods.</p>
<pre><code>def primeFact (i, f):
if i < f:
return []
if i % f == 0:
return [f] + primeFact (i / f, 2)
return primeFact (i, f + 1)
</code></pre>
<p>This is a completely recursive way of solving your problem</p>
<pre><code>>>> primeFact (300, 2)
[2, 2, 3, 5, 5]
>>> primeFact (17, 2)
[17]
>>> primeFact (2310, 2)
[2, 3, 5, 7, 11]
</code></pre>
| 5 | 2012-10-31T21:46:45Z | [
"python",
"algorithm",
"recursion",
"primes",
"prime-factoring"
] |
PyObjC development with Xcode 3.2 | 1,414,727 | <p>Xcode 3.2 has removed the default templates for the scripting languages (Ruby, Python etc). How do I find these templates to use in Xcode 3.2? Would I need to add anything else to Xcode to support working with and 'building' PyObjC programs?</p>
<p>Additionally, is there any documentation and/or resources that would help me get into PyObjC (and Cocoa), taking into account I am already a Python guy?</p>
| 16 | 2009-09-12T09:27:39Z | 1,414,954 | <p>Apple now encourages people to get the templates directly from the PyObjC project. There's a nice thread of explanation archived on <a href="http://www.cocoabuilder.com/archive/message/xcode/2009/8/31/30205">Cocoabuilder</a>, with the following advice from bbum:</p>
<blockquote>
<p>You'll need to download and install the templates from the PyObjC<br />
repository or web site.</p>
<p>The templates were pulled from the release because the template<br />
development moves at a different pace & schedule than the Xcode<br />
releases. Too often, the templates have been out of date by the time<br />
the discs were pressed.</p>
</blockquote>
<p>The <a href="http://pyobjc.sourceforge.net/">PyObjC website</a> has both the templates for download, and great documentation/tutorials to get up and going.</p>
<p><hr /></p>
<p>Edit: Being a bit more specific, here's what I have done to get PyObjC working in Snow Leopard:</p>
<ul>
<li><p>Using the Finder, I went to <code>Go > Connect to Server...</code> and connected to <a href="http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/">http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/</a> as a guest.</p></li>
<li><p>I then made a folder called <code>Xcode</code> on my local system at <code>~Library/Application Support/Developer/Shared/Xcode/</code>. (You may already have this folder, but I hadn't customized anything for myself yet).</p></li>
<li><p>I copied the <code>File Templates</code> folder from the red-bean server into my new Xcode folder.</p></li>
<li><p>Copied the <code>Project Templates</code> folder to some other place, for example, the Desktop.</p></li>
<li><p>Using the Terminal, navigated to the temporary Project Templates folder on my Desktop and ran this command to "build" the template.:</p></li>
</ul>
<blockquote>
<p>$ cd ~/Desktop/Project\ Templates/</p>
<p>$ ./project-tool.py -k -v --template ~/Desktop/Project\ Templates/Cocoa-Python\ Application/CocoaApp.xcodeproj/TemplateInfo.plist Cocoa-Python\ Application ~/Library/Application\ Support/Developer/Shared/Xcode/Project\ Templates/Cocoa-Python\ Application</p>
</blockquote>
<ul>
<li>Repeat for the other templates:</li>
</ul>
<blockquote>
<p>$./project-tool.py -k -v --template ~/Desktop/Project\ Templates/Cocoa-Python\ Document-based\ Application/CocoaDocApp.xcodeproj/TemplateInfo.plist Cocoa-Python\ Document-based\ Application/ ~/Library/Application\ Support/Developer/Shared/Xcode/Project\ Templates/Cocoa-Python\ Document-based\ Application</p>
<p>$ ./project-tool.py -k -v --template ~/Desktop/Project\ Templates/Cocoa-Python\ Core\ Data\ Application/CocoaApp.xcodeproj/TemplateInfo.plist Cocoa-Python\ Core\ Data\ Application/ ~/Library/Application\ Support/Developer/Shared/Xcode/Project\ Templates/Cocoa-Python\ Core\ Data\ Application</p>
<p>$ ./project-tool.py -k -v --template ~/Desktop/Project\ Templates/Cocoa-Python\ Core\ Data\ Document-based\ Application/CocoaDocApp.xcodeproj/TemplateInfo.plist Cocoa-Python\ Core\ Data\ Document-based\ Application/ ~/Library/Application\ Support/Developer/Shared/Xcode/Project\ Templates/Cocoa-Python\ Core\ Data\ Document-based\ Application</p>
</blockquote>
<ul>
<li>I launched Xcode. The templates are now located under the "User Templates" section of the <code>New Project...</code> and <code>New File...</code> windows.</li>
</ul>
<p>The default project built out of the box (no need to install anything else from the PyObjC project, or py2app). I cobbled up a silly program with one button and an action, and it worked beautifully, including integration with Interface Builder (I was able to control-drag to wire up actions and outlets).</p>
<p>I also recently stumbled across a <a href="http://scottr.org/blog/tags/pyobjc/">series of "Getting Started" tutorials</a> on a blog that seemed quite useful for beginners. The author appears to have put a lot of effort into the "Building Cocoa GUIs in Python with PyObjC" series (currently in 6 parts).</p>
| 29 | 2009-09-12T12:01:45Z | [
"python",
"xcode",
"pyobjc"
] |
PyObjC development with Xcode 3.2 | 1,414,727 | <p>Xcode 3.2 has removed the default templates for the scripting languages (Ruby, Python etc). How do I find these templates to use in Xcode 3.2? Would I need to add anything else to Xcode to support working with and 'building' PyObjC programs?</p>
<p>Additionally, is there any documentation and/or resources that would help me get into PyObjC (and Cocoa), taking into account I am already a Python guy?</p>
| 16 | 2009-09-12T09:27:39Z | 1,632,544 | <p>Check out this blog posting... fixed it perfectly for me: <a href="http://ioanna.me/2009/09/installing-pyobjc-xcode-templates-in-snow-leopard/" rel="nofollow">http://ioanna.me/2009/09/installing-pyobjc-xcode-templates-in-snow-leopard/</a></p>
| 4 | 2009-10-27T17:49:52Z | [
"python",
"xcode",
"pyobjc"
] |
PyObjC development with Xcode 3.2 | 1,414,727 | <p>Xcode 3.2 has removed the default templates for the scripting languages (Ruby, Python etc). How do I find these templates to use in Xcode 3.2? Would I need to add anything else to Xcode to support working with and 'building' PyObjC programs?</p>
<p>Additionally, is there any documentation and/or resources that would help me get into PyObjC (and Cocoa), taking into account I am already a Python guy?</p>
| 16 | 2009-09-12T09:27:39Z | 17,125,659 | <p>Xcode has been changed, this is the way you do it:</p>
<ol>
<li><p>Download the templates from <a href="https://github.com/gregneagle/Xcode4CocoaPythonTemplates" rel="nofollow">https://github.com/gregneagle/Xcode4CocoaPythonTemplates</a></p></li>
<li><p>Copy the two folders, File Templates and Project Templates to <code>~/Library/Developer/Xcode/Templates</code>. If you don't have this folder already create it.</p></li>
<li><p>When you open Xcode and create a new project, you will see a new section called "Cocoa-Python" with the 4 templates. </p></li>
</ol>
| 1 | 2013-06-15T16:27:24Z | [
"python",
"xcode",
"pyobjc"
] |
Prompt on exit in PyQt application | 1,414,781 | <p>Is there any way to promt user to exit the gui-program written in Python?</p>
<p>Something like "Are you sure you want to exit the program?"</p>
<p>I'm using PyQt.</p>
| 13 | 2009-09-12T10:06:04Z | 1,414,906 | <p>Yes. You need to override the default close behaviour of the QWidget representing your application so that it doesn't immediately accept the event. The basic structure you want is something like this:</p>
<pre><code>def closeEvent(self, event):
quit_msg = "Are you sure you want to exit the program?"
reply = QtGui.QMessageBox.question(self, 'Message',
quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
</code></pre>
<p>The PyQt <a href="http://zetcode.com/tutorials/pyqt4/">tutorial</a> mentioned by <a href="http://stackoverflow.com/questions/1414781/prompt-on-exit-in-pyqt-application/1414828#1414828">las3rjock</a> has a nice discussion of this. Also check out the links from the <a href="http://wiki.python.org/moin/PyQt">PyQt page</a> at Python.org, in particular the <a href="http://www.riverbankcomputing.com/static/Docs/PyQt4/html/">official reference</a>, to learn more about events and how to handle them.</p>
| 31 | 2009-09-12T11:25:00Z | [
"python",
"pyqt",
"exit"
] |
Profiling a python multiprocessing pool | 1,414,841 | <p>I'm trying to run cProfile.runctx() on each process in a multiprocessing pool, to get an idea of what the multiprocessing bottlenecks are in my source. Here is a simplified example of what I'm trying to do:</p>
<pre><code>from multiprocessing import Pool
import cProfile
def square(i):
return i*i
def square_wrapper(i):
cProfile.runctx("result = square(i)",
globals(), locals(), "file_"+str(i))
# NameError happens here - 'result' is not defined.
return result
if __name__ == "__main__":
pool = Pool(8)
results = pool.map_async(square_wrapper, range(15)).get(99999)
print results
</code></pre>
<p>Unfortunately, trying to execute "result = square(i)" in the profiler does not affect 'result' in the scope it was called from. How can I accomplish what I am trying to do here?</p>
| 5 | 2009-09-12T10:41:21Z | 1,414,859 | <p>Try this:</p>
<pre><code>def square_wrapper(i):
result = [None]
cProfile.runctx("result[0] = square(i)", globals(), locals(), "file_%d" % i)
return result[0]
</code></pre>
| 5 | 2009-09-12T10:54:16Z | [
"python",
"profiling",
"multiprocessing",
"pool"
] |
Using safe filter in Django for rich text fields | 1,414,986 | <p>I am using <a href="http://en.wikipedia.org/wiki/TinyMCE">TinyMCE</a> editor for textarea fileds in <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> forms.</p>
<p>Now, in order to display the rich text back to the user, I am forced to use the "safe" filter in Django templates so that HTML rich text can be displayed on the browser.</p>
<p>Suppose JavaScript is disabled on the user's browser, TinyMCE won't load and the user could pass <code><script></code> or other <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> tags from such a textarea field. Such HTML won't be safe to display back to the User.</p>
<p>How do I take care of such unsafe HTML Text that doesn't come from TinyMCE?</p>
| 7 | 2009-09-12T12:20:59Z | 1,414,993 | <p>You are right to be concerned about raw HTML, but not just for Javascript-disabled browsers. When considering the security of your server, you have to ignore any work done in the browser, and look solely at what the server accepts and what happens to it. Your server accepts HTML and displays it on the page. This is unsafe.</p>
<p>The fact that TinyMce quotes HTML is a false security: the server trusts what it accepts, which it should not.</p>
<p>The solution to this is to process the HTML when it arrives, to remove dangerous constructs. This is a complicated problem to solve. Take a look at the <a href="http://ha.ckers.org/xss.html" rel="nofollow">XSS Cheat Sheet</a> to see the wide variety of inputs that could cause a problem.</p>
<p>lxml has a function to clean HTML: <a href="http://lxml.de/lxmlhtml.html#cleaning-up-html" rel="nofollow">http://lxml.de/lxmlhtml.html#cleaning-up-html</a>, but I've never used it, so I can't vouch for its quality.</p>
| 10 | 2009-09-12T12:26:04Z | [
"python",
"django",
"django-templates",
"filter"
] |
Using safe filter in Django for rich text fields | 1,414,986 | <p>I am using <a href="http://en.wikipedia.org/wiki/TinyMCE">TinyMCE</a> editor for textarea fileds in <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> forms.</p>
<p>Now, in order to display the rich text back to the user, I am forced to use the "safe" filter in Django templates so that HTML rich text can be displayed on the browser.</p>
<p>Suppose JavaScript is disabled on the user's browser, TinyMCE won't load and the user could pass <code><script></code> or other <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> tags from such a textarea field. Such HTML won't be safe to display back to the User.</p>
<p>How do I take care of such unsafe HTML Text that doesn't come from TinyMCE?</p>
| 7 | 2009-09-12T12:20:59Z | 1,414,996 | <p>There isn't a good answer to this one. TinyMCE generates HTML, and django's auto-escape specifically removes HTML. </p>
<p>The traditional solution to this problem has been to either use some non-html markup language in the user input side (bbcode, markdown, etc.) or to whitelist a limited number of HTML tags. TinyMCE/HTML are generally only appropriate input solutions for more or less trusted users.</p>
<p>The whitelist approach is tricky to implement without any security holes. The one thing you don't want to do is try to just detect "bad" tags - you WILL miss edge cases.</p>
| 3 | 2009-09-12T12:27:11Z | [
"python",
"django",
"django-templates",
"filter"
] |
Using safe filter in Django for rich text fields | 1,414,986 | <p>I am using <a href="http://en.wikipedia.org/wiki/TinyMCE">TinyMCE</a> editor for textarea fileds in <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> forms.</p>
<p>Now, in order to display the rich text back to the user, I am forced to use the "safe" filter in Django templates so that HTML rich text can be displayed on the browser.</p>
<p>Suppose JavaScript is disabled on the user's browser, TinyMCE won't load and the user could pass <code><script></code> or other <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> tags from such a textarea field. Such HTML won't be safe to display back to the User.</p>
<p>How do I take care of such unsafe HTML Text that doesn't come from TinyMCE?</p>
| 7 | 2009-09-12T12:20:59Z | 3,376,419 | <p>You can use the template filter "<a href="http://docs.djangoproject.com/en/1.1/ref/templates/builtins/#removetags">removetags</a>" and just remove 'script'.</p>
| 8 | 2010-07-31T01:36:21Z | [
"python",
"django",
"django-templates",
"filter"
] |
Using safe filter in Django for rich text fields | 1,414,986 | <p>I am using <a href="http://en.wikipedia.org/wiki/TinyMCE">TinyMCE</a> editor for textarea fileds in <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> forms.</p>
<p>Now, in order to display the rich text back to the user, I am forced to use the "safe" filter in Django templates so that HTML rich text can be displayed on the browser.</p>
<p>Suppose JavaScript is disabled on the user's browser, TinyMCE won't load and the user could pass <code><script></code> or other <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> tags from such a textarea field. Such HTML won't be safe to display back to the User.</p>
<p>How do I take care of such unsafe HTML Text that doesn't come from TinyMCE?</p>
| 7 | 2009-09-12T12:20:59Z | 27,523,737 | <p>Use <a href="https://django-bleach.readthedocs.org/en/latest/" rel="nofollow">django-bleach</a>. This provides you with a <code>bleach</code> template filter that allows you to filter out just the tags you want:</p>
<pre><code>{% load bleach_tags %}
{{ mymodel.my_html_field|bleach }}
</code></pre>
<p>The trick is to configure the editor to produce the same tags as you're willing to 'let through' in your bleach settings.</p>
<p>Here's an example of my bleach settings:</p>
<pre><code># Which HTML tags are allowed
BLEACH_ALLOWED_TAGS = ['p', 'h3', 'h4', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'blockquote']
# Which HTML attributes are allowed
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'name']
BLEACH_STRIP_TAGS = True
</code></pre>
<p>Then you can configure TinyMCE (or whatever WYSIWYG editor you're using) only to have the buttons that create the allowed tags.</p>
| 2 | 2014-12-17T10:45:04Z | [
"python",
"django",
"django-templates",
"filter"
] |
How do i set the PDU mode of a modem using python sms 0.3 module? | 1,415,162 | <p>Am using python <a href="http://pypi.python.org/pypi/sms/0.3" rel="nofollow">sms 0.3</a> module to access my modem on com port. Am trying to send an sms but am getting the following error</p>
<p>sms.ModemError: ['\r\n', '+CMS ERROR: 304\r\n']</p>
<p>When i read the Modem error codes, Error code 304 is for PDU mode, am just wondering how do i set the mode using sms 0.3</p>
<p>Am using a USB modem, Huawei model E220.</p>
<p>Gath</p>
| 0 | 2009-09-12T13:48:15Z | 2,203,986 | <p>Not sure if you can do it via the SMS library, but you can do it directly by sending via the serial port to the modem.:
"AT+CMGF=0" sets PDU mode for SMS messages
"AT+CMGF=1" sets text mode for SMS messages
"AT+CMGF?" should give the current setting</p>
| 0 | 2010-02-04T23:23:08Z | [
"python",
"sms",
"modem"
] |
Resources for developing Python and Google App Engine | 1,415,208 | <p>I would like to ask about some sources for developing applications with Python and Google App Engine.</p>
<p>For example, some controls to generate automatically pages with the insert/update/delete of a database table, or any other useful resources are welcome.</p>
<p>Thank you!</p>
| 2 | 2009-09-12T14:07:55Z | 1,415,236 | <p>The google app engine "Getting Started" tutorial is very good. The django documentation is also really detailed.
Take a look at GoogleIO on youtube and watch some of the tutorials.</p>
| 3 | 2009-09-12T14:16:50Z | [
"python",
"google-app-engine",
"user-controls",
"controls"
] |
Resources for developing Python and Google App Engine | 1,415,208 | <p>I would like to ask about some sources for developing applications with Python and Google App Engine.</p>
<p>For example, some controls to generate automatically pages with the insert/update/delete of a database table, or any other useful resources are welcome.</p>
<p>Thank you!</p>
| 2 | 2009-09-12T14:07:55Z | 1,419,518 | <p>The Python community tends to look askance at code generation; so, @Hoang, if you think code generation is THE way to go, I suggest you try just about any other language BUT Python.</p>
<p>@Dominic has already suggested some excellent resources, I could point you to more (App Engine Fan, App Engine Utilities, etc, etc) but they're all based on the Pythonic mindset: understand what you need and what you could be doing, wrap as much of it as feasible into reusable components, reuse those components from your own sources.</p>
<p>You want magic, wizards and code generation that basically excused you (in theory) from STUDYING and UNDERSTANDING: give up on Python, it's SO not the language for <strong>that</strong>,</p>
| 7 | 2009-09-14T03:08:32Z | [
"python",
"google-app-engine",
"user-controls",
"controls"
] |
Resources for developing Python and Google App Engine | 1,415,208 | <p>I would like to ask about some sources for developing applications with Python and Google App Engine.</p>
<p>For example, some controls to generate automatically pages with the insert/update/delete of a database table, or any other useful resources are welcome.</p>
<p>Thank you!</p>
| 2 | 2009-09-12T14:07:55Z | 1,424,765 | <p>App Engine Documentation
<a href="http://code.google.com/appengine/docs/" rel="nofollow">http://code.google.com/appengine/docs/</a></p>
<p>App Engine Google Group
<a href="http://code.google.com/appengine/docs/" rel="nofollow">http://groups.google.com/group/google-appengine</a></p>
<p>Google I/O conference videos
<a href="http://code.google.com/appengine/docs/" rel="nofollow">http://code.google.com/events/io/</a> </p>
<p>App Engine Cookbook
<a href="http://code.google.com/appengine/docs/" rel="nofollow">http://appengine-cookbook.appspot.com/</a></p>
<p>and, of course, stackoverflow</p>
| 2 | 2009-09-15T02:01:27Z | [
"python",
"google-app-engine",
"user-controls",
"controls"
] |
How to improve speed of this readline loop in python? | 1,415,369 | <p>i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:</p>
<pre><code>def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
sline = ""
# loop till 1st "customernum:" is found
while sline.startswith("customernum: ") is False:
sline = txtdb.readline()
while sline.startswith("customernum: "):
data = []
data.append(sline)
sline = txtdb.readline()
while sline.startswith("customernum: ") is False:
data.append(sline)
sline = txtdb.readline()
if len(sline) == 0:
break
customernum = getitem(data, "customernum: ")
street = getitem(data, "street: ")
country = getitem(data, "country: ")
zip = getitem(data, "zip: ")
</code></pre>
<p>The Textfile is pretty huge, so just looping till the first wanted entry takes very much time. Anyone has an idea if this could be done faster (or if the whole way i fixed this is not the best idea) ?</p>
<p>Many thanks in advance!</p>
| 2 | 2009-09-12T15:26:19Z | 1,415,399 | <p>This might help: <a href="http://braydon.com/blog/2009/2/11/python-performance-part-2%3A-parsing-large-strings-for-a-href-hypertext" rel="nofollow">Python Performance Part 2: Parsing Large Strings for 'A Href' Hypertext</a></p>
| 0 | 2009-09-12T15:40:33Z | [
"python",
"loops",
"readline"
] |
How to improve speed of this readline loop in python? | 1,415,369 | <p>i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:</p>
<pre><code>def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
sline = ""
# loop till 1st "customernum:" is found
while sline.startswith("customernum: ") is False:
sline = txtdb.readline()
while sline.startswith("customernum: "):
data = []
data.append(sline)
sline = txtdb.readline()
while sline.startswith("customernum: ") is False:
data.append(sline)
sline = txtdb.readline()
if len(sline) == 0:
break
customernum = getitem(data, "customernum: ")
street = getitem(data, "street: ")
country = getitem(data, "country: ")
zip = getitem(data, "zip: ")
</code></pre>
<p>The Textfile is pretty huge, so just looping till the first wanted entry takes very much time. Anyone has an idea if this could be done faster (or if the whole way i fixed this is not the best idea) ?</p>
<p>Many thanks in advance!</p>
| 2 | 2009-09-12T15:26:19Z | 1,415,402 | <p>I guess you are writing this import script and it gets boring to wait during testing it, so the data stays the same all the time.</p>
<p>You can run the script once to detect the actual positions in the file you want to jump to, with <code>print txtdb.tell()</code>. Write those down and replace the searching code with <code>txtdb.seek( pos )</code>. Basically that's builing an index for the file ;-)</p>
<p>Another more convetional way would be to read data in larger chunks, a few MB at a time, not just the few bytes on a line.</p>
| 1 | 2009-09-12T15:40:52Z | [
"python",
"loops",
"readline"
] |
How to improve speed of this readline loop in python? | 1,415,369 | <p>i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:</p>
<pre><code>def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
sline = ""
# loop till 1st "customernum:" is found
while sline.startswith("customernum: ") is False:
sline = txtdb.readline()
while sline.startswith("customernum: "):
data = []
data.append(sline)
sline = txtdb.readline()
while sline.startswith("customernum: ") is False:
data.append(sline)
sline = txtdb.readline()
if len(sline) == 0:
break
customernum = getitem(data, "customernum: ")
street = getitem(data, "street: ")
country = getitem(data, "country: ")
zip = getitem(data, "zip: ")
</code></pre>
<p>The Textfile is pretty huge, so just looping till the first wanted entry takes very much time. Anyone has an idea if this could be done faster (or if the whole way i fixed this is not the best idea) ?</p>
<p>Many thanks in advance!</p>
| 2 | 2009-09-12T15:26:19Z | 1,415,407 | <p>Tell us more about the file.</p>
<p>Can you use file.seek to do a binary search? Seek to the halfway mark, read a few lines, determine if you are before or after the part you need, recurse. That will turn your O(n) search into O(logn).</p>
| 0 | 2009-09-12T15:42:35Z | [
"python",
"loops",
"readline"
] |
How to improve speed of this readline loop in python? | 1,415,369 | <p>i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:</p>
<pre><code>def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
sline = ""
# loop till 1st "customernum:" is found
while sline.startswith("customernum: ") is False:
sline = txtdb.readline()
while sline.startswith("customernum: "):
data = []
data.append(sline)
sline = txtdb.readline()
while sline.startswith("customernum: ") is False:
data.append(sline)
sline = txtdb.readline()
if len(sline) == 0:
break
customernum = getitem(data, "customernum: ")
street = getitem(data, "street: ")
country = getitem(data, "country: ")
zip = getitem(data, "zip: ")
</code></pre>
<p>The Textfile is pretty huge, so just looping till the first wanted entry takes very much time. Anyone has an idea if this could be done faster (or if the whole way i fixed this is not the best idea) ?</p>
<p>Many thanks in advance!</p>
| 2 | 2009-09-12T15:26:19Z | 1,415,451 | <p>The general idea for optimization is to proceed "by big blocks" (mostly-ignoring line structure) to locate the first line of interest, then move on to by-line processing for the rest). It's somewhat finicky and error-prone (off-by-one and the like) so it really needs testing, but the general idea is as follows...:</p>
<pre><code>import itertools
def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
tag = "customernum: "
BIGBLOCK = 1024 * 1024
# locate first occurrence of tag at line-start
# (assumes the VERY FIRST line doesn't start that way,
# else you need a special-case and slight refactoring)
blob = ''
while True:
blob = blob + txtdb.read(BIGBLOCK)
if not blob:
# tag not present at all -- warn about that, then
return
where = blob.find('\n' + tag)
if where != -1: # found it!
blob = blob[where+1:] + txtdb.readline()
break
blob = blob[-len(tag):]
# now make a by-line iterator over the part of interest
thelines = itertools.chain(blob.splitlines(1), txtdb)
sline = next(thelines, '')
while sline.startswith(tag):
data = []
data.append(sline)
sline = next(thelines, '')
while not sline.startswith(tag):
data.append(sline)
sline = next(thelines, '')
if not sline:
break
customernum = getitem(data, "customernum: ")
street = getitem(data, "street: ")
country = getitem(data, "country: ")
zip = getitem(data, "zip: ")
</code></pre>
<p>Here, I've tried to keep as much of your structure intact as feasible, doing only minor enhancements beyond the "big idea" of this refactoring.</p>
| 1 | 2009-09-12T16:10:31Z | [
"python",
"loops",
"readline"
] |
How to improve speed of this readline loop in python? | 1,415,369 | <p>i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:</p>
<pre><code>def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
sline = ""
# loop till 1st "customernum:" is found
while sline.startswith("customernum: ") is False:
sline = txtdb.readline()
while sline.startswith("customernum: "):
data = []
data.append(sline)
sline = txtdb.readline()
while sline.startswith("customernum: ") is False:
data.append(sline)
sline = txtdb.readline()
if len(sline) == 0:
break
customernum = getitem(data, "customernum: ")
street = getitem(data, "street: ")
country = getitem(data, "country: ")
zip = getitem(data, "zip: ")
</code></pre>
<p>The Textfile is pretty huge, so just looping till the first wanted entry takes very much time. Anyone has an idea if this could be done faster (or if the whole way i fixed this is not the best idea) ?</p>
<p>Many thanks in advance!</p>
| 2 | 2009-09-12T15:26:19Z | 1,416,116 | <p>Please do not write this code:</p>
<pre><code>while condition is False:
</code></pre>
<p>Boolean conditions are <em>boolean</em> for cryin' out loud, so they can be tested (or negated and tested) directly:</p>
<pre><code>while not condition:
</code></pre>
<p>Your second while loop isn't written as "while condition is True:", I'm curious why you felt the need to test "is False" in the first one.</p>
<p>Pulling out the dis module, I thought I'd dissect this a little further. In my pyparsing experience, function calls are total performance killers, so it would be nice to avoid function calls if possible. Here is your original test:</p>
<pre><code>>>> test = lambda t : t.startswith('customernum') is False
>>> dis.dis(test)
1 0 LOAD_FAST 0 (t)
3 LOAD_ATTR 0 (startswith)
6 LOAD_CONST 0 ('customernum')
9 CALL_FUNCTION 1
12 LOAD_GLOBAL 1 (False)
15 COMPARE_OP 8 (is)
18 RETURN_VALUE
</code></pre>
<p>Two expensive things happen here, <code>CALL_FUNCTION</code> and <code>LOAD_GLOBAL</code>. You could cut back on <code>LOAD_GLOBAL</code> by defining a local name for False:</p>
<pre><code>>>> test = lambda t,False=False : t.startswith('customernum') is False
>>> dis.dis(test)
1 0 LOAD_FAST 0 (t)
3 LOAD_ATTR 0 (startswith)
6 LOAD_CONST 0 ('customernum')
9 CALL_FUNCTION 1
12 LOAD_FAST 1 (False)
15 COMPARE_OP 8 (is)
18 RETURN_VALUE
</code></pre>
<p>But what if we just drop the 'is' test completely?:</p>
<pre><code>>>> test = lambda t : not t.startswith('customernum')
>>> dis.dis(test)
1 0 LOAD_FAST 0 (t)
3 LOAD_ATTR 0 (startswith)
6 LOAD_CONST 0 ('customernum')
9 CALL_FUNCTION 1
12 UNARY_NOT
13 RETURN_VALUE
</code></pre>
<p>We've collapsed a <code>LOAD_xxx</code> and <code>COMPARE_OP</code> with a simple <code>UNARY_NOT</code>. "is False" certainly isn't helping the performance cause any.</p>
<p>Now what if we can do some gross elimination of a line without doing any function calls at all. If the first character of the line is not a 'c', there is no way it will startswith('customernum'). Let's try that:</p>
<pre><code>>>> test = lambda t : t[0] != 'c' and not t.startswith('customernum')
>>> dis.dis(test)
1 0 LOAD_FAST 0 (t)
3 LOAD_CONST 0 (0)
6 BINARY_SUBSCR
7 LOAD_CONST 1 ('c')
10 COMPARE_OP 3 (!=)
13 JUMP_IF_FALSE 14 (to 30)
16 POP_TOP
17 LOAD_FAST 0 (t)
20 LOAD_ATTR 0 (startswith)
23 LOAD_CONST 2 ('customernum')
26 CALL_FUNCTION 1
29 UNARY_NOT
>> 30 RETURN_VALUE
</code></pre>
<p>(Note that using [0] to get the first character of a string does <em>not</em> create a slice - this is in fact very fast.)</p>
<p>Now, assuming there are not a large number of lines starting with 'c', the rough-cut filter can eliminate a line using all fairly fast instructions. In fact, by testing "t[0] != 'c'" instead of "not t[0] == 'c'" we save ourselves an extraneous <code>UNARY_NOT</code> instruction. </p>
<p>So using this learning about short-cut optimization and I suggest changing this code:</p>
<pre><code>while sline.startswith("customernum: ") is False:
sline = txtdb.readline()
while sline.startswith("customernum: "):
... do the rest of the customer data stuff...
</code></pre>
<p>To this:</p>
<pre><code>for sline in txtdb:
if sline[0] == 'c' and \
sline.startswith("customernum: "):
... do the rest of the customer data stuff...
</code></pre>
<p>Note that I have also removed the .readline() function call, and just iterate over the file using "for sline in txtdb".</p>
<p>I realize Alex has provided a different body of code entirely for finding that first 'customernum' line, but I would try optimizing within the general bounds of your algorithm, before pulling out big but obscure block reading guns.</p>
| 5 | 2009-09-12T20:54:14Z | [
"python",
"loops",
"readline"
] |
Does anybody use DjVu files in their production tools? | 1,415,400 | <p>When it's about archiving and doc portability, it's all about PDF. I heard about <a href="http://djvu.org/" rel="nofollow">DjVu</a> somes years ago, and it seems to be now mature enough for serious usages. The benefits seems to be a small size format and a fast open / read experience.</p>
<p>But I have absolutely no feedback on how good / bad it is in the real world :</p>
<ul>
<li>Is it technically hard to implement in traditional information management tools ?</li>
<li>Is is worth learning / implementing solution to generate / parse it when you now PDF ?</li>
<li>Is the final user feedback good when it comes to day to day use ?</li>
<li>How do you manage exchanges with the external world (the one with a PDF only state of mind) ?</li>
<li>As a programmer, what are the pro and cons ?</li>
<li>And what would you use to convince your boss to (or not to) use DjVU ?</li>
<li>And globally, what gain did you noticed after including DjVu in your workflow ?</li>
</ul>
<p>Bonus question : do you know some good Python libs to hack some quick and dirty scripts as a begining ?</p>
<p>EDIT : doing some research, I ended up getting that Wikimedia use it to internally store its book collection but can't find any feedback about it. Anybody involved in that project around here ?</p>
| 5 | 2009-09-12T15:40:34Z | 1,415,721 | <p>I've found DjVu to be ideal for image-intensive documents. I used to sell books of highly details maps, and those were always in DjVu. PDF however works really well; it's a standard, and -everybody- will be able to open it without installing additional software.</p>
<p>There's more info at:
<a href="http://print-driver.com/news/pdf-vs-djvu-i1909.html" rel="nofollow">http://print-driver.com/news/pdf-vs-djvu-i1909.html</a></p>
<p>Personally, I'd say until its graphic-rich documents, just stick to PDF.</p>
| 3 | 2009-09-12T17:50:40Z | [
"python",
"pdf",
"djvu"
] |
How to get instance type of a win32com object? | 1,415,405 | <p>First of all, please excuse me for any incoherence in the tile of this question. It probably has some, but really don't know better.</p>
<p>This question was raised in the context of controlling iTunes via COM from python.</p>
<pre><code>>>> itunes = win32com.client.Dispatch("iTunes.Application")
>>> itunes
<win32com.gen_py.iTunes 1.12 Type Library.IiTunes instance at 0x27248400>
>>> lib = itunes.LibraryPlaylist
>>> lib
<win32com.gen_py.iTunes 1.12 Type Library.IITLibraryPlaylist instance at 0x27249880>
</code></pre>
<p>What I would like to do is to retrieve '<strong>IiTunes</strong>' from itunes and '<strong>IITLibraryPlaylist</strong>' from lib. I have tried type(itunes) and type(lib) but they both only return "" and that's not what I am looking for.</p>
<p>Thanks.</p>
| 1 | 2009-09-12T15:41:33Z | 1,415,479 | <p>Unfortunately I have no Windows machine at hand to try, but I think <code>itunes.__class__</code> is the (old_style) class of the <code>itunes</code> object in question, and <code>lib.__class__</code> that of <code>lib</code>. So looking at the <code>__name__</code> attribute of the classes should give you what you desire.</p>
<p>It's unfortunately that these are old-style classes (so <code>type(...)</code> does not work right), but win32com has been around for a LONG time, from well before the shiny new-style classes were born in Python 2.2, so it's fully understandable, I think;-).</p>
| 1 | 2009-09-12T16:17:16Z | [
"python",
"com",
"itunes",
"instance"
] |
GQL get ID field | 1,415,553 | <p>On google appengine, you can retrieve the hash key value by doing a query like</p>
<pre>
select __key__ from furniture
</pre>
<p>But appengine datastore maintains a nicely autoincremented field ID for each kind.</p>
<p>How can I access it from a query? </p>
<pre>
select ID from furniture
</pre>
<p>Doesn't work</p>
| 3 | 2009-09-12T16:45:08Z | 1,415,669 | <p>I believe that a Gcl query cannot incorporate calls to accessor methods or attribute extraction (much in the same vein as the fact it can only do <code>"SELECT * FROM"</code> to fetch whole entities or <code>"SELECT __key__ FROM"</code> to fetch keys only -- it cannot pick and choose fields as in [hypothetical!-)] <code>"SELECT this, that FROM</code>").</p>
<p>So, you need to fetch the keys, then call each key's <code>.id()</code> accessor (if you want <code>None</code> for keys that don't have an ID but rather a name; use <code>.id_or_name()</code> if you'd rather get the name, if available, and <code>None</code> only as a last resort). E.g., to get non-None IDs only:</p>
<pre><code>thekeys = db.GqlQuery('SELECT __key__ FROM Whatever').fetch(1000)
theids = [k.id() for k in thekeys if k.id() is not None]
</code></pre>
| 4 | 2009-09-12T17:31:26Z | [
"python",
"google-app-engine"
] |
GQL get ID field | 1,415,553 | <p>On google appengine, you can retrieve the hash key value by doing a query like</p>
<pre>
select __key__ from furniture
</pre>
<p>But appengine datastore maintains a nicely autoincremented field ID for each kind.</p>
<p>How can I access it from a query? </p>
<pre>
select ID from furniture
</pre>
<p>Doesn't work</p>
| 3 | 2009-09-12T16:45:08Z | 9,053,686 | <p>you could also try </p>
<pre><code>entity.key().id()
</code></pre>
| 4 | 2012-01-29T13:53:15Z | [
"python",
"google-app-engine"
] |
GQL get ID field | 1,415,553 | <p>On google appengine, you can retrieve the hash key value by doing a query like</p>
<pre>
select __key__ from furniture
</pre>
<p>But appengine datastore maintains a nicely autoincremented field ID for each kind.</p>
<p>How can I access it from a query? </p>
<pre>
select ID from furniture
</pre>
<p>Doesn't work</p>
| 3 | 2009-09-12T16:45:08Z | 17,932,630 | <p>I am not sure if it was there back then when you have asked this question, but now it is pretty easy to retrieve entity by id. </p>
<pre><code>YourModel.get_by_id (int(ids))
</code></pre>
<p>You can read more about it here in the documentation: <a href="https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_get_by_id" rel="nofollow">https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_get_by_id</a></p>
| 0 | 2013-07-29T19:32:17Z | [
"python",
"google-app-engine"
] |
How to create hover effect on StaticBitmap in wxpython? | 1,415,727 | <p>I want to create hover effect on StaticBitmap - If the cursor of mouse is over the the bitmap, shows one image, if not, shows second image. It's trivial program (works perfectly with a button). However, StaticBitmap doesn't emit EVT_WINDOW_ENTER, EVT_WINDOW_LEAVE events.</p>
<p>I can work with EVT_MOTION. If images are switched when the cursor is on the edge of image, switch sometimes doesn't work. (Mainly with fast moving over the edge).</p>
<p>Example code:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
def onWindow(event):
print "window event:", event.m_x, event.m_y
def onMotion(event):
print "motion event:", event.m_x, event.m_y
app = wx.App()
imageA = wx.Image("b.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
imageB = wx.Image("a.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect", size=(100+imageA.GetWidth(), 100+imageA.GetHeight()))
w = wx.Window(frame)
bmp = wx.StaticBitmap(w, -1, imageA, (50, 50), (imageA.GetWidth(), imageA.GetHeight()))
bmp.Bind(wx.EVT_MOTION, onMotion)
bmp.Bind(wx.EVT_ENTER_WINDOW, onWindow)
bmp.Bind(wx.EVT_LEAVE_WINDOW, onWindow)
frame.Show()
app.MainLoop()
</code></pre>
| 4 | 2009-09-12T17:52:55Z | 1,415,815 | <p>It looks like this is a wxGTK bug, ENTER and LEAVE events work fine on windows. You should direct the attention of the core developers to the problem, a good place to do this is their <a href="http://trac.wxwidgets.org/" rel="nofollow">bug tracker</a>. This is an issue you should not have to work around IMHO.</p>
<p>I have found that GenericButtons do not have this problem on wxGTK, so maybe you can use that until StaticBitmap gets fixed.</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
from wx.lib import buttons
def onWindow(event):
print "window event:", event.m_x, event.m_y
def onMotion(event):
print "motion event:", event.m_x, event.m_y
app = wx.App()
imageA = wx.Image("b.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
imageB = wx.Image("a.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect", size=(100+imageA.GetWidth(), 100+imageA.GetHeight()))
w = wx.Window(frame)
#bmp = wx.StaticBitmap(w, -1, imageA, (50, 50), (imageA.GetWidth(), imageA.GetHeight()))
bmp = buttons.GenBitmapButton(w, -1, imageA, style=wx.BORDER_NONE)
#bmp.Bind(wx.EVT_MOTION, onMotion)
bmp.Bind(wx.EVT_ENTER_WINDOW, onWindow)
bmp.Bind(wx.EVT_LEAVE_WINDOW, onWindow)
frame.Show()
app.MainLoop()
</code></pre>
| 1 | 2009-09-12T18:44:06Z | [
"python",
"image",
"wxpython",
"wxwidgets",
"hover"
] |
How to create hover effect on StaticBitmap in wxpython? | 1,415,727 | <p>I want to create hover effect on StaticBitmap - If the cursor of mouse is over the the bitmap, shows one image, if not, shows second image. It's trivial program (works perfectly with a button). However, StaticBitmap doesn't emit EVT_WINDOW_ENTER, EVT_WINDOW_LEAVE events.</p>
<p>I can work with EVT_MOTION. If images are switched when the cursor is on the edge of image, switch sometimes doesn't work. (Mainly with fast moving over the edge).</p>
<p>Example code:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
def onWindow(event):
print "window event:", event.m_x, event.m_y
def onMotion(event):
print "motion event:", event.m_x, event.m_y
app = wx.App()
imageA = wx.Image("b.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
imageB = wx.Image("a.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect", size=(100+imageA.GetWidth(), 100+imageA.GetHeight()))
w = wx.Window(frame)
bmp = wx.StaticBitmap(w, -1, imageA, (50, 50), (imageA.GetWidth(), imageA.GetHeight()))
bmp.Bind(wx.EVT_MOTION, onMotion)
bmp.Bind(wx.EVT_ENTER_WINDOW, onWindow)
bmp.Bind(wx.EVT_LEAVE_WINDOW, onWindow)
frame.Show()
app.MainLoop()
</code></pre>
| 4 | 2009-09-12T17:52:55Z | 1,416,831 | <p>There may be bug in wxStaticBitmap implementation, but if wxBitmapButton works you can use it for same effect, with less code</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect")
w = wx.Window(frame)
c = wx.BitmapButton(w, -1, wx.EmptyBitmap(25,25), style = wx.NO_BORDER)
c.SetBitmapHover(wx.EmptyBitmap(3,3))
frame.Show()
app.MainLoop()
</code></pre>
| 0 | 2009-09-13T04:13:45Z | [
"python",
"image",
"wxpython",
"wxwidgets",
"hover"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,817 | <p><code>**kwargs</code> are good if you don't know in advance the name of the parameters. For example the <code>dict</code> constructor uses them to initialize the keys of the new dictionary. </p>
<blockquote>
<pre><code>dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
</code></pre>
</blockquote>
<pre><code>In [3]: dict(one=1, two=2)
Out[3]: {'one': 1, 'two': 2}
</code></pre>
| 3 | 2009-09-12T18:45:42Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,826 | <p>Real-world examples:</p>
<p>Decorators - they're usually generic, so you can't specify the arguments upfront:</p>
<pre><code>def decorator(old):
def new(*args, **kwargs):
# ...
return old(*args, **kwargs)
return new
</code></pre>
<p>Places where you want to do magic with an unknown number of keyword arguments. Django's ORM does that, e.g.:</p>
<pre><code>Model.objects.filter(foo__lt = 4, bar__iexact = 'bar')
</code></pre>
| 29 | 2009-09-12T18:50:27Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,827 | <p>One example is implementing <a href="http://stackoverflow.com/questions/277922/python-argument-binders">python-argument-binders</a>, used like this:</p>
<blockquote>
<pre><code>>>> from functools import partial
>>> def f(a, b):
... return a+b
>>> p = partial(f, 1, 2)
>>> p()
3
>>> p2 = partial(f, 1)
>>> p2(7)
8
</code></pre>
</blockquote>
<p>This is from the <a href="http://docs.python.org/library/functools.html?highlight=functools#functools.partial" rel="nofollow">functools.partial</a> python docs: partial is 'relatively equivalent' to this impl:</p>
<blockquote>
<pre><code>def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
</code></pre>
</blockquote>
| 0 | 2009-09-12T18:50:59Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,830 | <p>You may want to accept nearly-arbitrary named arguments for a series of reasons -- and that's what the <code>**kw</code> form lets you do.</p>
<p>The most common reason is to pass the arguments right on to some other function you're wrapping (decorators are one case of this, but FAR from the only one!) -- in this case, <code>**kw</code> loosens the coupling between wrapper and wrappee, as the wrapper doesn't have to know or care about all of the wrappee's arguments. Here's another, completely different reason:</p>
<pre><code>d = dict(a=1, b=2, c=3, d=4)
</code></pre>
<p>if all the names had to be known in advance, then obviously this approach just couldn't exist, right? And btw, when applicable, I much prefer this way of making a dict whose keys are literal strings to:</p>
<pre><code>d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
</code></pre>
<p>simply because the latter is quite punctuation-heavy and hence less readable.</p>
<p>When none of the excellent reasons for accepting <code>**kwargs</code> applies, then don't accept it: it's as simple as that. IOW, if there's no good reason to allow the caller to pass extra named args with arbitrary names, don't allow that to happen -- just avoid putting a <code>**kw</code> form at the end of the function's signature in the <code>def</code> statement.</p>
<p>As for <em>using</em> <code>**kw</code> in a call, that lets you put together the exact set of named arguments that you must pass, each with corresponding values, in a dict, independently of a single call point, then use that dict at the single calling point. Compare:</p>
<pre><code>if x: kw['x'] = x
if y: kw['y'] = y
f(**kw)
</code></pre>
<p>to:</p>
<pre><code>if x:
if y:
f(x=x, y=y)
else:
f(x=x)
else:
if y:
f(y=y)
else:
f()
</code></pre>
<p>Even with just two possibilities (and of the very simplest kind!), the lack of <code>**kw</code> is aleady making the second option absolutely untenable and intolerable -- just imagine how it plays out when there half a dozen possibilities, possibly in slightly richer interaction... without <code>**kw</code>, life would be absolute hell under such circumstances!</p>
| 47 | 2009-09-12T18:52:09Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,840 | <p>There are two common cases:</p>
<p>First: You are wrapping another function which takes a number of keyword argument, but you are just going to pass them along:</p>
<pre><code>def my_wrapper(a, b, **kwargs):
do_something_first(a, b)
the_real_function(**kwargs)
</code></pre>
<p>Second: You are willing to accept any keyword argument, for example, to set attributes on an object:</p>
<pre><code>class OpenEndedObject:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
foo = OpenEndedObject(a=1, foo='bar')
assert foo.a == 1
assert foo.foo == 'bar'
</code></pre>
| 9 | 2009-09-12T18:56:22Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,882 | <p>Another reason you might want to use <code>**kwargs</code> (and <code>*args</code>) is if you're extending an existing method in a subclass. You want to pass all the existing arguments onto the superclass's method, but want to ensure that your class keeps working even if the signature changes in a future version:</p>
<pre><code>class MySubclass(Superclass):
def __init__(self, *args, **kwargs):
self.myvalue = kwargs.pop('myvalue', None)
super(MySubclass, self).__init__(*args, **kwargs)
</code></pre>
| 29 | 2009-09-12T19:15:33Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,415,956 | <p>Here's an example, I used in CGI Python. I created a class that took <code>**kwargs</code> to the <code>__init__</code> function. That allowed me to emulate the DOM on the server-side with classes:</p>
<pre><code>document = Document()
document.add_stylesheet('style.css')
document.append(Div(H1('Imagist\'s Page Title'), id = 'header'))
document.append(Div(id='body'))
</code></pre>
<p>The only problem is that you can't do the following, because <code>class</code> is a Python keyword.</p>
<pre><code>Div(class = 'foo')
</code></pre>
<p>The solution is to access the underlying dictionary.</p>
<pre><code>Div(**{'class':'foo'})
</code></pre>
<p>I'm not saying that this is a "correct" usage of the feature. What I'm saying is that there are all kinds of unforseen ways in which features like this can be used.</p>
| 2 | 2009-09-12T19:49:47Z | [
"python",
"kwargs"
] |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | <p>I come from a background in static languages. Can someone explain (ideally through example) the real world <strong>advantages of using **kwargs over named arguments</strong>?</p>
<p>To me it only seems to make the function call more ambiguous. Thanks.</p>
| 42 | 2009-09-12T18:38:01Z | 1,416,928 | <p>And here's another typical example:</p>
<pre><code>MESSAGE = "Lo and behold! A message {message!r} came from {object_} with data {data!r}."
def proclaim(object_, message, data):
print(MESSAGE.format(**locals()))
</code></pre>
| 1 | 2009-09-13T05:30:16Z | [
"python",
"kwargs"
] |
how can i obtain pattern string from compiled regexp pattern in python | 1,415,924 | <p>I have some code like this one:</p>
<pre><code>>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
</code></pre>
<p>Is it possible to get string <code>"my pattern"</code> from <code>p</code> variable?</p>
| 49 | 2009-09-12T19:34:41Z | 1,415,932 | <pre><code>p.pattern
</code></pre>
<p>Read more about re module here:
<a href="http://docs.python.org/library/re.html">http://docs.python.org/library/re.html</a></p>
| 52 | 2009-09-12T19:38:30Z | [
"python",
"regex"
] |
how can i obtain pattern string from compiled regexp pattern in python | 1,415,924 | <p>I have some code like this one:</p>
<pre><code>>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
</code></pre>
<p>Is it possible to get string <code>"my pattern"</code> from <code>p</code> variable?</p>
| 49 | 2009-09-12T19:34:41Z | 1,415,934 | <p>Yes:</p>
<pre><code>print p.pattern
</code></pre>
<p>hint, use the <code>dir</code> function in python to obtain a list of members:</p>
<pre><code>dir(p)
</code></pre>
<p>this lists:</p>
<pre><code>['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'findall', 'finditer', 'flags', 'groupindex', 'groups', 'match', 'pattern',
'scanner', 'search', 'split', 'sub', 'subn']
</code></pre>
| 4 | 2009-09-12T19:39:16Z | [
"python",
"regex"
] |
how can i obtain pattern string from compiled regexp pattern in python | 1,415,924 | <p>I have some code like this one:</p>
<pre><code>>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
</code></pre>
<p>Is it possible to get string <code>"my pattern"</code> from <code>p</code> variable?</p>
| 49 | 2009-09-12T19:34:41Z | 1,415,943 | <p>Thanks. p.pattern really works. But my dir don't display this attribute</p>
<pre>
<code>
>>> sys.version
'2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)]'
>>> dir(p)
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
>>> p.pattern
'my pattern'
>>>
>>> dir
built-in function dir
</code>
</pre>
| 0 | 2009-09-12T19:44:50Z | [
"python",
"regex"
] |
how can i obtain pattern string from compiled regexp pattern in python | 1,415,924 | <p>I have some code like this one:</p>
<pre><code>>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
</code></pre>
<p>Is it possible to get string <code>"my pattern"</code> from <code>p</code> variable?</p>
| 49 | 2009-09-12T19:34:41Z | 1,415,977 | <p>From the <a href="http://docs.python.org/library/re.html#regular-expression-objects">"Regular Expression Objects"</a> section of the <code>re</code> module documentation:</p>
<blockquote>
<p><code>RegexObject.pattern</code></p>
<p>The pattern string from which the RE object was compiled.</p>
</blockquote>
<p>For example:</p>
<pre><code>>>> import re
>>> p = re.compile('my pattern')
>>> p
<_sre.SRE_Pattern object at 0x1001ba818>
>>> p.pattern
'my pattern'
</code></pre>
<p>With the <code>re</code> module in Python 3.0 and above, you can find this by doing a simple <code>dir(p)</code>:</p>
<pre><code>>>> print(dir(p))
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'findall', 'finditer', 'flags',
'groupindex', 'groups', 'match', 'pattern', 'scanner', 'search',
'split', 'sub', 'subn']
</code></pre>
<p>This however does <em>not</em> work on Python 2.6 (or 2.5) - the <code>dir</code> command isn't perfect, so it's always worth checking the docs!</p>
<pre><code>>>> print dir(p)
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner',
'search', 'split', 'sub', 'subn']
</code></pre>
| 12 | 2009-09-12T19:59:20Z | [
"python",
"regex"
] |
Python - Virtualenv , python 3? | 1,416,005 | <p>Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks.</p>
<p>OK I realized virtualenv is not what I'm looking for.</p>
| 8 | 2009-09-12T20:10:43Z | 1,416,051 | <p>Not sure if I understood you correctly, but here goes :) </p>
<p>I don't know about OS X, but in Linux you can install both 2.6 and 3. Then you can either specify to use python25 or python3, or change the /usr/bin/python symlink to the version you want to use by default.</p>
| 0 | 2009-09-12T20:25:12Z | [
"python",
"osx",
"python-3.x",
"pygame",
"virtualenv"
] |
Python - Virtualenv , python 3? | 1,416,005 | <p>Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks.</p>
<p>OK I realized virtualenv is not what I'm looking for.</p>
| 8 | 2009-09-12T20:10:43Z | 1,416,152 | <p><code>virtualenv</code> is designed to create isolated environments of a Python environment. The trick to using it with multiple Python instances is to either install <code>virtualenv</code> into each of the Python versions you want to use it with, for example:</p>
<pre><code>/usr/bin/easy_install-2.6 virtualenv
/usr/local/bin/easy_install virtualenv
sudo port install py26-virtualenv
</code></pre>
<p>or to invoke it with the intended Python version, for example:</p>
<pre><code>/usr/bin/python2.6 virtualenv.py ENV
/usr/local/bin/python2.6 virtualenv.py ENV
/opt/local/bin/python2.5 virtualenv.py ENV
</code></pre>
<p>So, as such, it doesn't directly solve the problem (particularly acute on OS X) of which Python you want to work with. There are various ways to deal with that issue: use absolute paths to the intended Python (as in the above examples), define shell aliases, carefully manage the <code>$PATH</code> search order, among others.</p>
<p>At the moment, AFAIK, <code>virtualenv</code> is not supported with Python 3 because, among other things, <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools</a> (the magic behind easy_install) is not yet supported on Python 3, although there is <a href="http://pypi.python.org/pypi/distribute" rel="nofollow">work in progress</a> towards a solution for that.</p>
<p>BTW, many people use Doug Hellman's <a href="http://www.doughellmann.com/docs/virtualenvwrapper/" rel="nofollow">virtualenvwrapper</a> to simplify use of virtualenv.</p>
| 1 | 2009-09-12T21:12:19Z | [
"python",
"osx",
"python-3.x",
"pygame",
"virtualenv"
] |
Python - Virtualenv , python 3? | 1,416,005 | <p>Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks.</p>
<p>OK I realized virtualenv is not what I'm looking for.</p>
| 8 | 2009-09-12T20:10:43Z | 1,416,162 | <p>Your use case doesn't actually need virtualenv. You just need to install several different Python versions.</p>
| 3 | 2009-09-12T21:18:14Z | [
"python",
"osx",
"python-3.x",
"pygame",
"virtualenv"
] |
Python - Virtualenv , python 3? | 1,416,005 | <p>Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks.</p>
<p>OK I realized virtualenv is not what I'm looking for.</p>
| 8 | 2009-09-12T20:10:43Z | 3,211,439 | <p>For me <a href="http://bitbucket.org/brandon/virtualenv3" rel="nofollow">virtualenv3</a> works very well. I also have pypi.python.org/pypi/distribute installed. That also works with the mentioned www.doughellmann.com/docs/virtualenvwrapper/ . I've only tested that on Linux though.</p>
| 1 | 2010-07-09T09:39:29Z | [
"python",
"osx",
"python-3.x",
"pygame",
"virtualenv"
] |
Python - Virtualenv , python 3? | 1,416,005 | <p>Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks.</p>
<p>OK I realized virtualenv is not what I'm looking for.</p>
| 8 | 2009-09-12T20:10:43Z | 28,298,765 | <p>It's an old question by now, but I found it myself on top of google search for the answer, and I don't think the answers provided are what people are looking for.</p>
<p>As I understand it you want to create different virtual environments with different Python versions?</p>
<p>This is very easy, and you only need virtualenv itself.</p>
<p>For, say, a Python 3:</p>
<pre><code>$ virtualenv -p python3 p34env
(...)
New python executable in p34env/bin/python3.4
Also creating executable in p34env/bin/python
Installing setuptools, pip...done.
$ source p34env/bin/activate
(p34env)$ python -V
Python 3.4.2
(p34env)$ deactivate
$
</code></pre>
<p>You use the <code>source</code> command to activate the venv, and <code>deactivate</code> to - you guessed it - deactivate it. Notice the prompt changes to indicate the env.</p>
<p>For your system's standard version of Python you just skip the <code>-p python3</code> argument, and you can use the argument to point to any version you want given a path.</p>
<p>The last argument is the name (<code>p34env</code>) and you can make as many as you like, just give them different names.</p>
| 11 | 2015-02-03T12:19:05Z | [
"python",
"osx",
"python-3.x",
"pygame",
"virtualenv"
] |
To Ruby or not to Ruby | 1,416,570 | <p>I know that this is a difficult question to answer, but I thought I would try anwyays....</p>
<p>I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. </p>
<p>It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. </p>
<p>The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). </p>
<p>I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason.</p>
<p>If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language?</p>
<p>How do the libraries stack up?</p>
<p>Thanks!!!</p>
| 1 | 2009-09-13T00:59:06Z | 1,416,574 | <p>Rails apps can potentially make a great REST backend for a php based system.</p>
<p>The REST stuff is made for it. You want xml? ok. You want json? ok. </p>
<p>If you and the staff aren't comfy with it, use something you are more comfy in to write a REST interface. :)</p>
| 1 | 2009-09-13T01:01:23Z | [
"python",
"ruby"
] |
To Ruby or not to Ruby | 1,416,570 | <p>I know that this is a difficult question to answer, but I thought I would try anwyays....</p>
<p>I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. </p>
<p>It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. </p>
<p>The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). </p>
<p>I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason.</p>
<p>If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language?</p>
<p>How do the libraries stack up?</p>
<p>Thanks!!!</p>
| 1 | 2009-09-13T00:59:06Z | 1,416,583 | <p>Why wouldn't you just keep it consistent and use PHP?</p>
| 0 | 2009-09-13T01:07:16Z | [
"python",
"ruby"
] |
To Ruby or not to Ruby | 1,416,570 | <p>I know that this is a difficult question to answer, but I thought I would try anwyays....</p>
<p>I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. </p>
<p>It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. </p>
<p>The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). </p>
<p>I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason.</p>
<p>If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language?</p>
<p>How do the libraries stack up?</p>
<p>Thanks!!!</p>
| 1 | 2009-09-13T00:59:06Z | 1,416,625 | <p>IMO, if you're comfortable with Python then you shouldn't have too much trouble picking up Ruby. This doesn't mean Ruby is the best choice - you should still evaluate the options.</p>
| 0 | 2009-09-13T01:40:25Z | [
"python",
"ruby"
] |
To Ruby or not to Ruby | 1,416,570 | <p>I know that this is a difficult question to answer, but I thought I would try anwyays....</p>
<p>I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. </p>
<p>It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. </p>
<p>The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). </p>
<p>I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason.</p>
<p>If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language?</p>
<p>How do the libraries stack up?</p>
<p>Thanks!!!</p>
| 1 | 2009-09-13T00:59:06Z | 1,416,827 | <h3>Ruby Madness. Sure, it seems cool, but it might lead to the hard stuff: Lisp</h3>
<hr>
<p>My predictions:</p>
<ol>
<li><p>It's pretty clear that you are OK with either <strong>Ruby</strong> or <strong>Python</strong>, and obviously <strong>php</strong> can be made to work. </p></li>
<li><p>You will really like <strong>Ruby</strong>.</p></li>
</ol>
<p>I'm a little bit worried that after <strong>Ruby</strong> the only place left to go will be <strong>Lisp</strong>, and that I will become one of those raving lisp maniacs with bad haircuts waving my arms and muttering about The One True Macro Processor.</p>
<p>Slightly more seriously, though Lisp and Smalltalk are still in tiny niche spaces after 60 and 40 years, it turns out that the child of the two bore fruit. Various Lisp and Smalltalk hackers are starting to show up speaking about their child Ruby at Ruby and Rails cons. As it happens, Ruby (timeframe 15 years) has quite a bit of the Lisp and Smalltalk magic.</p>
<p>And, to this party, Ruby brings about every single bit of the day-to-day and 3-line-script usefulness of Perl. Ruby is an explosion on the language scene that combines the scripting superpower of Perl with the object-orient superpower of an exotic language like Smalltalk.</p>
<p>Ruby is an awesome and groundbreaking language with or without Rails. I say, drink the kool-aid.</p>
| 4 | 2009-09-13T04:11:43Z | [
"python",
"ruby"
] |
To Ruby or not to Ruby | 1,416,570 | <p>I know that this is a difficult question to answer, but I thought I would try anwyays....</p>
<p>I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. </p>
<p>It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. </p>
<p>The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). </p>
<p>I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason.</p>
<p>If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language?</p>
<p>How do the libraries stack up?</p>
<p>Thanks!!!</p>
| 1 | 2009-09-13T00:59:06Z | 1,417,451 | <p>My advice would depend on your own goals, which might look like this... you might want to ask yourself (or score each of these from 1-10) if you prefer to:</p>
<ol>
<li>learn a new language you might use in future? = Ruby</li>
<li>deepen your Python skills by using it for everything (say <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> or <a href="http://webpy.org/" rel="nofollow">Web.Py</a>) = Python</li>
<li>move the <a href="http://ruby-toolbox.com/categories/testing%5Fframeworks.html" rel="nofollow">Ruby testing away from Rails</a> = Ruby</li>
</ol>
<p>Other questions you could ask yourself to help the decision might be:</p>
<ol>
<li>is speed important? Do some tests in the various languages. (If Ruby, then use <a href="http://rads.stackoverflow.com/amzn/click/0596516177" rel="nofollow">Ruby 1.9</a> and get <a href="http://rads.stackoverflow.com/amzn/click/0672328844" rel="nofollow">the other Ruby book</a>).</li>
<li>is integration important? If so, why use a PHP front end?</li>
<li>is your connection to the language community important? If so, choose on 'community feel'.</li>
<li>is there a lot of backend text processing? (Perl?)</li>
<li>do you want to use an ORM or write SQL? = look at Ruby and Python <a href="http://www.linux-mag.com/id/7324" rel="nofollow">lightweight frameworks</a>.</li>
</ol>
<p>I don't think the libraries will be an issue, since (I'm pretty sure that) libraries for popular languages cover all common tasks.</p>
<p>If you can score all the above from 1-10 it may help isolate a preferred direction...</p>
<p>Then, as I see it, the issue breaks down into 3 things:</p>
<ol>
<li>what language do you most like to code in (work should be enjoyable)?</li>
<li>can the front end and back end be generated in a single language?</li>
<li>do you want to use a framework or a ready-made CMS for the front end?</li>
</ol>
<p>It's worth looking at the origins of languages: <a href="http://groups.google.ch/group/comp.infosystems.www.authoring.cgi/msg/cc7d43454d64d133?oe=UTF-8&output=gplain" rel="nofollow">PHP was originally announced</a> as an extension of <a href="http://vr-zone.com/manual/en/howto/ssi.html" rel="nofollow">SSI</a>, Ruby tries to take the best of Perl, Smalltalk and Lisp but has elements of a C/Java-like syntax, Perl is intimately connected to Unix and everywhere, although usually invisible to end users (despite some <a href="http://mark.stosberg.com/blog/2008/12/titanium-a-new-release-and-more.html" rel="nofollow">very good Perl web frameworks</a>). You already know about Python.</p>
<p>As for frameworks and CMSs, a trawl through the distinctions/limitations/features might also help. It is too easy to install a PHP CMS (fine for a site with a well-defined purpose) but then find yourself hampered in acres of impenetrable code when you want do do something it can't do out of the box. A framework in the backend language will enable you to hook the back and front ends together more easily.</p>
| 7 | 2009-09-13T10:53:08Z | [
"python",
"ruby"
] |
To Ruby or not to Ruby | 1,416,570 | <p>I know that this is a difficult question to answer, but I thought I would try anwyays....</p>
<p>I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. </p>
<p>It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. </p>
<p>The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). </p>
<p>I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason.</p>
<p>If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language?</p>
<p>How do the libraries stack up?</p>
<p>Thanks!!!</p>
| 1 | 2009-09-13T00:59:06Z | 25,123,266 | <p>Using Ruby für two years now , i find it powerful, easy to learn, having good libraries, good community.</p>
<p>But how should we know if it fits your needs? Try it an you will find out.</p>
| 0 | 2014-08-04T16:25:39Z | [
"python",
"ruby"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,659 | <p>This seems like a reasonable way to do it. You're wanting to test if the element is a list, and this accomplishes that directly. It gets more complicated if you want to support other 'list-like' data types, too, for example:</p>
<pre><code>isinstance(input, (list, tuple))
</code></pre>
<p>or more generally, abstract away the question:</p>
<pre><code>def iterable(obj):
try:
len(obj)
return True
except TypeError:
return False
</code></pre>
<p>but again, in summary, your method is simple and correct, which sounds good to me!</p>
| -1 | 2009-09-13T02:14:30Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,668 | <p>You can do direct type comparisons using <code>type()</code>.</p>
<pre><code>def my_func(input):
if not type(input) is list:
input = [input]
for e in input:
# do something
</code></pre>
<p>However, the way you have it will allow <em>any</em> type derived from the <code>list</code> type to be passed through. Thus preventing the any derived types from accidentally being wrapped.</p>
| 0 | 2009-09-13T02:17:16Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,672 | <p>Your aproach seems right to me.</p>
<p>It's similar to how you use <code>atom?</code> in Lisp when you iterate over lists and check the current item to see if it is a list or not, because if it is a list you want to process its items, too.</p>
<p>So, yeah, don't see anything wrong with that.</p>
| 0 | 2009-09-13T02:17:43Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,674 | <p>You can put * before your argument, this way you'll always get a tuple:</p>
<pre><code>def a(*p):
print type(p)
print p
a(4)
>>> <type 'tuple'>
>>> (4,)
a(4, 5)
>>> <type 'tuple'>
>>> (4,5,)
</code></pre>
<p>But that will force you to call your function with variable parameters, I don't know if that 's acceptable for you.</p>
| 2 | 2009-09-13T02:19:59Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,677 | <p>Typically, strings (plain and unicode) are the only iterables that you want to nevertheless consider as "single elements" -- the <code>basestring</code> builtin exists SPECIFICALLY to let you test for either kind of strings with <code>isinstance</code>, so it's very UN-grotty for that special case;-).</p>
<p>So my suggested approach for the most general case is:</p>
<pre><code> if isinstance(input, basestring): input = [input]
else:
try: iter(input)
except TypeError: input = [input]
else: input = list(input)
</code></pre>
<p>This is THE way to treat EVERY iterable EXCEPT strings as a list directly, strings and numbers and other non-iterables as scalars (to be normalized into single-item lists).</p>
<p>I'm explicitly making a list out of every kind of iterable so you KNOW you can further on perform EVERY kind of list trick - sorting, iterating more than once, adding or removing items to facilitate iteration, etc, all without altering the ACTUAL input list (if list indeed it was;-). If all you need is a single plain <code>for</code> loop then that last step is unnecessary (and indeed unhelpful if e.g. input is a huge open file) and I'd suggest an auxiliary generator instead:</p>
<pre><code>def justLoopOn(input):
if isinstance(input, basestring):
yield input
else:
try:
for item in input:
yield item
except TypeError:
yield input
</code></pre>
<p>now in every single one of your functions needing such argument normalization, you just use:</p>
<pre><code> for item in justLoopOn(input):
</code></pre>
<p>You can use an auxiliary normalizing-function even in the other case (where you need a real list for further nefarious purposes); actually, in such (rarer) cases, you can just do:</p>
<pre><code> thelistforme = list(justLoopOn(input))
</code></pre>
<p>so that the (inevitably) somewhat-hairy normalization logic is just in ONE place, just as it should be!-)</p>
| 9 | 2009-09-13T02:24:29Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,678 | <p>That is an ok way to do it (don't forget to include tuples).</p>
<p>However, you may also want to consider if the argument has a __iter__ <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fiter%5F%5F" rel="nofollow">method</a> or __getitem__ <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetitem%5F%5F" rel="nofollow">method</a>. (note that strings have __getitem__ instead of __iter__.)</p>
<pre><code>hasattr(arg, '__iter__') or hasattr(arg, '__getitem__')
</code></pre>
<p>This is probably the most general requirement for a list-like type than only checking the type.</p>
| 0 | 2009-09-13T02:24:46Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,684 | <p>I like Andrei Vajna's suggestion of <code>hasattr(var,'__iter__')</code>. Note these results from some typical Python types:</p>
<pre><code>>>> hasattr("abc","__iter__")
False
>>> hasattr((0,),"__iter__")
True
>>> hasattr({},"__iter__")
True
>>> hasattr(set(),"__iter__")
True
</code></pre>
<p>This has the added advantage of treating a string as a non-iterable - strings are a grey area, as sometimes you want to treat them as an element, other times as a sequence of characters.</p>
<p>Note that in Python 3 the <code>str</code> type <em>does</em> have the <code>__iter__</code> attribute and this does not work:</p>
<pre><code>>>> hasattr("abc", "__iter__")
True
</code></pre>
| 6 | 2009-09-13T02:29:35Z | [
"python",
"list",
"arguments"
] |
pythonic way to convert variable to list | 1,416,646 | <p>I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner. </p>
<p>Currently I have this:</p>
<pre><code>def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
</code></pre>
<p>I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a <em>proper</em> way to do this?</p>
| 7 | 2009-09-13T02:01:29Z | 1,416,924 | <p>First, there is no general method that could tell a "single element" from "list of elements" since by definition list can be an element of another list.</p>
<p>I would say you need to define what kinds of data you might have, so that you might have:</p>
<ul>
<li>any descendant of <code>list</code> against anything else
<ul>
<li>Test with <code>isinstance(input, list)</code> (so your example is correct)</li>
</ul></li>
<li>any sequence type except strings (<code>basestring</code> in Python 2.x, <code>str</code> in Python 3.x)
<ul>
<li>Use sequence metaclass: <code>isinstance(myvar, collections.Sequence) and not isinstance(myvar, str)</code></li>
</ul></li>
<li>some sequence type against known cases, like <code>int</code>, <code>str</code>, <code>MyClass</code>
<ul>
<li>Test with <code>isinstance(input, (int, str, MyClass))</code></li>
</ul></li>
<li>any iterable except strings:
<ul>
<li>Test with </li>
</ul></li>
</ul>
<p>.</p>
<pre><code> try:
input = iter(input) if not isinstance(input, str) else [input]
except TypeError:
input = [input]
</code></pre>
| 1 | 2009-09-13T05:25:58Z | [
"python",
"list",
"arguments"
] |
Emacs defadvice on python-mode function | 1,416,882 | <p>In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function:</p>
<pre><code>(defadvice py-execute-region
(after py-execute-region-other-window activate)
""" After execution, return cursor to script buffer """
(other-window 1)
)
</code></pre>
<p>But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks!</p>
| 5 | 2009-09-13T04:52:45Z | 1,417,682 | <p>What you have there works fine for me. And it should auto-activate, so a separate activation should be unnecessary. However, you do need to de-active and re-activate advice for changes to take effect:</p>
<p>1) define and activate advice</p>
<p>2) it doesn't do what you want, so change the advice</p>
<p>3) deactivate it: (ad-deactivate 'py-execute-region)</p>
<p>4) reactivate it: (ad-activate 'py-execute-region)</p>
<p>Step 4 should pick up the changes you made in step 2. Alternately, you can change the code in step 2 and then just re-evaluate the code in step 4 (assuming the activate flag is set).</p>
| 1 | 2009-09-13T12:51:22Z | [
"python",
"emacs",
"elisp",
"advising-functions",
"defadvice"
] |
Emacs defadvice on python-mode function | 1,416,882 | <p>In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function:</p>
<pre><code>(defadvice py-execute-region
(after py-execute-region-other-window activate)
""" After execution, return cursor to script buffer """
(other-window 1)
)
</code></pre>
<p>But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks!</p>
| 5 | 2009-09-13T04:52:45Z | 1,418,640 | <p>Use around-advice to wrap the function in a call to
<code>save-window-excursion</code>, which will restore the previous window
configuration after the command completes.</p>
<pre><code>(defadvice py-execute-region
(around preserve-window-configuration activate)
"After execution, return cursor to script buffer"
(save-window-excursion ad-do-it))
</code></pre>
<p>Keep in mind, though, that if the Python buffer wasn't already shown,
it will still be hidden after the command completes. To remedy that,
you can add another piece of advice to call switch-to-buffer-other-window at the
end:</p>
<pre><code>(defadvice py-execute-region
(after show-pybuf-other-window activate)
"After execution, show the python buffer in another window."
(switch-to-buffer-other-window "[PYTHON BUFFER NAME]"))
</code></pre>
<p>Also, make sure you don't use <code>"""triple quotes"""</code> in elisp. I don't
think they work.</p>
| 2 | 2009-09-13T19:30:32Z | [
"python",
"emacs",
"elisp",
"advising-functions",
"defadvice"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.