title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Django: how to include the file?
1,550,601
<p>I have a Django Application. I want to have all my models to be separated in files and lay in the specific directory, for instance:</p> <pre><code>/usr/project/models/myModel.py </code></pre> <p>Is it any possible? Just importing through from myModel import * doesn't work, unfortunately.</p> <p>Is there any speci...
0
2009-10-11T12:37:46Z
1,550,634
<p>You can split your models into separate files, it's just Python code. </p>
0
2009-10-11T12:54:17Z
[ "python", "django-urls" ]
Django: how to include the file?
1,550,601
<p>I have a Django Application. I want to have all my models to be separated in files and lay in the specific directory, for instance:</p> <pre><code>/usr/project/models/myModel.py </code></pre> <p>Is it any possible? Just importing through from myModel import * doesn't work, unfortunately.</p> <p>Is there any speci...
0
2009-10-11T12:37:46Z
1,550,685
<p>Create file <code>/usr/project/models/__init__.py</code> containing <code>from myModel import *</code>. <code>__init__.py</code> file is required to make directory a python package.</p>
1
2009-10-11T13:23:18Z
[ "python", "django-urls" ]
web2py SQLTABLE - How can I transpose the table?
1,550,707
<p>I am using:</p> <pre><code>rows = db(db.member.membership_id==request.args[0]).select(db.member.membership_id, db.member.first_name, db.member.middle_name, db.member.last_name, db.member.birthdate, db.member.registration_date, db.member.membership_end_date) rows.colnames = ('Membership Id',...
2
2009-10-11T13:35:25Z
1,551,021
<p>Try this:</p> <pre><code>rows=db(query).select(*fields).as_list() if rows: table=TABLE(*[TR(TH(field),*[TD(row[field]) for row in rows]) \ for field in row[0].keys()]) else: table="nothing to see here" return dict(table=table) </code></pre>
1
2009-10-11T15:59:28Z
[ "python", "web2py" ]
Dynamically importing modules in Python3.0?
1,551,063
<p>I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an <code>ImportError</code> and tells me my module doesn't exist.</p> <p>First I get the list of module filenames and chop off the <code>".py"</code> suffixes, like so:</p> <pre><code>viable_plugins = filter(is...
2
2009-10-11T16:17:17Z
1,551,073
<p>It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path.</p> <p>What you need to do, instead of changing to the directory where the modules are located, is to insert that directory into <code>sys.path</code>.</p> <pre><code>impor...
7
2009-10-11T16:21:31Z
[ "python", "import", "python-3.x" ]
Knight's Tour using a Neural Network
1,551,157
<p>I was looking at the knights tour problem and decided to have a go at implementing it in python using a neural network to find solutions.</p> <p>The general explanation of the method can be found on <a href="http://en.wikipedia.org/wiki/Knight%27s_tour#Neural_network_solutions" rel="nofollow">Wikipedia</a></p> <p>...
2
2009-10-11T16:57:09Z
1,551,427
<p>First impression is that you only have one buffer for the board. I'm basing this on the fact that I don't see any buffer swaps between iterations - I haven't looked that closely and may easily be wrong.</p> <p>If you modify a single buffer in place, when you do the neighbour counts, you base them on a partly modifi...
2
2009-10-11T18:47:02Z
[ "python", "graph", "neural-network" ]
Knight's Tour using a Neural Network
1,551,157
<p>I was looking at the knights tour problem and decided to have a go at implementing it in python using a neural network to find solutions.</p> <p>The general explanation of the method can be found on <a href="http://en.wikipedia.org/wiki/Knight%27s_tour#Neural_network_solutions" rel="nofollow">Wikipedia</a></p> <p>...
2
2009-10-11T16:57:09Z
1,551,547
<p>You can't update the neurons in place. Since U[t+1] depends on U[t] and V[t], if you have already updated V the calculation for U will be wrong</p> <p>I think you should split the update into two phases update_state and update_output, so all the U are updated and then all the V</p> <pre><code> for n in neurons:...
3
2009-10-11T19:34:35Z
[ "python", "graph", "neural-network" ]
Knight's Tour using a Neural Network
1,551,157
<p>I was looking at the knights tour problem and decided to have a go at implementing it in python using a neural network to find solutions.</p> <p>The general explanation of the method can be found on <a href="http://en.wikipedia.org/wiki/Knight%27s_tour#Neural_network_solutions" rel="nofollow">Wikipedia</a></p> <p>...
2
2009-10-11T16:57:09Z
8,369,821
<p>After looking over your code, I think your explanation for the formula you used may be incorrect. You say that when updating the state you add four rather than two and subtract the output of the neuron itself. It looks to me like you're subtracting the output of the neuron itself twice. Your code which finds neig...
0
2011-12-03T18:15:35Z
[ "python", "graph", "neural-network" ]
Extracting text fields from HTML using Python?
1,551,293
<p>what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?</p> <pre><code>&lt;/tr&gt;&lt;tr class="tableRowOdd"&gt; &lt;td&gt;"JSC company inc. 00" &amp;lt;email@email.com&amp;gt;&lt;/td&gt; ...
0
2009-10-11T17:58:30Z
1,551,312
<p>For extracting and general HTML munging look at</p> <pre><code>http://www.crummy.com/software/BeautifulSoup/ </code></pre> <p>For the MySQL I suggest googling on: MySQL tutorial python </p>
6
2009-10-11T18:07:22Z
[ "python", "text" ]
Extracting text fields from HTML using Python?
1,551,293
<p>what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?</p> <pre><code>&lt;/tr&gt;&lt;tr class="tableRowOdd"&gt; &lt;td&gt;"JSC company inc. 00" &amp;lt;email@email.com&amp;gt;&lt;/td&gt; ...
0
2009-10-11T17:58:30Z
1,551,358
<p>Here is how you get the <code>td</code> contents into a python list using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow"><code>BeautifulSoup</code></a>:</p> <pre><code>#!/usr/bin/python from BeautifulSoup import BeautifulSoup, SoupStrainer def find_rows(data): table_rows = SoupStrainer(...
1
2009-10-11T18:22:37Z
[ "python", "text" ]
Extracting text fields from HTML using Python?
1,551,293
<p>what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?</p> <pre><code>&lt;/tr&gt;&lt;tr class="tableRowOdd"&gt; &lt;td&gt;"JSC company inc. 00" &amp;lt;email@email.com&amp;gt;&lt;/td&gt; ...
0
2009-10-11T17:58:30Z
1,552,640
<p>For the parsing, I definitely also recommend <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>.</p> <p>To put the text in a database, I recommend a good Python ORM. My top suggestion is to use the ORM from <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, if...
1
2009-10-12T04:03:09Z
[ "python", "text" ]
Extracting text fields from HTML using Python?
1,551,293
<p>what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?</p> <pre><code>&lt;/tr&gt;&lt;tr class="tableRowOdd"&gt; &lt;td&gt;"JSC company inc. 00" &amp;lt;email@email.com&amp;gt;&lt;/td&gt; ...
0
2009-10-11T17:58:30Z
1,552,698
<p>With <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> you can do it almost as easily as you could do it with jQuery.</p> <pre><code>from lxml import html doc = html.parse('test.html').getroot() for row in doc.cssselect('tr'): name, phone_number = row.cssselect('td')[:2] print name.text_content(...
1
2009-10-12T04:27:37Z
[ "python", "text" ]
Extracting text fields from HTML using Python?
1,551,293
<p>what is the best way to extract data from this HTML file and put it into MySQL database with company phone number, company name and email with a primary key as phone number?</p> <pre><code>&lt;/tr&gt;&lt;tr class="tableRowOdd"&gt; &lt;td&gt;"JSC company inc. 00" &amp;lt;email@email.com&amp;gt;&lt;/td&gt; ...
0
2009-10-11T17:58:30Z
1,552,790
<p>+1 for BeautifulSoup</p> <p>Now that you've got the data, you need to put it into MySQL. If you want a pure python solution, you'll also need the <a href="http://mysql-python.sourceforge.net/" rel="nofollow">MySQL-Python</a> binding. </p> <p>Otherwise, the SQL you'll need to generate is relatively painless. We'...
0
2009-10-12T04:58:58Z
[ "python", "text" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
1,551,394
<p><a href="http://evaisse.com/post/93417709/python-pretty-date-function" rel="nofollow" title="Python Pretty Date function">Yes, there is</a>. Or, write your own and tailor it to your needs.</p> <hr> <p>The function (as the blog author deleted it).</p> <pre><code>def pretty_date(time=False): """ Get a datet...
93
2009-10-11T18:32:06Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
2,611,952
<p>In looking for the same thing with the additional requirement that it handle future dates, I found this: <a href="http://pypi.python.org/pypi/py-pretty/1">http://pypi.python.org/pypi/py-pretty/1</a></p> <p>Example code (from site):</p> <pre><code>from datetime import datetime, timedelta now = datetime.now() hrago...
14
2010-04-10T02:03:36Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
2,718,322
<p>I have written a detailed blog post for the solution on <a href="http://sunilarora.org/17329071" rel="nofollow">http://sunilarora.org/17329071</a> I am posting a quick snippet here as well.</p> <pre><code>from datetime import datetime from dateutil.relativedelta import relativedelta def get_fancy_time(d, display_f...
1
2010-04-27T02:19:41Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
9,969,729
<p>If you happen to be using <a href="https://www.djangoproject.com/">Django</a>, then new in version 1.4 is the <code>naturaltime</code> template filter.</p> <p>To use it, first add <code>'django.contrib.humanize'</code> to your <code>INSTALLED_APPS</code> setting in settings.py, and <code>{% load humanize %}</code> ...
27
2012-04-02T00:49:46Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
11,709,931
<p>The <a href="https://pypi.python.org/pypi/ago" rel="nofollow">ago</a> package provides this. Call <code>human</code> on a <code>datetime</code> object to get a human readable description of the difference. </p> <pre><code>from ago import human from datetime import datetime from datetime import timedelta ts = date...
5
2012-07-29T14:18:37Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
18,421,524
<p>The answer Jed Smith linked to is good, and I used it for a year or so, but I think it could be improved in a few ways:</p> <ul> <li>It's nice to be able to define each time unit in terms of the preceding unit, instead of having "magic" constants like 3600, 86400, etc. sprinkled throughout the code.</li> <li>After ...
3
2013-08-24T17:58:48Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
27,671,515
<p>This is the gist of @sunil 's post</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; from dateutil.relativedelta import relativedelta &gt;&gt;&gt; then = datetime(2003, 9, 17, 20, 54, 47, 282310) &gt;&gt;&gt; relativedelta(then, datetime.now()) relativedelta(years=-11, months=-3, days=-9, hours...
0
2014-12-27T21:13:24Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
27,674,340
<p>There is <a href="https://pypi.python.org/pypi/humanize" rel="nofollow"><code>humanize</code> package</a>:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; import humanize # $ pip install humanize &gt;&gt;&gt; humanize.naturaltime(datetime.now() - timedelta(days=1)) 'a day ago' &gt;...
3
2014-12-28T07:00:52Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
33,925,074
<p>Using datetime objects with tzinfo:</p> <pre><code>def time_elapsed(etime): # need to add tzinfo to datetime.utcnow now = datetime.datetime.utcnow().replace(tzinfo=etime.tzinfo) opened_for = (now - etime).total_seconds() names = ["seconds","minutes","hours","days","weeks","months"] modulos = [ 1...
0
2015-11-25T19:38:36Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
38,221,895
<p>You can download and install from below link. It should be more helpful for you. It has been providing user friendly message from second to year.</p> <p>It's well tested.</p> <p><a href="https://github.com/nareshchaudhary37/timestamp_content" rel="nofollow">https://github.com/nareshchaudhary37/timestamp_content</a...
0
2016-07-06T10:33:26Z
[ "python", "datetime", "date", "time", "formatting" ]
User-friendly time format in Python?
1,551,382
<p>Python: I need to show file modification times in the "1 day ago", "two hours ago", format.</p> <p>Is there something ready to do that? It should be in English.</p>
49
2009-10-11T18:28:45Z
39,749,283
<p>You can also do that with <a href="https://arrow.readthedocs.io/en/latest/" rel="nofollow">arrow</a> package</p> <p>From <a href="https://github.com/crsmithdev/arrow" rel="nofollow">github page</a>:</p> <blockquote> <pre><code>&gt;&gt;&gt; import arrow &gt;&gt;&gt; utc = arrow.utcnow() &gt;&gt;&gt; utc = utc.repla...
1
2016-09-28T13:41:12Z
[ "python", "datetime", "date", "time", "formatting" ]
Using Python locale or equivalent in web applications?
1,551,508
<p>Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.</p> <p>And there are warnings in the <a href="h...
3
2009-10-11T19:20:00Z
1,551,542
<p>Your best approach will be to <code>setlocale</code> on the locale that the browser passes you, if you're doing currencies, dates, and numbers. There's a lot of zomgz warnings in the Python documentation for really off-color platforms; most of these can be ignored.</p> <p>"Frequent locale changes" shouldn't matter...
0
2009-10-11T19:32:59Z
[ "python", "django", "internationalization" ]
Using Python locale or equivalent in web applications?
1,551,508
<p>Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.</p> <p>And there are warnings in the <a href="h...
3
2009-10-11T19:20:00Z
1,551,600
<p><strong>Don't use setlocale.</strong></p> <p>Check how it is done in <a href="http://docs.djangoproject.com/en/dev/topics/i18n/" rel="nofollow">django</a>. It looks like they use class api of gettext library and do not use the setlocale function I bet there is a reason for this.</p> <p>They manually store a <a hre...
1
2009-10-11T19:57:52Z
[ "python", "django", "internationalization" ]
Using Python locale or equivalent in web applications?
1,551,508
<p>Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.</p> <p>And there are warnings in the <a href="h...
3
2009-10-11T19:20:00Z
1,551,834
<p><code>locale</code> is no good for any app that needs to support several locales -- it's really badly designed for those apps (basically any server-side app, including web apps). Where feasible, <a href="http://pyicu.osafoundation.org/">PyICU</a> is a <em>vastly</em> superior solution -- top-quality i18n/L10n suppo...
9
2009-10-11T21:31:34Z
[ "python", "django", "internationalization" ]
Using Python locale or equivalent in web applications?
1,551,508
<p>Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.</p> <p>And there are warnings in the <a href="h...
3
2009-10-11T19:20:00Z
1,554,811
<p>Django's i18n framework works out the shortcomings of <code>setlocale()</code> by not using it. This way the locale is set per request and if you use <code>LocaleMiddleware</code> it can be set to change according to UserAgent <code>Accept-Language</code> setting. See the <a href="http://docs.djangoproject.com/en/de...
0
2009-10-12T14:10:27Z
[ "python", "django", "internationalization" ]
python: parse HTTP POST request w/file upload and additional params
1,551,552
<p>The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters.</p> <p>I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chunk.</p> <p>All methods I found are based on cgi.FieldStorage,...
3
2009-10-11T19:36:45Z
1,551,594
<p>It seems counter-intuitive (and I feel that the module is poorly-named), but <code>email</code> will likely do what you want. I've never used it, but a coworker has in an e-mail processing system; since these messages are simply RFC 2822 in nature, <code>email</code> will probably parse them.</p> <p><a href="http:...
1
2009-10-11T19:55:56Z
[ "python", "upload", "wsgi" ]
python: parse HTTP POST request w/file upload and additional params
1,551,552
<p>The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters.</p> <p>I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chunk.</p> <p>All methods I found are based on cgi.FieldStorage,...
3
2009-10-11T19:36:45Z
1,551,614
<p>As you suggested, I would (and have done before) override the <code>make_file</code> method of a <code>FieldStorage</code> object. Just return an object which has a <code>write</code> method that both accepts the data (into a file or memory or what-have-you) and tracks how much has been received for your progress in...
2
2009-10-11T20:01:45Z
[ "python", "upload", "wsgi" ]
python: parse HTTP POST request w/file upload and additional params
1,551,552
<p>The task is simple: on the server side (python) accept an HTTP POST which contains an uploaded file and more form parameters.</p> <p>I am trying to implement upload progress indicator, and therefore I need to be able to read the file content chunk-by-chunk.</p> <p>All methods I found are based on cgi.FieldStorage,...
3
2009-10-11T19:36:45Z
1,551,732
<p>You might want to take a look at what Django has done. They have a really nice implementation of custom file upload handlers, which allows you to subclass them to enable things like progress bars etc. See <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers" rel="nofollow">the docu...
0
2009-10-11T20:48:41Z
[ "python", "upload", "wsgi" ]
How to perform this RegExp in Python?
1,552,124
<p>I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00</p> <p>+33 is the indicatif it could be 2 or 3 digits length.</p> <p>Digits after the . are the phone number. It could be 9 or 10 digits length.</p> <p>I try like this :</p> <pre><code>p = re.compile( "\+[0-9]+\.([0-9]+)", re.V...
0
2009-10-11T23:50:59Z
1,552,143
<p>In the terminal it works like that :</p> <pre><code>p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE) number = "+33.300000000" p.sub("0\\1", number) </code></pre> <p>And in the python script it works like that :</p> <pre><code>p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE) number = "+33.300000000" p.sub("0\1",...
0
2009-10-11T23:59:44Z
[ "python", "string" ]
How to perform this RegExp in Python?
1,552,124
<p>I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00</p> <p>+33 is the indicatif it could be 2 or 3 digits length.</p> <p>Digits after the . are the phone number. It could be 9 or 10 digits length.</p> <p>I try like this :</p> <pre><code>p = re.compile( "\+[0-9]+\.([0-9]+)", re.V...
0
2009-10-11T23:50:59Z
1,552,161
<p>The simplest approach is a mix of RE and pure string manipulation, e.g.:</p> <pre><code>import re def doitall(number): # get 9 or 10 digits, or None: mo = re.search(r'\d{9,10}', number) if mo is None: return None # add a leading 0 if they were just 9 digits = ('0' + mo.group())[-10:] # now put a dot af...
3
2009-10-12T00:09:04Z
[ "python", "string" ]
Rules of thumb for when to use operator overloading in python
1,552,260
<p>From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading <code>+</code> you probably also want to overload <code>++</code> and <code>+=</code>, and also make sure to handle end c...
10
2009-10-12T01:00:03Z
1,552,267
<p>I've written software with significant amounts of overloading, and lately I regret that policy. I would say this:</p> <p><strong>Only overload operators if it's the natural, expected thing to do and doesn't have any side effects.</strong></p> <p>So if you make a new <code>RomanNumeral</code> class, it makes sense ...
12
2009-10-12T01:04:38Z
[ "python", "operator-overloading" ]
Rules of thumb for when to use operator overloading in python
1,552,260
<p>From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading <code>+</code> you probably also want to overload <code>++</code> and <code>+=</code>, and also make sure to handle end c...
10
2009-10-12T01:00:03Z
1,552,285
<p>Python's overloading is "safer" in general than C++'s -- for example, the assignment operator can't be overloaded, and <code>+=</code> has a sensible default implementation.</p> <p>In some ways, though, overloading in Python is still as "broken" as in C++. Programmers should restrain the desire to "re-use" an opera...
3
2009-10-12T01:15:43Z
[ "python", "operator-overloading" ]
Rules of thumb for when to use operator overloading in python
1,552,260
<p>From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading <code>+</code> you probably also want to overload <code>++</code> and <code>+=</code>, and also make sure to handle end c...
10
2009-10-12T01:00:03Z
1,552,292
<p>Here is an example that uses the bitwise or operation to simulate a unix pipeline. This is intended as a counter example to most of the rules of thumb.</p> <p>I just found <a href="http://code.zacharyvoase.com/lumberjack/src/" rel="nofollow">Lumberjack</a> which uses this syntax in real code</p> <pre><code> class...
5
2009-10-12T01:21:40Z
[ "python", "operator-overloading" ]
Rules of thumb for when to use operator overloading in python
1,552,260
<p>From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading <code>+</code> you probably also want to overload <code>++</code> and <code>+=</code>, and also make sure to handle end c...
10
2009-10-12T01:00:03Z
1,552,299
<p>Operator overloading is mostly useful when you're making a new class that falls into an existing "Abstract Base Class" (ABC) -- indeed, many of the ABCs in standard library module <a href="http://docs.python.org/library/collections.html#module-collections">collections</a> rely on the presence of certain special meth...
21
2009-10-12T01:23:07Z
[ "python", "operator-overloading" ]
Is there a cleaner way to chain empty list checks in Python?
1,552,310
<p>I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:</p> <pre><code>if a.get("key") and a["key"][0] and a["key"][0][0] : for b in a["key"][0][0] : ...
3
2009-10-12T01:28:33Z
1,552,313
<pre><code>try: bs = a["key"][0][0] # Note: the syntax for catching exceptions is different in old versions # of Python. Use whichever one of these lines is appropriate to your version. except KeyError, IndexError, TypeError: # Python 3 except (KeyError, IndexError, TypeError): # Python 2 bs = [] for b in bs: </c...
14
2009-10-12T01:30:17Z
[ "python", "coding-style" ]
Is there a cleaner way to chain empty list checks in Python?
1,552,310
<p>I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:</p> <pre><code>if a.get("key") and a["key"][0] and a["key"][0][0] : for b in a["key"][0][0] : ...
3
2009-10-12T01:28:33Z
1,552,314
<p>What about this:</p> <pre><code>try: for b in a['key'][0][0]: # do stuff. except KeyError, TypeError, IndexError: # respond appropriately. </code></pre>
2
2009-10-12T01:30:29Z
[ "python", "coding-style" ]
Is there a cleaner way to chain empty list checks in Python?
1,552,310
<p>I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:</p> <pre><code>if a.get("key") and a["key"][0] and a["key"][0][0] : for b in a["key"][0][0] : ...
3
2009-10-12T01:28:33Z
1,552,320
<p>I would write a custom indexer function like this:</p> <pre><code>def safe_indexer(obj, *indices): for idx in indices: if not obj: break if hasattr(obj, "get"): obj = obj.get(idx) else: obj = obj[idx] return obj </code></pre> <p>Usage:</p> <pre><code>a = {...
3
2009-10-12T01:38:21Z
[ "python", "coding-style" ]
SMTP and XMPP deployment/workflow
1,552,417
<p>I'm developing a website that incorporates an XMPP bot and a custom SMTP server (mainly these services process commands and reply). I'd like to set up a system where I can develop locally, push changes to a staging server, and finally to a production system. (Essentially I'm developing on the live server currently...
0
2009-10-12T02:27:04Z
1,675,742
<p>Partial answer: DNS has no way to tell you to connect to a non-standard SMTP port, even with SRV records. (XMPP does.)</p> <p>So, for sending email, you'll have to do something like:</p> <pre><code>import smtplib server = smtplib.SMTP('localhost:2525') server.sendmail(fromaddr, toaddrs, msg) server.quit() </code>...
2
2009-11-04T18:28:57Z
[ "python", "deployment", "smtp", "xmpp" ]
python adding gibberish when reading from a .rtf file?
1,552,886
<p>I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that? How can I avoid it? For example, trying to read in thi...
0
2009-10-12T05:36:40Z
1,552,906
<p>That's the nature of .RTF (i.e Rich Text files), they include extra data to define how the text is layed-out and formated.</p> <p>It is not recommended to store data in such files lest you encounter the difficulties you noted. Would you go through the effort to parse this file and "recover" your one numeric value...
4
2009-10-12T05:42:00Z
[ "python", "file-io", "rtf" ]
python adding gibberish when reading from a .rtf file?
1,552,886
<p>I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that? How can I avoid it? For example, trying to read in thi...
0
2009-10-12T05:36:40Z
1,552,907
<p>That's exactly what the RTF file contains, so Python (in the absence of further instruction) is giving you what the file contains.</p> <p>You may be looking for a library to read the <em>contents</em> of RTF files, such as <a href="http://code.google.com/p/pyrtf-ng/" rel="nofollow">pyrtf-ng</a>.</p>
4
2009-10-12T05:43:07Z
[ "python", "file-io", "rtf" ]
IPython tab completes only some modules
1,552,961
<p>I'm using the EPD version of python and IPython. After installing some modules using easy_install I notice that, although they can be imported, they cannot be tab completed. They exist on the path but, while included modules (pylab, readline, math) <em>can</em> be completed, these new modules cannot.</p> <p>Anyone ...
4
2009-10-12T06:05:19Z
1,552,999
<p>right at the end of Ipython/completer.py is this code:</p> <p><pre><code> except: #from IPython.ultraTB import AutoFormattedTB; # dbg #tb=AutoFormattedTB('Verbose');tb() #dbg<br /> # If completion fails, don't annoy the user. return None </pre></code></p> <p>...
2
2009-10-12T06:20:44Z
[ "python", "module", "ipython", "tab-completion", "enthought" ]
IPython tab completes only some modules
1,552,961
<p>I'm using the EPD version of python and IPython. After installing some modules using easy_install I notice that, although they can be imported, they cannot be tab completed. They exist on the path but, while included modules (pylab, readline, math) <em>can</em> be completed, these new modules cannot.</p> <p>Anyone ...
4
2009-10-12T06:05:19Z
1,553,207
<p>Locally installed, <em>non-egg</em> modules can have their name tab-completed, when doing <code>import</code>, but <em>egg</em> modules cannot (IPython 0.10, Python 2.6.2, Mac OS X).</p> <p>I would suggest to file a feature request / bug report with IPython!</p>
0
2009-10-12T07:35:53Z
[ "python", "module", "ipython", "tab-completion", "enthought" ]
IPython tab completes only some modules
1,552,961
<p>I'm using the EPD version of python and IPython. After installing some modules using easy_install I notice that, although they can be imported, they cannot be tab completed. They exist on the path but, while included modules (pylab, readline, math) <em>can</em> be completed, these new modules cannot.</p> <p>Anyone ...
4
2009-10-12T06:05:19Z
3,631,259
<p>I found an answer to this question yesterday, after I got tired of this behavior.</p> <p>It seems that IPython has a simple database with all the modules it can find in <code>sys.path</code>. Every time you install a new module you have to write the magic</p> <pre><code>In [1]: %rehashx </code></pre> <p>so that I...
10
2010-09-02T21:04:23Z
[ "python", "module", "ipython", "tab-completion", "enthought" ]
Generate random directories/files given number of files and depth
1,553,114
<p>I'd like to profile some VCS software, and to do so I want to generate a set of random files, in randomly arranged directories. I'm writing the script in Python, but my question is briefly: <strong>how do I generate a random directory tree with an average number of sub-directories per directory and some broad distri...
2
2009-10-12T07:06:48Z
1,553,126
<p>Why not download some real open source repos and use those?</p> <p>Have you thought about what goes into the files? is that random data too?</p>
4
2009-10-12T07:12:25Z
[ "python", "algorithm" ]
Generate random directories/files given number of files and depth
1,553,114
<p>I'd like to profile some VCS software, and to do so I want to generate a set of random files, in randomly arranged directories. I'm writing the script in Python, but my question is briefly: <strong>how do I generate a random directory tree with an average number of sub-directories per directory and some broad distri...
2
2009-10-12T07:06:48Z
1,553,402
<p>Your question is fairly long and involved, but I think it boils down to asking for a random number generator with certain statistical properties. </p> <p>If you don't like python's random number generator, you might look at some of the other statistical packages on pypi, or if you want something a little more heavy...
0
2009-10-12T08:39:06Z
[ "python", "algorithm" ]
How to generate a list of 150 cases initialised with a dict in Python?
1,553,145
<p>I would like to create a list like this </p> <pre><code>list = [] for i in range(150): list.append({'open': False, 'serve': False}) </code></pre> <p>But is there a better way in Python to do it ?</p>
0
2009-10-12T07:18:59Z
1,553,158
<p>With a list comprehension (don't use <code>list</code> as a variable name, as it shadows the python built-in):</p> <pre><code># use range() in Python 3 l = [{'open': False, 'serve': False} for i in xrange(150)] </code></pre>
5
2009-10-12T07:21:40Z
[ "python", "list", "dictionary", "initialization" ]
How to generate a list of 150 cases initialised with a dict in Python?
1,553,145
<p>I would like to create a list like this </p> <pre><code>list = [] for i in range(150): list.append({'open': False, 'serve': False}) </code></pre> <p>But is there a better way in Python to do it ?</p>
0
2009-10-12T07:18:59Z
1,553,232
<p>The list comprehension to build your data structure is probably slightly more efficient. It's also much much terser. Sometimes the terseness is a nice thing, and sometimes it just obscures what is going on. In this case I think the listcomp is pretty clear.</p> <p>But the listcomp and the for loop both end up bu...
0
2009-10-12T07:42:14Z
[ "python", "list", "dictionary", "initialization" ]
How to generate a list of 150 cases initialised with a dict in Python?
1,553,145
<p>I would like to create a list like this </p> <pre><code>list = [] for i in range(150): list.append({'open': False, 'serve': False}) </code></pre> <p>But is there a better way in Python to do it ?</p>
0
2009-10-12T07:18:59Z
1,742,883
<p>Whatever you do, don't try list = [{'open':False,'serve':False}]*150, as you will have the same dictionary 150 times. :D</p> <p>You will then get fun behavior, like</p> <pre><code>&gt;&gt;&gt; list[0]['open'] = True &gt;&gt;&gt; list[1]['open'] = False &gt;&gt;&gt; print list[0]['open'] False &gt;&gt;&gt; list[0]...
1
2009-11-16T15:26:23Z
[ "python", "list", "dictionary", "initialization" ]
Python sqlite3 version
1,553,160
<pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; sqlite3.version '2.4.1' </code></pre> <p>Questions:</p> <ul> <li>Why is the version of the sqlite**3** module...
19
2009-10-12T07:22:09Z
1,553,190
<pre><code>Python 2.5.1 &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; sqlite3.version '2.3.2' &gt;&gt;&gt; sqlite3.sqlite_version '3.3.4' </code></pre> <p>version - pysqlite version<br /> sqlite_version - sqlite version</p>
47
2009-10-12T07:31:01Z
[ "python", "sqlite" ]
multiple django sites with apache & mod_wsgi
1,553,165
<p>I want to host several sites with under the same server which uses Debian 5, say I have <code>site1</code>, <code>site2</code> and <code>site3</code>, and assume my ip is <code>155.55.55.1</code>:</p> <pre><code>site1: 155.55.55.1:80 , script at /opt/django/site1/ site2: 155.55.55.1:8080, script at /opt/django/sit...
49
2009-10-12T07:22:51Z
1,553,751
<p>Your ServerName/ServerAlias directives are wrong. ServerName should be hostname. You probably should just delete ServerAlias.</p> <p>Then just do the obvious and duplicate VirtualHost/Listen directives, just changing the port number and locations of scripts in the file system.</p> <p>Finally, do not set DocumentRo...
89
2009-10-12T10:13:05Z
[ "python", "django", "apache2", "hosting", "mod-wsgi" ]
multiple django sites with apache & mod_wsgi
1,553,165
<p>I want to host several sites with under the same server which uses Debian 5, say I have <code>site1</code>, <code>site2</code> and <code>site3</code>, and assume my ip is <code>155.55.55.1</code>:</p> <pre><code>site1: 155.55.55.1:80 , script at /opt/django/site1/ site2: 155.55.55.1:8080, script at /opt/django/sit...
49
2009-10-12T07:22:51Z
19,741,803
<p>Putting all virtualHost configuration in one place works fine, but Debian has its own concept by separating them in a file for each site in /etc/apache2/sites-available, which are activated by symlinking them in ../sites-enabled. In this way a server-admin could also assign separate access rights to the config file...
2
2013-11-02T12:16:43Z
[ "python", "django", "apache2", "hosting", "mod-wsgi" ]
How to strip a list of tuple with python?
1,553,275
<p>I have an array with some flag for each case. In order to use print the array in HTML and use colspan, I need to convert this :</p> <pre><code>[{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve...
1
2009-10-12T07:53:20Z
1,553,324
<pre><code>def cluster(dicts, key): current_value = None current_span = 0 result = [] for d in dicts: value = d[key] if current_value is None: current_value = value elif current_value != value: result.append({'colspan': current_span, key: current_value}) ...
4
2009-10-12T08:06:54Z
[ "python", "list", "dictionary", "flags" ]
How to strip a list of tuple with python?
1,553,275
<p>I have an array with some flag for each case. In order to use print the array in HTML and use colspan, I need to convert this :</p> <pre><code>[{'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve...
1
2009-10-12T07:53:20Z
1,553,358
<p>This is not clear what you need, but I hope the following examples will help you:</p> <pre><code>&gt;&gt;&gt; groupped = itertools.groupby(your_list, operator.itemgetter('open')) &gt;&gt;&gt; [{'colspan': len(list(group)), 'open': open} for open, group in groupped] [{'colspan': 12, 'open': False}, {'colspan': 60, '...
4
2009-10-12T08:18:48Z
[ "python", "list", "dictionary", "flags" ]
% operator in python over string
1,553,434
<p>What does the following Python statement mean?</p> <pre><code>send_data="" str_len = "%#04d" % (len(send_data)/2) </code></pre>
1
2009-10-12T08:50:54Z
1,553,447
<p>This sets <code>str_len</code> to show half the length of <code>send_data</code>, padded with zeros to be four characters right. The <code>%</code> character is carrying out <strong>interpolation</strong>. See the <a href="https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting" rel="nofollow"...
4
2009-10-12T08:53:39Z
[ "python", "string-formatting" ]
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
1,553,467
<p>Here's a common situation when compiling data in dictionaries from different sources: </p> <p>Say you have a dictionary that stores lists of things, such as things I like:</p> <pre><code>likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } </code></pre> <p>and a second dictionary ...
3
2009-10-12T09:01:02Z
1,553,478
<p>Use <a href="http://docs.python.org/3.1/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>, where the default value is a new <code>list</code> instance.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; mydict = collections.defaultdict(list) </code></...
5
2009-10-12T09:03:50Z
[ "python", "iteration" ]
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
1,553,467
<p>Here's a common situation when compiling data in dictionaries from different sources: </p> <p>Say you have a dictionary that stores lists of things, such as things I like:</p> <pre><code>likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } </code></pre> <p>and a second dictionary ...
3
2009-10-12T09:01:02Z
1,553,483
<p>Use collections.defaultdict:</p> <pre><code>import collections likes = collections.defaultdict(list) for key, value in favorites.items(): likes[key].append(value) </code></pre> <p><code>defaultdict</code> takes a single argument, a factory for creating values for unknown keys on demand. <code>list</code> is...
3
2009-10-12T09:04:45Z
[ "python", "iteration" ]
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
1,553,467
<p>Here's a common situation when compiling data in dictionaries from different sources: </p> <p>Say you have a dictionary that stores lists of things, such as things I like:</p> <pre><code>likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } </code></pre> <p>and a second dictionary ...
3
2009-10-12T09:01:02Z
1,553,495
<pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(list, likes) &gt;&gt;&gt; d defaultdict(&lt;class 'list'&gt;, {'colors': ['blue', 'red', 'purple'], 'foods': ['apples', 'oranges']}) &gt;&gt;&gt; for i, j in favorites.items(): d[i].append(j) &gt;&gt;&gt; d defaultdict(&lt;cla...
1
2009-10-12T09:08:12Z
[ "python", "iteration" ]
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
1,553,467
<p>Here's a common situation when compiling data in dictionaries from different sources: </p> <p>Say you have a dictionary that stores lists of things, such as things I like:</p> <pre><code>likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } </code></pre> <p>and a second dictionary ...
3
2009-10-12T09:01:02Z
1,553,510
<p>Except defaultdict, the regular dict offers one possibility (that might look a bit strange): <code>dict.setdefault(k[, d])</code>:</p> <pre><code>for key, val in favorites.iteritems(): likes.setdefault(key, []).append(val) </code></pre> <p>Thank you for the +20 in rep -- I went from 1989 to 2009 in 30 seconds....
2
2009-10-12T09:11:26Z
[ "python", "iteration" ]
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
1,553,467
<p>Here's a common situation when compiling data in dictionaries from different sources: </p> <p>Say you have a dictionary that stores lists of things, such as things I like:</p> <pre><code>likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } </code></pre> <p>and a second dictionary ...
3
2009-10-12T09:01:02Z
3,810,724
<p>All of the answers are <code>defaultdict</code>, but I'm not sure that's the best way to go about it. Giving out <code>defaultdict</code> to code that expects a dict can be bad. (See: <a href="http://stackoverflow.com/questions/3031817/how-do-i-make-a-defaultdict-safe-for-unexpecting-clients">http://stackoverflow.c...
1
2010-09-28T07:54:03Z
[ "python", "iteration" ]
Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath)
1,553,511
<p>I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the html files are not marked up semantically (table based layout, with meaning-less ...
1
2009-10-12T09:11:29Z
1,553,525
<p>You might give <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> in Python a try. It's a pretty great parser for generating a usable DOM out of garbage HTML. That with some regex skills might get you what you need. Happy hunting!</p> <p>Most comparative operations in Python a...
2
2009-10-12T09:16:34Z
[ "php", "python", "html", "regex", "xpath" ]
Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath)
1,553,511
<p>I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the html files are not marked up semantically (table based layout, with meaning-less ...
1
2009-10-12T09:11:29Z
1,553,559
<p>As the previous post mentions Python in general is faster than php due to byte-code compilation (those .pyc files). And a lot of DOM/SAX parsers use fair bit of regexp internally anyway. Those who told you to use regexp need to be told that it is not a magic bullet. For 40k+ documents I would recommend parallelizing...
0
2009-10-12T09:26:06Z
[ "php", "python", "html", "regex", "xpath" ]
Extracting info from html using PHP(XPath), PHP/Python(Regexp) or Python(XPath)
1,553,511
<p>I have approx. 40k+ html documents where I need to extract information from. I have tried to do so using PHP+Tidy(because most files are not well-formed)+DOMDocument+XPath but it is extremely slow.... I am advised to use regexp but the html files are not marked up semantically (table based layout, with meaning-less ...
1
2009-10-12T09:11:29Z
1,554,489
<p>If speed is a requirement have a look at <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. lxml is a pythonic binding for the <a href="http://xmlsoft.org/" rel="nofollow">libxml2</a> and <a href="http://xmlsoft.org/XSLT/" rel="nofollow">libxslt</a> C libraries. Using the C libraries is much faster than a...
3
2009-10-12T13:10:43Z
[ "php", "python", "html", "regex", "xpath" ]
After submitting form, the value is different due to encoding? (Python)
1,553,564
<p>I am using Django.</p> <p>In a regular form, the user enters "Gerry &amp; Pacemakers".</p> <p>(Notice the Ampersand sign.)</p> <p>When I go views.py...</p> <pre><code>def myview(request): q = request.GET.get('q','').strip() print q </code></pre> <p>q is "Gerry"...but it's supposed to be "Gerry &amp; Pac...
1
2009-10-12T09:27:38Z
1,553,697
<p>Since you are pulling the data from request.GET, it looks like you're building the URL in the browser somehow. You need to use the Javascript <code>escape()</code> function to handle URL-significant characters properly.</p>
2
2009-10-12T09:57:28Z
[ "python", "django" ]
How to upload html documentation generated from sphinx to github?
1,553,800
<p>I just documented loads of my code and learnt how to use sphinx to generate the documentation. I want to include that into my github project page but I do not know how to. Does anyone know existing tutorial or simple step to do so?</p> <p>Thanks.</p>
15
2009-10-12T10:25:40Z
1,622,472
<p>github will serve static content for you using their <a href="http://github.com/blog/272-github-pages">github pages</a> feature. Essentially, you create a branch called gh-pages, into which you commit your static pages. The pages are then served at you.github.com/yourproject.</p> <p>See the instructions at <a href...
30
2009-10-25T23:29:02Z
[ "python", "github", "python-sphinx" ]
How to upload html documentation generated from sphinx to github?
1,553,800
<p>I just documented loads of my code and learnt how to use sphinx to generate the documentation. I want to include that into my github project page but I do not know how to. Does anyone know existing tutorial or simple step to do so?</p> <p>Thanks.</p>
15
2009-10-12T10:25:40Z
11,215,999
<p><a href="http://pypi.python.org/pypi/github-tools/" rel="nofollow">github-tools</a> has a feature doing exactly what you are asking for:</p> <pre><code>paver gh_pages_create gh_pages_build </code></pre> <p>Refer to the <a href="http://dinoboff.github.com/github-tools" rel="nofollow">excellent documentation</a> (of...
0
2012-06-26T21:13:17Z
[ "python", "github", "python-sphinx" ]
How to upload html documentation generated from sphinx to github?
1,553,800
<p>I just documented loads of my code and learnt how to use sphinx to generate the documentation. I want to include that into my github project page but I do not know how to. Does anyone know existing tutorial or simple step to do so?</p> <p>Thanks.</p>
15
2009-10-12T10:25:40Z
15,619,374
<p><a href="http://stackoverflow.com/a/1622472/45773">John Paulett's answer</a> is obviously correct and likely sufficient for most users already (+1).</p> <p>Alternatively you might want to check out Ben Welsh's thorough tutorial <a href="http://datadesk.latimes.com/posts/2012/01/sphinx-on-github/" rel="nofollow">Sph...
3
2013-03-25T16:01:49Z
[ "python", "github", "python-sphinx" ]
python: interact with the session in cgi scripts
1,554,250
<p>Can python cgi scripts write and read data to the session? If so how? Is there a high-level API or must I roll my own classes?</p>
2
2009-10-12T12:21:38Z
1,554,303
<p>There's no "<em>session</em>" on <code>cgi</code>. You must roll your own session handling code if you're using raw <code>cgi</code>.</p> <p>Basically, sessions work by creating a unique cookie number and sending it on a response header to the client, and then checking for this cookie on every connection. Store the...
7
2009-10-12T12:28:43Z
[ "python", "session", "cgi" ]
reading midi input
1,554,362
<p>is there a module to read midi input (live) with python?</p>
1
2009-10-12T12:41:43Z
1,554,454
<p>I used <a href="http://alumni.media.mit.edu/~harrison/code.html" rel="nofollow">PyPortMidi</a> successfully in 2006 to record Midi input in real time (on OS X). It should work on Windows, OS X, and Linux. It was very light on the processor side, which was great!</p>
3
2009-10-12T13:02:30Z
[ "python", "input", "midi" ]
reading midi input
1,554,362
<p>is there a module to read midi input (live) with python?</p>
1
2009-10-12T12:41:43Z
1,554,481
<p>I had this discussion like ages ago once, and the consensus kinda ended up on using <a href="http://midishare.sourceforge.net/" rel="nofollow">MidiShare</a>, which has Python bindings. But things may have moved on since then, that was like 2004 or something. So it's not a recommendation, just a "check it out".</p>
1
2009-10-12T13:08:09Z
[ "python", "input", "midi" ]
Worker/Timeslot permutation/constraint filtering algorithm
1,554,366
<p>Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have.</p> <p>If anyone knows of a good third-party app which (certainly) automate this, that would almost ...
6
2009-10-12T12:41:52Z
1,554,777
<blockquote> <p>I've tried implementing this with a Genetic Algorithm, but can't seem to get it tuned quite right, so although the basic principle seems to work on single shifts, it can't solve even easy cases with a few shifts and a few workers.</p> </blockquote> <p><strong>In short, don't! Unless you have...
3
2009-10-12T14:05:22Z
[ "python", "scheduling", "permutation", "timetable", "timeslots" ]
Worker/Timeslot permutation/constraint filtering algorithm
1,554,366
<p>Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have.</p> <p>If anyone knows of a good third-party app which (certainly) automate this, that would almost ...
6
2009-10-12T12:41:52Z
1,555,209
<p>I don't have an algorithm choice but I can relate some practical considerations.</p> <p>Since the algorithm is dealing with cancellations, it has to run whenever a scheduling exception occurs to reschedule everyone. </p> <p>Consider that some algorithms are not very linear and might radically reschedule everyone f...
1
2009-10-12T15:23:55Z
[ "python", "scheduling", "permutation", "timetable", "timeslots" ]
Worker/Timeslot permutation/constraint filtering algorithm
1,554,366
<p>Hope you can help me out with this guys. It's not help with work -- it's for a charity of very hard working volunteers, who could really use a less confusing/annoying timetable system than what they currently have.</p> <p>If anyone knows of a good third-party app which (certainly) automate this, that would almost ...
6
2009-10-12T12:41:52Z
1,555,386
<p>Okay, I don't know about a particular algorithm, but here is what I would take into consideration.</p> <p><strong>Evaluation</strong> </p> <p>Whatever the method you will need a function to evaluate how much your solution is satisfying the constraints. You may take the 'comparison' approach (no global score but a...
1
2009-10-12T15:58:43Z
[ "python", "scheduling", "permutation", "timetable", "timeslots" ]
Python Clientform-can not get expexted result
1,554,534
<p>I am trying to search through http://www.wegottickets.com/ with the keywords "Live music". But the returned result is still the main page, not the search result page including lots of live music information. Could anyone show me out what the problem is?</p> <pre><code>from urllib2 import urlopen from ClientForm imp...
0
2009-10-12T13:19:16Z
1,554,607
<p>Never used it, but I've had success with the python mechanize module, if it turns out to be a fault in clientform.</p> <p>However, as a first step, I'd suggest removing your try...except wrapper. What you're basically doing is saying "catch any error, then ignore the actual error and print 'Unsuccessful Query' ins...
0
2009-10-12T13:31:32Z
[ "python", "clientform" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
1,554,617
<p>The idea is to allow you to avoid having to write getters and setters until you actually need them.</p> <p>So, to start off you write:</p> <pre><code>class MyClass(object): def __init__(self): self.myval = 4 </code></pre> <p>Obviously you can now write <code>myobj.myval = 5</code>.</p> <p>But later o...
26
2009-10-12T13:34:19Z
[ "python", "properties" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
1,554,639
<p>A basic reason is really simply that it looks better. It is more pythonic. Especially for libraries. something.getValue() looks less nice than something.value</p> <p>In plone (a pretty big CMS), you used to have document.setTitle() which does a lot of things like storing the value, indexing it again and so. Jus...
5
2009-10-12T13:38:10Z
[ "python", "properties" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
1,554,753
<blockquote> <p>but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble</p> </blockquote> <p>You're not hiding that fact though; that fact was never there to begin with. This is python -- a high-level language; not assembly. Few of the "simple" statements in it boil down to sin...
14
2009-10-12T14:01:05Z
[ "python", "properties" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
1,555,169
<p>In languages that rely on getters and setters, like Java, they're not supposed nor expected to do anything but what they say -- it would be astonishing if <code>x.getB()</code> did anything but return the current value of logical attribute <code>b</code>, or if <code>x.setB(2)</code> did anything but whatever small ...
101
2009-10-12T15:16:54Z
[ "python", "properties" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
1,555,929
<p>Here's an old example of mine. I wrapped a C library which had functions like "void dt_setcharge(int atom_handle, int new_charge)" and "int dt_getcharge(int atom_handle)". I wanted at the Python level to do "atom.charge = atom.charge + 1".</p> <p>The "property" decorator makes that easy. Something like:</p> <pre><...
2
2009-10-12T17:40:00Z
[ "python", "properties" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
1,556,870
<p>You are correct, it is just syntactic sugar. It may be that there are no good uses of it depending on your definition of problematic code.</p> <p>Consider that you have a class Foo that is widely used in your application. Now this application has got quite large and further lets say it's a webapp that has become ve...
3
2009-10-12T20:51:53Z
[ "python", "properties" ]
When and how to use the builtin function property() in python
1,554,546
<p>It appears to me that except for a little syntactic sugar, property() does nothing good.</p> <p>Sure, it's nice to be able to write <code>a.b=2</code> instead of <code>a.setB(2)</code>, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result ca...
52
2009-10-12T13:22:07Z
34,562,077
<p>getters and setters are needed for many purposes, and are very useful because they are transparent to the code. Having object Something the property height, you assign a value as Something.height = 10, but if height has a getter and setter then at the time you do assign that value you can do many things in the proce...
0
2016-01-02T02:40:30Z
[ "python", "properties" ]
Implementing "Starts with" and "Ends with" queries with Google App Engine
1,554,600
<p>Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python?</p> <p>In pseudo code, it would work something like...</p> <p>Query for all entities A where property P starts with X</p> <p>or</p> <p>Query for all entities B where ...
5
2009-10-12T13:30:22Z
1,554,615
<p>Seems you can't do it for the general case, but can do it for prefix searches (starts with):</p> <p><a href="http://stackoverflow.com/questions/1402769/wildcard-search-on-appengine-in-python">http://stackoverflow.com/questions/1402769/wildcard-search-on-appengine-in-python</a></p>
2
2009-10-12T13:34:07Z
[ "python", "google-app-engine", "gae-datastore" ]
Implementing "Starts with" and "Ends with" queries with Google App Engine
1,554,600
<p>Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python?</p> <p>In pseudo code, it would work something like...</p> <p>Query for all entities A where property P starts with X</p> <p>or</p> <p>Query for all entities B where ...
5
2009-10-12T13:30:22Z
1,554,837
<p>You can do a 'starts with' query by using inequality filters:</p> <pre><code>MyModel.all().filter('prop &gt;=', prefix).filter('prop &lt;', prefix + u'\ufffd') </code></pre> <p>Doing an 'ends with' query would require storing the reverse of the string, then applying the same tactic as above.</p>
14
2009-10-12T14:13:27Z
[ "python", "google-app-engine", "gae-datastore" ]
Problem to make an apache server run correctly under mod_python
1,554,673
<p>We try to migrate our old server to a new one but we experienced some problems with mod_python.</p> <p>The problem is under this web page: </p> <p><a href="http://auction.tinyerp.org/auction-in-europe.com/aie/" rel="nofollow">http://auction.tinyerp.org/auction-in-europe.com/aie/</a> </p> <p>Here is our apache2 co...
0
2009-10-12T13:46:00Z
1,554,991
<pre><code> #!/usr/bin/python import os, sys base_dir = "/home/www/auction-in-europe.com/aie/" sys.path.insert(0, base_dir) import albatross import sql_db from albatross.apacheapp import Request from albatross import apacheapp from albatross.template import Content, EmptyTag, EnclosingTag import string import common cl...
0
2009-10-12T14:45:26Z
[ "python", "apache2", "mod-python" ]
Problem to make an apache server run correctly under mod_python
1,554,673
<p>We try to migrate our old server to a new one but we experienced some problems with mod_python.</p> <p>The problem is under this web page: </p> <p><a href="http://auction.tinyerp.org/auction-in-europe.com/aie/" rel="nofollow">http://auction.tinyerp.org/auction-in-europe.com/aie/</a> </p> <p>Here is our apache2 co...
0
2009-10-12T13:46:00Z
1,555,295
<p>Is that the index.py? I believe you are mixing up your install. You use the "PythonHandler mod_python.publisher" if you do not want to write your own handler. The file you just posted contains a handler, the lines:</p> <pre><code>def handler(req): return app.run(apacheapp.Request(req)) </code></pre> <p>This ...
0
2009-10-12T15:41:46Z
[ "python", "apache2", "mod-python" ]
How do I ask for an authenticated url directly with python
1,554,745
<p>I want to get to an authenticated page using urllib2. I'm hoping there's a hack to do it directly. something like:</p> <pre><code>urllib2.urlopen('http://username:pwd@server/page') </code></pre> <p>If not, how do I use authentication?</p>
0
2009-10-12T13:57:54Z
1,554,791
<p>It depends on the type of authentication used. </p> <ul> <li>A simple example is <a href="http://docs.python.org/library/urllib2.html#examples" rel="nofollow">Http Authentication</a></li> <li>If the site uses cookies for auth you need to add a <a href="http://docs.python.org/library/cookielib.html?highlight=cookiej...
2
2009-10-12T14:07:20Z
[ "python", "authentication", "urllib2" ]
How do I ask for an authenticated url directly with python
1,554,745
<p>I want to get to an authenticated page using urllib2. I'm hoping there's a hack to do it directly. something like:</p> <pre><code>urllib2.urlopen('http://username:pwd@server/page') </code></pre> <p>If not, how do I use authentication?</p>
0
2009-10-12T13:57:54Z
1,554,848
<p>AFAIK, there isn't a trivial way of doing this. Basically, you make a request and the server responds with a 401 authorization required, which urllib2 translates into an exception. </p> <pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python25\lib\urllib2....
1
2009-10-12T14:14:58Z
[ "python", "authentication", "urllib2" ]
Getting input from MIDI devices live (Python)
1,554,896
<p>I've got a trigger finger (MIDI tablet) and I want to be able to read its input live and make python execute actions depending on the pressed key.</p> <p>I need it for Windows, and preferably working with python 2.5 +</p> <p>Thanks</p>
4
2009-10-12T14:23:45Z
1,555,001
<p><a href="http://www.pygame.org/">PyGame</a> includes a built-in <a href="http://www.pygame.org/docs/ref/midi.html">midi module</a>, available for Linux, Windows and MacOS and is very well supported.</p> <p>For example, here is the documentation for <a href="http://www.pygame.org/docs/ref/midi.html#pygame.midi.Input...
6
2009-10-12T14:47:12Z
[ "python", "midi" ]
How do I know what's the realm and uri of a site
1,555,018
<p>I want to use python's urllib2 with authentication and I need the realm and uri of a url. How do I get it?</p> <p>thanks</p>
2
2009-10-12T14:49:38Z
1,555,138
<p>When you make a request for a resource that requires authentication, the server will respond with a 401 status code, and a header that contains the realm:</p> <pre><code>WWW-Authenticate: Basic realm="the realm" </code></pre> <p>The URI is the URL you're trying to access.</p>
1
2009-10-12T15:09:40Z
[ "python", "authentication", "urllib2" ]
How to save a model without sending a signal?
1,555,060
<p>How can I save a model, such that signals arent sent. (post_save and pre_save)</p>
12
2009-10-12T14:56:46Z
1,555,120
<p>There is currently a <a href="http://code.djangoproject.com/ticket/8077" rel="nofollow">ticket</a> pending a Django design decision for this feature.</p> <p>Included in the ticket is a diff for a patch with the proposed implementation.</p>
0
2009-10-12T15:04:29Z
[ "python", "django", "django-models" ]
How to save a model without sending a signal?
1,555,060
<p>How can I save a model, such that signals arent sent. (post_save and pre_save)</p>
12
2009-10-12T14:56:46Z
1,556,235
<p>It's a bit of a hack, but you can do something like this:</p> <p>use a unique identifier with a filter and then use the update method of the queryset (which does not trigger the signals)</p> <pre><code>user_id = 142187 User.objects.filter(id=user_id).update(name='tom') </code></pre>
17
2009-10-12T18:46:43Z
[ "python", "django", "django-models" ]
How to save a model without sending a signal?
1,555,060
<p>How can I save a model, such that signals arent sent. (post_save and pre_save)</p>
12
2009-10-12T14:56:46Z
11,513,856
<p>This <a href="https://code.djangoproject.com/ticket/8077" rel="nofollow">ticket</a> has been marked as "wontfix" because:</p> <blockquote> <p>In short, it sounds like, given the defined purpose of signals, it is the attached signal handler that needs to become more intelligent (like in davedash's suggestion),...
4
2012-07-16T23:04:35Z
[ "python", "django", "django-models" ]
Fill form values in a web page via a Python script (not testing)
1,555,234
<p>I need to fill form values on a target page then click a button via Python. I've looked at Selenium and Windmill, but these are testing frameworks - I'm not testing. I'm trying to log into a 3rd party website programatically, then download and parse a file we need to insert into our database. The problem with the te...
17
2009-10-12T15:28:41Z
1,555,247
<p>You are looking for <a href="http://wwwsearch.sourceforge.net/mechanize/">Mechanize</a></p> <p>Form submitting sample:</p> <pre><code>import re from mechanize import Browser br = Browser() br.open("http://www.example.com/") br.select_form(name="order") # Browser passes through unknown attributes (including method...
17
2009-10-12T15:31:59Z
[ "python" ]
Fill form values in a web page via a Python script (not testing)
1,555,234
<p>I need to fill form values on a target page then click a button via Python. I've looked at Selenium and Windmill, but these are testing frameworks - I'm not testing. I'm trying to log into a 3rd party website programatically, then download and parse a file we need to insert into our database. The problem with the te...
17
2009-10-12T15:28:41Z
1,555,332
<p>You can use the standard <code>urllib</code> library to do this like so:</p> <pre><code>import urllib urllib.urlretrieve("http://www.google.com/", "somefile.html", lambda x,y,z:0, urllib.urlencode({"username": "xxx", "password": "pass"})) </code></pre>
1
2009-10-12T15:48:42Z
[ "python" ]
Fill form values in a web page via a Python script (not testing)
1,555,234
<p>I need to fill form values on a target page then click a button via Python. I've looked at Selenium and Windmill, but these are testing frameworks - I'm not testing. I'm trying to log into a 3rd party website programatically, then download and parse a file we need to insert into our database. The problem with the te...
17
2009-10-12T15:28:41Z
5,685,569
<p>The Mechanize example as suggested seems to work. In input fields where you must enter text, use something like:</p> <pre><code>br["kw"] = "rowling" # (the method here is __setitem__) </code></pre> <p>If some content is generated after you submit the form, as in a search engine, you get it via:</p> <pre><code>pr...
1
2011-04-16T09:32:01Z
[ "python" ]
Fill form values in a web page via a Python script (not testing)
1,555,234
<p>I need to fill form values on a target page then click a button via Python. I've looked at Selenium and Windmill, but these are testing frameworks - I'm not testing. I'm trying to log into a 3rd party website programatically, then download and parse a file we need to insert into our database. The problem with the te...
17
2009-10-12T15:28:41Z
18,498,044
<p>Have a look on this example: it will give the basic idea:</p> <pre><code>#!/usr/bin/python import re from mechanize import Browser br = Browser() # Ignore robots.txt br.set_handle_robots( False ) # Google demands a user-agent that isn't a robot br.addheaders = [('User-agent', 'Firefox')] # Retrieve the Google ho...
10
2013-08-28T20:57:46Z
[ "python" ]
webbrowser.get("firefox") on a Mac with Firefox "could not locate runnable browser"
1,555,283
<p>I think what I need here is to know which magic command-line or OSA script program to run to start up a URL in an existing Firefox browser, if one is running, or to also start up Firefox if it isn't. On Mac.</p> <p>I'm testing a Python program (Crunchy Python) which sets up a web server then uses Firefox for the fr...
2
2009-10-12T15:39:33Z
1,555,575
<p>Apple uses launch services to find applications. An application can be used by the open command - <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/open.1.html" rel="nofollow">Apple developer man page for open</a></p> <p>The python command you want is</p> <pre><code>clien...
0
2009-10-12T16:31:14Z
[ "python", "osx", "firefox", "browser" ]
webbrowser.get("firefox") on a Mac with Firefox "could not locate runnable browser"
1,555,283
<p>I think what I need here is to know which magic command-line or OSA script program to run to start up a URL in an existing Firefox browser, if one is running, or to also start up Firefox if it isn't. On Mac.</p> <p>I'm testing a Python program (Crunchy Python) which sets up a web server then uses Firefox for the fr...
2
2009-10-12T15:39:33Z
1,555,941
<p>You should use Launch Services to open the URL. You can do this with the <code>LaunchServices</code> module, or with Apple's <code>open</code> utility, or with my <code>launch</code> utility (<a href="http://web.sabi.net/nriley/software/" rel="nofollow">here</a>):</p> <p><code>open</code> is probably easiest:</p> ...
1
2009-10-12T17:41:47Z
[ "python", "osx", "firefox", "browser" ]
Cherrypy server unavailable from anything but localhost
1,555,319
<p>I am having an issue with cherrypy that looks solved, but doesn't work. I can only bind on localhost or 127.0.0.1. Windows XP Home and Mac OS X (linux untested), cherrypy 3.1.2, python 2.5.4. This is the end of my app:</p> <pre><code>global_conf = { 'global': { 'server.environment= "production"' ...
2
2009-10-12T15:46:01Z
1,555,656
<p>huh, you're doing something wrong with your dict:</p> <pre><code>&gt;&gt;&gt; global_conf = { ... 'global': { 'server.environment= "production"' ... 'engine.autoreload_on : True' ... 'engine.autoreload_frequency = 5 ' ... 'server.socket_hos...
6
2009-10-12T16:44:13Z
[ "python", "cherrypy" ]