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
Error while posting a Twitter message through a python app
2,416,548
<pre><code>#!/usr/bin/python # -*- coding: iso-8859-1 -*- import Tkinter import twitter class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() api=twitter.api()(...
-1
2010-03-10T11:45:43Z
2,416,573
<p>The error message is clear, isn't it? The twitter module has no attribute named "api".</p> <p>A quick google showed me some examples that have a ".Api()" method (capital A). Maybe that is your problem.</p>
3
2010-03-10T11:49:41Z
[ "python", "twitter", "tkinter" ]
stop django from taking out javascript/frames?
2,416,677
<p>Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we allow javascript to be used in stories? Is it being...
0
2010-03-10T12:08:10Z
2,416,764
<p>Django is probably automatically escaping the content the javascript / html as the template renders the content. It does this for security purposes.</p> <p>The solution depends on which version of django you're running, whether you'll be rendering any content from untrusted sources, how the templates are put togeth...
2
2010-03-10T12:21:36Z
[ "python", "django", "django-templates" ]
stop django from taking out javascript/frames?
2,416,677
<p>Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we allow javascript to be used in stories? Is it being...
0
2010-03-10T12:08:10Z
2,416,776
<p>Django doesn't strip out javascript, because it is client side agnostic.</p> <p>How are you inserting javascript into your website? If you are trying to put it into database (like ) it will escaped.</p>
0
2010-03-10T12:22:51Z
[ "python", "django", "django-templates" ]
stop django from taking out javascript/frames?
2,416,677
<p>Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we allow javascript to be used in stories? Is it being...
0
2010-03-10T12:08:10Z
2,418,820
<p>Read through the docs on automatic HTML escaping:</p> <p><a href="http://docs.djangoproject.com/en/1.1/topics/templates/#id2" rel="nofollow">http://docs.djangoproject.com/en/1.1/topics/templates/#id2</a></p>
0
2010-03-10T16:59:09Z
[ "python", "django", "django-templates" ]
Django and "get() returned more than one Model name" error in multi-threaded program
2,416,819
<p>Django's get_or_create function always cause "get() returned more than one Model name" error in a multi-threaded program.</p> <p>I even tried to put get_or_create statement inside a lock.acquire() and lock.release() block but still didn't work.</p> <p>The program only works when I set thread_count=1</p> <p>The da...
1
2010-03-10T12:31:40Z
2,417,080
<p>This is not caused by multithreading, but because there are more than one object in database, that satisfies your query. You must select exactly one object from the database using get, otherwise it will raise an exception.</p>
2
2010-03-10T13:11:13Z
[ "python", "mysql", "database", "multithreading", "insert" ]
How to get the content of a Html page in Python
2,416,823
<p>I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.</p> <p>To be clear:</p> <p>Input:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/head&gt; ...
4
2010-03-10T12:32:20Z
2,416,839
<p>The quickest way to get a usable sample of what a browser would display is to remove any tags from the html and print the rest. This can, for example, be done using python's <code>re</code>.</p>
-3
2010-03-10T12:34:52Z
[ "python", "html", "parsing" ]
How to get the content of a Html page in Python
2,416,823
<p>I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.</p> <p>To be clear:</p> <p>Input:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/head&gt; ...
4
2010-03-10T12:32:20Z
2,416,841
<p>Parse the HTML with <a href="http://www.crummy.com/software/BeautifulSoup" rel="nofollow">Beautiful Soup</a>.</p> <p>To get all the text, without the tags, try:</p> <pre><code>''.join(soup.findAll(text=True)) </code></pre>
12
2010-03-10T12:35:10Z
[ "python", "html", "parsing" ]
How to get the content of a Html page in Python
2,416,823
<p>I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.</p> <p>To be clear:</p> <p>Input:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/head&gt; ...
4
2010-03-10T12:32:20Z
2,416,915
<p>If I am getting your question correctly, this can simply be done by using urlopen function of urllib. Just have a look at this function to open an url and read the response which will be the html code of that page.</p>
-2
2010-03-10T12:46:31Z
[ "python", "html", "parsing" ]
How to get the content of a Html page in Python
2,416,823
<p>I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.</p> <p>To be clear:</p> <p>Input:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/head&gt; ...
4
2010-03-10T12:32:20Z
2,416,937
<p>The best modules for this task are lxml or html5lib; Beautifull Soap is imho not worth to use anymore. And for recursive models regular expressions are definitly the wrong method.</p>
2
2010-03-10T12:49:50Z
[ "python", "html", "parsing" ]
How to get the content of a Html page in Python
2,416,823
<p>I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.</p> <p>To be clear:</p> <p>Input:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/head&gt; ...
4
2010-03-10T12:32:20Z
2,417,100
<p>You want to look at <a href="http://diveintopython.net/html_processing/index.html#dialect.divein" rel="nofollow"><strong>Extracting data from HTML documents - Dive into Python</strong></a> because <a href="http://diveintopython.net/html_processing/introducing_sgmllib.html" rel="nofollow"><strong>HERE</strong></a> i...
2
2010-03-10T13:15:12Z
[ "python", "html", "parsing" ]
How to get the content of a Html page in Python
2,416,823
<p>I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.</p> <p>To be clear:</p> <p>Input:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/head&gt; ...
4
2010-03-10T12:32:20Z
2,419,998
<p>Personally, I use lxml because it's a swiss-army knife...</p> <pre> from lxml import html print html.parse('http://someurl.at.domain').xpath('//body')[0].text_content() </pre> <p>This tells lxml to retrieve the page, locate the <code>&lt;body&gt;</code> tag then extract and print all the text.</p> <p>I do a lot ...
7
2010-03-10T19:43:26Z
[ "python", "html", "parsing" ]
Python __init__ issue: unbound method __init__() must be called with Bank instance as first argument (got int instance instead)
2,417,192
<pre><code>class Teller(object): def __init__(self): self.occupied = False self.timeLeft = 0 self.totTime def occupy(self, timeOcc): self.occupied = True self.timeLeft = timeOcc def nextMin(self): self.timeLeft -= 1 self.totTime += 1 if self....
0
2010-03-10T13:31:24Z
2,417,207
<p>2 points to make here:</p> <ol> <li><p>You shouldn't be calling <code>__init__</code> directly, it's a magic method which is invoked when you construct an object like this:</p> <pre><code>virtBank = Bank(3, 7) </code></pre></li> <li><p>The instance is implicitly passed to the constructor, but it must be explicitly...
9
2010-03-10T13:34:25Z
[ "python", "methods", "init" ]
Finding a module's directory
2,417,215
<p>How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.</p> <p>edit:</p> <p>combining several answers:</p> <pre><code>module_path = os.path.dirname(imp.find_module(self.__module__)[1]) </code></pre> <p>got me what i wanted</p>
2
2010-03-10T13:35:15Z
2,417,230
<p>This would work:</p> <pre><code>yourmodule.__file__ </code></pre> <p>and if you want to find the module an object was imported from:</p> <pre><code>myobject.__module__ </code></pre>
1
2010-03-10T13:37:22Z
[ "python", "module", "dirname" ]
Finding a module's directory
2,417,215
<p>How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.</p> <p>edit:</p> <p>combining several answers:</p> <pre><code>module_path = os.path.dirname(imp.find_module(self.__module__)[1]) </code></pre> <p>got me what i wanted</p>
2
2010-03-10T13:35:15Z
2,417,232
<p>The path to the module's file is in <code>module.__file__</code>. You can use that with <code>os.path.dirname</code> to get the directory.</p>
1
2010-03-10T13:37:29Z
[ "python", "module", "dirname" ]
Finding a module's directory
2,417,215
<p>How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.</p> <p>edit:</p> <p>combining several answers:</p> <pre><code>module_path = os.path.dirname(imp.find_module(self.__module__)[1]) </code></pre> <p>got me what i wanted</p>
2
2010-03-10T13:35:15Z
2,417,305
<p>Using the re module as an example:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; path = re.__file__ &gt;&gt;&gt; print path C:\python26\lib\re.pyc &gt;&gt;&gt; import os.path &gt;&gt;&gt; print os.path.dirname(os.path.abspath(path)) C:\python26\lib </code></pre> <p>Note that if the module is in your current w...
1
2010-03-10T13:48:03Z
[ "python", "module", "dirname" ]
Finding a module's directory
2,417,215
<p>How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.</p> <p>edit:</p> <p>combining several answers:</p> <pre><code>module_path = os.path.dirname(imp.find_module(self.__module__)[1]) </code></pre> <p>got me what i wanted</p>
2
2010-03-10T13:35:15Z
2,417,329
<p>If you want to modules directory by specifying <code>module_name</code> as string <em>i.e. without actually importing the module</em> then use</p> <pre><code>def get_dir(module_name): import os,imp (file, pathname, description) = imp.find_module(module_name) return os.path.dirname(pathname) print get_d...
1
2010-03-10T13:50:59Z
[ "python", "module", "dirname" ]
How to convert this regular expression into Python
2,417,330
<p>I want to use this regular expression in Python:</p> <pre><code> &lt;(?:"[^"]*"['"]*|'[^']*'['"]*|[^'"&gt;])+&gt; </code></pre> <p>(from <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/">http://stackoverflow.com/questions/1732348/regex-match-open-tags-exce...
0
2010-03-10T13:51:04Z
2,417,389
<p>Works fine here. You're probably having trouble because of the quotes. Just triple-quote it:</p> <pre><code>def removeHtmlTags(page): p = re.compile(r'''&lt;(?:"[^"]*"['"]*|'[^']*'['"]*|[^'"&gt;])+&gt;''') return p.sub('', page) </code></pre>
1
2010-03-10T13:59:13Z
[ "python", "regex" ]
How to convert this regular expression into Python
2,417,330
<p>I want to use this regular expression in Python:</p> <pre><code> &lt;(?:"[^"]*"['"]*|'[^']*'['"]*|[^'"&gt;])+&gt; </code></pre> <p>(from <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/">http://stackoverflow.com/questions/1732348/regex-match-open-tags-exce...
0
2010-03-10T13:51:04Z
2,417,431
<p>If you need to remove HTML tags, this should do it:</p> <pre><code>import re def removeHtmlTags(page): pattern = re.compile(r'\&lt;[^&gt;]+\&gt;', re.I) return pattern.sub('', page) </code></pre>
0
2010-03-10T14:04:54Z
[ "python", "regex" ]
How to use lazy_gettext with Pylons and setup.py
2,417,479
<p>Just a quick question. When I use the _() function provided by the Pylons i18n module, everything works just as expected. My problem is with the lazy version of this function, lazy_gettext. When I run :</p> <pre><code>python setup.py extract_messages </code></pre> <p>I get in the POT file the strings to be transla...
3
2010-03-10T14:13:56Z
2,417,498
<p>In the modules where you use <code>lazy_gettext()</code>, just assign <code>_ = lazy_gettext</code> and use <code>_()</code> instead.</p>
2
2010-03-10T14:17:33Z
[ "python", "internationalization", "pylons" ]
How to check with python if a table is empty?
2,417,545
<p>Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?</p>
3
2010-03-10T14:22:18Z
2,417,593
<p>Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)</p> <pre><code>import MySQLdb db = MySQLdb.connect(passwd="moonpie", db="thangs") results = db.query("""SELECT * from mytable limit 1""") if not results: print "This table is empty!" </code></pre>
7
2010-03-10T14:27:17Z
[ "python", "mysql" ]
How to check with python if a table is empty?
2,417,545
<p>Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?</p>
3
2010-03-10T14:22:18Z
2,417,598
<p>Something like</p> <pre><code>import MySQLdb db = MySQLdb.connect("host", "user", "password", "dbname") cursor = db.cursor() sql = """SELECT count(*) as tot FROM simpletable""" cursor.execute(sql) data = cursor.fetchone() db.close() print data </code></pre> <p>will print the number or records in the <code>simpleta...
3
2010-03-10T14:27:48Z
[ "python", "mysql" ]
Memory usage with Django + SQLite3
2,417,572
<p>I've got a very large SQLite table with over 500,000 rows with about 15 columns (mostly floats). I'm wanting to transfer data from the SQLite DB to a Django app (which could be backed by many RDBMs, but Postgres in my case). Everything works OK, but as the iteration continues, memory usage jumps by 2-3 meg a second ...
3
2010-03-10T14:25:19Z
2,417,622
<p>I think a <code>select * from mapDenormalize</code> and loading the result into memory will always be a bad idea. My advise is - spread script into chunks. Use <code>LIMIT</code> to get data in portions.</p> <p>Get first portion, work with it, close to cursor, and then get the next portion.</p>
1
2010-03-10T14:30:30Z
[ "python", "django", "sqlite", "sqlite3" ]
Memory usage with Django + SQLite3
2,417,572
<p>I've got a very large SQLite table with over 500,000 rows with about 15 columns (mostly floats). I'm wanting to transfer data from the SQLite DB to a Django app (which could be backed by many RDBMs, but Postgres in my case). Everything works OK, but as the iteration continues, memory usage jumps by 2-3 meg a second ...
3
2010-03-10T14:25:19Z
2,418,176
<p>Silly me, this was addressed in the <a href="http://docs.djangoproject.com/en/dev/faq/models/#why-is-django-leaking-memory" rel="nofollow">Django FAQ</a>.</p> <p>Needed to clear the DB query cache while in DEBUG mode. </p> <pre><code>from django import db db.reset_queries() </code></pre>
3
2010-03-10T15:39:18Z
[ "python", "django", "sqlite", "sqlite3" ]
Sending a List through an URL
2,417,611
<p>I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using. </p> <p>The list prints out like this:</p> <pre><code>[u'1', u'6', u'5'] </code></pre> <p>I know that the u encodes the string in utf-8 right? So a couple of questions.</p> <p>Can I send a list thr...
2
2010-03-10T14:29:22Z
2,417,631
<p><code>u''</code> is not utf-8, its python unicode strings for python 2.x</p> <p>To send it through url, you need to encode them with utf8 like <code>.encode('utf-8')</code>, and also need to urlencode, and list cannot send it through URL, you need to make it as string.</p> <p>Basically, you need to do it in follow...
1
2010-03-10T14:31:24Z
[ "python", "string", "url", "unicode" ]
Sending a List through an URL
2,417,611
<p>I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using. </p> <p>The list prints out like this:</p> <pre><code>[u'1', u'6', u'5'] </code></pre> <p>I know that the u encodes the string in utf-8 right? So a couple of questions.</p> <p>Can I send a list thr...
2
2010-03-10T14:29:22Z
2,417,635
<p>Incorrect. unicode literals use Python's internal encoding, decided when it was compiled.</p> <p>You can't send anything "through" URLs. Pick a protocol instead. And encode before sending, probably to UTF-8.</p>
0
2010-03-10T14:32:38Z
[ "python", "string", "url", "unicode" ]
Sending a List through an URL
2,417,611
<p>I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using. </p> <p>The list prints out like this:</p> <pre><code>[u'1', u'6', u'5'] </code></pre> <p>I know that the u encodes the string in utf-8 right? So a couple of questions.</p> <p>Can I send a list thr...
2
2010-03-10T14:29:22Z
2,418,829
<blockquote> <p>Can I send a list through a URL?</p> </blockquote> <p>No. A URL is just text. If you want a way to package structured information in it, you'll have to agree that with the provider you're talking to.</p> <p>One standard encoding for structure in URLs, that might or might not be what you need, is the...
4
2010-03-10T16:59:42Z
[ "python", "string", "url", "unicode" ]
How do I retrieve a modules path when I have a class from that module
2,417,639
<p>In python, If I have a class <code>foo</code>, I can <code>call foo.__module__</code> to get a string with the name of the module it is part of.</p> <p>If I have a module <code>bar</code>, I can call <code>bar.__file__</code> to get a string with the path where the module was loaded from.</p> <p>How, when I only h...
1
2010-03-10T14:32:44Z
2,417,653
<p><code>sys.modules</code> is a mapping from module name to module:</p> <pre><code>sys.modules[foo.__module__].__file__ </code></pre>
5
2010-03-10T14:33:48Z
[ "python" ]
How do I retrieve a modules path when I have a class from that module
2,417,639
<p>In python, If I have a class <code>foo</code>, I can <code>call foo.__module__</code> to get a string with the name of the module it is part of.</p> <p>If I have a module <code>bar</code>, I can call <code>bar.__file__</code> to get a string with the path where the module was loaded from.</p> <p>How, when I only h...
1
2010-03-10T14:32:44Z
2,419,682
<p>For such introspection tasks, I always recommend using Python standard library's <code>inspect</code> module: it can handle some corner cases &amp;c and makes the whole process much smoother. For your specific task, <a href="http://docs.python.org/library/inspect.html?highlight=getsourcefile#inspect.getsourcefile" ...
4
2010-03-10T18:59:13Z
[ "python" ]
Dynamic resize with MPlayer and PyGTK
2,417,705
<p>I've wrote a piece of code in python and pygtk for an embeded mplayer in a gui. I assume I use GtkSocket and the slave mode of mplayer with the -wid option.</p> <p>But I've got an issue, when the size of my GTK window is smaller than my stream, the stream appears to be cropped. And when the size of my window is big...
0
2010-03-10T14:39:52Z
2,425,426
<p>You'll want to connect to the <code>'size-allocate'</code> signal of whatever widget you embedded MPlayer in. Once you know the new size of the widget, say 200x300, send the commands</p> <pre><code>set_property width 300 set_property height 200 </code></pre> <p>to MPlayer in slave mode.</p> <p>(See <a href="http:...
0
2010-03-11T13:57:21Z
[ "python", "gtk", "pygtk", "mplayer" ]
Dynamic resize with MPlayer and PyGTK
2,417,705
<p>I've wrote a piece of code in python and pygtk for an embeded mplayer in a gui. I assume I use GtkSocket and the slave mode of mplayer with the -wid option.</p> <p>But I've got an issue, when the size of my GTK window is smaller than my stream, the stream appears to be cropped. And when the size of my window is big...
0
2010-03-10T14:39:52Z
2,944,206
<p>You need to tell mplayer to zoom video according to window size. This can be done either in command line (-zoom) or in the configuration file (zoom = 1).</p>
1
2010-05-31T14:39:08Z
[ "python", "gtk", "pygtk", "mplayer" ]
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
<p>I am using matplotlib and numpy to make a polar plot. Here is some sample code:</p> <pre><code>import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angl...
21
2010-03-10T14:53:13Z
2,420,447
<p>You could modify your matplotlib/projections/polar.py.</p> <p>Where it says:</p> <pre><code>def transform(self, tr): xy = npy.zeros(tr.shape, npy.float_) t = tr[:, 0:1] r = tr[:, 1:2] x = xy[:, 0:1] y = xy[:, 1:2] x[:] = r * npy.cos(t) y[:] = r ...
4
2010-03-10T20:46:09Z
[ "python", "numpy", "matplotlib", "plot" ]
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
<p>I am using matplotlib and numpy to make a polar plot. Here is some sample code:</p> <pre><code>import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angl...
21
2010-03-10T14:53:13Z
2,433,287
<p>I found it out -- matplotlib allows you to create custom projections. I created one that inherits from <code>PolarAxes</code>.</p> <pre><code>import numpy as N import matplotlib.pyplot as P from matplotlib.projections import PolarAxes, register_projection from matplotlib.transforms import Affine2D, Bbox, IdentityT...
17
2010-03-12T14:20:07Z
[ "python", "numpy", "matplotlib", "plot" ]
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
<p>I am using matplotlib and numpy to make a polar plot. Here is some sample code:</p> <pre><code>import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angl...
21
2010-03-10T14:53:13Z
4,199,606
<p>Both invert routines should use the full path to the transforms:</p> <pre><code>return NorthPolarAxes.InvertedNorthPolarTransform() </code></pre> <p>and </p> <pre><code>return NorthPolarAxes.NorthPolarTransform() </code></pre> <p>Now, automatically created subclasses of NorthPolarAxes such as NorthPolarAxesSubpl...
2
2010-11-16T22:17:24Z
[ "python", "numpy", "matplotlib", "plot" ]
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
<p>I am using matplotlib and numpy to make a polar plot. Here is some sample code:</p> <pre><code>import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angl...
21
2010-03-10T14:53:13Z
8,302,530
<p>Updating this question, in Matplotlib 1.1, there are now two methods in <code>PolarAxes</code> for setting the theta direction (CW/CCW) and location for theta=0. </p> <p>Check out <a href="http://matplotlib.sourceforge.net/devel/add_new_projection.html#matplotlib.projections.polar.PolarAxes">http://matplotlib.sou...
24
2011-11-28T21:24:34Z
[ "python", "numpy", "matplotlib", "plot" ]
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
<p>I am using matplotlib and numpy to make a polar plot. Here is some sample code:</p> <pre><code>import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angl...
21
2010-03-10T14:53:13Z
11,475,973
<p>To expand klimaat's answer with an example:</p> <pre><code>import math angle=[0.,5.,10.,15.,20.,25.,30.,35.,40.,45.,50.,55.,60.,65.,70.,75.,\ 80.,85.,90.,95.,100.,105.,110.,115.,120.,125.] angle = [math.radians(a) for a in angle] lux=[12.67,12.97,12.49,14.58,12.46,12.59,11.26,10.71,17.74,25.95,\ 15.0...
10
2012-07-13T18:09:50Z
[ "python", "numpy", "matplotlib", "plot" ]
Can I use the variable name "type" as function argument in Python?
2,417,979
<p>Can I use <code>type</code> as a name for a python function argument?</p> <pre><code>def fun(name, type): .... </code></pre>
11
2010-03-10T15:13:20Z
2,418,007
<p>You can, but you shouldn't. It's not a good habit to use names of built-ins because they will override the name of the built-in in that scope. If you must use that word, modify it slightly for the given context.</p> <p>While it probably won't matter for a small project that is not using <code>type</code>, it's bet...
21
2010-03-10T15:16:09Z
[ "python" ]
Can I use the variable name "type" as function argument in Python?
2,417,979
<p>Can I use <code>type</code> as a name for a python function argument?</p> <pre><code>def fun(name, type): .... </code></pre>
11
2010-03-10T15:13:20Z
2,418,010
<p>You can, but you would be masking the built-in name type. So it's better not to do that.</p>
2
2010-03-10T15:16:43Z
[ "python" ]
Can I use the variable name "type" as function argument in Python?
2,417,979
<p>Can I use <code>type</code> as a name for a python function argument?</p> <pre><code>def fun(name, type): .... </code></pre>
11
2010-03-10T15:13:20Z
2,418,012
<p>You can use any non-keyword that follows the identifier rules as an identifier. <code>type</code> is not a keyword, but using it will shadow the <code>type</code> built-in.</p>
3
2010-03-10T15:16:54Z
[ "python" ]
Can I use the variable name "type" as function argument in Python?
2,417,979
<p>Can I use <code>type</code> as a name for a python function argument?</p> <pre><code>def fun(name, type): .... </code></pre>
11
2010-03-10T15:13:20Z
2,418,044
<p>You can, and that's fine. Even though the advice not to shadow builtins is important, it applies more strongly if an identifier is common, as it will increase confusion and collision. It does not appear <em>type</em> will cause confusion here (but you'll know about that more than anyone else), and I could use exac...
8
2010-03-10T15:20:05Z
[ "python" ]
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?
2,418,125
<p>With, say, 3 rows of subplots in matplotlib, <code>xlabels</code> of one row can overlap the title of the next. One has to fiddle with <code>pl.subplots_adjust(hspace)</code>, which is annoying. </p> <p>Is there a recipe for <code>hspace</code> that prevents overlaps and works for any nrow?</p> <pre><code>""" ma...
22
2010-03-10T15:32:03Z
2,516,508
<p>I find this quite tricky, but there is some information on it <a href="http://matplotlib.sourceforge.net/faq/howto_faq.html#automatically-make-room-for-tick-labels" rel="nofollow">here at the MatPlotLib FAQ</a>. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take ...
7
2010-03-25T14:51:30Z
[ "python", "matplotlib" ]
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?
2,418,125
<p>With, say, 3 rows of subplots in matplotlib, <code>xlabels</code> of one row can overlap the title of the next. One has to fiddle with <code>pl.subplots_adjust(hspace)</code>, which is annoying. </p> <p>Is there a recipe for <code>hspace</code> that prevents overlaps and works for any nrow?</p> <pre><code>""" ma...
22
2010-03-10T15:32:03Z
6,541,482
<p>You can use plt.subplots_adjust to change the spacing between the subplots Link</p> <pre><code>subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = ...
28
2011-06-30T21:48:17Z
[ "python", "matplotlib" ]
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?
2,418,125
<p>With, say, 3 rows of subplots in matplotlib, <code>xlabels</code> of one row can overlap the title of the next. One has to fiddle with <code>pl.subplots_adjust(hspace)</code>, which is annoying. </p> <p>Is there a recipe for <code>hspace</code> that prevents overlaps and works for any nrow?</p> <pre><code>""" ma...
22
2010-03-10T15:32:03Z
8,729,186
<p>The link posted by Jose has been updated and pylab now has a <code>tight_layout()</code> function that does this automatically (in matplotlib version 1.1.0).</p> <p><a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_la...
26
2012-01-04T15:16:41Z
[ "python", "matplotlib" ]
How to set wxPython grid background color?
2,418,145
<p>I'm working with a wxPython grid, but I cannot set the background color of it (the grid part that isn't filled with cells). I tried with grid.SetBackgroundColour, but without luck; the backcolor shown is always the default system color for windows.</p> <p>wx.version() -> 2.8.10.1 (msw-unicode)</p> <p>sys.version ...
0
2010-03-10T15:34:06Z
2,418,340
<p><code>grid.SetDefaultCellBackgroundColour(color)</code> will color everything, including the area outside the cells.</p>
2
2010-03-10T15:57:58Z
[ "python", "wxpython", "wxwidgets" ]
SOAP, Python, suds
2,418,172
<p>Please advise library for working with soap in python.<br> Now, I'm trying to use "suds" and I can't undestand how get http headers from server reply<br> Code example: </p> <pre><code>from suds.client import Client url = "http://10.1.0.36/money_trans/api3.wsdl" client = Client(url) login_res = client.service.Login...
6
2010-03-10T15:38:40Z
2,485,664
<p>I think you actually want to look in the Cookie Jar for that.</p> <pre><code>client = Client(url) login_res = client.service.Login("login", "password") for c in client.options.transport.cookiejar: if "sess" in str(c).lower(): print "Session cookie:", c </code></pre> <p>I'm not sure. I'm still a SUDS noob...
4
2010-03-21T02:36:47Z
[ "python", "soap", "suds" ]
SOAP, Python, suds
2,418,172
<p>Please advise library for working with soap in python.<br> Now, I'm trying to use "suds" and I can't undestand how get http headers from server reply<br> Code example: </p> <pre><code>from suds.client import Client url = "http://10.1.0.36/money_trans/api3.wsdl" client = Client(url) login_res = client.service.Login...
6
2010-03-10T15:38:40Z
5,628,988
<p>The response from <a href="http://stackoverflow.com/users/296703/ishpeck">Ishpeck</a> is on the right path. I just wanted to add a few things about the Suds internals.</p> <p>The suds client is a big fat abstraction layer on top of a urllib2 HTTP opener. The HTTP client, cookiejar, headers, request and responses a...
4
2011-04-12T00:14:11Z
[ "python", "soap", "suds" ]
What's the correct way to extract a regexp match in Python?
2,418,312
<p>I have found two ways to extract matches in Python:</p> <p>1.</p> <pre><code>def extract_matches(regexp, text): matches = re.match(regexp, text) if matches: return matches.group(1) </code></pre> <p>2.</p> <pre><code>def extract_matches(regexp, text): try: return re.findall(regexp, text)[0] except...
1
2010-03-10T15:54:08Z
2,418,341
<p>I would more often use <a href="http://docs.python.org/library/re.html?highlight=finditer#re.search" rel="nofollow"><code>re.search</code></a> (which returns <em>any</em> match, not just one constrained to start at the beginning of the string as <a href="http://docs.python.org/library/re.html?highlight=finditer#re.m...
6
2010-03-10T15:58:02Z
[ "python", "regex" ]
Testing warnings with doctest
2,418,570
<p>I'd like to use <a href="http://docs.python.org/library/doctest.html">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = F...
7
2010-03-10T16:24:50Z
2,418,678
<p>docs suggest that you could <a href="http://docs.python.org/library/warnings.html#the-warnings-filter" rel="nofollow">pass <code>-Wd</code></a> when running doctest to always trigger warnings.</p>
0
2010-03-10T16:39:49Z
[ "python", "warnings", "doctest" ]
Testing warnings with doctest
2,418,570
<p>I'd like to use <a href="http://docs.python.org/library/doctest.html">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = F...
7
2010-03-10T16:24:50Z
2,475,814
<p>Perhaps you could try <a href="http://www.voidspace.org.uk/python/mock/" rel="nofollow">mocking</a> (patch print!) the troublesome bit. I admit this would add some clutter to the docstring but it might worth a go.</p> <p>If you wish to use that approach while retaining the current syntax, perhaps you could try impl...
0
2010-03-19T08:15:56Z
[ "python", "warnings", "doctest" ]
Testing warnings with doctest
2,418,570
<p>I'd like to use <a href="http://docs.python.org/library/doctest.html">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = F...
7
2010-03-10T16:24:50Z
2,479,005
<p>The issue you're facing is that <code>warnings.warn()</code> calls <code>warnings.showwarning()</code>, which writes the result of <code>warnings.formatwarning()</code> to a file, defaulting to <code>sys.stderr</code>.</p> <p>(See: <a href="http://docs.python.org/library/warnings.html#warnings.showwarning" rel="nof...
1
2010-03-19T16:44:45Z
[ "python", "warnings", "doctest" ]
Testing warnings with doctest
2,418,570
<p>I'd like to use <a href="http://docs.python.org/library/doctest.html">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = F...
7
2010-03-10T16:24:50Z
2,479,062
<p>This isn't the most elegant way to do it, but it works for me:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; import sys; sys.stderr = sys.stdout &gt;&gt;&gt; foo = Foo() # doctest:+ELLIPSIS /.../testdocs.py:14: UserWarnin...
2
2010-03-19T16:52:01Z
[ "python", "warnings", "doctest" ]
Testing warnings with doctest
2,418,570
<p>I'd like to use <a href="http://docs.python.org/library/doctest.html">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = F...
7
2010-03-10T16:24:50Z
2,484,695
<p>The <a href="http://docs.python.org/library/warnings.html#testing-warnings" rel="nofollow">Testing Warnings</a> sections of the Python documentation is dedicated to this topic. However, to summarize, you have two options:</p> <h2>(A) Use the <code>catch_warnings</code> context manager</h2> <p>This is recommended c...
3
2010-03-20T20:39:50Z
[ "python", "warnings", "doctest" ]
Testing warnings with doctest
2,418,570
<p>I'd like to use <a href="http://docs.python.org/library/doctest.html">doctests</a> to test the presence of certain warnings. For example, suppose I have the following module:</p> <pre><code>from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; foo = F...
7
2010-03-10T16:24:50Z
2,488,372
<p>This is one example of why doctests are not appropriate for all tests. If you have inline examples in your docstrings and they need to be tested, that's one thing, but as you've discovered there are behaviors you want to test for that aren't best done with string matching. And cases where you don't need to have th...
0
2010-03-21T19:16:30Z
[ "python", "warnings", "doctest" ]
Problem importing pylab in Ubuntu 8.1
2,418,583
<p>I have installed numpy1.3,scipy 0.7.1,matplotlib 0.99.1.1 and python 2.5 when I import pylab I get the following error. Someone please help.</p> <pre><code> /var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:72: GtkWarning: could not open display warnings.warn(str(e), _gtk.Warning) /usr/lib/python2...
2
2010-03-10T16:26:12Z
2,418,650
<p>try using a different backend for plotting than Gtk. </p> <p>Open the python console and type:</p> <pre><code>&gt;&gt;&gt; import matplotlib &gt;&gt;&gt; matplotlib.matplotlib_fname() </code></pre> <p>This will print a file name. Edit this file and modify the section 'Backend' and change Gtk or GtkAgg with any ot...
8
2010-03-10T16:35:42Z
[ "python" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
2,418,764
<p>Hmm perhaps you need to process the image, i.e. put it though some filters like 'edge detection', emboss/engrave or a noise filter...</p>
5
2010-03-10T16:50:56Z
[ "python", "ocr", "tesseract" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
2,418,796
<p>Good OCRs are strongly guided by redundancies in natural languages to yield a subset for "what might be the next character". Perl code gives no such aid to the OCR. Type it in by hand.</p>
5
2010-03-10T16:56:02Z
[ "python", "ocr", "tesseract" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
2,418,817
<p>If I were you I'd start by cleaning up the image as much as possible, using a picture-manipulation program (GIMP, for example) so that the input for the OCR would be more easily understandable.</p> <p>If possible, aim for creating a black-and-white only image.</p>
7
2010-03-10T16:58:53Z
[ "python", "ocr", "tesseract" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
2,418,837
<p>You can probably type faster than you can clean up images and install OCR engines:</p> <pre><code>#!/usr/bin/perl (my$d=q[AA GTCAGTTCCT CGCTATGTA ACACACACCA TTTGTGAGT ATGTAACATA CTCGCTGGC TATGTCAGAC AGATTGATC GATCGATAGA ...
35
2010-03-10T17:00:10Z
[ "python", "ocr", "tesseract" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
2,418,850
<p>pre-processing will definitely yield a more workable image. </p> <p>For example, here is the result of Gimp "Levels", "Difference-of-Gaussians", and "Levels" filters on the image.</p> <p><img src="http://www.jkk.us.s3.amazonaws.com/FS7oo.gif" alt="alt text"></p>
15
2010-03-10T17:01:29Z
[ "python", "ocr", "tesseract" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
2,418,975
<p>Just a few small typos in RedDwight code.</p> <pre><code>#!/usr/bin/perl (my $d=q[AA GTCAGTTCCT CGCTATGTA ACACACACCA TTTGTGAGT ATGTAACATA CTCGCTGGC TATGTCAGAC AGATTGATC GATCGATAGA ATGATAGATC GAACGAGTGA ...
8
2010-03-10T17:17:13Z
[ "python", "ocr", "tesseract" ]
Extracting code from photograph of T-shirt via OCR
2,418,722
<p>I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:</p> <p><img src="http://i.imgur.com/FS7oo.jpg" alt="alt text"></p> <p>Next I tried to extract the code from the image via OCR, so I installed <a href="http://code.google.com/p/tesseract-ocr/">...
36
2010-03-10T16:43:36Z
8,955,872
<p>The key for a task like this is to take advantage of the evident constraints. Find a library that lets you specify your own character set. Require all the characters in the main DNA helices to be one of A T G C. Require that the whole thing parse as perl. Type in the hard parts by hand if necessary.</p>
0
2012-01-21T19:11:28Z
[ "python", "ocr", "tesseract" ]
OSX : Defining a new URL handler that points straight at a Python script
2,418,910
<p>I'm trying to define a new URL handler under OSX that will point at a python script.</p> <p>I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet)</p> <p>I've added the following into the applet's Info.plist:</p> <pre><code>&lt;key&gt;CFBundleURLTypes&lt;/k...
10
2010-03-10T17:09:33Z
2,499,107
<p>After a lot of messing around, I've managed to get this working under OSX...</p> <p>This is how I'm doing it:</p> <p>in the AppleScript Script Editor, write the following script:</p> <pre><code>on open location this_URL do shell script "/scripts/runLocalCommand.py '" &amp; this_URL &amp; "'" end open location...
11
2010-03-23T10:35:10Z
[ "python", "osx", "url", "handler" ]
RegExp in Python
2,419,147
<p>This is an example that searches PDF files in the current directory.</p> <pre><code>import os, os.path import re def print_pdf (arg, dir, files): for file in files: path = os.path.join(dir, file) path = os.path.normcase(path) if re.search(r".*\.pdf", path): print path os.path.walk('.', print_pdf, 0) </c...
0
2010-03-10T17:38:19Z
2,419,168
<p>it means any character zero or more times, followed by the literal dot and letters pdf (due to the greedy nature of the asterisk, it's basically guaranteed that the <code>'.pdf'</code> are going to be at the end of the subject string).</p> <p>There is <a href="http://docs.python.org/library/glob.html" rel="nofollow...
8
2010-03-10T17:41:41Z
[ "python", "regex" ]
RegExp in Python
2,419,147
<p>This is an example that searches PDF files in the current directory.</p> <pre><code>import os, os.path import re def print_pdf (arg, dir, files): for file in files: path = os.path.join(dir, file) path = os.path.normcase(path) if re.search(r".*\.pdf", path): print path os.path.walk('.', print_pdf, 0) </c...
0
2010-03-10T17:38:19Z
2,419,170
<p>The <code>.</code> means match any character but "\n". The <code>*</code> means "repeat the previous character 0 or more times". The <code>\.</code> matches an actual ".".</p> <p>BTW, this is all in <a href="http://docs.python.org/library/re.html" rel="nofollow">the docs</a>.</p>
2
2010-03-10T17:42:04Z
[ "python", "regex" ]
RegExp in Python
2,419,147
<p>This is an example that searches PDF files in the current directory.</p> <pre><code>import os, os.path import re def print_pdf (arg, dir, files): for file in files: path = os.path.join(dir, file) path = os.path.normcase(path) if re.search(r".*\.pdf", path): print path os.path.walk('.', print_pdf, 0) </c...
0
2010-03-10T17:38:19Z
2,419,173
<p>This searches for a string containing zero or more chars followed by ".pdf" The .* is a common idiom in regexps and it means match any char 0 or more times. The . is because in regexps, the . has a special meaning, and the \ escapes that.</p>
1
2010-03-10T17:42:15Z
[ "python", "regex" ]
RegExp in Python
2,419,147
<p>This is an example that searches PDF files in the current directory.</p> <pre><code>import os, os.path import re def print_pdf (arg, dir, files): for file in files: path = os.path.join(dir, file) path = os.path.normcase(path) if re.search(r".*\.pdf", path): print path os.path.walk('.', print_pdf, 0) </c...
0
2010-03-10T17:38:19Z
2,419,175
<blockquote> <p>Why <code>".*\"</code>?</p> </blockquote> <p>Wrong question, you missed a crucial character of the expression. ;-)</p> <p>In fact, <code>.*</code> will match <em>any</em> character (<code>.</code> in regex), <em>as many times as possible</em> (<code>*</code> in regex; relates to the previous string,...
3
2010-03-10T17:42:40Z
[ "python", "regex" ]
RegExp in Python
2,419,147
<p>This is an example that searches PDF files in the current directory.</p> <pre><code>import os, os.path import re def print_pdf (arg, dir, files): for file in files: path = os.path.join(dir, file) path = os.path.normcase(path) if re.search(r".*\.pdf", path): print path os.path.walk('.', print_pdf, 0) </c...
0
2010-03-10T17:38:19Z
2,419,197
<p><strong>The period (.)</strong><br> will match any character except newlines</p> <p><strong>The following asterisk (*)</strong><br> means unlimited number of repetitions of the preceding period</p> <p><strong>The backslash ()</strong><br> escapes the period in .pdf So it looks for a real period, so ONLY t...
0
2010-03-10T17:46:07Z
[ "python", "regex" ]
RegExp in Python
2,419,147
<p>This is an example that searches PDF files in the current directory.</p> <pre><code>import os, os.path import re def print_pdf (arg, dir, files): for file in files: path = os.path.join(dir, file) path = os.path.normcase(path) if re.search(r".*\.pdf", path): print path os.path.walk('.', print_pdf, 0) </c...
0
2010-03-10T17:38:19Z
2,421,710
<p>use <a href="http://docs.python.org/library/os.html" rel="nofollow">os.walk()</a> instead. And there's no need to use regex.</p> <pre><code>for r,d,f in os.walk(path): for files in f: if files[-4:].lower() == ".pdf": print "found pdf: ",os.path.join(r,files) </code></pre>
0
2010-03-11T00:23:14Z
[ "python", "regex" ]
Decorator class to test for required class variables
2,419,196
<p>First of all I don't know if this is the right approach. I want to write a decorator class that will be used with methods of other class. Before running the method I'd like to check if all required class variables are initialized. The ideal case would be something similar to this:</p> <pre><code>class Test(object):...
0
2010-03-10T17:45:54Z
2,419,242
<p>I'd say decorators are a bit unfit here for the purpose of checking if a variable exists.</p> <p>Think about what you're planning to do if the required variables are not supplied: raise an exception (it's in your comment). </p> <p>I'd say (based on the code above):</p> <pre><code>def sum(self): return self.a ...
1
2010-03-10T17:52:32Z
[ "python", "decorator" ]
Decorator class to test for required class variables
2,419,196
<p>First of all I don't know if this is the right approach. I want to write a decorator class that will be used with methods of other class. Before running the method I'd like to check if all required class variables are initialized. The ideal case would be something similar to this:</p> <pre><code>class Test(object):...
0
2010-03-10T17:45:54Z
2,419,816
<p>If you insist on checking before the decorated method's body starts, the following is one reasonable way to do it...:</p> <pre><code>import functools class test(object): def __init__(self, requiredvars): self.reqs = requiredvars.split() def __call__(self, f): @functools.wraps(f) de...
0
2010-03-10T19:17:16Z
[ "python", "decorator" ]
django deployment apache
2,419,279
<p>I would like to create a python script, which will:</p> <ol> <li>Create a django project in the current directory. Fix <code>settings.py</code>, <code>urls.py</code>.</li> <li>Do <code>syncdb</code></li> <li>Install new apache instance listening on specific port (command line argument), with WSGI configured to serv...
1
2010-03-10T17:58:00Z
2,420,797
<p>Jacob Kaplan Moss' Django Deployment Workshop assets have some nice examples. You'll probably still need to do some legwork on your end to automate things to your taste but there may be some stuff in there you can use as a starting point.</p> <p><a href="http://github.com/jacobian/django-deployment-workshop" rel="n...
1
2010-03-10T21:34:35Z
[ "python", "django", "apache", "deployment" ]
django deployment apache
2,419,279
<p>I would like to create a python script, which will:</p> <ol> <li>Create a django project in the current directory. Fix <code>settings.py</code>, <code>urls.py</code>.</li> <li>Do <code>syncdb</code></li> <li>Install new apache instance listening on specific port (command line argument), with WSGI configured to serv...
1
2010-03-10T17:58:00Z
2,446,808
<p>One way is to use Apache's mod_wsgi. After installing, you create a wsgi file and point Apache's config to it.</p> <p>Sample wsgi file:</p> <pre><code>import os import sys sys.path.append('/path/to/settings.py') os.environ['DJANGO_SETTINGS_MODULE'] = 'mydjangoapp.settings' import django.core.handlers.wsgi applic...
1
2010-03-15T11:48:06Z
[ "python", "django", "apache", "deployment" ]
Silence output from SimpleXMLRPCServer
2,419,405
<p>I am running an xml-rpc server using SimpleXMLRPCServer from the stdlib.</p> <p>My code looks something like this:</p> <pre><code>import SimpleXMLRPCServer import socket class RemoteStarter: def start(self): return 'foo' rs = RemoteStarter() host = socket.gethostbyaddr(socket.gethostname())[0] port =...
0
2010-03-10T18:16:01Z
2,428,336
<p>the answer is:</p> <p>pass <code>logRequests=False</code> to SimpleXMLRPCServer when you create it:</p> <pre><code>server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port), logRequests=False) </code></pre>
4
2010-03-11T20:15:18Z
[ "python", "xml-rpc" ]
Get function import path
2,419,416
<pre><code>from pack.mod import f </code></pre> <p>How to get from object f information about import - <code>'pack.mod'</code></p> <p>I can get it using <code>f.__module__</code> but if function def in module where i get this attribute (<code>f.__module__</code>) it return <code>'__main__'</code>. But i need real pat...
6
2010-03-10T18:17:51Z
2,419,541
<p>What <code>inspect.getmodule(f)</code> does internally, per <a href="http://svn.python.org/view/python/trunk/Lib/inspect.py?revision=75433&amp;view=markup">inspect.py's sources</a>, is essentially <code>sys.modules.get(object.__module__)</code> -- I wouldn't call using that code directly "more convenient", though (b...
8
2010-03-10T18:34:35Z
[ "python", "function", "import", "path" ]
Get function import path
2,419,416
<pre><code>from pack.mod import f </code></pre> <p>How to get from object f information about import - <code>'pack.mod'</code></p> <p>I can get it using <code>f.__module__</code> but if function def in module where i get this attribute (<code>f.__module__</code>) it return <code>'__main__'</code>. But i need real pat...
6
2010-03-10T18:17:51Z
18,712,381
<p>You want the <code>__name__</code> attribute from <code>__module__</code>:</p> <pre><code>In [16]: import inspect In [17]: inspect.getmodule(MyObject).__name__ Out[17]: 'lib.objects.MyObject' </code></pre>
1
2013-09-10T06:53:50Z
[ "python", "function", "import", "path" ]
PostgreSQL pgdb driver raises "can't rollback" exception
2,419,500
<p>for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:</p> <pre><code>try: cursors[instance].execute("lock revision, app, timeout IN SHARE MODE") cursors[instance].execute("insert into app (type, active, activ...
1
2010-03-10T18:28:45Z
2,419,621
<p>What happens if you exclude the lock statement?</p> <p>This is what's happening inside pgdb.py:</p> <pre><code>def rollback(self): """Roll back to the start of any pending transaction.""" if self._cnx: if self._tnx: self._tnx = False try: self._cnx.source().e...
0
2010-03-10T18:48:18Z
[ "python", "exception", "postgresql", "transactions" ]
PostgreSQL pgdb driver raises "can't rollback" exception
2,419,500
<p>for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:</p> <pre><code>try: cursors[instance].execute("lock revision, app, timeout IN SHARE MODE") cursors[instance].execute("insert into app (type, active, activ...
1
2010-03-10T18:28:45Z
2,419,631
<p>Where do you start the transaction? I do see a COMMIT but don't see a BEGIN or START TRANSACTION.</p>
0
2010-03-10T18:49:47Z
[ "python", "exception", "postgresql", "transactions" ]
PostgreSQL pgdb driver raises "can't rollback" exception
2,419,500
<p>for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:</p> <pre><code>try: cursors[instance].execute("lock revision, app, timeout IN SHARE MODE") cursors[instance].execute("insert into app (type, active, activ...
1
2010-03-10T18:28:45Z
2,427,335
<p>You are looking in the wrong place. What does the PostgreSQL log say about what you are doing?</p>
1
2010-03-11T17:48:22Z
[ "python", "exception", "postgresql", "transactions" ]
How do you position a wx.MessageDialog (wxPython)?
2,419,619
<p>Is there any reason why the position, pos, flag doesn't seem to work in the following example?</p> <pre><code>dlg = wx.MessageDialog( parent=self, message='You must enter a URL', caption='Error', style=wx.OK | wx.ICON_ERROR | wx.STAY_ON_TOP, pos=(200,200) ) dlg.ShowModal() dlg.Destroy() </code>...
0
2010-03-10T18:48:15Z
2,437,372
<p>It seems to be a bug and i think you should file the same. for time being you can user your own dervied dialog class to center it as you wish. Also instead of wx.MessageDialog you can use wx.MessageBox, it will save you few lines.</p>
0
2010-03-13T05:31:07Z
[ "python", "windows", "wxpython" ]
Using Python & XML-RPC to add a custom field to a Wordpress post?
2,419,768
<p>I want to add an 'enclosure' custom field to an existing Wordpress post using Python &amp; XML-RPC.</p> <p>My code looks like this:</p> <pre><code>def add_enclosure(server, post_id, enclosure): post_data = server.metaWeblog.getPost(post_id, username, password) custom_fields = post_data['custom_fields'] ...
1
2010-03-10T19:11:16Z
4,943,981
<p>Custom fields are a set of key/value pairs that look like:</p> <pre><code>"custom_fields" = ( {key = city; value = Sacramento; }, {key = city; value = Sandy; } ) </code></pre> <p>Try fetching post data with <code>metaWeblog.getPost</code> for a post that already has custom fields and you'll see...
0
2011-02-09T11:03:38Z
[ "python", "wordpress", "xml-rpc" ]
How to get one value from a generator in Python?
2,419,770
<p>Very basic question - how to get one value from a generator in Python?</p> <p>So far I found I can get one by writing <code>gen.next()</code>. I just want to make sure this is the right way?</p>
40
2010-03-10T19:11:28Z
2,419,780
<p>This is the correct way to do it.</p> <p>You can also use <code>next(gen)</code>.</p> <p><a href="http://docs.python.org/library/functions.html#next">http://docs.python.org/library/functions.html#next</a></p>
7
2010-03-10T19:13:00Z
[ "python", "generator" ]
How to get one value from a generator in Python?
2,419,770
<p>Very basic question - how to get one value from a generator in Python?</p> <p>So far I found I can get one by writing <code>gen.next()</code>. I just want to make sure this is the right way?</p>
40
2010-03-10T19:11:28Z
2,419,782
<p>Yes, or <code>next(gen)</code> in 2.6+.</p>
50
2010-03-10T19:13:03Z
[ "python", "generator" ]
How to get one value from a generator in Python?
2,419,770
<p>Very basic question - how to get one value from a generator in Python?</p> <p>So far I found I can get one by writing <code>gen.next()</code>. I just want to make sure this is the right way?</p>
40
2010-03-10T19:11:28Z
2,421,288
<p>In Python &lt;= 2.5, use <code>gen.next()</code>. This will work for all Python 2.x versions, but not Python 3.x</p> <p>In Python >= 2.6, use <code>next(gen)</code>. This is a built in function, and is clearer. It will also work in Python 3.</p> <p>Both of these end up calling a specially named function, <code>nex...
29
2010-03-10T22:54:12Z
[ "python", "generator" ]
How to get one value from a generator in Python?
2,419,770
<p>Very basic question - how to get one value from a generator in Python?</p> <p>So far I found I can get one by writing <code>gen.next()</code>. I just want to make sure this is the right way?</p>
40
2010-03-10T19:11:28Z
37,890,506
<p>In python 3 you don't have gen.next(), but you still can use next(gen). A bit bizarre if you ask me but that's how it is.</p>
0
2016-06-17T21:17:56Z
[ "python", "generator" ]
How to get one value from a generator in Python?
2,419,770
<p>Very basic question - how to get one value from a generator in Python?</p> <p>So far I found I can get one by writing <code>gen.next()</code>. I just want to make sure this is the right way?</p>
40
2010-03-10T19:11:28Z
39,541,906
<p>Use (for python 3)</p> <pre><code>next(generator) </code></pre> <p>Here is an example</p> <pre><code>def fun(x): n = 0 while n &lt; x: yield n n += 1 z = fun(10) next(z) next(z) </code></pre> <p>should print</p> <pre><code>0 1 </code></pre>
0
2016-09-17T01:00:47Z
[ "python", "generator" ]
Open Windows shared folder trought linux machine
2,419,953
<p>I am using python 2.5 on Ubuntu, and there's a machine in the same network called <code>machine1</code>. The folder is shared.</p> <p>How to to get a file in a specific folder of that machine?</p> <p>I have tried, with no success:</p> <pre><code>urllib.urlopen('\\machine1\folder\file.txt') </code></pre>
1
2010-03-10T19:38:18Z
2,420,004
<p>You should look for the default file browser.</p> <p>And then you can execute the process and pass in the folder you want as an argument (smb://machine1/folder/).</p> <p>For example on windows you would do:</p> <pre><code>execl("explorer.exe", "D:") </code></pre> <p>Try to look for the path to your file browser ...
-1
2010-03-10T19:44:37Z
[ "python", "urllib" ]
Open Windows shared folder trought linux machine
2,419,953
<p>I am using python 2.5 on Ubuntu, and there's a machine in the same network called <code>machine1</code>. The folder is shared.</p> <p>How to to get a file in a specific folder of that machine?</p> <p>I have tried, with no success:</p> <pre><code>urllib.urlopen('\\machine1\folder\file.txt') </code></pre>
1
2010-03-10T19:38:18Z
2,420,080
<p><code>urllib</code> does not understand the SMB protocol. You will need to use <a href="http://library.gnome.org/devel/gio/unstable/" rel="nofollow"><code>gio</code></a> via pygobject in order to retrieve the file.</p>
1
2010-03-10T19:56:05Z
[ "python", "urllib" ]
Open Windows shared folder trought linux machine
2,419,953
<p>I am using python 2.5 on Ubuntu, and there's a machine in the same network called <code>machine1</code>. The folder is shared.</p> <p>How to to get a file in a specific folder of that machine?</p> <p>I have tried, with no success:</p> <pre><code>urllib.urlopen('\\machine1\folder\file.txt') </code></pre>
1
2010-03-10T19:38:18Z
2,420,168
<p>Linux has a utiliy called <code>smbmount</code>, which can be found in package smbutils I believe.</p> <p>This is a command line utility which mounts a Windows share to a directory on the local machine, optionally with username/password.</p> <p>smbmount is I believe a utility which runs as root, so whether it's su...
2
2010-03-10T20:05:04Z
[ "python", "urllib" ]
Open Windows shared folder trought linux machine
2,419,953
<p>I am using python 2.5 on Ubuntu, and there's a machine in the same network called <code>machine1</code>. The folder is shared.</p> <p>How to to get a file in a specific folder of that machine?</p> <p>I have tried, with no success:</p> <pre><code>urllib.urlopen('\\machine1\folder\file.txt') </code></pre>
1
2010-03-10T19:38:18Z
2,420,173
<p>If the folder is shared, I think it should be mounted in ~/.gvfs. Perhaps you can simply use <code>open</code> on the path as you see it in ~/.gvfs.</p>
0
2010-03-10T20:05:36Z
[ "python", "urllib" ]
DNA sequence alignement in native Python (no biopython)
2,420,035
<p>I have an interesting genetics problem that I would like to solve in native Python (nothing outside the standard library). This in order for the solution to be very easy to use on any computer, without requiring the user to install additional modules.</p> <p>Here it is. I received 100,000s of DNA sequences (up to 2...
1
2010-03-10T19:50:29Z
2,420,073
<p>Here's a paper on approximately that subject:</p> <p><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.56.7569" rel="nofollow">Rocke, On finding novel gapped motifs in DNA sequences, 1998</a>.</p> <p>Hopefully from that paper and its references, plus other papers which cite the above, you can find m...
1
2010-03-10T19:55:25Z
[ "python", "alignment", "dna-sequence", "genetics" ]
DNA sequence alignement in native Python (no biopython)
2,420,035
<p>I have an interesting genetics problem that I would like to solve in native Python (nothing outside the standard library). This in order for the solution to be very easy to use on any computer, without requiring the user to install additional modules.</p> <p>Here it is. I received 100,000s of DNA sequences (up to 2...
1
2010-03-10T19:50:29Z
2,421,342
<p>Researching that algorithm briefly, this is not easy stuff. This is going to take some very serious algorithm work. Try re-aligning your expectations from "hours" to "days or weeks".</p> <p>The programmer implementing this will need:</p> <ul> <li>High competence in general python programming</li> <li>Algorithm pro...
1
2010-03-10T23:04:07Z
[ "python", "alignment", "dna-sequence", "genetics" ]
DNA sequence alignement in native Python (no biopython)
2,420,035
<p>I have an interesting genetics problem that I would like to solve in native Python (nothing outside the standard library). This in order for the solution to be very easy to use on any computer, without requiring the user to install additional modules.</p> <p>Here it is. I received 100,000s of DNA sequences (up to 2...
1
2010-03-10T19:50:29Z
3,683,046
<p>You could do this quite simply using regex? I don't think it would be that complicated! In fact, I have just completed some code to do something pretty much the same as this for one of the guys at the university here!</p> <p>If not looking for exact copies of the primers, due to mutation then an element of fuzzy ma...
1
2010-09-10T08:01:41Z
[ "python", "alignment", "dna-sequence", "genetics" ]
Django: create HTML input array using a django form
2,420,094
<p>I am trying to automate the creation of something like this:</p> <pre><code>&lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; </code></pre> <p>By cycling through a range in the form. I've been trying things like this, along with several ot...
6
2010-03-10T19:57:42Z
2,420,183
<p>It should be more like e.g.:</p> <pre><code># in a model class for i in range(1, prim+1): self.fields['asdf_%s' % i] = forms.CharField(label='Label %i' % i) </code></pre> <p>But it very depends on what you want to achieve.</p>
1
2010-03-10T20:06:41Z
[ "python", "django", "django-forms" ]
Django: create HTML input array using a django form
2,420,094
<p>I am trying to automate the creation of something like this:</p> <pre><code>&lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; </code></pre> <p>By cycling through a range in the form. I've been trying things like this, along with several ot...
6
2010-03-10T19:57:42Z
2,420,285
<p>Jacob Kaplan-Moss (co-author of Django) recently posted a great article for handling dynamic forms, which should solve your problem in a preferred way: <a href="http://jacobian.org/writing/dynamic-form-generation/" rel="nofollow">http://jacobian.org/writing/dynamic-form-generation/</a></p> <p>He's using the same me...
6
2010-03-10T20:20:54Z
[ "python", "django", "django-forms" ]
Django: create HTML input array using a django form
2,420,094
<p>I am trying to automate the creation of something like this:</p> <pre><code>&lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; </code></pre> <p>By cycling through a range in the form. I've been trying things like this, along with several ot...
6
2010-03-10T19:57:42Z
2,420,361
<p>It looks like I can do what I need to do by breaking the form into multiple formsets...</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets</a></p> <p>Then, I should be ab...
0
2010-03-10T20:32:29Z
[ "python", "django", "django-forms" ]
How does OS handle a python dict that's larger than memory?
2,420,219
<p>I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computation...
3
2010-03-10T20:11:32Z
2,420,257
<p>You need a database, if the data will exceed memory. The indexing of dictionaries isn't designed for good performance when a dictionary is bigger than memory.</p>
5
2010-03-10T20:17:03Z
[ "python", "memory", "data-structures", "matrix", "swap" ]
How does OS handle a python dict that's larger than memory?
2,420,219
<p>I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computation...
3
2010-03-10T20:11:32Z
2,420,259
<p>Swap space is a kernel feature and transparant to the user (python).</p> <p>If you do have a huge dict and don't need all the data at once, you could look at <a href="http://code.google.com/p/redis/" rel="nofollow">redis</a> which might do what you want. Or maybe not :)</p>
1
2010-03-10T20:17:17Z
[ "python", "memory", "data-structures", "matrix", "swap" ]
How does OS handle a python dict that's larger than memory?
2,420,219
<p>I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computation...
3
2010-03-10T20:11:32Z
2,420,260
<p>It will just end up in swap trashing, because a hash table has very much randomized memory access patterns.</p> <p>If you know that the map exceeds the size of the physical memory, you could consider using a data structure on the disk in the first place. This especially if you don't need the data structure during t...
0
2010-03-10T20:17:29Z
[ "python", "memory", "data-structures", "matrix", "swap" ]
How does OS handle a python dict that's larger than memory?
2,420,219
<p>I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computation...
3
2010-03-10T20:11:32Z
2,420,271
<p>As far as I can remember, when a dict is expanded it just relies on C's malloc. The program will keep running as long as malloc keeps succeeding. Most OS's will keep malloc working as long as there is enough memory, and then as long as there are pages that can be swapped in. In either case Python will throw a Mem...
0
2010-03-10T20:19:33Z
[ "python", "memory", "data-structures", "matrix", "swap" ]
Python String with HTML /
2,420,246
<p>I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.</p> <p>The code:</p> <pre><code>c.send( str.encode("&lt;HTML&gt;&lt;BODY&gt;Test Page&lt;///BODY&gt;&lt;///HTML&gt;") ) </code></pre> <p>My python client receives: </p> <pre><code>b'&lt;HTML&gt;&lt;BODY&gt;Test P...
0
2010-03-10T20:15:36Z
2,420,267
<p>You want <code>'...'.encode()</code> and <code>b'...'.decode()</code>. Saying "str.encode" is shorthand for saying that all str literals have this method.</p>
0
2010-03-10T20:18:13Z
[ "python", "html", "string", "decode" ]
Python String with HTML /
2,420,246
<p>I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.</p> <p>The code:</p> <pre><code>c.send( str.encode("&lt;HTML&gt;&lt;BODY&gt;Test Page&lt;///BODY&gt;&lt;///HTML&gt;") ) </code></pre> <p>My python client receives: </p> <pre><code>b'&lt;HTML&gt;&lt;BODY&gt;Test P...
0
2010-03-10T20:15:36Z
2,420,453
<p>The extra '/' is wrong. You only need to worry about escaping for '\'</p>
-1
2010-03-10T20:46:29Z
[ "python", "html", "string", "decode" ]