title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Django not picking up changes to INSTALLED_APPS in settings.py
901,061
<p>I'm trying to get South to work - it worked fine on my PC, but I'm struggling to deploy it on my webhost.</p> <p>Right now it seems that any changes I make to add/remove items from INSTALLED_APPS aren't being picked up by <code>syncdb</code> or <code>diffsettings</code>. I've added <code>south</code> to my list of INSTALLED_APPS, but the tables it needs aren't being created when I run <code>syncdb</code>. If I change other settings, they are picked up, it just seems to be INSTALLED_APPS that doesn't work.</p> <p>If I run</p> <pre><code>from south.db import db </code></pre> <p>from the shell I get with <code>manage.py shell</code>, I don't get any import errors, so I don't think it's a problem with where <code>south</code> is. I've tried removing all my other applications (other than the Django standard ones), and tables for them still get created when I run <code>syncdb</code>.</p> <p>Even if I delete INSTALLED_APPS completely, I still get the old list of INSTALLED_APPS when I run manage.py diffsettings.</p> <p>Any ideas what I've done wrong?</p> <p>Thanks,</p> <p>Dom</p>
2
2009-05-23T07:15:26Z
902,195
<p>The answer, it turns out, is that I'm a moron. I'd done this:</p> <p>In <code>settings.py</code>:</p> <pre><code>... INSTALLED_APPS = ( ... ) ... from localsettings import * </code></pre> <p>In <code>localsettings.py</code></p> <pre><code>... INSTALLED_APPS = ( ... ) ... </code></pre> <p>I'd created <code>localsettings.py</code> from <code>settings.py</code>, to contain things only relevant to the current location of the project (like database settings), and forgot to delete the <code>INSTALLED_APPS</code> section.</p> <p>Apologies for doing such a flagrantly stupid thing.</p>
2
2009-05-23T18:52:06Z
[ "python", "django" ]
finding substring
901,070
<p><br /> Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example<br /> a='KANNKAAN'</p> <p>OUTPUT;<br /> [KANNKAAN, KANN , KAN ,KAAN]</p>
1
2009-05-23T07:29:12Z
901,098
<pre><code>import re def occurences(ch_searched, str_input): return [i.start() for i in re.finditer(ch_searched, str_input)] def betweeners(str_input, ch_from, ch_to): starts = occurences(ch_from, str_input) ends = occurences(ch_to, str_input) result = [] for start in starts: for end in ends: if start&lt;end: result.append( str_input[start:end+1] ) return result print betweeners('KANNKAAN', "K", "N") </code></pre> <p>Is that what You need?</p>
2
2009-05-23T07:51:05Z
[ "python" ]
finding substring
901,070
<p><br /> Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example<br /> a='KANNKAAN'</p> <p>OUTPUT;<br /> [KANNKAAN, KANN , KAN ,KAAN]</p>
1
2009-05-23T07:29:12Z
901,418
<p>Another way:</p> <pre><code>def findbetween(text, begin, end): for match in re.findall(begin + '.*' +end, text): yield match for m in findbetween(match[1:], begin, end): yield m for m in findbetween(match[:-1], begin, end): yield m &gt;&gt;&gt; list(findbetween('KANNKAAN', 'K', 'N')) ['KANNKAAN', 'KAAN', 'KANN', 'KAN'] </code></pre>
1
2009-05-23T12:06:24Z
[ "python" ]
Replace in Python-* equivalent?
901,074
<p>If I am finding &amp; replacing some text how can I get it to replace some text that will change each day so ie anything between (( &amp; )) whatever it is?</p> <p>Cheers!</p>
0
2009-05-23T07:30:50Z
901,080
<p>Use regular expressions (<a href="http://docs.python.org/library/re.html" rel="nofollow">http://docs.python.org/library/re.html</a>)?</p> <p>Could you please be more specific, I don't think I fully understand what you are trying to accomplish.</p> <p>EDIT:</p> <p>Ok, now I see. This may be done even easier, but here goes:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "foo(bar)whatever" &gt;&gt;&gt; r = re.compile(r"(\()(.+?)(\))") &gt;&gt;&gt; r.sub(r"\1baz\3",s) 'foo(baz)whatever' </code></pre> <p>For multiple levels of parentheses this will not work, or rather it WILL work, but will do something you probably don't want it to do.</p> <p>Oh hey, as a bonus here's the same regular expression, only now it will replace the string in the innermost parentheses:</p> <pre><code>r1 = re.compile(r"(\()([^)^(]+?)(\))") </code></pre>
4
2009-05-23T07:36:49Z
[ "python", "replace" ]
Dynamic function calls in Python using XMLRPC
901,391
<p>I'm writing a class which I intend to use to create subroutines, constructor as following:</p> <pre><code>def __init__(self,menuText,RPC_params,RPC_call): #Treat the params #Call the given RPC_call with the treated params </code></pre> <p>The problem is that I want to call the function on the pattern "<strong>rpc.serve.(function name here)(params)</strong>", where rpc is a serverProxy object that I'm using to call XMLRPC functions, and serve.-function name- is the method I'm calling on the XMLRPC-server.</p> <p>I've looked at <a href="http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python">Calling a function from a string with the function's name in Python</a>, but seeing how my serverProxy object doesnt know which "remote attributes" it have, I cant use the getattr() function to retrieve the method.</p> <p>I've seen a example by making a dictionary to call a given function, but is there no way to make the function truly dynamic by creating the function call as you would create a String? Like running a String as a function?</p>
1
2009-05-23T11:41:19Z
901,400
<p>You <em>can</em> use <code>getattr</code> to get the function name from the server proxy, so calling the function like this will work:</p> <pre><code>getattr(rpc, function_name)(*params) </code></pre>
2
2009-05-23T11:53:56Z
[ "python", "function", "xml-rpc", "rpc" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC O/ABC noez/ABC !/ABC </code></pre> <p>How do I do that please? Yes, with the empty space in between!</p>
3
2009-05-23T12:01:08Z
901,415
<p>If you put them all in a list, for example like this:</p> <pre><code>a = [ [u'This/ABC'], [u'is/ABC'], ... ] </code></pre> <p>You can get your result by adding all the lists and using a regular join on the result:</p> <pre><code>result = ' '.join(sum(a, [])) </code></pre> <p><hr /></p> <p>After re-reading the question a couple of times, I suppose you also want that empty line. This is just more of the same. Add:</p> <pre><code>b = [ [u'O/ABC'], [u'HAI/ABC'], ... ] lines = [a, b] result = '\n\n'.join([' '.join(sum(line, [])) for line in lines]) </code></pre>
6
2009-05-23T12:05:16Z
[ "python", "list", "join" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC O/ABC noez/ABC !/ABC </code></pre> <p>How do I do that please? Yes, with the empty space in between!</p>
3
2009-05-23T12:01:08Z
901,419
<p>If you put all your lists in one list, you can do it like this:</p> <pre><code>' '.join(e[0] for e in [[u'This/ABC'], [u'is/ABC']]) </code></pre>
0
2009-05-23T12:06:26Z
[ "python", "list", "join" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC O/ABC noez/ABC !/ABC </code></pre> <p>How do I do that please? Yes, with the empty space in between!</p>
3
2009-05-23T12:01:08Z
901,422
<p>Easy:</p> <pre><code>x = [[u'O/ABC'], [u'noez/ABC'], [u'!/ABC']] print ' '.join(y[0] for y in x) </code></pre>
1
2009-05-23T12:06:55Z
[ "python", "list", "join" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC O/ABC noez/ABC !/ABC </code></pre> <p>How do I do that please? Yes, with the empty space in between!</p>
3
2009-05-23T12:01:08Z
901,624
<p>To join lists, try the chain function in the module itertools, For example, you can try</p> <pre><code>import itertools print ' '.join(itertools.chain(mylist)) </code></pre> <p>if the new line between the two lists are intentional, then add '\n' at the end of the first list</p> <pre><code>import itertools a = [[u'This/ABZ'], [u'is/ABZ'], ....] b = [[u'O/ABZ'], [u'O/noez'], ...] a.append('\n') print ' '.join(itertools.chain(a + b)) </code></pre>
3
2009-05-23T14:34:35Z
[ "python", "list", "join" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
901,587
<p>In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example</p> <pre><code>&lt;img src="../media/foo.png"&gt; </code></pre> <p>And then you'll just make sure that directory is there with the relevant file(s).</p> <p>during development is a different issue. The django docs explain it succinctly and clearly enough that it's more effective to link there and type it up here, but basically you'll define a view for site media with a hardcoded path to location on disk.</p> <p>Right <a href="http://docs.djangoproject.com/en/dev/howto/static-files/">here</a>.</p>
20
2009-05-23T14:04:01Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
901,701
<p>Your </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>will work for a HTML file read from disk, as it will assume the URL is <code>file:///home/...</code>. For a file served from a webserver though, the URL will become something like: <code>http://www.yourdomain.com/home/tony/london.jpg</code>, which can be an invalid URL and not what you really mean.</p> <p>For about how to serve and where to place your static files, check out this <a href="http://docs.djangoproject.com/en/dev/howto/static-files/" rel="nofollow">document</a>. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your <code>urls.py</code> serve those files (for example, by using some <code>/static/</code> url prefix).</p> <p>Will require you to put something like this in your <code>urls.py</code>:</p> <pre><code>(r'^site_media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}), </code></pre> <p>In production environment you want to skip this and make your http server (<em>apache</em>, <em>lighttpd</em>, etc) serve static files. </p>
3
2009-05-23T15:12:28Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
1,235,542
<p>Try this,</p> <h2>settings.py</h2> <pre><code># typically, os.path.join(os.path.dirname(__file__), 'media') MEDIA_ROOT = '&lt;your_path&gt;/media' MEDIA_URL = '/media/' </code></pre> <h2>urls.py</h2> <pre><code>urlpatterns = patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <h2>.html</h2> <pre><code>&lt;img src="{{ MEDIA_URL }}&lt;sub-dir-under-media-if-any&gt;/&lt;image-name.ext&gt;" /&gt; </code></pre> <h2>Caveat</h2> <p>Beware! using <code>Context()</code> will yield you an empty value for <code>{{MEDIA_URL}}</code>. You must use <code>RequestContext()</code>, instead. </p> <p>I hope, this will help.</p>
53
2009-08-05T20:25:36Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
4,284,974
<p>I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you <em>settings.py</em>:</p> <pre><code>MEDIA_ROOT = "&lt;path_to_files&gt;" (i.e. /home/project/django/app/templates/static) MEDIA_URL = "http://localhost:8000/static/" </code></pre> <p>*(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*</p> <p>Then in you <em>url.py</em> place the following:</p> <pre><code>import settings # stuff (r'^static/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>Then in your html you can use:</p> <pre><code>&lt;img src="{{ MEDIA_URL }}foo.jpg"&gt; </code></pre> <p>The way django works (as far as I can figure is:</p> <ol> <li>In the html file it replaces MEDIA_URL with the MEDIA_URL path found in setting.py</li> <li>It looks in url.py to find any matches for the MEDIA_URL and then if it finds a match (like <em>r'^static/(?P.</em>)$'* relates to <em>http://localhost:8000/static/</em>) it searches for the file in the MEDIA_ROOT and then loads it</li> </ol>
8
2010-11-26T11:42:45Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
11,161,478
<p>Another way to do it:</p> <pre><code>MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/' MEDIA_URL = '/static/media/' </code></pre> <p>This would require you to move your media folder to a sub directory of a static folder.</p> <p>Then in your template you can use:</p> <pre><code>&lt;img class="scale-with-grid" src="{{object.photo.url}}"/&gt; </code></pre>
1
2012-06-22T17:44:40Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
12,356,998
<p>I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.<br> May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?</p> <p>In that case I see no contra to store such a content in STATIC.<br> And all becomes really simple:</p> <blockquote> <h3>static</h3> <p>To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you're using RequestContext or not.</p> <p><code>{% load static %} &lt;img src="{% static "images/hi.jpg" %}" alt="Hi!" /&gt;</code></p> </blockquote> <p>copied from <a href="https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#static">Official django 1.4 documentation / Built-in template tags and filters</a></p>
5
2012-09-10T17:54:12Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
17,036,758
<p>I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:</p> <p>projec/your_app/templates project/your_app/static</p> <h2>settings.py</h2> <pre><code>import os PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____)) STATIC_ROOT = '/your_path/static/' </code></pre> <p>example:</p> <pre><code>STATIC_ROOT = '/home/project_name/your_app/static/' STATIC_URL = '/static/' STATICFILES_DIRS =( PROJECT_DIR+'/static', ##//don.t forget comma ) TEMPLATE_DIRS = ( PROJECT_DIR+'/templates/', ) </code></pre> <h2>proj/app/templates/filename.html</h2> <p>inside body</p> <pre><code>{% load staticfiles %} //for image img src="{% static "fb.png" %}" alt="image here" //note that fb.png is at /home/project/app/static/fb.png </code></pre> <p>If fb.png was inside /home/project/app/static/image/fb.png then </p> <pre><code>img src="{% static "images/fb.png" %}" alt="image here" </code></pre>
0
2013-06-11T04:59:48Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
25,724,854
<p>If your file is a model field within a model, you can also use ".url" in your template tag to get the image.</p> <p>For example.</p> <p>If this is your model:</p> <pre><code>class Foo(models.Model): foo = models.TextField() bar = models.FileField(upload_to="foo-pictures", blank = True) </code></pre> <p>Pass the model in context in your views.</p> <pre><code>return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)}) </code></pre> <p>In your template you could have:</p> <pre><code>&lt;img src = "{{foo.bar.url}}"&gt; </code></pre>
2
2014-09-08T12:58:19Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.</p> <p>...</p> <p>Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template: </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?</p>
39
2009-05-23T13:45:07Z
30,411,331
<p>/media directory under project root</p> <h2>Settings.py</h2> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') </code></pre> <h2>urls.py</h2> <pre><code> urlpatterns += patterns('django.views.static',(r'^media/(?P&lt;path&gt;.*)','serve',{'document_root':settings.MEDIA_ROOT}), ) </code></pre> <h2>template</h2> <pre><code>&lt;img src="{{MEDIA_URL}}/image.png" &gt; </code></pre>
2
2015-05-23T09:58:05Z
[ "python", "django", "django-templates" ]
Wxwidget Grid
901,704
<p>I posted this in the mailing list, but the reply I got wasn't too clear, so maybe I'll have better luck here.</p> <p>I currently have a grid with data in it. I would like to know if there is a way to give each generated row an ID, or at least, associate each row with an object.</p> <p>It may make it more clear if I clarify what i'm doing. It is described below.</p> <p>I pull data from an SQL table and display them in the grid. I am allowing for the user to add/delete rows and edit cells.</p> <p>Say the user is viewing a grid that has 3 rows(which is, in turn, a mysql table with 3 rows). If he is on the last row and presses the down arrow key, a new row is created and he can enter data into it and it will be inserted in the database when he presses enter.</p> <p>However, I need a way to find out which rows will use "insert" query and which will use "update" query.</p> <p>So ideally, when the user creates a new row by pressing the down arrow, I would give that row an ID and store it in a list(or, if rows already have IDs, just store it in a list) and when the user finishes entering data in the cells and presses enter, I would check if that row's ID is in the in the list. If it is, i would insert all of that row's cells values into the table, if not, i would update mysql with the values.</p> <p>Hope I made this clear. </p>
2
2009-05-23T15:13:30Z
901,806
<p>What I did when I encountered such a case was to create a column for IDs and set its width to 0.</p>
3
2009-05-23T16:02:23Z
[ "python", "wxpython", "wxwidgets" ]
Wxwidget Grid
901,704
<p>I posted this in the mailing list, but the reply I got wasn't too clear, so maybe I'll have better luck here.</p> <p>I currently have a grid with data in it. I would like to know if there is a way to give each generated row an ID, or at least, associate each row with an object.</p> <p>It may make it more clear if I clarify what i'm doing. It is described below.</p> <p>I pull data from an SQL table and display them in the grid. I am allowing for the user to add/delete rows and edit cells.</p> <p>Say the user is viewing a grid that has 3 rows(which is, in turn, a mysql table with 3 rows). If he is on the last row and presses the down arrow key, a new row is created and he can enter data into it and it will be inserted in the database when he presses enter.</p> <p>However, I need a way to find out which rows will use "insert" query and which will use "update" query.</p> <p>So ideally, when the user creates a new row by pressing the down arrow, I would give that row an ID and store it in a list(or, if rows already have IDs, just store it in a list) and when the user finishes entering data in the cells and presses enter, I would check if that row's ID is in the in the list. If it is, i would insert all of that row's cells values into the table, if not, i would update mysql with the values.</p> <p>Hope I made this clear. </p>
2
2009-05-23T15:13:30Z
902,083
<p>You could make your own GridTableBase that implements this, for a simple example to get you started see my answer to <a href="http://stackoverflow.com/questions/328003/wxpython-updating-a-dict-or-other-appropriate-data-type-from-wx-lib-sheet-csheet/328078#328078">this</a> question.</p>
2
2009-05-23T18:05:19Z
[ "python", "wxpython", "wxwidgets" ]
Executing *nix binaries in Python
901,829
<p>I need to run the following command:</p> <pre><code>screen -dmS RealmD top </code></pre> <p><em>Essentially invoking GNU screen in the background with the session title 'RealmD' with the top command being run inside screen. The command MUST be invoked this way so there can't be a substitute for screen at this time until the server is re-tooled. (Another project for another time)</em></p> <p><em>I've subbed in the top command for the server binary that needs to run. But top is a decent substitute while the code is being debugged for this python module.</em></p> <p><strong>What I really need is a way to execute screen with the above parameters in Python.</strong></p>
1
2009-05-23T16:12:09Z
901,836
<p>Use <a href="http://docs.python.org/3.0/library/os.html#os.system" rel="nofollow">os.system</a>:</p> <pre><code>os.system("screen -dmS RealmD top") </code></pre> <p>Then in a separate shell you can have a look at <code>top</code> by running <code>screen -rd RealmD</code>.</p>
6
2009-05-23T16:16:13Z
[ "python", "screen" ]
Executing *nix binaries in Python
901,829
<p>I need to run the following command:</p> <pre><code>screen -dmS RealmD top </code></pre> <p><em>Essentially invoking GNU screen in the background with the session title 'RealmD' with the top command being run inside screen. The command MUST be invoked this way so there can't be a substitute for screen at this time until the server is re-tooled. (Another project for another time)</em></p> <p><em>I've subbed in the top command for the server binary that needs to run. But top is a decent substitute while the code is being debugged for this python module.</em></p> <p><strong>What I really need is a way to execute screen with the above parameters in Python.</strong></p>
1
2009-05-23T16:12:09Z
901,842
<p><code>os.system</code> is the simplest way, but, for many more possibilities and degrees of freedom, also look at the standard library <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> module (unless Stephan202's wonderfully simple use of <code>os.system</code> meets all your needs, of course;-).</p> <p><strong>Edit</strong> Here's the standard replacement for <code>os.system()</code></p> <pre><code>p = Popen("screen -dmS RealmD top", shell=True) sts = p.wait() </code></pre> <p><a href="http://docs.python.org/library/subprocess.html#replacing-os-system" rel="nofollow">http://docs.python.org/library/subprocess.html#replacing-os-system</a></p>
11
2009-05-23T16:20:59Z
[ "python", "screen" ]
python factory functions compared to class
901,892
<p>Just working through learning python and started to look at nested/factory functions (simple example):</p> <pre><code>def maker(N): def action(X): return X * N return action </code></pre> <p>Are there any advantages of factory functions over creating a class? performance? memory? clean up?</p>
13
2009-05-23T16:43:25Z
901,902
<p>Nesting functions allows one to create custom functions on the fly.</p> <p>Have a look at e.g. <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorators</a>. The resulting functions depend on variables that are bound at creation time and do not need to be changed afterwards. So using a class for this purpose would make <em>less</em> sense.</p>
2
2009-05-23T16:49:17Z
[ "python", "function" ]
python factory functions compared to class
901,892
<p>Just working through learning python and started to look at nested/factory functions (simple example):</p> <pre><code>def maker(N): def action(X): return X * N return action </code></pre> <p>Are there any advantages of factory functions over creating a class? performance? memory? clean up?</p>
13
2009-05-23T16:43:25Z
902,010
<p>What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is:</p> <pre><code>class clsmaker(object): def __init__(self, N): self.N = N def __call__(self, X): return X * self.N </code></pre> <p>That doesn't seem so bad until you start adding more arguments to the constructor. Then doing it the class way takes an extra line for each argument, while the function just gets the extra args.</p> <p>It turns out that there is a speed advantage to the nested functions as well:</p> <pre><code>&gt;&gt;&gt; T1 = timeit.Timer('maker(3)(4)', 'from __main__ import maker') &gt;&gt;&gt; T1.timeit() 1.2818338871002197 &gt;&gt;&gt; T2 = timeit.Timer('clsmaker(3)(4)', 'from __main__ import clsmaker') &gt;&gt;&gt; T2.timeit() 2.2137160301208496 </code></pre> <p>This may be due to there being fewer opcodes involved in the nested functions version:</p> <pre><code>&gt;&gt;&gt; dis(clsmaker.__call__) 5 0 LOAD_FAST 1 (X) 3 LOAD_FAST 0 (self) 6 LOAD_ATTR 0 (N) 9 BINARY_MULTIPLY 10 RETURN_VALUE &gt;&gt;&gt; act = maker(3) &gt;&gt;&gt; dis(act) 3 0 LOAD_FAST 0 (X) 3 LOAD_DEREF 0 (N) 6 BINARY_MULTIPLY 7 RETURN_VALUE </code></pre>
23
2009-05-23T17:38:58Z
[ "python", "function" ]
python factory functions compared to class
901,892
<p>Just working through learning python and started to look at nested/factory functions (simple example):</p> <pre><code>def maker(N): def action(X): return X * N return action </code></pre> <p>Are there any advantages of factory functions over creating a class? performance? memory? clean up?</p>
13
2009-05-23T16:43:25Z
902,809
<p>Comparing a function factory to a class is comparing apples and oranges. Use a class if you have a cohesive collection of data and functions, together called an object. Use a function factory if you need a function, and want to parameterize its creation.</p> <p>Your choice of the two techniques should depend on the meaning of the code.</p>
9
2009-05-24T00:55:57Z
[ "python", "function" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: continue # still running else: # restart this one programs[i]= subprocess.Popen(commands[i]) time.sleep(1.0) </code></pre> <p>Upon executing the code the following exception is thrown:</p> <pre><code>Traceback (most recent call last): File "./marp.py", line 82, in &lt;module&gt; programs = [ subprocess.Popen(c) for c in commands ] File "/usr/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre> <p>I think I'm missing something obvious, can anyone see what's wrong with the code above?</p>
31
2009-05-23T17:24:03Z
901,990
<p>Only guess is that it can't find <code>screen</code>. Try <code>/usr/bin/screen</code> or whatever <code>which screen</code> gives you.</p>
6
2009-05-23T17:29:51Z
[ "python", "subprocess" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: continue # still running else: # restart this one programs[i]= subprocess.Popen(commands[i]) time.sleep(1.0) </code></pre> <p>Upon executing the code the following exception is thrown:</p> <pre><code>Traceback (most recent call last): File "./marp.py", line 82, in &lt;module&gt; programs = [ subprocess.Popen(c) for c in commands ] File "/usr/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre> <p>I think I'm missing something obvious, can anyone see what's wrong with the code above?</p>
31
2009-05-23T17:24:03Z
901,992
<p>Use <code>["screen", "-dmS", "RealmD", "top"]</code> instead of <code>["screen -dmS RealmD top"]</code>.</p> <p>Maybe also use the complete path to <code>screen</code>.</p> <p>If the program still cannot be found you can also go through your shell with <code>shell=True</code>, but then you need to quote and escape your parameters etc. Make sure to read the <a href="http://docs.python.org/2/library/subprocess.html#subprocess.Popen">information in the docs</a> if you plan to do that.</p>
53
2009-05-23T17:31:21Z
[ "python", "subprocess" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: continue # still running else: # restart this one programs[i]= subprocess.Popen(commands[i]) time.sleep(1.0) </code></pre> <p>Upon executing the code the following exception is thrown:</p> <pre><code>Traceback (most recent call last): File "./marp.py", line 82, in &lt;module&gt; programs = [ subprocess.Popen(c) for c in commands ] File "/usr/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre> <p>I think I'm missing something obvious, can anyone see what's wrong with the code above?</p>
31
2009-05-23T17:24:03Z
15,282,684
<p>The problem is that your command should be split. subprocces requires that the cmd is a list, not a string. It shouldn't be:</p> <pre><code>subprocess.call('''awk 'BEGIN {FS="\t";OFS="\n"} {a[$1]=a [$1] OFS $2 FS $3 FS $4} END {for (i in a) {print i a[i]}}' 2_lcsorted.txt &gt; 2_locus_2.txt''') </code></pre> <p>That won't work. If you feed subprocess a string, it assumes that that is the path to the command you want to execute. The command needs to be a list. Check out <a href="http://www.gossamer-threads.com/lists/python/python/724330" rel="nofollow">http://www.gossamer-threads.com/lists/python/python/724330</a>. Also, because you're using file redirection, you should use <code>subprocess.call(cmd, shell=True)</code>. You can also use <code>shlex</code>.</p>
6
2013-03-07T22:05:54Z
[ "python", "subprocess" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: continue # still running else: # restart this one programs[i]= subprocess.Popen(commands[i]) time.sleep(1.0) </code></pre> <p>Upon executing the code the following exception is thrown:</p> <pre><code>Traceback (most recent call last): File "./marp.py", line 82, in &lt;module&gt; programs = [ subprocess.Popen(c) for c in commands ] File "/usr/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre> <p>I think I'm missing something obvious, can anyone see what's wrong with the code above?</p>
31
2009-05-23T17:24:03Z
17,066,679
<pre><code>commands = [ "screen -dmS RealmD top", "screen -DmS RealmD top -d 5" ] programs = [ subprocess.Popen(c.split()) for c in commands ] </code></pre>
2
2013-06-12T13:21:50Z
[ "python", "subprocess" ]
Why can I not view my Google App Engine cron admin page?
902,039
<p>When I go to <a href="http://localhost:8080/%5Fah/admin/cron" rel="nofollow">http://localhost:8080/_ah/admin/cron</a>, as stated in Google's docs, I get the following:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 501, in __call__ handler.get(*groups) File "C:\Program Files\Google\google_appengine\google\appengine\ext\admin\__init__.py", line 239, in get schedule = groctimespecification.GrocTimeSpecification(entry.schedule) File "C:\Program Files\Google\google_appengine\google\appengine\cron\groctimespecification.py", line 71, in GrocTimeSpecification parser.period_string) File "C:\Program Files\Google\google_appengine\google\appengine\cron\groctimespecification.py", line 122, in __init__ super(IntervalTimeSpecification, self).__init__(self) TypeError: object.__init__() takes no parameters </code></pre> <p>I have the latest SDK, and it looks like my config files are correct.</p>
1
2009-05-23T17:50:14Z
902,200
<p>Congratulations! You've found a bug. Can you file a bug on the <a href="http://code.google.com/p/googleappengine/issues/list" rel="nofollow">public issue tracker</a>, please? If you want to fix it for yourself immediately, delete the 'self' argument in the line referenced at the end of that stacktrace.</p>
3
2009-05-23T18:54:58Z
[ "python", "google-app-engine", "cron", "stack-trace" ]
Why can I not view my Google App Engine cron admin page?
902,039
<p>When I go to <a href="http://localhost:8080/%5Fah/admin/cron" rel="nofollow">http://localhost:8080/_ah/admin/cron</a>, as stated in Google's docs, I get the following:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 501, in __call__ handler.get(*groups) File "C:\Program Files\Google\google_appengine\google\appengine\ext\admin\__init__.py", line 239, in get schedule = groctimespecification.GrocTimeSpecification(entry.schedule) File "C:\Program Files\Google\google_appengine\google\appengine\cron\groctimespecification.py", line 71, in GrocTimeSpecification parser.period_string) File "C:\Program Files\Google\google_appengine\google\appengine\cron\groctimespecification.py", line 122, in __init__ super(IntervalTimeSpecification, self).__init__(self) TypeError: object.__init__() takes no parameters </code></pre> <p>I have the latest SDK, and it looks like my config files are correct.</p>
1
2009-05-23T17:50:14Z
903,334
<p>This is definitely a bug in Google App Engine. If you check <a href="http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/cron/groctimespecification.py?r=54#112" rel="nofollow">groctimespecification.py</a>, you'll see that <code>IntervalTimeSpecification</code> inherits from <code>TimeSpecification</code>, which in turn inherits directly from <code>object</code> and doesn't override its <code>__init__</code> method.</p> <p>So the <code>__init__</code> of <code>IntervalTimeSpecification</code> is incorrect:</p> <pre><code>class IntervalTimeSpecification(TimeSpecification): def __init__(self, interval, period): super(IntervalTimeSpecification, self).__init__(self) </code></pre> <p>My guess is, someone converted an old-style parent class init call:</p> <pre><code>TimeSpecification.__init__(self) </code></pre> <p>to the current one, but forgot that with <code>super</code>, <code>self</code> is passed implicitly. The correct line should look like this:</p> <pre><code>super(IntervalTimeSpecification, self).__init__() </code></pre>
4
2009-05-24T08:30:19Z
[ "python", "google-app-engine", "cron", "stack-trace" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.</p>
5
2009-05-23T18:07:22Z
902,142
<p>I haven't tried it myself, but there is a <a href="http://pypi.python.org/pypi/PSI" rel="nofollow">Python System Information</a> module that can be used to find processes and get information about them. AFAIR there is a <code>ProcessTable</code> class that can be used to inspect the running processes, but it doesn't seem to be very well documented...</p>
0
2009-05-23T18:31:42Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.</p>
5
2009-05-23T18:07:22Z
902,166
<p>I'd go the command-line route (it's just easier imho) as long as you only check every second or two the resource usage should be infintesimal compared to the available processing on any system less than 10 years old.</p>
0
2009-05-23T18:42:11Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.</p>
5
2009-05-23T18:07:22Z
902,189
<p>Why implement it yourself? An existing utility like <a href="http://libslack.org/daemon/" rel="nofollow">daemon</a> or Debian's <code>start-stop-daemon</code> is more likely to get the other difficult stuff right about running long-living server processes.</p> <p>Anyway, when you start the service, put its pid in <code>/var/run/&lt;name&gt;.pid</code> and then make your <code>ps</code> command just look for that process ID, and check that it is the right process. On Linux you can simply look at <code>/proc/&lt;pid&gt;/exe</code> to check that it points to the right executable.</p>
4
2009-05-23T18:50:19Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.</p>
5
2009-05-23T18:07:22Z
902,258
<p>Please don't reinvent init. Your OS has capabilities to do this that require nearly no system resources and will definitely do it better and more reliably than anything you can reproduce.</p> <p>Classic Linux has /etc/inittab</p> <p>Ubuntu has /etc/event.d (upstart)</p> <p>OS X has launchd</p> <p>Solaris has smf</p>
3
2009-05-23T19:22:54Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.</p>
5
2009-05-23T18:07:22Z
902,477
<p>The following code checks a given process in a given interval, and restarts it.</p> <pre><code>#Restarts a given process if it is finished. #Compatible with Python 2.5, tested on Windows XP. import threading import time import subprocess class ProcessChecker(threading.Thread): def __init__(self, process_path, check_interval): threading.Thread.__init__(self) self.process_path = process_path self.check_interval = check_interval def run (self): while(1): time.sleep(self.check_interval) if self.is_ok(): self.make_sure_process_is_running() def is_ok(self): ok = True #do the database locks, client data corruption check here, #and return true/false return ok def make_sure_process_is_running(self): #This call is blocking, it will wait for the #other sub process to be finished. retval = subprocess.call(self.process_path) def main(): process_path = "notepad.exe" check_interval = 1 #In seconds pm = ProcessChecker(process_path, check_interval) pm.start() print "Checker started..." if __name__ == "__main__": main() </code></pre>
1
2009-05-23T20:55:14Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.</p>
5
2009-05-23T18:07:22Z
7,682,140
<p>maybe you need <a href="http://supervisord.org" rel="nofollow">http://supervisord.org</a></p>
1
2011-10-07T01:08:17Z
[ "python", "linux", "restart", "pid" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <code>[[ThisIsAWikiLink | This is the alt text]]</code></p> <p>Here's a working example that does not query the database:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): return re.sub(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', r'&lt;a href="/Sites/wiki/\1"&gt;\2&lt;/a&gt;', value) wikilink.is_safe = True </code></pre> <p>The <strong>input</strong> (<code>value</code>) is a multi-line string, containing HTML and many WikiLinks.</p> <p>The expected <strong>output</strong> is substituting <code>[[ThisIsAWikiLink | This is the alt text]]</code> with </p> <ul> <li><p><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is the alt text&lt;/a&gt;</code> </p> <p><strong>or</strong> if "ThisIsAWikiLink" doesn't exist in the database: </p></li> <li><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink/edit" class="redlink"&gt;This is the alt text&lt;/a&gt;</code></li> </ul> <p>and returning value.</p> <p>Here's the non-working code (edited in response to comments/answers):</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): m = re.match(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) if(m): page_alias = m.group(2) page_title = m.group(3) try: page = Page.objects.get(alias=page_alias) return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2"&gt;\3&lt;/a&gt;', value) except Page.DoesNotExist: return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2\/edit" class="redlink"&gt;\3&lt;/a&gt;', value) else: return value wikilink.is_safe = True </code></pre> <p>What the code needs to do is:</p> <ul> <li>extract all the WikiLinks in <em>value</em></li> <li>query the <em>Page</em> model to see if the page exists</li> <li>substitute all the WikiLinks with normal links, styled dependent on each wikipage existence.</li> <li>return the altered <em>value</em></li> </ul> <p>The updated question is: What regular expression (method) can return a python List of WikiLinks, which can be altered and used to substitute the original matches (after being altered).</p> <p>Edit:</p> <p>I'd like to do something like this:</p> <pre><code>def wikilink(value): regex = re.magic_method(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) foreach wikilink in regex: alias = wikilink.group(0) text = wikilink.group(1) if(alias exists in Page): regex.sub("&lt;a href="+alias+"&gt;"+ text +"&lt;/a&gt;") else: regex.sub("&lt;a href="+alias+" class='redlink'&gt;"+ text +"&lt;/a&gt;") return value </code></pre>
2
2009-05-23T18:48:57Z
902,263
<p>This is the type of problem that falls quickly to a small set of unit tests.</p> <p>Pieces of the filter that can be tested in isolation (with a bit of code restructuring):</p> <ul> <li>Determining whether or not value contains the pattern you're looking for</li> <li>What string gets generated if there is a matching Page</li> <li>What string gets generated is there isn't a matching Page</li> </ul> <p>That would help you isolate where things are going wrong. You'll probably find that you'll need to rewire the regexps to account for optional spaces around the |.</p> <p>Also, on first glance it looks like your filter is exploitable. You're claiming the result is safe, but you haven't filtered the alt text for nasties like script tags.</p>
3
2009-05-23T19:24:19Z
[ "python", "regex", "django", "django-templates" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <code>[[ThisIsAWikiLink | This is the alt text]]</code></p> <p>Here's a working example that does not query the database:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): return re.sub(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', r'&lt;a href="/Sites/wiki/\1"&gt;\2&lt;/a&gt;', value) wikilink.is_safe = True </code></pre> <p>The <strong>input</strong> (<code>value</code>) is a multi-line string, containing HTML and many WikiLinks.</p> <p>The expected <strong>output</strong> is substituting <code>[[ThisIsAWikiLink | This is the alt text]]</code> with </p> <ul> <li><p><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is the alt text&lt;/a&gt;</code> </p> <p><strong>or</strong> if "ThisIsAWikiLink" doesn't exist in the database: </p></li> <li><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink/edit" class="redlink"&gt;This is the alt text&lt;/a&gt;</code></li> </ul> <p>and returning value.</p> <p>Here's the non-working code (edited in response to comments/answers):</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): m = re.match(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) if(m): page_alias = m.group(2) page_title = m.group(3) try: page = Page.objects.get(alias=page_alias) return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2"&gt;\3&lt;/a&gt;', value) except Page.DoesNotExist: return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2\/edit" class="redlink"&gt;\3&lt;/a&gt;', value) else: return value wikilink.is_safe = True </code></pre> <p>What the code needs to do is:</p> <ul> <li>extract all the WikiLinks in <em>value</em></li> <li>query the <em>Page</em> model to see if the page exists</li> <li>substitute all the WikiLinks with normal links, styled dependent on each wikipage existence.</li> <li>return the altered <em>value</em></li> </ul> <p>The updated question is: What regular expression (method) can return a python List of WikiLinks, which can be altered and used to substitute the original matches (after being altered).</p> <p>Edit:</p> <p>I'd like to do something like this:</p> <pre><code>def wikilink(value): regex = re.magic_method(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) foreach wikilink in regex: alias = wikilink.group(0) text = wikilink.group(1) if(alias exists in Page): regex.sub("&lt;a href="+alias+"&gt;"+ text +"&lt;/a&gt;") else: regex.sub("&lt;a href="+alias+" class='redlink'&gt;"+ text +"&lt;/a&gt;") return value </code></pre>
2
2009-05-23T18:48:57Z
902,273
<p>If your string contains other text in addition to the wiki-link, your filter won't work because you are using <code>re.match</code> instead of <code>re.search</code>. <code>re.match</code> matches at the beginning of the string. <code>re.search</code> matches anywhere in the string. See <a href="http://docs.python.org/library/re.html#matching-vs-searching" rel="nofollow">matching vs. searching</a>.</p> <p>Also, your regex uses the greedy <code>*</code>, so it won't work if one line contains multiple wiki-links. Use <code>*?</code> instead to make it non-greedy:</p> <pre><code>re.search(r'\[\[(.*?)\|(.*?)\]\]', value) </code></pre> <p>Edit:</p> <p>As for tips on how to fix your code, I suggest that you use <a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow"><code>re.sub</code> with a callback</a>. The advantages are:</p> <ul> <li>It works correctly if you have multiple wiki-links in the same line.</li> <li>One pass over the string is enough. You don't need a pass to find wiki-links, and another one to do the replacement.</li> </ul> <p>Here is a sketch of the implmentation:</p> <pre><code>import re WIKILINK_RE = re.compile(r'\[\[(.*?)\|(.*?)\]\]') def wikilink(value): def wikilink_sub_callback(match_obj): alias = match_obj.group(1).strip() text = match_obj.group(2).strip() if(alias exists in Page): class_attr = '' else: class_attr = ' class="redlink"' return '&lt;a href="%s"%s&gt;%s&lt;/a&gt;' % (alias, class_attr, text) return WIKILINK_RE.sub(wikilink_sub_callback, value) </code></pre>
4
2009-05-23T19:28:33Z
[ "python", "regex", "django", "django-templates" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <code>[[ThisIsAWikiLink | This is the alt text]]</code></p> <p>Here's a working example that does not query the database:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): return re.sub(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', r'&lt;a href="/Sites/wiki/\1"&gt;\2&lt;/a&gt;', value) wikilink.is_safe = True </code></pre> <p>The <strong>input</strong> (<code>value</code>) is a multi-line string, containing HTML and many WikiLinks.</p> <p>The expected <strong>output</strong> is substituting <code>[[ThisIsAWikiLink | This is the alt text]]</code> with </p> <ul> <li><p><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is the alt text&lt;/a&gt;</code> </p> <p><strong>or</strong> if "ThisIsAWikiLink" doesn't exist in the database: </p></li> <li><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink/edit" class="redlink"&gt;This is the alt text&lt;/a&gt;</code></li> </ul> <p>and returning value.</p> <p>Here's the non-working code (edited in response to comments/answers):</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): m = re.match(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) if(m): page_alias = m.group(2) page_title = m.group(3) try: page = Page.objects.get(alias=page_alias) return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2"&gt;\3&lt;/a&gt;', value) except Page.DoesNotExist: return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2\/edit" class="redlink"&gt;\3&lt;/a&gt;', value) else: return value wikilink.is_safe = True </code></pre> <p>What the code needs to do is:</p> <ul> <li>extract all the WikiLinks in <em>value</em></li> <li>query the <em>Page</em> model to see if the page exists</li> <li>substitute all the WikiLinks with normal links, styled dependent on each wikipage existence.</li> <li>return the altered <em>value</em></li> </ul> <p>The updated question is: What regular expression (method) can return a python List of WikiLinks, which can be altered and used to substitute the original matches (after being altered).</p> <p>Edit:</p> <p>I'd like to do something like this:</p> <pre><code>def wikilink(value): regex = re.magic_method(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) foreach wikilink in regex: alias = wikilink.group(0) text = wikilink.group(1) if(alias exists in Page): regex.sub("&lt;a href="+alias+"&gt;"+ text +"&lt;/a&gt;") else: regex.sub("&lt;a href="+alias+" class='redlink'&gt;"+ text +"&lt;/a&gt;") return value </code></pre>
2
2009-05-23T18:48:57Z
902,579
<p>Code:</p> <pre><code>import re def page_exists(alias): if alias == 'ThisIsAWikiLink': return True return False def wikilink(value): if value == None: return None for alias, text in re.findall('\[\[\s*(.*?)\s*\|\s*(.*?)\s*\]\]',value): if page_exists(alias): value = re.sub('\[\[\s*%s\s*\|\s*%s\s*\]\]' % (alias,text), '&lt;a href="/Sites/wiki/%s"&gt;%s&lt;/a&gt;' % (alias, text),value) else: value = re.sub('\[\[\s*%s\s*\|\s*%s\s*\]\]' % (alias,text), '&lt;a href="/Sites/wiki/%s/edit/" class="redtext"&gt;%s&lt;/a&gt;' % (alias, text), value) return value </code></pre> <p>Sample results:</p> <pre><code>&gt;&gt;&gt; import wikilink &gt;&gt;&gt; wikilink.wikilink(None) &gt;&gt;&gt; wikilink.wikilink('') '' &gt;&gt;&gt; wikilink.wikilink('Test') 'Test' &gt;&gt;&gt; wikilink.wikilink('[[ThisIsAWikiLink | This is the alt text]]') '&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is the alt text&lt;/a&gt;' &gt;&gt;&gt; wikilink.wikilink('[[ThisIsABadWikiLink | This is the alt text]]') '&lt;a href="/Sites/wiki/ThisIsABadWikiLink/edit/" class="redtext"&gt;This is the alt text&lt;/a&gt;' &gt;&gt;&gt; wikilink.wikilink('[[ThisIsAWikiLink | This is the alt text]]\n[[ThisIsAWikiLink | This is another instance]]') '&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is the alt text&lt;/a&gt;\n&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is another instance&lt;/a&gt;' &gt;&gt;&gt; wikilink.wikilink('[[ThisIsAWikiLink | This is the alt text]]\n[[ThisIsAWikiLink | This is another instance]]') </code></pre> <p>General comments:</p> <ul> <li><em>findall</em> is the magic re function you're looking for</li> <li>Change *page_exists* to run whatever query you want</li> <li>Vulnerable to HTML injection (as mentioned by Dave W. Smith above)</li> <li>Having to recompile the regex on each iteration is inefficient</li> <li>Querying the database each time is inefficient</li> </ul> <p>I think you'd run into performance issues pretty quickly with this approach.</p>
1
2009-05-23T21:57:04Z
[ "python", "regex", "django", "django-templates" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <code>[[ThisIsAWikiLink | This is the alt text]]</code></p> <p>Here's a working example that does not query the database:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): return re.sub(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', r'&lt;a href="/Sites/wiki/\1"&gt;\2&lt;/a&gt;', value) wikilink.is_safe = True </code></pre> <p>The <strong>input</strong> (<code>value</code>) is a multi-line string, containing HTML and many WikiLinks.</p> <p>The expected <strong>output</strong> is substituting <code>[[ThisIsAWikiLink | This is the alt text]]</code> with </p> <ul> <li><p><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink"&gt;This is the alt text&lt;/a&gt;</code> </p> <p><strong>or</strong> if "ThisIsAWikiLink" doesn't exist in the database: </p></li> <li><code>&lt;a href="/Sites/wiki/ThisIsAWikiLink/edit" class="redlink"&gt;This is the alt text&lt;/a&gt;</code></li> </ul> <p>and returning value.</p> <p>Here's the non-working code (edited in response to comments/answers):</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): m = re.match(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) if(m): page_alias = m.group(2) page_title = m.group(3) try: page = Page.objects.get(alias=page_alias) return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2"&gt;\3&lt;/a&gt;', value) except Page.DoesNotExist: return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'&lt;a href="Sites\/wiki\/\2\/edit" class="redlink"&gt;\3&lt;/a&gt;', value) else: return value wikilink.is_safe = True </code></pre> <p>What the code needs to do is:</p> <ul> <li>extract all the WikiLinks in <em>value</em></li> <li>query the <em>Page</em> model to see if the page exists</li> <li>substitute all the WikiLinks with normal links, styled dependent on each wikipage existence.</li> <li>return the altered <em>value</em></li> </ul> <p>The updated question is: What regular expression (method) can return a python List of WikiLinks, which can be altered and used to substitute the original matches (after being altered).</p> <p>Edit:</p> <p>I'd like to do something like this:</p> <pre><code>def wikilink(value): regex = re.magic_method(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) foreach wikilink in regex: alias = wikilink.group(0) text = wikilink.group(1) if(alias exists in Page): regex.sub("&lt;a href="+alias+"&gt;"+ text +"&lt;/a&gt;") else: regex.sub("&lt;a href="+alias+" class='redlink'&gt;"+ text +"&lt;/a&gt;") return value </code></pre>
2
2009-05-23T18:48:57Z
902,871
<p>This is the working code in case someone needs it:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): WIKILINK_RE = re.compile(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]') def wikilink_sub_callback(match_obj): alias = match_obj.group(1).strip() text = match_obj.group(2).strip() class_attr = '' try: Page.objects.get(alias=alias) except Page.DoesNotExist: class_attr = ' class="redlink"' return '&lt;a href="%s"%s&gt;%s&lt;/a&gt;' % (alias, class_attr, text) return WIKILINK_RE.sub(wikilink_sub_callback, value) wikilink.is_safe = True </code></pre> <p>Many thanks for all the answers!</p>
0
2009-05-24T01:38:17Z
[ "python", "regex", "django", "django-templates" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names without python including them as part of the query text?</p>
30
2009-05-23T20:20:33Z
902,417
<pre><code>cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) </code></pre> <p>Note that the parameters are passed as a tuple.</p> <p>The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (<code>%</code>), because</p> <ol> <li>it does not do any escaping or quoting.</li> <li>it is prone to Uncontrolled string format attacks e.g. <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injection</a>.</li> </ol>
33
2009-05-23T20:25:24Z
[ "python", "sql" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names without python including them as part of the query text?</p>
30
2009-05-23T20:20:33Z
902,426
<p><a href="http://www.amk.ca/python/writing/DB-API.html">http://www.amk.ca/python/writing/DB-API.html</a></p> <p>Be careful when you simply append values of variables to your statements: Imagine a user naming himself <code>';DROP TABLE Users;'</code> -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:</p> <pre><code>cursor.execute("insert into Attendees values (?, ?, ?)", (name, seminar, paid) ) </code></pre>
12
2009-05-23T20:28:11Z
[ "python", "sql" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names without python including them as part of the query text?</p>
30
2009-05-23T20:20:33Z
902,836
<p>Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):</p> <pre><code>cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) </code></pre> <p>or (e.g. with sqlite3 from the Python standard library):</p> <pre><code>cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3)) </code></pre> <p>or others yet (after <code>VALUES</code> you could have <code>(:1, :2, :3)</code> , or "named styles" <code>(:fee, :fie, :fo)</code> or <code>(%(fee)s, %(fie)s, %(fo)s)</code> where you pass a dict instead of a map as the second argument to <code>execute</code>). Check the <code>paramstyle</code> string constant in the DB API module you're using, and look for paramstyle at <a href="http://www.python.org/dev/peps/pep-0249/">http://www.python.org/dev/peps/pep-0249/</a> to see what all the parameter-passing styles are!</p>
24
2009-05-24T01:14:23Z
[ "python", "sql" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names without python including them as part of the query text?</p>
30
2009-05-23T20:20:33Z
21,734,918
<p>Many ways. <strong>DON'T</strong> use the most obvious one (<code>%s</code> with <code>%</code>) in real code, it's open to <a href="http://en.wikipedia.org/wiki/SQL_injection">attacks</a>.</p> <p>Here copy-paste'd <strong><a href="http://docs.python.org/2/library/sqlite3.html">from pydoc of sqlite3</a></strong>:</p> <pre><code># Never do this -- insecure! symbol = 'RHAT' c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) # Do this instead t = ('RHAT',) c.execute('SELECT * FROM stocks WHERE symbol=?', t) print c.fetchone() # Larger example that inserts many records at a time purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) </code></pre> <p><strong>More examples if you need:</strong></p> <pre><code># Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) </code></pre>
11
2014-02-12T17:16:52Z
[ "python", "sql" ]
Problem with my hangman game
902,520
<p>I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the word, it doesn't work. What am I missing?</p> <pre><code>import sys import codecs import random if __name__ == '__main__': try: wordlist = codecs.open("words.txt", "r") except Exception as ex: print (ex) print ("\n**Could not open file!**\n") sys.exit(0) rand = int(random.random()*5 + 1) i = 0 for word in wordlist: i+=1 if i == rand: print (word, end = '') break wordlist.close() guess = input("Guess a letter: ") print (guess) #for testing purposes for letters in word: if guess == letters: print ("Yessssh") #guessing part and user interface here </code></pre>
0
2009-05-23T21:25:17Z
902,530
<p>In your "<code>for word in wordlist</code>" loop, each word will end in a newline. Try adding <code>word = word.strip()</code> as the next line.</p> <p>By the way your last loop could be replaced with:</p> <pre><code>if guess in word: print ("Yessssh") </code></pre> <p>Bonus tip: when adding "debug prints", it's often a good idea to use repr (especially when dealing with strings). For example, your line:</p> <pre><code>print (guess) #for testing purposes </code></pre> <p>Might be more useful if you wrote:</p> <pre><code>print (repr(guess)) #for testing purposes </code></pre> <p>That way if there are weird characters in <code>guess</code>, you'll see them more easily in your debug output.</p>
8
2009-05-23T21:31:59Z
[ "python", "python-3.x" ]
Problem with my hangman game
902,520
<p>I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the word, it doesn't work. What am I missing?</p> <pre><code>import sys import codecs import random if __name__ == '__main__': try: wordlist = codecs.open("words.txt", "r") except Exception as ex: print (ex) print ("\n**Could not open file!**\n") sys.exit(0) rand = int(random.random()*5 + 1) i = 0 for word in wordlist: i+=1 if i == rand: print (word, end = '') break wordlist.close() guess = input("Guess a letter: ") print (guess) #for testing purposes for letters in word: if guess == letters: print ("Yessssh") #guessing part and user interface here </code></pre>
0
2009-05-23T21:25:17Z
19,480,398
<p>This is what i did for my hangman game:</p> <pre><code> for x in range(0, len(secretword)): if letter == secretword[x]: for x in range(len(secretword)): if secretword[x] in letter: hiddenletter = hiddenletter[:x] + secretword[x] +hiddenletter[x+1:] for letter in hiddenletter: print(letter, end=' ') </code></pre> <p>secretword is the hidden word that the user is trying to guess. hidden letter contains the amount of "_" in the word: i.e. hiddenletter = " _ " * len(secretword)</p> <p>this replaces the blanks with the correctly guessed letters and then shows the underscores with the letters in the right places i did my best...</p>
0
2013-10-20T17:15:34Z
[ "python", "python-3.x" ]
Issue with adding new properties to existing Google AppEngine data models / entities
902,633
<p>In GAE, I have a model called Foo, with existing entities, and attempt to add a new property called <em>memcached</em> to Foo that takes datetime values for the last time this value was set to memcache. If I try to query and sort on this property, or even filter for entities that do not have a value for <em>memcached</em>, entities that haven't had a value set for this property yet are not returned. Is there something I'm missing here, or as an alternative, is there a quick way to set a value for a <em>new</em> property on every entity of a given model?</p> <p>I have created a bunch of entities of the following model,</p> <pre><code>class Foo(db.Model): name = db.StringProperty(required=True) </code></pre> <p>and then add a property to this model,</p> <pre><code>class Foo(db.Model): name = db.StringProperty(required=True) memcached = db.DateTimeProperty(required=True, auto_now=True, auto_now_add=True, default=datetime.min) </code></pre> <p>the default value of the new property is not considered when I do a sort or filter on a query.</p>
4
2009-05-23T22:24:15Z
902,672
<p>There's nothing for it but to go through each of your existing entities and add the property, <a href="http://code.google.com/appengine/articles/update%5Fschema.html">here is the official documentation which walks you through the process</a>.</p>
8
2009-05-23T22:53:58Z
[ "python", "google-app-engine", "properties", "bigtable" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
902,774
<p>You can use <a href="https://github.com/drj11/pypng/" rel="nofollow">PyPNG</a>. It's a pure Python (no dependencies) open source PNG encoder/decoder and it <a href="http://packages.python.org/pypng/ex.html#numpy" rel="nofollow">supports</a> writing NumPy arrays as images.</p>
21
2009-05-24T00:26:05Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
977,040
<p>If you have matplotlib, you can do:</p> <pre><code>import matplotlib.pyplot as plt plt.imshow(matrix) #Needs to be in row,col order plt.savefig(filename) </code></pre>
15
2009-06-10T17:29:37Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
978,306
<p>matplotlib svn has a new function to save images as just an image -- no axes etc. it's a very simple function to backport too, if you don't want to install svn (copied straight from image.py in matplotlib svn, removed the docstring for brevity):</p> <pre><code>def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None): from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False) canvas = FigureCanvas(fig) fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin) fig.savefig(fname, dpi=1, format=format) </code></pre>
2
2009-06-10T21:43:06Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
1,713,101
<p>This uses PIL, but maybe some might find it useful:</p> <pre><code>import scipy.misc scipy.misc.imsave('outfile.jpg', image_array) </code></pre> <p><strong>EDIT</strong>: The current <code>scipy</code> version started to normalize all images so that min(data) become black and max(data) become white. This is unwanted if the data should be exact grey levels or exact RGB channels. The solution:</p> <pre><code>import scipy.misc scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg') </code></pre>
107
2009-11-11T04:53:29Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
8,538,444
<p>An answer using PIL (just in case it's useful).</p> <p>given a numpy array "A":</p> <pre><code>import Image im = Image.fromarray(A) im.save("your_file.jpeg") </code></pre> <p>you can replace "jpeg" with almost any format you want. More details about the formats <a href="http://www.pythonware.com/library/pil/handbook/index.htm">here</a></p>
32
2011-12-16T18:21:39Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
19,174,800
<p>Pure Python (2 &amp; 3), a snippet without 3rd party dependencies.</p> <p>This function writes compressed, true-color (4 bytes per pixel) <code>RGBA</code> PNG's.</p> <pre><code>def write_png(buf, width, height): """ buf: must be bytes or a bytearray in Python3.x, a regular string in Python2.x. """ import zlib, struct # reverse the vertical line order and add null bytes at the start width_byte_4 = width * 4 raw_data = b''.join(b'\x00' + buf[span:span + width_byte_4] for span in range((height - 1) * width_byte_4, -1, - width_byte_4)) def png_pack(png_tag, data): chunk_head = png_tag + data return (struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF &amp; zlib.crc32(chunk_head))) return b''.join([ b'\x89PNG\r\n\x1a\n', png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)), png_pack(b'IDAT', zlib.compress(raw_data, 9)), png_pack(b'IEND', b'')]) </code></pre> <p>... The data should be written directly to a file opened as binary, as in:</p> <pre><code>data = write_png(buf, 64, 64) with open("my_image.png", 'wb') as fd: fd.write(data) </code></pre> <p><a href="https://developer.blender.org/diffusion/B/browse/master/release/bin/blender-thumbnailer.py$155">Original source</a></p> <p>Example usage thanks to @Evgeni Sergeev: <a href="http://stackoverflow.com/a/21034111/432509">http://stackoverflow.com/a/21034111/432509</a></p>
28
2013-10-04T06:33:01Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
21,034,111
<p>Addendum to @ideasman42's answer:</p> <pre><code>def saveAsPNG(array, filename): import struct if any([len(row) != len(array[0]) for row in array]): raise ValueError, "Array should have elements of equal size" #First row becomes top row of image. flat = []; map(flat.extend, reversed(array)) #Big-endian, unsigned 32-byte integer. buf = b''.join([struct.pack('&gt;I', ((0xffFFff &amp; i32)&lt;&lt;8)|(i32&gt;&gt;24) ) for i32 in flat]) #Rotate from ARGB to RGBA. data = write_png(buf, len(array[0]), len(array)) f = open(filename, 'wb') f.write(data) f.close() </code></pre> <p>So you can do:</p> <pre><code>saveAsPNG([[0xffFF0000, 0xffFFFF00], [0xff00aa77, 0xff333333]], 'test_grid.png') </code></pre> <p>Producing <code>test_grid.png</code>:</p> <p><img src="http://i.stack.imgur.com/5eWSa.png" alt="Grid of red, yellow, dark-aqua, grey"></p> <p>(Transparency also works, by reducing the high byte from <code>0xff</code>.)</p>
6
2014-01-10T00:33:20Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
22,823,821
<p>With <code>matplotlib</code>:</p> <pre><code>import matplotlib matplotlib.image.imsave('name.png', array) </code></pre> <p>Works with matplotlib 1.3.1, I don't know about lower version. From the docstring:</p> <pre><code>Arguments: *fname*: A string containing a path to a filename, or a Python file-like object. If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename. *arr*: An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array. </code></pre>
9
2014-04-02T21:51:28Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
25,377,156
<p>If you happen to use [Py]Qt already, you may be interested in <a href="http://hmeine.github.io/qimage2ndarray/" rel="nofollow">qimage2ndarray</a>. Starting with version 1.4 (just released), PySide is supported as well, and there will be a tiny <code>imsave(filename, array)</code> function similar to scipy's, but using Qt instead of PIL. With 1.3, just use something like the following:</p> <pre><code>qImage = array2qimage(image, normalize = False) # create QImage from ndarray success = qImage.save(filename) # use Qt's image IO functions for saving PNG/JPG/.. </code></pre> <p>(Another advantage of 1.4 is that it is a pure python solution, which makes this even more lightweight.)</p>
1
2014-08-19T06:46:08Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
27,115,931
<p>There's <code>opencv</code> for python (<a href="http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html">http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html</a>).</p> <pre><code>import cv2 import numpy as np cv2.imwrite("filename.png", np.zeros((10,10))) </code></pre> <p>useful if you need to do more processing other than saving.</p>
10
2014-11-24T23:10:45Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
32,853,604
<p>The world probably doesn't need yet another package for writing a numpy array to a PNG file, but for those who can't get enough, I recently put up <code>numpngw</code> on github:</p> <p><a href="https://github.com/WarrenWeckesser/numpngw" rel="nofollow">https://github.com/WarrenWeckesser/numpngw</a></p> <p>and on pypi: <a href="https://pypi.python.org/pypi/numpngw/" rel="nofollow">https://pypi.python.org/pypi/numpngw/</a></p> <p>The only external dependency is numpy.</p> <p>Here's the first example from the <code>examples</code> directory of the repository. The essential line is simply</p> <pre><code>write_png('example1.png', img) </code></pre> <p>where <code>img</code> is a numpy array. All the code before that line is import statements and code to create <code>img</code>.</p> <pre><code>import numpy as np from numpngw import write_png # Example 1 # # Create an 8-bit RGB image. img = np.zeros((80, 128, 3), dtype=np.uint8) grad = np.linspace(0, 255, img.shape[1]) img[:16, :, :] = 127 img[16:32, :, 0] = grad img[32:48, :, 1] = grad[::-1] img[48:64, :, 2] = grad img[64:, :, :] = 127 write_png('example1.png', img) </code></pre> <p>Here's the PNG file that it creates:</p> <p><a href="http://i.stack.imgur.com/fykhB.png" rel="nofollow"><img src="http://i.stack.imgur.com/fykhB.png" alt="example1.png"></a></p>
1
2015-09-29T20:56:04Z
[ "python", "image", "numpy" ]
Compiling Python, curses.h not found
902,833
<p>I'm attempting to build Python 2.6.2 from source on my Linux system. It has ncurses installed on /usr/local/, and curses.h is on /usr/local/include/ncurses. So curses.h isn't found on the include path, and those packages fail in the Python build.</p> <p>What's the right solution to this? Is Python supposed to include &lt;ncurses/curses.h>? Should /usr/local/include/ncurses be in the include path? Should there be a link from the files in the ncurses directory to /usr/local/include?</p> <p>Or is there some simpler solution?</p>
1
2009-05-24T01:12:18Z
902,866
<p>With many Open Source packages, you can set:</p> <pre><code>export CPPFLAGS="-I/usr/local/include" </code></pre> <p>or even:</p> <pre><code>export CPPFLAGS="-I/usr/local/include/ncurses" </code></pre> <p>before running the configure script. I haven't compiled Python recently enough to be sure that works, but it probably does -- I have ncurses installed under /usr/gnu (because /usr/local/ is automounted and contains antiques) and I don't remember having to use anything special to get it to work.</p> <p><hr></p> <p>Double-checked...</p> <p>The configure script only includes <code>&lt;curses.h&gt;</code>. I had to use:</p> <pre><code>export CPPFLAGS="-I/usr/gnu/include -I/usr/gnu/include/ncurses" export LDFLAGS="-L/usr/gnu/lib" ./configure </code></pre> <p>To get the Python (2.5) configure to accept curses. You'd replace '<code>gnu</code>' with '<code>local</code>' for your configuration.</p>
4
2009-05-24T01:35:02Z
[ "python", "configure", "curses" ]
How does the win32com python.Interpreter work?
902,895
<p>Ok, so I'm trying to google the win32com python package and the python.Interpreter COM server. Unfortunately, python.Interpreter ends up as "python Interpreter" and not giving me any COM server results.</p> <p>I'm trying to make a pluggable program that has a plugin to allow python code to run, and it seems like the python.Interpreter would be a good way to go. But I haven't used it before and I'm not sure how to make objects created from it available through COM.</p> <p>Any advice or pointers to documentation/examples would be appreciated. </p> <p>Also, would a user need to install a python package to use the COM server, or is the interpreter built into the server dll?</p> <p>Thanks Brett</p>
0
2009-05-24T01:58:11Z
902,939
<p>See <a href="http://books.google.com/books?id=ns1WMyLVnRMC&amp;pg=PA232&amp;lpg=PA232&amp;dq=win32com+%22python.interpreter%22&amp;source=bl&amp;ots=NVpe-E8eGg&amp;sig=imGi73WQyOmP4rJC6-jpz4stb9M&amp;hl=en&amp;ei=xrAYSsTHBZH0tAORqeCSDw&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=6#PPA232,M1" rel="nofollow">http://books.google.com/books?id=ns1WMyLVnRMC&amp;pg=PA232&amp;lpg=PA232&amp;dq=win32com+%22python.interpreter%22&amp;source=bl&amp;ots=NVpe-E8eGg&amp;sig=imGi73WQyOmP4rJC6-jpz4stb9M&amp;hl=en&amp;ei=xrAYSsTHBZH0tAORqeCSDw&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=6#PPA232,M1</a> for excellent docs on python.interpreter -- as for your second question, normally win32com is installed as an add-on to an existing Python install, but of course you can pick a Python distro including the win32 extensions, such as Activestate's at <a href="http://www.activestate.com/activepython/" rel="nofollow">http://www.activestate.com/activepython/</a> .</p>
1
2009-05-24T02:31:21Z
[ "python", "com" ]
Data storage to ease data interpolation in Python
902,910
<p>I have 20+ tables similar to table 1. Where all letters represent actual values.</p> <pre><code>Table 1: $ / cars |&lt;1 | 2 | 3 | 4+ &lt;10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p </code></pre> <p>A user input could be for example, (2.4, 24594) which is a value between f, g, j, and k. My Python function definition and pseudo-code to calculate this bilinear interpolation is as follows.</p> <pre><code>def bilinear_interpolation( x_in, y_in, x_high, x_low, y_low, y_high ): # interpolate with respect to x # interpolate with respect to y # return result </code></pre> <p>How should I store the data from table 1 (a file, a dict, tuple of tuples, or dict of lists), so I can perform the bilinear interpolation most efficiently and correctly? </p>
6
2009-05-24T02:14:27Z
902,931
<p>There's nothing special about bilinear interpolation that makes your use case particularly odd; you just have to do two lookups (for storage units of full rows/columns) or four lookups (for array-type storage). The most efficient method depends on your access patterns and the structure of the data.</p> <p>If your example is truly representative, with 16 total entries, you can store it however you want and it'll be fast enough for any kind of sane loads.</p>
0
2009-05-24T02:23:35Z
[ "python", "interpolation" ]
Data storage to ease data interpolation in Python
902,910
<p>I have 20+ tables similar to table 1. Where all letters represent actual values.</p> <pre><code>Table 1: $ / cars |&lt;1 | 2 | 3 | 4+ &lt;10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p </code></pre> <p>A user input could be for example, (2.4, 24594) which is a value between f, g, j, and k. My Python function definition and pseudo-code to calculate this bilinear interpolation is as follows.</p> <pre><code>def bilinear_interpolation( x_in, y_in, x_high, x_low, y_low, y_high ): # interpolate with respect to x # interpolate with respect to y # return result </code></pre> <p>How should I store the data from table 1 (a file, a dict, tuple of tuples, or dict of lists), so I can perform the bilinear interpolation most efficiently and correctly? </p>
6
2009-05-24T02:14:27Z
902,933
<p>I'd keep a sorted list of the first column, and use the <code>bisect</code> module in the standard library to look for the values -- it's the best way to get the immediately-lower and immediately-higher indices. Every other column can be kept as another list parallel to this one. </p>
3
2009-05-24T02:25:32Z
[ "python", "interpolation" ]
Data storage to ease data interpolation in Python
902,910
<p>I have 20+ tables similar to table 1. Where all letters represent actual values.</p> <pre><code>Table 1: $ / cars |&lt;1 | 2 | 3 | 4+ &lt;10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p </code></pre> <p>A user input could be for example, (2.4, 24594) which is a value between f, g, j, and k. My Python function definition and pseudo-code to calculate this bilinear interpolation is as follows.</p> <pre><code>def bilinear_interpolation( x_in, y_in, x_high, x_low, y_low, y_high ): # interpolate with respect to x # interpolate with respect to y # return result </code></pre> <p>How should I store the data from table 1 (a file, a dict, tuple of tuples, or dict of lists), so I can perform the bilinear interpolation most efficiently and correctly? </p>
6
2009-05-24T02:14:27Z
903,071
<p>If you want the most computationally efficient solution I can think of and are not restricted to the standard library, then I would recommend scipy/numpy. First, store the a..p array as a 2D numpy array and then both the $4k-10k and 1-4 arrays as 1D numpy arrays. Use scipy's interpolate.interp1d if both 1D arrays are monotonically increasing, or interpolate.bsplrep (bivariate spline representation) if not and your example arrays are as small as your example. Or simply write your own and not bother with scipy. Here are some examples:</p> <pre><code># this follows your pseudocode most closely, but it is *not* # the most efficient since it creates the interpolation # functions on each call to bilinterp from scipy import interpolate import numpy data = numpy.arange(0., 16.).reshape((4,4)) #2D array prices = numpy.arange(10000., 50000., 10000.) cars = numpy.arange(1., 5.) def bilinterp(price,car): return interpolate.interp1d(cars, interpolate.interp1d(prices, a)(price))(car) print bilinterp(22000,2) </code></pre> <p>The last time I checked (a version of scipy from 2007-ish) it only worked for monotonically increasing arrays of x and y)</p> <p>for small arrays like this 4x4 array, I think you want to use this: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html#scipy.interpolate.bisplrep" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html#scipy.interpolate.bisplrep</a> which will handle more interestingly shaped surfaces and the function only needs to be created once. For larger arrays, I think you want this (not sure if this has the same restrictions as interp1d): <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html#scipy.interpolate.interp2d" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html#scipy.interpolate.interp2d</a> but they both require a different and more verbose data structure than the three arrays in the example above.</p>
7
2009-05-24T04:28:26Z
[ "python", "interpolation" ]
How to embed a Poll in a Web Page
903,104
<p>I want to create a simple online poll application. I have created a backend in python that handles vote tracking, poll display, results display and admin setup. However, if I wanted a third party to be able to embed the poll in their website, what would be the recommended way of doing so? I would love to be able to provide a little javascript to drop into the third parties web page, but I can't use javascript because it would require a cross-domain access. What approach would provide an easy general solution for third parties?</p>
1
2009-05-24T04:53:43Z
903,112
<p>Make your app into a Google Gadget, Open Social gadget, or other kind of gadgets -- these are all designed to be embeddable into third-party pages with as little fuss as possible.</p>
1
2009-05-24T04:57:23Z
[ "javascript", "python", "cross-domain" ]
How to embed a Poll in a Web Page
903,104
<p>I want to create a simple online poll application. I have created a backend in python that handles vote tracking, poll display, results display and admin setup. However, if I wanted a third party to be able to embed the poll in their website, what would be the recommended way of doing so? I would love to be able to provide a little javascript to drop into the third parties web page, but I can't use javascript because it would require a cross-domain access. What approach would provide an easy general solution for third parties?</p>
1
2009-05-24T04:53:43Z
903,139
<p>IFrame is the easiest no muss no fuss solution if you want to allow postbacks.</p> <p>Or, this is a bit left field and oldschool, but could you use a 1x1 transparent gif as your vote submission? They click the link (radio/span/whatever), you set the src of an image to something that lives on your server. Something like</p> <pre><code>document.getElementById('voteImage').src='http://your.server/vote.html?pollidentifier=123&amp;vote=4' </code></pre> <p>where vote.html is your server side code for processing a vote, poll identifier is the way of telling what poll it is, and vote is the vote they've chosen. All vote.html has to do is return something that smells like an image and the browser will be happy. Obviously you'll need to put <em>stuff</em> in place to stop people faking up votes, but an image + cookies is what the old timers used to use before that new fandangled xhr came along.</p>
1
2009-05-24T05:17:18Z
[ "javascript", "python", "cross-domain" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,135
<p>The first.</p> <p>Shorter is better. Exceptions should be exceptional.</p>
-1
2009-05-24T05:14:59Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,138
<p><code>hasattr</code> internally and rapidly performs the same task as the <code>try/except</code> block: it's a very specific, optimized, one-task tool and thus should be preferred, when applicable, to the very general-purpose alternative.</p>
60
2009-05-24T05:17:15Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,155
<p>If it's just one attribute you're testing, I'd say use <code>hasattr</code>. However, if you're doing <em>several</em> accesses to attributes which may or may not exist then using a <code>try</code> block may save you some typing.</p>
4
2009-05-24T05:32:01Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,162
<p>I would say it depends on whether your function may accept objects without the attribute <strong>by design</strong>, e.g. if you have two callers to the function, one providing an object with the attribute and the other providing an object without it. </p> <p>If the only case where you'll get an object without the attribute is due to some error, I would recommend using the exceptions mechanism even though it may be slower, because I believe it is a cleaner design. </p> <p>Bottom line: I think it's a design and readability issue rather than an efficiency issue. </p>
13
2009-05-24T05:37:42Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,173
<p>From a practical point of view, in most languages using a conditional will always be consderably faster than handling an exception.</p> <p>If you're wanting to handle the case of an attribute not existing somewhere outside of the current function, the exception is the better way to go. An indicator that you may want to be using an exception instead of a conditional is that the conditional merely sets a flag and aborts the current operation, and something elsewhere checks this flag and takes action based on that.</p> <p>That said, as Rax Olgud points out, communication with others is one important attribute of code, and what you want to say by saying "this is an exceptional situation" rather than "this is is something I expect to happen" may be more important.</p>
2
2009-05-24T05:44:44Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,238
<p><em>Any benches that illustrate difference in performance?</em></p> <p>timeit it's your friend</p> <pre><code>$ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "nonexistent")' 1000000 loops, best of 3: 1.87 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "a")' 1000000 loops, best of 3: 0.446 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'try: c.a except: pass' 1000000 loops, best of 3: 0.247 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'try: c.nonexistent except: pass' 100000 loops, best of 3: 3.13 usec per loop $ |positive|negative hasattr| 0.446 | 1.87 try | 0.247 | 3.13 </code></pre>
66
2009-05-24T06:41:27Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,304
<p>I'd suggest option 2. Option 1 has a race condition if some other thread is adding or removing the attribute.</p> <p>Also python has an <a href="http://jaynes.colorado.edu/PythonIdioms.html" rel="nofollow">Idiom</a>, that EAFP ('easier to ask forgiveness than permission') is better than LBYL ('look before you leap').</p>
2
2009-05-24T08:00:38Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
1,063,055
<p>If not having the attribute is <strong>not</strong> an error condition, the exception handling variant has a problem: it would catch also AttributeErrors that might come <em>internally</em> when accessing obj.attribute (for instance because attribute is a property so that accessing it calls some code).</p>
2
2009-06-30T10:52:28Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
12,855,092
<p>At least when it is up to just what's going on in the program, leaving out the human part of readability, etc. (which is actually most of the time more imortant than performance (at least in this case - with that performance span), as Roee Adler and others pointed out).</p> <p>Nevertheless looking at it from that perspective, it then becomes a matter of choosing between</p> <pre><code>try: getattr(obj, attr) except: ... </code></pre> <p>and</p> <pre><code>try: obj.attr except: ... </code></pre> <p>since <code>hasattr</code> just uses the first case to determine the result. Food for thought ;-)</p>
0
2012-10-12T08:29:57Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
16,186,050
<p>I almost always use <code>hasattr</code>: it's the correct choice for most cases.</p> <p>The problematic case is when a class overrides <code>__getattr__</code>: <code>hasattr</code> will <strong>catch all exceptions</strong> instead of catching just <code>AttributeError</code> like you expect. In other words, the code below will print <code>b: False</code> even though it would be more appropriate to see a <code>ValueError</code> exception:</p> <pre><code>class X(object): def __getattr__(self, attr): if attr == 'a': return 123 if attr == 'b': raise ValueError('important error from your database') raise AttributeError x = X() print 'a:', hasattr(x, 'a') print 'b:', hasattr(x, 'b') print 'c:', hasattr(x, 'c') </code></pre> <p>The important error has thus disappeared. This has been <a href="http://docs.python.org/3/whatsnew/3.2.html">fixed in Python 3.2</a> (<a href="http://bugs.python.org/issue9666">issue9666</a>) where <code>hasattr</code> now only catches <code>AttributeError</code>.</p> <p>An easy workaround is to write a utility function like this:</p> <pre><code>_notset = object() def safehasattr(thing, attr): return getattr(thing, attr, _notset) is not _notset </code></pre> <p>This let's <code>getattr</code> deal with the situation and it can then raise the appropriate exception.</p>
15
2013-04-24T07:32:57Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
16,727,179
<p>There is a third, and often better, alternative:</p> <pre><code>attr = getattr(obj, 'attribute', None) if attr is not None: print attr </code></pre> <p>Advantages:</p> <ol> <li><p><code>getattr</code> does not have the bad <a href="http://stackoverflow.com/a/16186050/243712">exception-swallowing behavior pointed out by Martin Geiser</a> - in old Pythons, <code>hasattr</code> will even swallow a <code>KeyboardInterrupt</code>.</p></li> <li><p>The normal reason you're checking if the object has an attribute is so that you can use the attribute, and this naturally leads in to it.</p></li> <li><p>The attribute is read off atomically, and is safe from other threads changing the object. (Though, if this is a major concern you might want to consider locking the object before accessing it.)</p></li> <li><p>It's shorter than <code>try/finally</code> and often shorter than <code>hasattr</code>.</p></li> <li><p>A broad <code>except AttributeError</code> block can catch other <code>AttributeErrors</code> than the one you're expecting, which can lead to confusing behaviour.</p></li> <li><p>Accessing an attribute is slower than accessing a local variable (especially if it's not a plain instance attribute). (Though, to be honest, micro-optimization in Python is often a fool's errand.)</p></li> </ol> <p>One thing to be careful of is if you care about the case where <code>obj.attribute</code> is set to None, you'll need to use a different sentinel value.</p>
12
2013-05-24T03:18:35Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
How to implement hotlinking prevention in Google App Engine
903,144
<p>My application is on GAE and I'm trying to figure out how to prevent hotlinking of images dynamically served (e.g. /image?id=E23432E) in Python. Please advise.</p>
5
2009-05-24T05:21:29Z
903,307
<p>In Google webapp framework, you can extract the referer from the <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html" rel="nofollow">Request class</a>:</p> <pre><code>def get(self): referer = self.request.headers.get("Referer") # Will be None if no referer given in header. </code></pre> <p>Note that's <code>referer</code>, not <code>referrer</code> (see <a href="http://dictionary.reference.com/browse/referer" rel="nofollow">this dictionary entry</a>).</p>
11
2009-05-24T08:02:20Z
[ "python", "google-app-engine", "hotlinking" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been able to.</p> <p>I went to <a href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a> and downloaded "Python Imaging Library 1.1.6 Source Kit (all platforms) (440k TAR GZ) (December 3, 2006)". Then I opened the folder in my command prompt and ran </p> <pre><code>$ python setup.py build_ext -i . </code></pre> <p>This was the output I got:</p> <pre><code>running build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -DHAVE_LIBZ -IlibImaging -I/opt/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include -I/usr/local/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c _imaging.c -o build/temp.macosx-10.5-i386-2.5/_imaging.o unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 </code></pre> <p>"import Image" produced an error when I tried it.</p> <p>Do you guys have any idea what's going on? I'm using a MacBook Pro with a Core 2 Duo.</p> <p>And I'm honestly sorry if this is ridiculously stupid.</p>
6
2009-05-24T06:47:30Z
903,244
<p>GCC is the GNU compiler. It's a very useful thing to have. You just need to install it in whatever mac-friendly way exists.</p> <p><a href="http://www.tech-recipes.com/rx/726/mac-os-x-install-gcc-compiler/" rel="nofollow">http://www.tech-recipes.com/rx/726/mac-os-x-install-gcc-compiler/</a></p>
0
2009-05-24T06:52:10Z
[ "python", "osx", "module" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been able to.</p> <p>I went to <a href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a> and downloaded "Python Imaging Library 1.1.6 Source Kit (all platforms) (440k TAR GZ) (December 3, 2006)". Then I opened the folder in my command prompt and ran </p> <pre><code>$ python setup.py build_ext -i . </code></pre> <p>This was the output I got:</p> <pre><code>running build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -DHAVE_LIBZ -IlibImaging -I/opt/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include -I/usr/local/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c _imaging.c -o build/temp.macosx-10.5-i386-2.5/_imaging.o unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 </code></pre> <p>"import Image" produced an error when I tried it.</p> <p>Do you guys have any idea what's going on? I'm using a MacBook Pro with a Core 2 Duo.</p> <p>And I'm honestly sorry if this is ridiculously stupid.</p>
6
2009-05-24T06:47:30Z
903,245
<p>You need to install the developer tools that come on your Mac OS X install DVD.</p>
3
2009-05-24T06:52:13Z
[ "python", "osx", "module" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been able to.</p> <p>I went to <a href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a> and downloaded "Python Imaging Library 1.1.6 Source Kit (all platforms) (440k TAR GZ) (December 3, 2006)". Then I opened the folder in my command prompt and ran </p> <pre><code>$ python setup.py build_ext -i . </code></pre> <p>This was the output I got:</p> <pre><code>running build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -DHAVE_LIBZ -IlibImaging -I/opt/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include -I/usr/local/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c _imaging.c -o build/temp.macosx-10.5-i386-2.5/_imaging.o unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 </code></pre> <p>"import Image" produced an error when I tried it.</p> <p>Do you guys have any idea what's going on? I'm using a MacBook Pro with a Core 2 Duo.</p> <p>And I'm honestly sorry if this is ridiculously stupid.</p>
6
2009-05-24T06:47:30Z
903,254
<p>Actually, assuming you're still using the default 2.5.x Python that comes with OS X (at least as of 10.5.6), there's a <a href="http://pythonmac.org/packages/py25-fat/index.html" rel="nofollow">pre-built installer package</a> for it (download the <a href="http://pythonmac.org/packages/py25-fat/dmg/PIL-1.1.6-py2.5-macosx10.4-2007-05-18.dmg" rel="nofollow">dmg for PIL</a>).</p> <p>Otherwise, you'll need to either build it from source -- which does require the mac dev tools -- or install it with <a href="http://www.macports.org/" rel="nofollow">MacPorts</a> or <a href="http://www.finkproject.org/" rel="nofollow">fink</a></p> <p><strong>edit:</strong> mono makes a good point, you'll still need the dev tools unless you use the pre-built installer.</p>
4
2009-05-24T07:00:48Z
[ "python", "osx", "module" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been able to.</p> <p>I went to <a href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a> and downloaded "Python Imaging Library 1.1.6 Source Kit (all platforms) (440k TAR GZ) (December 3, 2006)". Then I opened the folder in my command prompt and ran </p> <pre><code>$ python setup.py build_ext -i . </code></pre> <p>This was the output I got:</p> <pre><code>running build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -DHAVE_LIBZ -IlibImaging -I/opt/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include -I/usr/local/include -I/usr/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c _imaging.c -o build/temp.macosx-10.5-i386-2.5/_imaging.o unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 </code></pre> <p>"import Image" produced an error when I tried it.</p> <p>Do you guys have any idea what's going on? I'm using a MacBook Pro with a Core 2 Duo.</p> <p>And I'm honestly sorry if this is ridiculously stupid.</p>
6
2009-05-24T06:47:30Z
5,879,621
<p>So this is from awhile ago, but I just ran into the problem.</p> <p>The issues lies with -> </p> <pre><code>/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/sysconfig.py </code></pre> <p>or wherever your python install is.</p> <p>there is a line that sets the compile flags:</p> <pre><code>archflags = '-arch i386 -arch ppc -arch x86_64' </code></pre> <p>I just removed it from that line and went on my merry way. Now there is obviously a way to configure this from the line above:</p> <pre><code>os.environ['ARCHFLAGS'] </code></pre> <p>but I don't know about that, and didn't want to mess with it.</p>
0
2011-05-04T06:53:10Z
[ "python", "osx", "module" ]
Python - get static information
903,497
<p>i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file:</p> <pre><code>LogObject.Log('Describe error', STATIC_INFORMATION) </code></pre> <p>Static information is class name, file name and function name. I get it from this:</p> <pre><code>__file__ self.__class__.__name__ sys._getframe().f_code.co_name </code></pre> <p>But i don't want to write this variables during logging. Can i create some function and call it. For example:</p> <pre><code>LogObject.Log('Describe error', someFunction()) </code></pre> <p>How can i use it for getting static information?</p>
1
2009-05-24T10:35:43Z
903,553
<p>First, please use lower-case names for objects and methods. Only use UpperCase Names for Class definitions. </p> <p>More importantly, you want a clever introspective function in every class, it appears. </p> <pre><code>class Loggable( object ): def identification( self ): return self.__class__.__module__, self.__class__.__name__, sys._getframe().f_code.co_name class ARealClass( Loggable ): def someFunction( self ): logger.info( "Some Message from %r", self. identification() ) </code></pre> <p>If all of your classes are subclasses of Loggable, you'll inherit this identification function in all classes.</p>
2
2009-05-24T11:13:18Z
[ "python", "variables", "static" ]
Python - get static information
903,497
<p>i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file:</p> <pre><code>LogObject.Log('Describe error', STATIC_INFORMATION) </code></pre> <p>Static information is class name, file name and function name. I get it from this:</p> <pre><code>__file__ self.__class__.__name__ sys._getframe().f_code.co_name </code></pre> <p>But i don't want to write this variables during logging. Can i create some function and call it. For example:</p> <pre><code>LogObject.Log('Describe error', someFunction()) </code></pre> <p>How can i use it for getting static information?</p>
1
2009-05-24T10:35:43Z
903,588
<p>I don't think "static" is the world you're looking for. If I understand you correctly, you want to write a function that will return the filename, class name and method name of the caller.</p> <p>Basically, you should use sys._getframe(1) to access the previous frame, and work from there.</p> <p>Example:</p> <pre><code>def codeinfo(): import sys f = sys._getframe(1) filename = f.f_code.co_filename classname = '' if 'self' in f.f_locals: classname = f.f_locals['self'].__class__.__name__ funcname = f.f_code.co_name return "filename: %s\nclass: %s\nfunc: %s" % (filename, classname, funcname) </code></pre> <p>Then from a method somewhere you can write</p> <pre><code>logger.info("Some message \n %s" % codeinfo()) </code></pre>
3
2009-05-24T11:33:37Z
[ "python", "variables", "static" ]
Python's 'with' statement versus 'with .. as'
903,557
<p>Having just pulled my hair off because of a difference, I'd like to know what the difference <em>really</em> is in Python 2.5.</p> <p>I had two blocks of code (<code>dbao.getConnection()</code> returns a MySQLdb connection).</p> <pre><code>conn = dbao.getConnection() with conn: # Do stuff </code></pre> <p>And</p> <pre><code>with dbao.getConnection() as conn: # Do stuff </code></pre> <p>I thought these would have the same effect but apparently not as the <code>conn</code> object of the latter version was a <code>Cursor</code>. Where did the cursor come from and <em>is</em> there a way to combine the variable initialization and with statement somehow?</p>
14
2009-05-24T11:17:24Z
903,594
<p>The with statement is there to allow for example making sure that transaction is started and stopped correctly.</p> <p>In case of database connections in python, I think the natural thing to do is to create a cursor at the beginning of the with statement and then commit or rollback the transaction at the end of it.</p> <p>The two blocks you gave are same from the with statement point of view. You can add the as to the first one just as well and get the cursor.</p> <p>You need to check how the with support is implemented in the object you use it with.</p> <p>See <a href="http://docs.python.org/whatsnew/2.5.html#pep-343-the-with-statement" rel="nofollow">http://docs.python.org/whatsnew/2.5.html#pep-343-the-with-statement</a></p>
1
2009-05-24T11:36:54Z
[ "python", "syntax" ]
Python's 'with' statement versus 'with .. as'
903,557
<p>Having just pulled my hair off because of a difference, I'd like to know what the difference <em>really</em> is in Python 2.5.</p> <p>I had two blocks of code (<code>dbao.getConnection()</code> returns a MySQLdb connection).</p> <pre><code>conn = dbao.getConnection() with conn: # Do stuff </code></pre> <p>And</p> <pre><code>with dbao.getConnection() as conn: # Do stuff </code></pre> <p>I thought these would have the same effect but apparently not as the <code>conn</code> object of the latter version was a <code>Cursor</code>. Where did the cursor come from and <em>is</em> there a way to combine the variable initialization and with statement somehow?</p>
14
2009-05-24T11:17:24Z
904,357
<p>In general terms, the value assigned by the <code>as</code> part of a <code>with</code> statement is going to be whatever gets returned by the <a href="http://docs.python.org/library/stdtypes.html#contextmanager.%5F%5Fenter%5F%5F"><code>__enter__</code> method of the context manager</a>.</p>
18
2009-05-24T18:18:37Z
[ "python", "syntax" ]
Python's 'with' statement versus 'with .. as'
903,557
<p>Having just pulled my hair off because of a difference, I'd like to know what the difference <em>really</em> is in Python 2.5.</p> <p>I had two blocks of code (<code>dbao.getConnection()</code> returns a MySQLdb connection).</p> <pre><code>conn = dbao.getConnection() with conn: # Do stuff </code></pre> <p>And</p> <pre><code>with dbao.getConnection() as conn: # Do stuff </code></pre> <p>I thought these would have the same effect but apparently not as the <code>conn</code> object of the latter version was a <code>Cursor</code>. Where did the cursor come from and <em>is</em> there a way to combine the variable initialization and with statement somehow?</p>
14
2009-05-24T11:17:24Z
904,590
<p>It may be a little confusing at first glance, but </p> <pre><code>with babby() as b: ... </code></pre> <p>is <em>not</em> equivalent to</p> <pre><code>b = babby() with b: ... </code></pre> <p>To see why, here's how the context manager would be implemented:</p> <pre><code>class babby(object): def __enter__(self): return 'frigth' def __exit__(self, type, value, tb): pass </code></pre> <p>In the first case, the name <code>b</code> will be bound to whatever is returned from the <code>__enter__</code> method of the context manager. This is often the context manager itself (for example for file objects), but it doesn't have to be; in this case it's the string <code>'frigth'</code>, and in your case it's the database cursor.</p> <p>In the second case, <code>b</code> is the context manager object itself.</p>
27
2009-05-24T20:34:40Z
[ "python", "syntax" ]
python, regular expressions, named groups and "logical or" operator
903,562
<p>In python regular expression, named and unnamed groups are both defined with '(' and ')'. This leads to a weird behavior. Regexp</p> <pre><code>"(?P&lt;a&gt;1)=(?P&lt;b&gt;2)" </code></pre> <p>used with text "1=2" will find named group "a" with value "1" and named group "b" with value "2". But if i want to use "logical or" operator and concatenate multiple rules, the following regexp:</p> <pre><code>"((?P&lt;a&gt;1)=(?P&lt;b&gt;2))|(?P&lt;c&gt;3)" </code></pre> <p>used with same text "1=2" will find an <strong>unnamed</strong> group with value "1=2". I understood that regexp engine treats "(" and ")" that encloses groups "a" and "b" as an unnamed group and reports that it is found. But i don't want an unnamed groups to be reported, i just want to use "|" in order to "glue" multiple regexps together. Without creating any parasitic unnamed groups. Is it a way to do so in python?</p>
5
2009-05-24T11:18:20Z
903,567
<p>Use <code>(?:)</code> to get rid of the unnamed group:</p> <pre><code>r"(?:(?P&lt;a&gt;1)=(?P&lt;b&gt;2))|(?P&lt;c&gt;3)" </code></pre> <p>From the documentation of <a href="http://docs.python.org/library/re.html">re</a>:</p> <blockquote> <p>(?:...) A non-grouping version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.</p> </blockquote> <p>By the way, the alternation operator <code>|</code> has very low precedence in order to make parentheses unnecessary in cases like yours. You can drop the extra parentheses in your regex and it will continue to work as expected:</p> <pre><code>r"(?P&lt;a&gt;1)=(?P&lt;b&gt;2)|(?P&lt;c&gt;3)" </code></pre>
12
2009-05-24T11:21:18Z
[ "python", "regex" ]
How can I draw automatic graphs using dot in Python on a Mac?
903,582
<p>I am producing graphs in a Python program, and now I need to visualize them.</p> <p>I am using Tkinter as GUI to visualize all the other data, and I would like to have a small subwindow inside with the graph of the data. At the moment I have the data being represented in a .dot file. And then I keep graphviz open, which shows the graph. But this is of course suboptimal. I need to get the graph inside the tk window.</p> <p>I thought about using graphviz from the command line, but I always run into the same well known bug:</p> <pre><code>Desktop ibook$ dot -Tpng -O 1.dot dyld: lazy symbol binding failed: Symbol not found: _pixman_image_create_bits Referenced from: /usr/local/lib/graphviz/libgvplugin_pango.5.dylib Expected in: flat namespace dyld: Symbol not found: _pixman_image_create_bits Referenced from: /usr/local/lib/graphviz/libgvplugin_pango.5.dylib Expected in: flat namespace Trace/BPT trap </code></pre> <p>The bug seem to be well known in the Graphviz community:</p> <p><a href="http://www.graphviz.org/bugs/b1479.html" rel="nofollow">http://www.graphviz.org/bugs/b1479.html</a></p> <p><a href="http://www.graphviz.org/bugs/b1488.html" rel="nofollow">http://www.graphviz.org/bugs/b1488.html</a></p> <p><a href="http://www.graphviz.org/bugs/b1498.html" rel="nofollow">http://www.graphviz.org/bugs/b1498.html</a></p> <p>So since it seems that I cannot use the command line utility I was wondering if anyone knew a direct way to draw a dot graph in Python, without using the command line, or doing something that would incur the same error?</p> <p>I am programming on a Mac Leopard, python 2.5.2</p>
0
2009-05-24T11:28:35Z
903,833
<p>I do not have a mac to test it on, but the <a href="http://networkx.lanl.gov/index.html" rel="nofollow">NetworkX</a> package includes methods to <a href="http://networkx.lanl.gov/reference/generated/networkx.read%5Fdot.html" rel="nofollow">read .dot files</a> and <a href="http://networkx.lanl.gov/reference/generated/networkx.draw.html" rel="nofollow">draw graphs</a> using <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matplotlib</a>. You can embed a matplotlib figure in Tk (<a href="http://matplotlib.sourceforge.net/examples/user%5Finterfaces/embedding%5Fin%5Ftk.html" rel="nofollow">example 1</a>, <a href="http://matplotlib.sourceforge.net/examples/user%5Finterfaces/embedding%5Fin%5Ftk2.html" rel="nofollow">example 2</a>).</p>
2
2009-05-24T14:10:54Z
[ "python", "osx", "graphviz", "dot", "dyld" ]
How can I draw automatic graphs using dot in Python on a Mac?
903,582
<p>I am producing graphs in a Python program, and now I need to visualize them.</p> <p>I am using Tkinter as GUI to visualize all the other data, and I would like to have a small subwindow inside with the graph of the data. At the moment I have the data being represented in a .dot file. And then I keep graphviz open, which shows the graph. But this is of course suboptimal. I need to get the graph inside the tk window.</p> <p>I thought about using graphviz from the command line, but I always run into the same well known bug:</p> <pre><code>Desktop ibook$ dot -Tpng -O 1.dot dyld: lazy symbol binding failed: Symbol not found: _pixman_image_create_bits Referenced from: /usr/local/lib/graphviz/libgvplugin_pango.5.dylib Expected in: flat namespace dyld: Symbol not found: _pixman_image_create_bits Referenced from: /usr/local/lib/graphviz/libgvplugin_pango.5.dylib Expected in: flat namespace Trace/BPT trap </code></pre> <p>The bug seem to be well known in the Graphviz community:</p> <p><a href="http://www.graphviz.org/bugs/b1479.html" rel="nofollow">http://www.graphviz.org/bugs/b1479.html</a></p> <p><a href="http://www.graphviz.org/bugs/b1488.html" rel="nofollow">http://www.graphviz.org/bugs/b1488.html</a></p> <p><a href="http://www.graphviz.org/bugs/b1498.html" rel="nofollow">http://www.graphviz.org/bugs/b1498.html</a></p> <p>So since it seems that I cannot use the command line utility I was wondering if anyone knew a direct way to draw a dot graph in Python, without using the command line, or doing something that would incur the same error?</p> <p>I am programming on a Mac Leopard, python 2.5.2</p>
0
2009-05-24T11:28:35Z
905,316
<p>Quick <a href="http://www.google.com/search?q=python%2Bgraphviz" rel="nofollow">Google</a> pulls up <a href="http://code.google.com/p/pydot/" rel="nofollow">http://code.google.com/p/pydot/</a>. I haven't tried it but it looks promising.</p>
1
2009-05-25T04:28:13Z
[ "python", "osx", "graphviz", "dot", "dyld" ]
is it possible to call python methods from a C program?
903,596
<p>I remember seeing somewhere that you could call python methods from inside C using</p> <pre><code>#include "python.h" </code></pre> <p>But I can't seem to find the source for this or any examples.</p> <p>How can I call python methods from inside a C program?</p>
0
2009-05-24T11:37:32Z
903,602
<p><a href="http://www.python.org/doc/2.5.2/ext/callingPython.html" rel="nofollow">Here's</a> a doc item from the python site about extending C with python functionality</p> <p><a href="http://www.python.org/doc/2.5.2/ext/simpleExample.html" rel="nofollow">Here's</a> the start of the documentation (where it refers to python.h) where you can extend Python with C functionality.</p>
5
2009-05-24T11:40:03Z
[ "python", "c", "embedding" ]
is it possible to call python methods from a C program?
903,596
<p>I remember seeing somewhere that you could call python methods from inside C using</p> <pre><code>#include "python.h" </code></pre> <p>But I can't seem to find the source for this or any examples.</p> <p>How can I call python methods from inside a C program?</p>
0
2009-05-24T11:37:32Z
903,604
<p>Check out <a href="http://docs.python.org/c-api/" rel="nofollow">http://docs.python.org/c-api</a></p>
2
2009-05-24T11:41:58Z
[ "python", "c", "embedding" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has been called?</p> <p>I welcome any suggestions, but would like to know of some way to achieve this without making an instance of C2 inside C1.</p>
2
2009-05-24T14:03:45Z
903,831
<p>I believe that what you are trying to do would fit into the realm of <a href="http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming" rel="nofollow">Aspect Oriented Programming</a>. However I have never used this methodology and don't even know if it can/has been implemented in Python.</p> <p><strong>Edit</strong> I just took a look at the link I provided and saw that there are <a href="http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming#Implementations" rel="nofollow">8 Python implementations</a> mentioned. So the hard work has already been done for you :-)</p>
2
2009-05-24T14:10:13Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has been called?</p> <p>I welcome any suggestions, but would like to know of some way to achieve this without making an instance of C2 inside C1.</p>
2
2009-05-24T14:03:45Z
903,856
<p>You can do aspect-oriented programming with function and method decorators since Python 2.2:</p> <pre><code>@decorator(decorator_args) def functionToBeDecorated(function_args) : pass </code></pre>
2
2009-05-24T14:20:28Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has been called?</p> <p>I welcome any suggestions, but would like to know of some way to achieve this without making an instance of C2 inside C1.</p>
2
2009-05-24T14:03:45Z
903,861
<p>It really depends on why you don't want to call F2 directly from within F1. You could always create a third class (C3) which encapsulates both C1 and C2. When F3 is called, it will call both F1 and F2. This is known as the Mediator pattern - <a href="http://en.wikipedia.org/wiki/Mediator_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Mediator_pattern</a></p>
2
2009-05-24T14:21:31Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has been called?</p> <p>I welcome any suggestions, but would like to know of some way to achieve this without making an instance of C2 inside C1.</p>
2
2009-05-24T14:03:45Z
903,868
<p>You catch all accesses to F1 with <code>__getattr__</code> . This will allow you to do extra processing or return your own function in place of F1</p> <pre><code>class C1: def __getattr__(self,name): if name == 'F1': C2.F2() return self[name] </code></pre> <p>I should warn you that this will call C2.F2 even if F1 is only being accessed (not run). It's rare but not impossible that F1 might simply be accessed for another purpose like <code>f = myC1.F1</code> . To run F2 only on a call of F1 you need to expand this example to combine F2 with the returned function object. in other words:</p> <pre><code>def F1F2(): self.F1() C2.F2() return F1F2 </code></pre>
0
2009-05-24T14:25:27Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has been called?</p> <p>I welcome any suggestions, but would like to know of some way to achieve this without making an instance of C2 inside C1.</p>
2
2009-05-24T14:03:45Z
903,898
<p>You can write a little helper decorator that will make the call for you. The advantage is that it's easy to tell who is going to call what by looking at the code. And you can add as many function calls as you want. It works like registering a callback function:</p> <pre><code>from functools import wraps def oncall(call): def helper(fun): @wraps(fun) def wrapper(*args, **kwargs): result = fun(*args, **kwargs) call() return result return wrapper return helper class c1: @classmethod def f1(cls): print 'f1' class c2: @classmethod @oncall(c1.f1) def f2(cls): print 'f2' &gt;&gt;&gt; c2.f2() f2 f1 &gt;&gt;&gt; c1.f1() f1 </code></pre>
3
2009-05-24T14:37:29Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has been called?</p> <p>I welcome any suggestions, but would like to know of some way to achieve this without making an instance of C2 inside C1.</p>
2
2009-05-24T14:03:45Z
904,482
<p>Not knowing what is you are trying to achieve, i would suggest taking a look at pydispatcher. It allows you to implement the Observer pattern </p> <p>Basically, you register F2 with the dispatcher so that it will be called when a specific 'signal' is emitted. Your F1 'emits a signal' that says "I've been called". The dispatcher then calls F2 (or any number of functions that have registered themselves with that particular signal). Its actually really simpler than it sounds, easy to use, and de-couples your code (F1 does not need to know about F2).</p> <p>(arhh.. I'm a new user and not allowed to include hyperlinks, but pydispatcher is easy to google for)</p>
1
2009-05-24T19:25:44Z
[ "python", "class" ]
Prevent splitting Window when using pythoncomplete in Vim
903,847
<p>I'm using VIM with pythoncomplete. When I'm making a completion, the current window is splitted and calltips are shown in the upper pane. I hate that! Is there a way to prevent that behavior or at least limit the size of the upper pane automaticly?</p>
5
2009-05-24T14:17:20Z
903,882
<p>You need to do something like:</p> <pre><code>set completeopt-=preview </code></pre> <p>This will prevent the opening of the preview window. </p>
5
2009-05-24T14:29:10Z
[ "python", "autocomplete", "vim" ]
How do you extract a column from a multi-dimensional array?
903,853
<p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
80
2009-05-24T14:19:47Z
903,867
<p>Could it be that you're using a <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays">NumPy array</a>? Python has the <a href="http://docs.python.org/library/array.html">array</a> module, but that does not support multi-dimensional arrays. Normal Python lists are single-dimensional too.</p> <p>However, if you have a simple two-dimensional list like this:</p> <pre><code>A = [[1,2,3,4], [5,6,7,8]] </code></pre> <p>then you can extract a column like this:</p> <pre><code>def column(matrix, i): return [row[i] for row in matrix] </code></pre> <p>Extracting the second column (index 1):</p> <pre><code>&gt;&gt;&gt; column(A, 1) [2, 6] </code></pre> <p>Or alternatively, simply:</p> <pre><code>&gt;&gt;&gt; [row[1] for row in A] [2, 6] </code></pre>
75
2009-05-24T14:24:23Z
[ "python", "arrays", "multidimensional-array", "extraction" ]