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 specific way to do this?</p>
| 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 specific way to do this?</p>
| 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', 'First Name', 'Middle Name', 'Last Name',
'Birthday Date', 'Registration Date', 'Membership ending Date')
table = SQLTABLE(rows, _width="100%")
</code></pre>
<p>Now I want to transpose the table, how can I do this?</p>
| 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_plugin, os.listdir(plugin_dir))
viable_plugins = map(lambda name: name[:-3], viable_plugins)
</code></pre>
<p>Then I <code>os.chdir</code> to the plugins directory and <code>map __import__</code> the entire thing, like so:</p>
<pre><code>active_plugins = map(__import__, viable_plugins)
</code></pre>
<p>However, when I turn <code>active_plugins</code> into a list and try to access the modules within, Python will throw out an error, saying it cannot import the modules since they don't appear to be there.</p>
<p>What am I doing wrong?</p>
<p><hr /></p>
<p>Edit: By simply using the interactive interpreter, doing <code>os.chdir</code> and <code>__import__(modulefilename)</code> produces exactly what I need. Why isn't the above approach working, then? Am I doing something wrong with Python's more <em>functional</em> parts?</p>
| 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>import sys
sys.path.insert(0, directory_of_modules)
# do imports here.
</code></pre>
| 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>While I think I have implemented it correctly (I can't see anything else that is wrong), it doesn't work, it updates a few links, removing the edges where the connecting vertex has a degree more than two, but it doesn't converge on the solution.</p>
<p>I was wondering if anyone had any ideas on what I have implemented incorrectly (Sorry about the horrible code).</p>
<p><strong>EDIT</strong><br />
Working code can be found at <a href="http://www.yacoby.net" rel="nofollow">Yacoby.net</a></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 modified board - not the board you had at the start.</p>
| 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>While I think I have implemented it correctly (I can't see anything else that is wrong), it doesn't work, it updates a few links, removing the edges where the connecting vertex has a degree more than two, but it doesn't converge on the solution.</p>
<p>I was wondering if anyone had any ideas on what I have implemented incorrectly (Sorry about the horrible code).</p>
<p><strong>EDIT</strong><br />
Working code can be found at <a href="http://www.yacoby.net" rel="nofollow">Yacoby.net</a></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:
n.update_state()
for n in neurons:
n.update_output()
</code></pre>
| 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>While I think I have implemented it correctly (I can't see anything else that is wrong), it doesn't work, it updates a few links, removing the edges where the connecting vertex has a degree more than two, but it doesn't converge on the solution.</p>
<p>I was wondering if anyone had any ideas on what I have implemented incorrectly (Sorry about the horrible code).</p>
<p><strong>EDIT</strong><br />
Working code can be found at <a href="http://www.yacoby.net" rel="nofollow">Yacoby.net</a></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 neighbors does not appear to distinguish between neighbors of the neuron and the neuron itself, and you run this code twice- once for each vertex.</p>
<p>Tests on my own code seem to confirm this. Convergence rates drastically improve when I subtract the neuron's own output twice rather than once.</p>
| 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></tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" &lt;email@email.com&gt;</td>
<td>1231231234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 01" &lt;email01@email.com&gt;</td>
<td>234234234234234</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 02" &lt;email2@email.com&gt;</td>
<td>32423234234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 03" &lt;email3@email.com&gt;</td>
<td>23423424324</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 04" &lt;email4@email.com&gt;</td>
<td>234234232324244</td>
</tr> <tr>
</code></pre>
| 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></tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" &lt;email@email.com&gt;</td>
<td>1231231234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 01" &lt;email01@email.com&gt;</td>
<td>234234234234234</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 02" &lt;email2@email.com&gt;</td>
<td>32423234234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 03" &lt;email3@email.com&gt;</td>
<td>23423424324</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 04" &lt;email4@email.com&gt;</td>
<td>234234232324244</td>
</tr> <tr>
</code></pre>
| 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('tr')
rows = [tag for tag in BeautifulSoup(data, parseOnlyThese=table_rows)]
return rows
def cell_data(row):
cells = [tag.string for tag in row.contents]
return cells
if __name__ == "__main__":
f = open("testdata.html", "r")
data = f.read()
rows = find_rows(data)
for row in rows:
print cell_data(row)
</code></pre>
<p>Save your html file as <code>testdata.html</code>, and run this script from the same directory.
With the data you posted here, the output is</p>
<pre><code>[u'\n', u'"JSC company inc. 00" &lt;email@email.com&gt;', u'\n', u'1231231234', u'\n']
[u'\n', u'"JSC company inc. 01" &lt;email01@email.com&gt;', u'\n', u'234234234234234', u'\n']
[u'\n', u'"JSC company inc. 02" &lt;email2@email.com&gt;', u'\n', u'32423234234', u'\n']
[u'\n', u'"JSC company inc. 03" &lt;email3@email.com&gt;', u'\n', u'23423424324', u'\n']
[u'\n', u'"JSC company inc. 04" &lt;email4@email.com&gt;', u'\n', u'234234232324244', u'\n']
</code></pre>
| 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></tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" &lt;email@email.com&gt;</td>
<td>1231231234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 01" &lt;email01@email.com&gt;</td>
<td>234234234234234</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 02" &lt;email2@email.com&gt;</td>
<td>32423234234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 03" &lt;email3@email.com&gt;</td>
<td>23423424324</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 04" &lt;email4@email.com&gt;</td>
<td>234234232324244</td>
</tr> <tr>
</code></pre>
| 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 you can. With Django, you not only get an ORM, you also get a web interface that lets you browse through your database with a web browser; you can even enter data into the database using the web browser.</p>
<p>If you can't use Django, I recommend <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>.</p>
<p>Good luck.</p>
| 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></tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" &lt;email@email.com&gt;</td>
<td>1231231234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 01" &lt;email01@email.com&gt;</td>
<td>234234234234234</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 02" &lt;email2@email.com&gt;</td>
<td>32423234234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 03" &lt;email3@email.com&gt;</td>
<td>23423424324</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 04" &lt;email4@email.com&gt;</td>
<td>234234232324244</td>
</tr> <tr>
</code></pre>
| 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()
print phone_number.text_content()
</code></pre>
| 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></tr><tr class="tableRowOdd">
<td>"JSC company inc. 00" &lt;email@email.com&gt;</td>
<td>1231231234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 01" &lt;email01@email.com&gt;</td>
<td>234234234234234</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 02" &lt;email2@email.com&gt;</td>
<td>32423234234</td>
</tr><tr class="tableRowEven">
<td>"JSC company inc. 03" &lt;email3@email.com&gt;</td>
<td>23423424324</td>
</tr><tr class="tableRowOdd">
<td>"JSC company inc. 04" &lt;email4@email.com&gt;</td>
<td>234234232324244</td>
</tr> <tr>
</code></pre>
| 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'll hijack gnuds example. Add to the top of the file:</p>
<pre><code> import re
</code></pre>
<p>Then at the bottom:</p>
<pre><code>exp = r'\"(.*)\" &lt;(.*)&gt;'
for row in rows:
matcher = re.match(exp, row[1])
name, email = matcher.groups()
phone = row[3]
sql = "INSERT INTO company (email, name, phone) VALUES ('%s','%s','%s')" % (email, name, phone)
print sql
</code></pre>
<p>Which gives you output like:</p>
<pre><code>INSERT INTO company (email, name, phone) VALUES ('email@email.com','JSC company inc. 00','1231231234');
INSERT INTO company (email, name, phone) VALUES ('email01@email.com','JSC company inc. 01','234234234234234');
INSERT INTO company (email, name, phone) VALUES ('email2@email.com','JSC company inc. 02','32423234234');
INSERT INTO company (email, name, phone) VALUES ('email3@email.com','JSC company inc. 03','23423424324');
INSERT INTO company (email, name, phone) VALUES ('email4@email.com','JSC company inc. 04','234234232324244');
</code></pre>
| 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 datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtimestamp(time)
elif isinstance(time,datetime):
diff = now - time
elif not time:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff / 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff / 3600) + " hours ago"
if day_diff == 1:
return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 31:
return str(day_diff / 7) + " weeks ago"
if day_diff < 365:
return str(day_diff / 30) + " months ago"
return str(day_diff / 365) + " years ago"
</code></pre>
| 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 = now - timedelta(hours=1)
yesterday = now - timedelta(days=1)
tomorrow = now + timedelta(days=1)
dayafter = now + timedelta(days=2)
import pretty
print pretty.date(now) # 'now'
print pretty.date(hrago) # 'an hour ago'
print pretty.date(hrago, short=True) # '1h ago'
print pretty.date(hrago, asdays=True) # 'today'
print pretty.date(yesterday, short=True) # 'yest'
print pretty.date(tomorrow) # 'tomorrow'
</code></pre>
| 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_full_version = False):
"""Returns a user friendly date format
d: some datetime instace in the past
display_second_unit: True/False
"""
#some helpers lambda's
plural = lambda x: 's' if x > 1 else ''
singular = lambda x: x[:-1]
#convert pluran (years) --> to singular (year)
display_unit = lambda unit, name: '%s %s%s'%(unit, name, plural(unit)) if unit > 0 else ''
#time units we are interested in descending order of significance
tm_units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
rdelta = relativedelta(datetime.utcnow(), d) #capture the date difference
for idx, tm_unit in enumerate(tm_units):
first_unit_val = getattr(rdelta, tm_unit)
if first_unit_val > 0:
primary_unit = display_unit(first_unit_val, singular(tm_unit))
if display_full_version and idx < len(tm_units)-1:
next_unit = tm_units[idx + 1]
second_unit_val = getattr(rdelta, next_unit)
if second_unit_val > 0:
secondary_unit = display_unit(second_unit_val, singular(next_unit))
return primary_unit + ', ' + secondary_unit
return primary_unit
return None
</code></pre>
| 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> into the template you're using the filter in.</p>
<p>Then, in your template, if you have a datetime variable <code>my_date</code>, you can print its distance from the present by using <code>{{ my_date|naturaltime }}</code>, which will be rendered as something like <code>4 minutes ago</code>.</p>
<p><a href="https://docs.djangoproject.com/en/dev/releases/1.4/">Other new things in Django 1.4.</a></p>
<p><a href="https://docs.djangoproject.com/en/dev/ref/contrib/humanize/">Documentation for <code>naturaltime</code> and other filters in the <code>django.contrib.humanize</code> set.</a></p>
| 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 = datetime.now() - timedelta(days=1, hours=5)
print(human(ts))
# 1 day, 5 hours ago
print(human(ts, precision=1))
# 1 day ago
</code></pre>
| 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 much use, I find I don't want to go to the next unit quite so eagerly. Example: both 7 days and 13 days will show as "1 week"; I'd rather see "7 days" or "13 days" instead.</li>
</ul>
<p>Here's what I came up with:</p>
<pre><code>def PrettyRelativeTime(time_diff_secs):
# Each tuple in the sequence gives the name of a unit, and the number of
# previous units which go into it.
weeks_per_month = 365.242 / 12 / 7
intervals = [('minute', 60), ('hour', 60), ('day', 24), ('week', 7),
('month', weeks_per_month), ('year', 12)]
unit, number = 'second', abs(time_diff_secs)
for new_unit, ratio in intervals:
new_number = float(number) / ratio
# If the new number is too small, don't go to the next unit.
if new_number < 2:
break
unit, number = new_unit, new_number
shown_num = int(number)
return '{} {}'.format(shown_num, unit + ('' if shown_num == 1 else 's'))
</code></pre>
<p>Notice how every tuple in <code>intervals</code> is easy to interpret and check: a <code>'minute'</code> is <code>60</code> seconds; an <code>'hour'</code> is <code>60</code> minutes; etc. The only fudge is setting <code>weeks_per_month</code> to its average value; given the application, that should be fine. (And note that it's clear at a glance that the last three constants multiply out to 365.242, the number of days per year.)</p>
<p>One downside to my function is that it doesn't do anything outside the "## units" pattern: "Yesterday", "just now", etc. are right out. Then again, the original poster didn't ask for these fancy terms, so I prefer my function for its succinctness and the readability of its numerical constants. :)</p>
| 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>>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> then = datetime(2003, 9, 17, 20, 54, 47, 282310)
>>> relativedelta(then, datetime.now())
relativedelta(years=-11, months=-3, days=-9, hours=-18, minutes=-17, seconds=-8, microseconds=+912664)
</code></pre>
| 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>>>> from datetime import datetime, timedelta
>>> import humanize # $ pip install humanize
>>> humanize.naturaltime(datetime.now() - timedelta(days=1))
'a day ago'
>>> humanize.naturaltime(datetime.now() - timedelta(hours=2))
'2 hours ago'
</code></pre>
<p>It supports localization <a href="/questions/tagged/l10n" class="post-tag" title="show questions tagged 'l10n'" rel="tag">l10n</a>, internationalization <a href="/questions/tagged/i18n" class="post-tag" title="show questions tagged 'i18n'" rel="tag">i18n</a>:</p>
<pre><code>>>> _ = humanize.i18n.activate('ru_RU')
>>> print humanize.naturaltime(datetime.now() - timedelta(days=1))
Ð´ÐµÐ½Ñ Ð½Ð°Ð·Ð°Ð´
>>> print humanize.naturaltime(datetime.now() - timedelta(hours=2))
2 ÑаÑа назад
</code></pre>
| 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,60,3600,3600*24,3600*24*7,3660*24*30]
values = []
for m in modulos[::-1]:
values.append(int(opened_for / m))
opened_for -= values[-1]*m
pretty = []
for i,nm in enumerate(names[::-1]):
if values[i]!=0:
pretty.append("%i %s" % (values[i],nm))
return " ".join(pretty)
</code></pre>
| 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></p>
<p>Below steps to install into your virtual env.</p>
<pre><code>git clone https://github.com/nareshchaudhary37/timestamp_content
cd timestamp-content
python setup.py
</code></pre>
| 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>>>> import arrow
>>> utc = arrow.utcnow()
>>> utc = utc.replace(hours=-1)
>>> local.humanize()
'an hour ago'
</code></pre>
</blockquote>
| 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="http://docs.python.org/library/locale.html" rel="nofollow">locale docs</a> that make the whole thing scary:</p>
<blockquote>
<p>On top of that, some implementation
are broken in such a way that frequent
locale changes may cause core dumps.
This makes the locale somewhat painful
to use correctly</p>
</blockquote>
<p>And</p>
<blockquote>
<p>It is generally a bad idea to call
setlocale() in some library routine,
since as a side effect it affects the
entire program</p>
</blockquote>
<p>So, is there a reasonable locale alternative for use in web apps? Is <a href="http://babel.edgewall.org/wiki/Documentation/0.9/index.html" rel="nofollow">Babel</a> it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers.</p>
<p>[Update] To clarify, I'm most interested in date, number, and currency formatting for various locales.</p>
| 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, unless I'm missing something.</p>
<p>You're not doing message catalogs or anything fancy, so stick with what Python gives you.</p>
| 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="http://docs.python.org/library/locale.html" rel="nofollow">locale docs</a> that make the whole thing scary:</p>
<blockquote>
<p>On top of that, some implementation
are broken in such a way that frequent
locale changes may cause core dumps.
This makes the locale somewhat painful
to use correctly</p>
</blockquote>
<p>And</p>
<blockquote>
<p>It is generally a bad idea to call
setlocale() in some library routine,
since as a side effect it affects the
entire program</p>
</blockquote>
<p>So, is there a reasonable locale alternative for use in web apps? Is <a href="http://babel.edgewall.org/wiki/Documentation/0.9/index.html" rel="nofollow">Babel</a> it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers.</p>
<p>[Update] To clarify, I'm most interested in date, number, and currency formatting for various locales.</p>
| 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 href="http://docs.python.org/library/gettext.html#the-gnutranslations-class" rel="nofollow">translation</a> per thread <a href="http://www.google.com/codesearch/p?hl=en&sa=N&cd=1&ct=rc#yo88Sa0j8hQ/browser/django/branches/i18n/django/utils/translation.py?rev=726&format=txt&q=gettext&exact%5Fpackage=http%3A//code.djangoproject.net&l=123" rel="nofollow">check here</a> how it is implemented (gettext function and _active dictionary).</p>
| 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="http://docs.python.org/library/locale.html" rel="nofollow">locale docs</a> that make the whole thing scary:</p>
<blockquote>
<p>On top of that, some implementation
are broken in such a way that frequent
locale changes may cause core dumps.
This makes the locale somewhat painful
to use correctly</p>
</blockquote>
<p>And</p>
<blockquote>
<p>It is generally a bad idea to call
setlocale() in some library routine,
since as a side effect it affects the
entire program</p>
</blockquote>
<p>So, is there a reasonable locale alternative for use in web apps? Is <a href="http://babel.edgewall.org/wiki/Documentation/0.9/index.html" rel="nofollow">Babel</a> it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers.</p>
<p>[Update] To clarify, I'm most interested in date, number, and currency formatting for various locales.</p>
| 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 support, speed, flexibility (downside: while ICU's docs are good, PyICU's, well, not so much;-). Alas, not always are you allowed to deploy your own extensions...:-(.</p>
<p>In particular, I'm still looking for a solid i18n/L10n solution for App Engine apps -- "translation" per se is the least of issues (you can just switch to the right set of templates), the problem is that there are many other L10n aspects (the ones that ICU supports so well, such as collation rules for example, etc, etc). I guess the already-mentioned <a href="http://babel.edgewall.org/wiki">Babel</a> is the only sensible place to start from.</p>
| 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="http://docs.python.org/library/locale.html" rel="nofollow">locale docs</a> that make the whole thing scary:</p>
<blockquote>
<p>On top of that, some implementation
are broken in such a way that frequent
locale changes may cause core dumps.
This makes the locale somewhat painful
to use correctly</p>
</blockquote>
<p>And</p>
<blockquote>
<p>It is generally a bad idea to call
setlocale() in some library routine,
since as a side effect it affects the
entire program</p>
</blockquote>
<p>So, is there a reasonable locale alternative for use in web apps? Is <a href="http://babel.edgewall.org/wiki/Documentation/0.9/index.html" rel="nofollow">Babel</a> it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers.</p>
<p>[Update] To clarify, I'm most interested in date, number, and currency formatting for various locales.</p>
| 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/dev/topics/i18n/#id2" rel="nofollow">docs</a>.</p>
| 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, which somehow only allows me to obtain the file in its entirety (in memory, which is a disaster in itself). Some advise to redefine the FieldStorage.make_file method(), which seems to break down the cgi implementation (weird...).</p>
<p>I am currently able to read the entire wsgi input, chunk by chunk, to the filesystem, resulting in the following data:</p>
<pre><code>-----------------------------9514143097616
Content-Disposition: form-data; name="myfile"; filename="inbound_marketing_cartoon_ebook.pdf"
Content-Type: application/pdf
... 1.5 MB of PDF data
-----------------------------9514143097616
Content-Disposition: form-data; name="tid"
194
-----------------------------9514143097616--
</code></pre>
<p>Does anyone know if there are any Python libraries that could reliably parse this thing?
Or should I do this manually? (Python 2.5 that is)</p>
<p>Thanks.</p>
| 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://docs.python.org/library/email.html" rel="nofollow" title="email">The documentation for <code>email</code></a> is quite thorough, at first glance.</p>
<p>My gut feeling would be to say that you're likely going to end up with the file in memory, however, which you did express chagrin at.</p>
| 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, which somehow only allows me to obtain the file in its entirety (in memory, which is a disaster in itself). Some advise to redefine the FieldStorage.make_file method(), which seems to break down the cgi implementation (weird...).</p>
<p>I am currently able to read the entire wsgi input, chunk by chunk, to the filesystem, resulting in the following data:</p>
<pre><code>-----------------------------9514143097616
Content-Disposition: form-data; name="myfile"; filename="inbound_marketing_cartoon_ebook.pdf"
Content-Type: application/pdf
... 1.5 MB of PDF data
-----------------------------9514143097616
Content-Disposition: form-data; name="tid"
194
-----------------------------9514143097616--
</code></pre>
<p>Does anyone know if there are any Python libraries that could reliably parse this thing?
Or should I do this manually? (Python 2.5 that is)</p>
<p>Thanks.</p>
| 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 indicator.</p>
<p>Doing it this way you also get access to the length of the file (as supplied by the client), file name, and the key that it is posted under.</p>
<p>Why does this seem to break down the CGI implementation for you?</p>
<p>Another option is to do the progress tracking in the browser with a flash uploader (<a href="http://developer.yahoo.com/yui/uploader/" rel="nofollow">YUI Uploader</a> and <a href="http://swfupload.org/" rel="nofollow">SWFUpload</a> come to mind) and skip tracking it on the server entirely. Then you don't have to have a series of AJAX requests to get the progress.</p>
| 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, which somehow only allows me to obtain the file in its entirety (in memory, which is a disaster in itself). Some advise to redefine the FieldStorage.make_file method(), which seems to break down the cgi implementation (weird...).</p>
<p>I am currently able to read the entire wsgi input, chunk by chunk, to the filesystem, resulting in the following data:</p>
<pre><code>-----------------------------9514143097616
Content-Disposition: form-data; name="myfile"; filename="inbound_marketing_cartoon_ebook.pdf"
Content-Type: application/pdf
... 1.5 MB of PDF data
-----------------------------9514143097616
Content-Disposition: form-data; name="tid"
194
-----------------------------9514143097616--
</code></pre>
<p>Does anyone know if there are any Python libraries that could reliably parse this thing?
Or should I do this manually? (Python 2.5 that is)</p>
<p>Thanks.</p>
| 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 documentation</a> and <a href="http://code.djangoproject.com/browser/django/trunk/django/core/files/" rel="nofollow">the relevant code</a> - even if you don't want to use Django, it's bound to give you some ideas.</p>
| 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.VERBOSE)
number = "+33.300000000"
p.sub("0\1", number)
</code></pre>
<p>But this doesn't work.</p>
<p>However, the search seams to work :</p>
<pre><code>>>> p.search(number).groups()
('300000000',)
</code></pre>
<p>And after how to modify 0300000000 in 03.00.00.00.00 in Python ?</p>
<p>Thank you for your help,</p>
<p>Natim</p>
| 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", number)
</code></pre>
| 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.VERBOSE)
number = "+33.300000000"
p.sub("0\1", number)
</code></pre>
<p>But this doesn't work.</p>
<p>However, the search seams to work :</p>
<pre><code>>>> p.search(number).groups()
('300000000',)
</code></pre>
<p>And after how to modify 0300000000 in 03.00.00.00.00 in Python ?</p>
<p>Thank you for your help,</p>
<p>Natim</p>
| 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 after each 2 digits
# and discard the resulting trailing dot
return re.sub(r'(\d\d)', r'\1.', digits)[:-1]
number = "+33.300000000"
print doitall(number)
</code></pre>
<p>emits <code>03.00.00.00.00</code>, as required.</p>
<p>Yes, you can do it all in a RE, but it's not worth the headache -- the mix works fine;-).</p>
| 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 cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application.</p>
<p>Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me?</p>
| 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 to overload addition and subtraction etc. But don't overload it unless it's natural: it makes no sense to define addition and subtraction for a <code>Car</code> or a <code>Vehicle</code> object.</p>
<p>Another rule of thumb: <strong>don't overload <code>==</code></strong>. It makes it very hard (though not impossible) to actually test if two objects are the same. I made this mistake and paid for it for a long time.</p>
<p>As for when to overload <code>+=</code>, <code>++</code> etc, I'd actually say: only overload additional operators if you have a lot of demand for that functionality. It's easier to have one way to do something than five. Sure, it means sometimes you'll have to write <code>x = x + 1</code> instead of <code>x += 1</code>, but more code is ok if it's clearer.</p>
<p>In general, like with many 'fancy' features, it's easy to think that you want something when you don't really, implement a bunch of stuff, not notice the side effects, and then figure it out later. Err on the conservative side.</p>
<p>EDIT: I wanted to add an explanatory note about overloading <code>==</code>, because it seems various commenters misunderstand this, and it's caught me out. Yes, <code>is</code> exists, but it's a different operation. Say I have an object <code>x</code>, which is either from my custom class, or is an integer. I want to see if <code>x</code> is the number 500. But if you set <code>x = 500</code>, then later test <code>x is 500</code>, you will get <code>False</code>, due to the way Python caches numbers. With <code>50</code>, it would return <code>True</code>. But you can't use <code>is</code>, because you might want <code>x == 500</code> to return <code>True</code> if <code>x</code> is an instance of your class. Confusing? Definitely. But this is the kind of detail you need to understand to successfully overload operators.</p>
| 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 cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application.</p>
<p>Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me?</p>
| 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 operator for unrelated purposes, such as C++ re-using the bitshifts to perform string formatting and parsing. Don't overload an operator with different semantics from your implementation just to get prettier syntax.</p>
<p>Modern Python style strongly discourages "rogue" overloading, but many aspects of the language and standard library retain poorly-named operators for backwards compatibility. For example:</p>
<ul>
<li><code>%</code>: modulus and string formatting</li>
<li><code>+</code>: addition and sequence concatenation</li>
<li><code>*</code>: multiplication and sequence repetition</li>
</ul>
<p>So, rule of thumb? If your operator implementation will surprise people, don't do it.</p>
| 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 cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application.</p>
<p>Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me?</p>
| 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 pipely(object):
def __init__(self, *args, **kw):
self._args = args
self.__dict__.update(kw)
def __ror__(self, other):
return ( self.map(x) for x in other if self.filter(x) )
def map(self, x):
return x
def filter(self, x):
return True
class sieve(pipely):
def filter(self, x):
n = self._args[0]
return x==n or x%n
class strify(pipely):
def map(self, x):
return str(x)
class startswith(pipely):
def filter(self, x):
n=str(self._args[0])
if x.startswith(n):
return x
print"*"*80
for i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | strify() | startswith(5):
print i
print"*"*80
for i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | pipely(map=str) | startswith(5):
print i
print"*"*80
for i in xrange(2,100) | sieve(2) | sieve(3) | sieve(5) | sieve(7) | pipely(map=str) | pipely(filter=lambda x: x.startswith('5')):
print i
</code></pre>
| 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 cases like adding an object to itself etc.), you should only consider it in those cases where this feature will have a major impact on your code, like overloading the operators for the matrix class in a math application.</p>
<p>Does the same apply to python? Would you recommend overriding operator behavior in python? And what rules of thumb can you give me?</p>
| 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 methods (and special methods, one with names starting and ending with double underscores AKA "dunders", are exactly the way you perform operator overloading in Python). This provides good starting guidance.</p>
<p>For example, a <code>Container</code> class <em>must</em> override special method <code>__contains__</code>, i.e., the membership check operator <code>item in container</code> (as in, <code>if item in container:</code> -- don't confuse with the <code>for</code> statement, <code>for item in container:</code>, which relies on <code>__iter__</code>!-).
Similarly, a <code>Hashable</code> must override <code>__hash__</code>, a <code>Sized</code> must override <code>__len__</code>, a <code>Sequence</code> or a <code>Mapping</code> must override <code>__getitem__</code>, and so forth. (Moreover, the ABCs can provide your class with mixin functionality -- e.g., both <code>Sequence</code> and <code>Mapping</code> can provide <code>__contains__</code> on the basis of your supplied <code>__getitem__</code> override, and thereby automatically make your class a <code>Container</code>).</p>
<p>Beyond the <code>collections</code>, you'll want to override special methods (i.e. provide for operator overloading) mostly if your new class "is a number". Other special cases exist, but resist the temptation of overloading operators "just for coolness", with no semantic connection to the "normal" meanings, as C++'s streams do for <code><<</code> and <code>>></code> and Python strings (in Python <code>2.*</code>, fortunately not in <code>3.*</code> any more;-) do for <code>%</code> -- when such operators do not any more mean "bit-shifting" or "division remainder", you're just engendering confusion. A language's standard library can get away with it (though it shouldn't;-), but unless your library gets as widespread as the language's standard one, the confusion will hurt!-)</p>
| 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] :
#Do something
</code></pre>
<p>which works, but is pretty ugly. It seems there has to be a better way to do this, so what's a more elegant solution?</p>
| 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:
</code></pre>
<p>And you can package it up into a function, if you don't mind longer lines:</p>
<pre><code>def maybe_list(f):
try:
return f()
except KeyError, IndexError, TypeError:
return []
for b in maybe_list(lambda: a["key"][0][0]):
</code></pre>
| 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] :
#Do something
</code></pre>
<p>which works, but is pretty ugly. It seems there has to be a better way to do this, so what's a more elegant solution?</p>
| 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] :
#Do something
</code></pre>
<p>which works, but is pretty ugly. It seems there has to be a better way to do this, so what's a more elegant solution?</p>
| 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 = {"key": {0: {0: "foo"} } };
print safe_indexer(a, "key", 0, 0)
print safe_indexer(a, "bad", 0, 0)
</code></pre>
<p>Output:</p>
<pre><code>foo
None
</code></pre>
| 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.)</p>
<p>I'm using python, and I'm reading a bit about fabric, but I'm running into a mental block.</p>
<p>I am using sqlalchemy-migrate to manage database versions and have the basic DNS stuff set up for the host. Additionally, I have a library that I'm currently working on that these two services both use (in my global site-packages directory). I deploy this egg after I change anything. This would ideally also be deployable, but only available to the correct version. Would I need two versions, stage-lib and live-lib? Is this possible with python eggs?</p>
<p>Would I need another host to act as a staging server for these services? Or is there a way to tell DNS that something@staging.myhost.com goes to a different port than 25?</p>
<p>I have a fabfile right now that has a bunch of methods like stage_smtp, stage_xmpp, live_smtp, live_xmpp.</p>
| 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></pre>
| 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 this file, I get..</p>
<blockquote>
<p>{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460
{\fonttbl\f0\fswiss\fcharset0
Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl720\margr720\margb720\margt720\vieww9000\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural</p>
</blockquote>
| 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, you may expose your application to the risk of updated versions of the RTF format which may render the parsing logic partially incorrect and hence yield wrong numeric data for the application).</p>
<p>Why not store this info in a true text file. This could be a flat text file or preferably an XML, YAML, JSON file for example for added "forward" compatibility as your application and you may add extra parameters and such in the file.</p>
<p>If this file is a given, however, there probably exist Python libraries to read and write to it. Check the <a href="http://pypi.python.org/pypi" rel="nofollow">Python Package Index (PyPI)</a> for the RTF keyword.</p>
| 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 this file, I get..</p>
<blockquote>
<p>{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460
{\fonttbl\f0\fswiss\fcharset0
Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl720\margr720\margb720\margt720\vieww9000\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural</p>
</blockquote>
| 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 know what I should look into to find the problem? I've checked that the packages are in the same place as other modules:</p>
<pre><code>In [1]: import pylab
In [2]: pylab
Out[2]: <module 'pylab' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/pylab.pyc'>
In [3]: import BeautifulSoup
In [4]: BeautifulSoup
Out[4]: <module 'BeautifulSoup' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/BeautifulSoup-3.1.0.1-py2.5.egg/BeautifulSoup.pyc'>
</code></pre>
<p>Maybe something not handling the <code>.eggs</code> correctly? Thanks.</p>
<p><strong>Update</strong>: Following up on gnibbler's post, I've found that the tab completion hits an exception at line 633 in completer.py at:</p>
<pre><code> try:
ret = self.matches[state].replace(magic_prefix,magic_escape)
return ret
except IndexError:
return None
</code></pre>
<p>But what is causing the failiure...</p>
<p><strong>Update</strong>: </p>
<pre><code>In [5]: from Bea<tab_here>
*** COMPLETE: <Bea> (0)
matches: []
state: 0
</code></pre>
<p>So this is just saying that the matches list is an empty set: there are no matches. It is still not finding the module. I'll try to investigate where <code>matches</code> is getting the modules its looking for when I have time.</p>
| 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>Perhaps uncommenting it will give you a clue</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 know what I should look into to find the problem? I've checked that the packages are in the same place as other modules:</p>
<pre><code>In [1]: import pylab
In [2]: pylab
Out[2]: <module 'pylab' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/pylab.pyc'>
In [3]: import BeautifulSoup
In [4]: BeautifulSoup
Out[4]: <module 'BeautifulSoup' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/BeautifulSoup-3.1.0.1-py2.5.egg/BeautifulSoup.pyc'>
</code></pre>
<p>Maybe something not handling the <code>.eggs</code> correctly? Thanks.</p>
<p><strong>Update</strong>: Following up on gnibbler's post, I've found that the tab completion hits an exception at line 633 in completer.py at:</p>
<pre><code> try:
ret = self.matches[state].replace(magic_prefix,magic_escape)
return ret
except IndexError:
return None
</code></pre>
<p>But what is causing the failiure...</p>
<p><strong>Update</strong>: </p>
<pre><code>In [5]: from Bea<tab_here>
*** COMPLETE: <Bea> (0)
matches: []
state: 0
</code></pre>
<p>So this is just saying that the matches list is an empty set: there are no matches. It is still not finding the module. I'll try to investigate where <code>matches</code> is getting the modules its looking for when I have time.</p>
| 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 know what I should look into to find the problem? I've checked that the packages are in the same place as other modules:</p>
<pre><code>In [1]: import pylab
In [2]: pylab
Out[2]: <module 'pylab' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/pylab.pyc'>
In [3]: import BeautifulSoup
In [4]: BeautifulSoup
Out[4]: <module 'BeautifulSoup' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/BeautifulSoup-3.1.0.1-py2.5.egg/BeautifulSoup.pyc'>
</code></pre>
<p>Maybe something not handling the <code>.eggs</code> correctly? Thanks.</p>
<p><strong>Update</strong>: Following up on gnibbler's post, I've found that the tab completion hits an exception at line 633 in completer.py at:</p>
<pre><code> try:
ret = self.matches[state].replace(magic_prefix,magic_escape)
return ret
except IndexError:
return None
</code></pre>
<p>But what is causing the failiure...</p>
<p><strong>Update</strong>: </p>
<pre><code>In [5]: from Bea<tab_here>
*** COMPLETE: <Bea> (0)
matches: []
state: 0
</code></pre>
<p>So this is just saying that the matches list is an empty set: there are no matches. It is still not finding the module. I'll try to investigate where <code>matches</code> is getting the modules its looking for when I have time.</p>
| 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 IPython regenerates its database. Then you can have TAB-completion of new modules.</p>
| 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 distribution of files per directory?</strong></p>
<p><strong>Clarification:</strong> I'm not comparing different VCS repo formats (eg. SVN vs Git vs Hg), but profiling software that deals with SVN (and eventually other) working copies and repos.</p>
<p>The constraints I'd like are to specify the total number of files (call it 'N', probably ~10k-100k) and the maximum depth of the directory structure ('L', probably 2-10). I don't care how many directories are generated at each level, and I don't want to end up with 1 file per dir, or 100k all in one dir.</p>
<p>The distribution is something I'm not sure about, since I don't know whether VCS' (SVN in particular) would perform better or worse with a very uniform structure or a very skewed structure. Nonetheless, it would be nice if I could come up with an algorithm that didn't "even out" for large numbers.</p>
<p>My first thoughts were: generate the directory tree using some method, and then uniformly populate the tree with files (treating each dir equally, with no regard as to nesting). My back-of-the-envelope calcs tell me that if there are 'L' levels, with 'D' subdirs per dir, and about sqrt(N) files per dir, then there will be about D^L dirs, so N =~ sqrt(N)*(D^L) => D =~ N^(1/2L). So now I have an approximate value for 'D', how can I generate the tree? How do I populate the files?</p>
<p>I'd be grateful just for some pointers to good resources on algorithms I could use. My searching only found pretty applets/flash.</p>
| 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 distribution of files per directory?</strong></p>
<p><strong>Clarification:</strong> I'm not comparing different VCS repo formats (eg. SVN vs Git vs Hg), but profiling software that deals with SVN (and eventually other) working copies and repos.</p>
<p>The constraints I'd like are to specify the total number of files (call it 'N', probably ~10k-100k) and the maximum depth of the directory structure ('L', probably 2-10). I don't care how many directories are generated at each level, and I don't want to end up with 1 file per dir, or 100k all in one dir.</p>
<p>The distribution is something I'm not sure about, since I don't know whether VCS' (SVN in particular) would perform better or worse with a very uniform structure or a very skewed structure. Nonetheless, it would be nice if I could come up with an algorithm that didn't "even out" for large numbers.</p>
<p>My first thoughts were: generate the directory tree using some method, and then uniformly populate the tree with files (treating each dir equally, with no regard as to nesting). My back-of-the-envelope calcs tell me that if there are 'L' levels, with 'D' subdirs per dir, and about sqrt(N) files per dir, then there will be about D^L dirs, so N =~ sqrt(N)*(D^L) => D =~ N^(1/2L). So now I have an approximate value for 'D', how can I generate the tree? How do I populate the files?</p>
<p>I'd be grateful just for some pointers to good resources on algorithms I could use. My searching only found pretty applets/flash.</p>
| 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 duty, perhaps the python bindings for the GNU Scientific Library.</p>
<p><a href="http://sourceforge.net/projects/pygsl/" rel="nofollow">http://sourceforge.net/projects/pygsl/</a></p>
<p><a href="http://www.gnu.org/software/gsl/" rel="nofollow">http://www.gnu.org/software/gsl/</a></p>
| 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 building exactly the same thing for you, so this is really a case where there is no "best" answer.</p>
| 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>>>> list[0]['open'] = True
>>> list[1]['open'] = False
>>> print list[0]['open']
False
>>> list[0] is list[1]
True
</code></pre>
<p>As gs noted, tn python 2.6, you can use namedtuple, which is easier on memory: </p>
<pre><code>from collections import namedtuple
Socket = namedtuple('Socket', 'open serve')
sockets = [Socket(False,False) for i in range(150)]
</code></pre>
| 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.
>>> import sqlite3
>>> sqlite3.version
'2.4.1'
</code></pre>
<p>Questions:</p>
<ul>
<li>Why is the version of the sqlite**3** module <strong>'2.4.1'</strong></li>
<li>Whats the reason behind bundling such an old sqlite with Python? The sqlite releaselog says <strong>2002 Mar 13 (2.4.1)</strong>.</li>
</ul>
| 19 | 2009-10-12T07:22:09Z | 1,553,190 | <pre><code>Python 2.5.1
>>> import sqlite3
>>> sqlite3.version
'2.3.2'
>>> 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/site2/
site3: 155.55.55.1:8090, script at /opt/django/site3/
</code></pre>
<p>Here is my apache default: </p>
<pre><code><VirtualHost *:80>
ServerName /
ServerAlias */
DocumentRoot /opt/django/site1/
LogLevel warn
WSGIScriptAlias / /opt/django/site1/apache/django.wsgi
Alias /media /opt/django/site1/media/statics
Alias /admin_media /home/myuser/Django-1.1/django/contrib/admin/media
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/usr/share/phpmyadmin"
ServerName /phpmyadmin
Alias /phpmyadmin /usr/share/phpmyadmin
<Directory /usr/share/phpmyadmin>
Options Indexes FollowSymLinks
AllowOverride None
Order Deny,Allow
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<p>And here is my wsgi config for <code>site1</code>, at <code>/opt/django/site1/apache/django.wsgi</code>:</p>
<pre><code>import os, sys
import django.core.handlers.wsgi
sys.path.append('/opt/django')
sys.path.append('/opt/django/site1')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings'
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>How can I add <code>site2</code> and <code>site3</code>, which are Django-based sites and will be served like <code>site1</code>?</p>
| 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 DocumentRoot to be where your Django code is as it makes it easier to accidentally expose your source code to download if you stuff up Apache configuration. So, just remove DocumentRoot directive from VirtualHost for Django sites.</p>
<pre><code>Listen 80
<VirtualHost *:80>
ServerName www.example.com
WSGIScriptAlias / /opt/django/site1/apache/django.wsgi
Alias /media /opt/django/site1/media/statics
Alias /admin_media /home/myuser/Django-1.1/django/contrib/admin/media
<Directory opt/django/site1/apache>
Order allow,deny
Allow from all
</Directory>
<Directory /home/myuser/Django-1.1/django/contrib/admin/media>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Listen 8080
<VirtualHost *:8080>
ServerName www.example.com
WSGIScriptAlias / /opt/django/site2/apache/django.wsgi
Alias /media /opt/django/site2/media/statics
Alias /admin_media /home/myuser/Django-1.1/django/contrib/admin/media
<Directory opt/django/site2/apache>
Order allow,deny
Allow from all
</Directory>
<Directory /home/myuser/Django-1.1/django/contrib/admin/media>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Listen 8090
<VirtualHost *:8090>
ServerName www.example.com
WSGIScriptAlias / /opt/django/site3/apache/django.wsgi
Alias /media /opt/django/site3/media/statics
Alias /admin_media /home/myuser/Django-1.1/django/contrib/admin/media
<Directory opt/django/site3/apache>
Order allow,deny
Allow from all
</Directory>
<Directory /home/myuser/Django-1.1/django/contrib/admin/media>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<p>I have also add missing Directory directive for allowing access to static files. You should review paths however.</p>
<p>Make sure you read:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango">http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango</a>
<a href="http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting_Of_Static_Files">http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting_Of_Static_Files</a></p>
<p>for further information.</p>
<hr>
<p>UPDATE 1</p>
<p>BTW, since you are using PHP in same Apache, you would be much better off using mod_wsgi daemon mode and push each Django instance out into its own separate process. That allows those processes to be multithreaded, even though main Apache processes are forced to be single threaded because of PHP. End result will be much much less memory being used than if running multiple Django instances in each process under embedded mode with prefork MPM. Your Django code just needs to be thread safe. Configuration in addition to above would be to add WSGIDaemonProcess/WSGIProcessGroup to each Django VirtualHost, where name of daemon process group is different for each VirtualHost.</p>
<pre><code><VirtualHost *:80>
WSGIDaemonProcess site1 display-name=%{GROUP}
WSGIProcessGroup site1
... existing stuff
</VirtualHost>
<VirtualHost *:8080>
WSGIDaemonProcess site2 display-name=%{GROUP}
WSGIProcessGroup site2
... existing stuff
</VirtualHost>
<VirtualHost *:8090>
WSGIDaemonProcess site3 display-name=%{GROUP}
WSGIProcessGroup site3
... existing stuff
</VirtualHost>
</code></pre>
<p>This also allows you to more easily restart each Django instance without restart whole of Apache. Read:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide#Delegation_To_Daemon_Process">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide#Delegation_To_Daemon_Process</a>
<a href="http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode">http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode</a></p>
| 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/site2/
site3: 155.55.55.1:8090, script at /opt/django/site3/
</code></pre>
<p>Here is my apache default: </p>
<pre><code><VirtualHost *:80>
ServerName /
ServerAlias */
DocumentRoot /opt/django/site1/
LogLevel warn
WSGIScriptAlias / /opt/django/site1/apache/django.wsgi
Alias /media /opt/django/site1/media/statics
Alias /admin_media /home/myuser/Django-1.1/django/contrib/admin/media
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/usr/share/phpmyadmin"
ServerName /phpmyadmin
Alias /phpmyadmin /usr/share/phpmyadmin
<Directory /usr/share/phpmyadmin>
Options Indexes FollowSymLinks
AllowOverride None
Order Deny,Allow
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<p>And here is my wsgi config for <code>site1</code>, at <code>/opt/django/site1/apache/django.wsgi</code>:</p>
<pre><code>import os, sys
import django.core.handlers.wsgi
sys.path.append('/opt/django')
sys.path.append('/opt/django/site1')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings'
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>How can I add <code>site2</code> and <code>site3</code>, which are Django-based sites and will be served like <code>site1</code>?</p>
| 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 for each of the site-admin unix users, scripts can check if a site is active etc. </p>
<p>Basically it would be nice to have one central howto for Django-Admin installations, the current multitude of separate docs, links and blog articles is not really helpful for the proliferation of Django. </p>
| 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': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}]
</code></pre>
<p>In this for the open flag:</p>
<pre><code>[{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 24, 'open': False}]
</code></pre>
<p>And another to generate the serve one.</p>
<p>How can I do this the smartest way using Python ?</p>
<p>I could count the case one by one, but it doesn't seams to be a good idea.</p>
| 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})
current_value = value
current_span = 0
current_span += 1
result.append({'colspan': current_span, key: current_value})
return result
by_open = cluster(data, 'open')
by_serve = cluster(data, 'serve')
</code></pre>
<p>Second version, inspired by Denis' answer and his use of <code>itertools.groupby</code>:</p>
<pre><code>import itertools
import operator
def make_spans(data, key):
groups = itertools.groupby(data, operator.itemgetter(key))
return [{'colspan': len(list(items)), key: value} for value, items in groups]
</code></pre>
| 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': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': True, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': True}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}, {'serve': False, 'open': False}]
</code></pre>
<p>In this for the open flag:</p>
<pre><code>[{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 24, 'open': False}]
</code></pre>
<p>And another to generate the serve one.</p>
<p>How can I do this the smartest way using Python ?</p>
<p>I could count the case one by one, but it doesn't seams to be a good idea.</p>
| 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>>>> groupped = itertools.groupby(your_list, operator.itemgetter('open'))
>>> [{'colspan': len(list(group)), 'open': open} for open, group in groupped]
[{'colspan': 12, 'open': False}, {'colspan': 60, 'open': True}, {'colspan': 78, 'open': False}]
>>> groupped = itertools.groupby(your_list)
>>> [dict(d, colspan=len(list(group))) for d, group in groupped]
[{'serve': False, 'open': False, 'colspan': 12}, {'serve': True, 'open': True, 'colspan': 52}, {'serve': False, 'open': True, 'colspan': 8}, {'serve': False, 'open': False, 'colspan': 78}]
</code></pre>
| 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"><em>printf-style String Formatting</em></a> section of the documentation.</p>
| 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 with some related values in it:</p>
<pre><code>favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
</code></pre>
<p>You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".</p>
<p>There are several ways to do this:</p>
<pre><code>for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
</code></pre>
<p>or</p>
<pre><code>for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
</code></pre>
<p>And many more as well...</p>
<p>I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!</p>
| 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>>>> import collections
>>> mydict = collections.defaultdict(list)
</code></pre>
<p>In this way calling <code>.append(...)</code> will always succeed, because in case of a non-existing key <code>append</code> will be called on a fresh empty list.</p>
<p>You can instantiate the <code>defaultdict</code> with a previously generated list, in case you get the dict <code>likes</code> from another source, like so:</p>
<pre><code>>>> mydict = collections.defaultdict(list, likes)
</code></pre>
<p>Note that using <code>list</code> as the <code>default_factory</code> attribute of a <code>defaultdict</code> is also discussed as an example in the <a href="http://docs.python.org/3.1/library/collections.html#defaultdict-examples" rel="nofollow">documentation</a>.</p>
| 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 with some related values in it:</p>
<pre><code>favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
</code></pre>
<p>You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".</p>
<p>There are several ways to do this:</p>
<pre><code>for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
</code></pre>
<p>or</p>
<pre><code>for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
</code></pre>
<p>And many more as well...</p>
<p>I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!</p>
| 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 a such a function, it creates empty lists.</p>
<p>And iterating over .items() will save you from using the key to get the value.</p>
| 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 with some related values in it:</p>
<pre><code>favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
</code></pre>
<p>You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".</p>
<p>There are several ways to do this:</p>
<pre><code>for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
</code></pre>
<p>or</p>
<pre><code>for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
</code></pre>
<p>And many more as well...</p>
<p>I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!</p>
| 3 | 2009-10-12T09:01:02Z | 1,553,495 | <pre><code>>>> from collections import defaultdict
>>> d = defaultdict(list, likes)
>>> d
defaultdict(<class 'list'>, {'colors': ['blue', 'red', 'purple'], 'foods': ['apples', 'oranges']})
>>> for i, j in favorites.items():
d[i].append(j)
>>> d
defaultdict(<class 'list'>, {'desserts': ['ice cream'], 'colors': ['blue', 'red', 'purple', 'yellow'], 'foods': ['apples', 'oranges']})
</code></pre>
| 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 with some related values in it:</p>
<pre><code>favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
</code></pre>
<p>You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".</p>
<p>There are several ways to do this:</p>
<pre><code>for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
</code></pre>
<p>or</p>
<pre><code>for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
</code></pre>
<p>And many more as well...</p>
<p>I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!</p>
| 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. Let's remember it is 20 years since the Wall fell in Europe..</p>
| 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 with some related values in it:</p>
<pre><code>favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
</code></pre>
<p>You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".</p>
<p>There are several ways to do this:</p>
<pre><code>for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
</code></pre>
<p>or</p>
<pre><code>for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
</code></pre>
<p>And many more as well...</p>
<p>I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!</p>
| 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.com/questions/3031817/how-do-i-make-a-defaultdict-safe-for-unexpecting-clients</a> ) I'm personally torn on the matter. (I actually found this question looking for an answer to "which is better, <code>dict.get()</code> or <code>defaultdict</code>") Someone in the other thread said that you don't want a <code>defaultdict</code> if you don't want this behavior all the time, and that might be true. Maybe using defaultdict for the convenience is the wrong way to go about it. I think there are two needs being conflated here:</p>
<p>"I want a dict whose default values are empty lists." to which <code>defaultdict(list)</code> is the correct solution.</p>
<p>and</p>
<p>"I want to append to the list at this key if it exists and create a list if it does not exist." to which <code>my_dict.get('foo', [])</code> with <code>append()</code> is the answer.</p>
<p>What do you guys think?</p>
| 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 tag/classes used everywhere) and I don't know where i should start...</p>
<p>Just being curious, is using regexp (PHP/Python) faster than using Python's XPath library? Is Xpath library for Python generally faster than PHP's counterpart?</p>
| 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 are faster than in PHP in my subjective experience. Partly due to Python being a compiled language instead of interpreted at runtime, partly due to Python having been optimized for greater efficiency by its contributors...</p>
<p>Still, for 40k+ documents, find a nice fast machine ;-)</p>
| 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 tag/classes used everywhere) and I don't know where i should start...</p>
<p>Just being curious, is using regexp (PHP/Python) faster than using Python's XPath library? Is Xpath library for Python generally faster than PHP's counterpart?</p>
| 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 the task using the new multi-threads or the classic <a href="http://www.parallelpython.com/" rel="nofollow">parallel python</a>.</p>
| 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 tag/classes used everywhere) and I don't know where i should start...</p>
<p>Just being curious, is using regexp (PHP/Python) faster than using Python's XPath library? Is Xpath library for Python generally faster than PHP's counterpart?</p>
| 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 any pure php or python version.</p>
<p>There are some impressive <a href="http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/" rel="nofollow">benchmarks</a> from Ian Bicking:</p>
<blockquote>
<p><strong>In Conclusion</strong></p>
<p>I knew lxml was fast before I started these benchmarks, but I didnât expect it to be quite this fast.</p>
</blockquote>
<p>Parsing Results:</p>
<p><img src="http://1.2.3.9/bmi/blog.ianbicking.org/wp-content/uploads/images/parsing-results.png" alt="Parsing Resutls" /></p>
| 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 & 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 & Pacemakers"...encoded
Is the correct way doing this by using urllib??</p>
<p>How do I encode it BEFORE it hits the view?
It's very weird, because the URL contains the encoding:
?q=gerry+%26+pacemakers</p>
| 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="http://pages.github.com/">http://pages.github.com/</a>.</p>
<p>You will likely run into an issue using Sphinx on github, because Sphinx uses directories with leading underscores. You can fix this by adding a file called <code>.nojekyll</code> in the the directory with the generated sphinx html.</p>
| 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 course using itself) for how to set it up for your project.</p>
| 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">Sphinx documentation on GitHub</a>, which provides step by step instructions as well as a convenient <a href="http://fabfile.org/" rel="nofollow">Fabric</a> based script/task tying those together to get you started to <em>Quickly publish documentation alongside your code [...]</em> via a single command.</p>
| 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 session data somewhere on the server (memory, database, disk) and use the cookie number as a key to retrieve it on every request made by the client.</p>
<p>However <code>cgi</code> is not how you develop applications for the web in python. Use <a href="http://wsgi.org/" rel="nofollow"><code>wsgi</code></a>. Use a web framework.</p>
<p>Here's a quick example using <a href="http://cherrypy.org/" rel="nofollow">cherrypy</a>. <code>cherrypy.tools.sessions</code> is a cherrypy tool that handles cookie setting/retrieving and association with data automatically:</p>
<pre><code>import cherrypy
class HelloSessionWorld(object):
@cherrypy.tools.sessions()
def index(self):
if 'data' in cherrypy.session:
return "You have a cookie! It says: %r" % cherrypy.session['data']
else:
return "You don't have a cookie. <a href='getcookie'>Get one</a>."
index.exposed = True
@cherrypy.tools.sessions()
def getcookie(self):
cherrypy.session['data'] = 'Hello World'
return "Done. Please <a href='..'>return</a> to see it"
getcookie.exposed = True
application = cherrypy.tree.mount(HelloSessionWorld(), '/')
if __name__ == '__main__':
cherrypy.quickstart(application)
</code></pre>
<p>Note that this code is a <code>wsgi</code> application, in the sense that you can publish it to any <code>wsgi</code>-enabled web server (apache has <a href="http://code.google.com/p/modwsgi" rel="nofollow"><code>mod_wsgi</code></a>). Also, cherrypy has its own <code>wsgi</code> server, so you can just run the code with python and it will start serving on <a href="http://localhost:8080/" rel="nofollow"><code>http://localhost:8080/</code></a></p>
| 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 as good. Just... please don't suggest random timetabling stuff such as the ones for booking classrooms, as I don't think they can do this.</p>
<p>Thanks in advance for reading; I know it's a big post. I'm trying to do my best to document this clearly though, and to show that I've made efforts on my own.</p>
<h2>Problem</h2>
<p>I need a worker/timeslot scheduling algorithm which generates shifts for workers, which meets the following criteria:</p>
<p><strong>Input Data</strong></p>
<pre><code>import datetime.datetime as dt
class DateRange:
def __init__(self, start, end):
self.start = start
self.end = end
class Shift:
def __init__(self, range, min, max):
self.range = range
self.min_workers = min
self.max_workers = max
tue_9th_10pm = dt(2009, 1, 9, 22, 0)
wed_10th_4am = dt(2009, 1, 10, 4, 0)
wed_10th_10am = dt(2009, 1, 10, 10, 0)
shift_1_times = Range(tue_9th_10pm, wed_10th_4am)
shift_2_times = Range(wed_10th_4am, wed_10th_10am)
shift_3_times = Range(wed_10th_10am, wed_10th_2pm)
shift_1 = Shift(shift_1_times, 2,3) # allows 3, requires 2, but only 2 available
shift_2 = Shift(shift_2_times, 2,2) # allows 2
shift_3 = Shift(shift_3_times, 2,3) # allows 3, requires 2, 3 available
shifts = ( shift_1, shift_2, shift_3 )
joe_avail = [ shift_1, shift_2 ]
bob_avail = [ shift_1, shift_3 ]
sam_avail = [ shift_2 ]
amy_avail = [ shift_2 ]
ned_avail = [ shift_2, shift_3 ]
max_avail = [ shift_3 ]
jim_avail = [ shift_3 ]
joe = Worker('joe', joe_avail)
bob = Worker('bob', bob_avail)
sam = Worker('sam', sam_avail)
ned = Worker('ned', ned_avail)
max = Worker('max', max_avail)
amy = Worker('amy', amy_avail)
jim = Worker('jim', jim_avail)
workers = ( joe, bob, sam, ned, max, amy, jim )
</code></pre>
<h2>Processing</h2>
<p>From above, <em>shifts</em> and <em>workers</em> are the two main input variables to process</p>
<p>Each shift has a minimum and maximum number of workers needed. Filling the minimum requirements for a shift is crucial to success, but if all else fails, a rota with gaps to be filled manually is better than "error" :) The main algorithmic issue is that there shouldn't be unnecessary gaps, when enough workers are available.</p>
<p>Ideally, the maximum number of workers for a shift would be filled, but this is the lowest priority relative to other constraints, so if anything has to give, it should be this.</p>
<p><strong>Flexible constraints</strong></p>
<p>These are a little flexible, and their boundaries can be pushed a little if a "perfect" solution can't be found. This flexibility should be a last resort though, rather than being exploited randomly. Ideally, the flexibility would be configurable with a "fudge_factor" variable, or similar.</p>
<ul>
<li>There is a minimum time period
between two shifts. So, a worker
shouldn't be scheduled for two shifts
in the same day, for instance.</li>
<li>There are a maximum number of shifts a
worker can do in a given time period
(say, a month)</li>
<li>There are a maximum number of certain
shifts that can be done in a month
(say, overnight shifts)</li>
</ul>
<p><strong>Nice to have, but not necessary</strong></p>
<p>If you can come up with an algorithm which does the above and includes any/all of these, I'll be seriously impressed and grateful. Even an add-on script to do these bits separately would be great too.</p>
<ul>
<li><p>Overlapping shifts. For instance,
it would be good to be able to specify
a "front desk" shift and a "back office"
shift that both occur at the same time.
This could be done with separate invocations
of the program with different shift data,
except that the constraints about scheduling
people for multiple shifts in a given time
period would be missed.</p></li>
<li><p>Minimum reschedule time period for workers specifiable
on a per-worker (rather than global) basis. For instance,
if Joe is feeling overworked or is dealing with personal issues,
or is a beginner learning the ropes, we might want to schedule him
less often than other workers.</p></li>
<li><p>Some automated/random/fair way of selecting staff to fill minimum
shift numbers when no available workers fit.</p></li>
<li><p>Some way of handling sudden cancellations, and just filling the gaps
without rearranging other shifts.</p></li>
</ul>
<h2>Output Test</h2>
<p>Probably, the algorithm should generate as many matching Solutions as possible, where each Solution looks like this:</p>
<pre><code>class Solution:
def __init__(self, shifts_workers):
"""shifts_workers -- a dictionary of shift objects as keys, and a
a lists of workers filling the shift as values."""
assert isinstance(dict, shifts_workers)
self.shifts_workers = shifts_workers
</code></pre>
<p>Here's a test function for an individual solution, given the above data. I <em>think</em> this is right, but I'd appreciate some peer review on it too.</p>
<pre><code>def check_solution(solution):
assert isinstance(Solution, solution)
def shift_check(shift, workers, workers_allowed):
assert isinstance(Shift, shift):
assert isinstance(list, workers):
assert isinstance(list, workers_allowed)
num_workers = len(workers)
assert num_workers >= shift.min_workers
assert num_workers <= shift.max_workers
for w in workers_allowed:
assert w in workers
shifts_workers = solution.shifts_workers
# all shifts should be covered
assert len(shifts_workers.keys()) == 3
assert shift1 in shifts_workers.keys()
assert shift2 in shifts_workers.keys()
assert shift3 in shifts_workers.keys()
# shift_1 should be covered by 2 people - joe, and bob
shift_check(shift_1, shifts_workers[shift_1], (joe, bob))
# shift_2 should be covered by 2 people - sam and amy
shift_check(shift_2, shifts_workers[shift_2], (sam, amy))
# shift_3 should be covered by 3 people - ned, max, and jim
shift_check(shift_3, shifts_workers[shift_3], (ned,max,jim))
</code></pre>
<h2>Attempts</h2>
<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>
<p>My latest attempt is to generate every possible permutation as a solution, then whittle down the permutations that don't meet the constraints. This seems to work much more quickly, and has gotten me further, but I'm using python 2.6's itertools.product() to help generate the permutations, and I can't quite get it right. It wouldn't surprise me if there are many bugs as, honestly, the problem doesn't fit in my head that well :)</p>
<p>Currently my code for this is in two files: models.py and rota.py. models.py looks like:</p>
<pre><code># -*- coding: utf-8 -*-
class Shift:
def __init__(self, start_datetime, end_datetime, min_coverage, max_coverage):
self.start = start_datetime
self.end = end_datetime
self.duration = self.end - self.start
self.min_coverage = min_coverage
self.max_coverage = max_coverage
def __repr__(self):
return "<Shift %s--%s (%r<x<%r)" % (self.start, self.end, self.min_coverage, self.max_coverage)
class Duty:
def __init__(self, worker, shift, slot):
self.worker = worker
self.shift = shift
self.slot = slot
def __repr__(self):
return "<Duty worker=%r shift=%r slot=%d>" % (self.worker, self.shift, self.slot)
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Duty shift=%s slot=%s" % (self.shift, self.slot)
self.worker.dump(indent=indent, depth=depth+1)
print ind + ">"
class Avail:
def __init__(self, start_time, end_time):
self.start = start_time
self.end = end_time
def __repr__(self):
return "<%s to %s>" % (self.start, self.end)
class Worker:
def __init__(self, name, availabilities):
self.name = name
self.availabilities = availabilities
def __repr__(self):
return "<Worker %s Avail=%r>" % (self.name, self.availabilities)
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Worker %s" % self.name
for avail in self.availabilities:
print ind + " " * indent + repr(avail)
print ind + ">"
def available_for_shift(self, shift):
for a in self.availabilities:
if shift.start >= a.start and shift.end <= a.end:
return True
print "Worker %s not available for %r (Availability: %r)" % (self.name, shift, self.availabilities)
return False
class Solution:
def __init__(self, shifts):
self._shifts = list(shifts)
def __repr__(self):
return "<Solution: shifts=%r>" % self._shifts
def duties(self):
d = []
for s in self._shifts:
for x in s:
yield x
def shifts(self):
return list(set([ d.shift for d in self.duties() ]))
def dump_shift(self, s, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<ShiftList"
for duty in s:
duty.dump(indent=indent, depth=depth+1)
print ind + ">"
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Solution"
for s in self._shifts:
self.dump_shift(s, indent=indent, depth=depth+1)
print ind + ">"
class Env:
def __init__(self, shifts, workers):
self.shifts = shifts
self.workers = workers
self.fittest = None
self.generation = 0
class DisplayContext:
def __init__(self, env):
self.env = env
def status(self, msg, *args):
raise NotImplementedError()
def cleanup(self):
pass
def update(self):
pass
</code></pre>
<p>and rota.py looks like:</p>
<pre><code>#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
from datetime import datetime as dt
am2 = dt(2009, 10, 1, 2, 0)
am8 = dt(2009, 10, 1, 8, 0)
pm12 = dt(2009, 10, 1, 12, 0)
def duties_for_all_workers(shifts, workers):
from models import Duty
duties = []
# for all shifts
for shift in shifts:
# for all slots
for cov in range(shift.min_coverage, shift.max_coverage):
for slot in range(cov):
# for all workers
for worker in workers:
# generate a duty
duty = Duty(worker, shift, slot+1)
duties.append(duty)
return duties
def filter_duties_for_shift(duties, shift):
matching_duties = [ d for d in duties if d.shift == shift ]
for m in matching_duties:
yield m
def duty_permutations(shifts, duties):
from itertools import product
# build a list of shifts
shift_perms = []
for shift in shifts:
shift_duty_perms = []
for slot in range(shift.max_coverage):
slot_duties = [ d for d in duties if d.shift == shift and d.slot == (slot+1) ]
shift_duty_perms.append(slot_duties)
shift_perms.append(shift_duty_perms)
all_perms = ( shift_perms, shift_duty_perms )
# generate all possible duties for all shifts
perms = list(product(*shift_perms))
return perms
def solutions_for_duty_permutations(permutations):
from models import Solution
res = []
for duties in permutations:
sol = Solution(duties)
res.append(sol)
return res
def find_clashing_duties(duty, duties):
"""Find duties for the same worker that are too close together"""
from datetime import timedelta
one_day = timedelta(days=1)
one_day_before = duty.shift.start - one_day
one_day_after = duty.shift.end + one_day
for d in [ ds for ds in duties if ds.worker == duty.worker ]:
# skip the duty we're considering, as it can't clash with itself
if duty == d:
continue
clashes = False
# check if dates are too close to another shift
if d.shift.start >= one_day_before and d.shift.start <= one_day_after:
clashes = True
# check if slots collide with another shift
if d.slot == duty.slot:
clashes = True
if clashes:
yield d
def filter_unwanted_shifts(solutions):
from models import Solution
print "possibly unwanted:", solutions
new_solutions = []
new_duties = []
for sol in solutions:
for duty in sol.duties():
duty_ok = True
if not duty.worker.available_for_shift(duty.shift):
duty_ok = False
if duty_ok:
print "duty OK:"
duty.dump(depth=1)
new_duties.append(duty)
else:
print "duty **NOT** OK:"
duty.dump(depth=1)
shifts = set([ d.shift for d in new_duties ])
shift_lists = []
for s in shifts:
shift_duties = [ d for d in new_duties if d.shift == s ]
shift_lists.append(shift_duties)
new_solutions.append(Solution(shift_lists))
return new_solutions
def filter_clashing_duties(solutions):
new_solutions = []
for sol in solutions:
solution_ok = True
for duty in sol.duties():
num_clashing_duties = len(set(find_clashing_duties(duty, sol.duties())))
# check if many duties collide with this one (and thus we should delete this one
if num_clashing_duties > 0:
solution_ok = False
break
if solution_ok:
new_solutions.append(sol)
return new_solutions
def filter_incomplete_shifts(solutions):
new_solutions = []
shift_duty_count = {}
for sol in solutions:
solution_ok = True
for shift in set([ duty.shift for duty in sol.duties() ]):
shift_duties = [ d for d in sol.duties() if d.shift == shift ]
num_workers = len(set([ d.worker for d in shift_duties ]))
if num_workers < shift.min_coverage:
solution_ok = False
if solution_ok:
new_solutions.append(sol)
return new_solutions
def filter_solutions(solutions, workers):
# filter permutations ############################
# for each solution
solutions = filter_unwanted_shifts(solutions)
solutions = filter_clashing_duties(solutions)
solutions = filter_incomplete_shifts(solutions)
return solutions
def prioritise_solutions(solutions):
# TODO: not implemented!
return solutions
# prioritise solutions ############################
# for all solutions
# score according to number of staff on a duty
# score according to male/female staff
# score according to skill/background diversity
# score according to when staff last on shift
# sort all solutions by score
def solve_duties(shifts, duties, workers):
# ramify all possible duties #########################
perms = duty_permutations(shifts, duties)
solutions = solutions_for_duty_permutations(perms)
solutions = filter_solutions(solutions, workers)
solutions = prioritise_solutions(solutions)
return solutions
def load_shifts():
from models import Shift
shifts = [
Shift(am2, am8, 2, 3),
Shift(am8, pm12, 2, 3),
]
return shifts
def load_workers():
from models import Avail, Worker
joe_avail = ( Avail(am2, am8), )
sam_avail = ( Avail(am2, am8), )
ned_avail = ( Avail(am2, am8), )
bob_avail = ( Avail(am8, pm12), )
max_avail = ( Avail(am8, pm12), )
joe = Worker("joe", joe_avail)
sam = Worker("sam", sam_avail)
ned = Worker("ned", sam_avail)
bob = Worker("bob", bob_avail)
max = Worker("max", max_avail)
return (joe, sam, ned, bob, max)
def main():
import sys
shifts = load_shifts()
workers = load_workers()
duties = duties_for_all_workers(shifts, workers)
solutions = solve_duties(shifts, duties, workers)
if len(solutions) == 0:
print "Sorry, can't solve this. Perhaps you need more staff available, or"
print "simpler duty constraints?"
sys.exit(20)
else:
print "Solved. Solutions found:"
for sol in solutions:
sol.dump()
if __name__ == "__main__":
main()
</code></pre>
<p>Snipping the debugging output before the result, this currently gives:</p>
<pre><code>Solved. Solutions found:
<Solution
<ShiftList
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker joe
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker sam
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker ned
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
>
<ShiftList
<Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1
<Worker bob
<2009-10-01 08:00:00 to 2009-10-01 12:00:00>
>
>
<Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1
<Worker max
<2009-10-01 08:00:00 to 2009-10-01 12:00:00>
>
>
>
>
</code></pre>
| 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 lots of experience with genetic algorithms, you won't get this right.</strong></p>
<ul>
<li>They are approximate methods that do not guarantee converging to a workable solution. </li>
<li>They work only if you can reasonably well establish the quality of your current solution (i.e. number of criteria not met). </li>
<li>Their quality critically depends on the quality of operators you use to combine/mutate previous solutions into new ones.</li>
</ul>
<p>It is a tough thing to get right in small python program if you have close to zero experience with GA. If you have a small group of people exhaustive search is not that bad option. The problem is that it may work right for <code>n</code> people, will be slow for <code>n+1</code> people and will be unbearably slow for <code>n+2</code> and it may very well be that your <code>n</code> will end up as low as 10.</p>
<p>You are working on an NP-complete problem and there are no easy win solutions. If the fancy timetable scheduling problem of your choice does not work good enough, it is very unlikely you will have something better with your python script.</p>
<p>If you insist on doing this via your own code, it is <em>much</em> easier to get some results with min-max or simulated annealing.</p>
| 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 as good. Just... please don't suggest random timetabling stuff such as the ones for booking classrooms, as I don't think they can do this.</p>
<p>Thanks in advance for reading; I know it's a big post. I'm trying to do my best to document this clearly though, and to show that I've made efforts on my own.</p>
<h2>Problem</h2>
<p>I need a worker/timeslot scheduling algorithm which generates shifts for workers, which meets the following criteria:</p>
<p><strong>Input Data</strong></p>
<pre><code>import datetime.datetime as dt
class DateRange:
def __init__(self, start, end):
self.start = start
self.end = end
class Shift:
def __init__(self, range, min, max):
self.range = range
self.min_workers = min
self.max_workers = max
tue_9th_10pm = dt(2009, 1, 9, 22, 0)
wed_10th_4am = dt(2009, 1, 10, 4, 0)
wed_10th_10am = dt(2009, 1, 10, 10, 0)
shift_1_times = Range(tue_9th_10pm, wed_10th_4am)
shift_2_times = Range(wed_10th_4am, wed_10th_10am)
shift_3_times = Range(wed_10th_10am, wed_10th_2pm)
shift_1 = Shift(shift_1_times, 2,3) # allows 3, requires 2, but only 2 available
shift_2 = Shift(shift_2_times, 2,2) # allows 2
shift_3 = Shift(shift_3_times, 2,3) # allows 3, requires 2, 3 available
shifts = ( shift_1, shift_2, shift_3 )
joe_avail = [ shift_1, shift_2 ]
bob_avail = [ shift_1, shift_3 ]
sam_avail = [ shift_2 ]
amy_avail = [ shift_2 ]
ned_avail = [ shift_2, shift_3 ]
max_avail = [ shift_3 ]
jim_avail = [ shift_3 ]
joe = Worker('joe', joe_avail)
bob = Worker('bob', bob_avail)
sam = Worker('sam', sam_avail)
ned = Worker('ned', ned_avail)
max = Worker('max', max_avail)
amy = Worker('amy', amy_avail)
jim = Worker('jim', jim_avail)
workers = ( joe, bob, sam, ned, max, amy, jim )
</code></pre>
<h2>Processing</h2>
<p>From above, <em>shifts</em> and <em>workers</em> are the two main input variables to process</p>
<p>Each shift has a minimum and maximum number of workers needed. Filling the minimum requirements for a shift is crucial to success, but if all else fails, a rota with gaps to be filled manually is better than "error" :) The main algorithmic issue is that there shouldn't be unnecessary gaps, when enough workers are available.</p>
<p>Ideally, the maximum number of workers for a shift would be filled, but this is the lowest priority relative to other constraints, so if anything has to give, it should be this.</p>
<p><strong>Flexible constraints</strong></p>
<p>These are a little flexible, and their boundaries can be pushed a little if a "perfect" solution can't be found. This flexibility should be a last resort though, rather than being exploited randomly. Ideally, the flexibility would be configurable with a "fudge_factor" variable, or similar.</p>
<ul>
<li>There is a minimum time period
between two shifts. So, a worker
shouldn't be scheduled for two shifts
in the same day, for instance.</li>
<li>There are a maximum number of shifts a
worker can do in a given time period
(say, a month)</li>
<li>There are a maximum number of certain
shifts that can be done in a month
(say, overnight shifts)</li>
</ul>
<p><strong>Nice to have, but not necessary</strong></p>
<p>If you can come up with an algorithm which does the above and includes any/all of these, I'll be seriously impressed and grateful. Even an add-on script to do these bits separately would be great too.</p>
<ul>
<li><p>Overlapping shifts. For instance,
it would be good to be able to specify
a "front desk" shift and a "back office"
shift that both occur at the same time.
This could be done with separate invocations
of the program with different shift data,
except that the constraints about scheduling
people for multiple shifts in a given time
period would be missed.</p></li>
<li><p>Minimum reschedule time period for workers specifiable
on a per-worker (rather than global) basis. For instance,
if Joe is feeling overworked or is dealing with personal issues,
or is a beginner learning the ropes, we might want to schedule him
less often than other workers.</p></li>
<li><p>Some automated/random/fair way of selecting staff to fill minimum
shift numbers when no available workers fit.</p></li>
<li><p>Some way of handling sudden cancellations, and just filling the gaps
without rearranging other shifts.</p></li>
</ul>
<h2>Output Test</h2>
<p>Probably, the algorithm should generate as many matching Solutions as possible, where each Solution looks like this:</p>
<pre><code>class Solution:
def __init__(self, shifts_workers):
"""shifts_workers -- a dictionary of shift objects as keys, and a
a lists of workers filling the shift as values."""
assert isinstance(dict, shifts_workers)
self.shifts_workers = shifts_workers
</code></pre>
<p>Here's a test function for an individual solution, given the above data. I <em>think</em> this is right, but I'd appreciate some peer review on it too.</p>
<pre><code>def check_solution(solution):
assert isinstance(Solution, solution)
def shift_check(shift, workers, workers_allowed):
assert isinstance(Shift, shift):
assert isinstance(list, workers):
assert isinstance(list, workers_allowed)
num_workers = len(workers)
assert num_workers >= shift.min_workers
assert num_workers <= shift.max_workers
for w in workers_allowed:
assert w in workers
shifts_workers = solution.shifts_workers
# all shifts should be covered
assert len(shifts_workers.keys()) == 3
assert shift1 in shifts_workers.keys()
assert shift2 in shifts_workers.keys()
assert shift3 in shifts_workers.keys()
# shift_1 should be covered by 2 people - joe, and bob
shift_check(shift_1, shifts_workers[shift_1], (joe, bob))
# shift_2 should be covered by 2 people - sam and amy
shift_check(shift_2, shifts_workers[shift_2], (sam, amy))
# shift_3 should be covered by 3 people - ned, max, and jim
shift_check(shift_3, shifts_workers[shift_3], (ned,max,jim))
</code></pre>
<h2>Attempts</h2>
<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>
<p>My latest attempt is to generate every possible permutation as a solution, then whittle down the permutations that don't meet the constraints. This seems to work much more quickly, and has gotten me further, but I'm using python 2.6's itertools.product() to help generate the permutations, and I can't quite get it right. It wouldn't surprise me if there are many bugs as, honestly, the problem doesn't fit in my head that well :)</p>
<p>Currently my code for this is in two files: models.py and rota.py. models.py looks like:</p>
<pre><code># -*- coding: utf-8 -*-
class Shift:
def __init__(self, start_datetime, end_datetime, min_coverage, max_coverage):
self.start = start_datetime
self.end = end_datetime
self.duration = self.end - self.start
self.min_coverage = min_coverage
self.max_coverage = max_coverage
def __repr__(self):
return "<Shift %s--%s (%r<x<%r)" % (self.start, self.end, self.min_coverage, self.max_coverage)
class Duty:
def __init__(self, worker, shift, slot):
self.worker = worker
self.shift = shift
self.slot = slot
def __repr__(self):
return "<Duty worker=%r shift=%r slot=%d>" % (self.worker, self.shift, self.slot)
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Duty shift=%s slot=%s" % (self.shift, self.slot)
self.worker.dump(indent=indent, depth=depth+1)
print ind + ">"
class Avail:
def __init__(self, start_time, end_time):
self.start = start_time
self.end = end_time
def __repr__(self):
return "<%s to %s>" % (self.start, self.end)
class Worker:
def __init__(self, name, availabilities):
self.name = name
self.availabilities = availabilities
def __repr__(self):
return "<Worker %s Avail=%r>" % (self.name, self.availabilities)
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Worker %s" % self.name
for avail in self.availabilities:
print ind + " " * indent + repr(avail)
print ind + ">"
def available_for_shift(self, shift):
for a in self.availabilities:
if shift.start >= a.start and shift.end <= a.end:
return True
print "Worker %s not available for %r (Availability: %r)" % (self.name, shift, self.availabilities)
return False
class Solution:
def __init__(self, shifts):
self._shifts = list(shifts)
def __repr__(self):
return "<Solution: shifts=%r>" % self._shifts
def duties(self):
d = []
for s in self._shifts:
for x in s:
yield x
def shifts(self):
return list(set([ d.shift for d in self.duties() ]))
def dump_shift(self, s, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<ShiftList"
for duty in s:
duty.dump(indent=indent, depth=depth+1)
print ind + ">"
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Solution"
for s in self._shifts:
self.dump_shift(s, indent=indent, depth=depth+1)
print ind + ">"
class Env:
def __init__(self, shifts, workers):
self.shifts = shifts
self.workers = workers
self.fittest = None
self.generation = 0
class DisplayContext:
def __init__(self, env):
self.env = env
def status(self, msg, *args):
raise NotImplementedError()
def cleanup(self):
pass
def update(self):
pass
</code></pre>
<p>and rota.py looks like:</p>
<pre><code>#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
from datetime import datetime as dt
am2 = dt(2009, 10, 1, 2, 0)
am8 = dt(2009, 10, 1, 8, 0)
pm12 = dt(2009, 10, 1, 12, 0)
def duties_for_all_workers(shifts, workers):
from models import Duty
duties = []
# for all shifts
for shift in shifts:
# for all slots
for cov in range(shift.min_coverage, shift.max_coverage):
for slot in range(cov):
# for all workers
for worker in workers:
# generate a duty
duty = Duty(worker, shift, slot+1)
duties.append(duty)
return duties
def filter_duties_for_shift(duties, shift):
matching_duties = [ d for d in duties if d.shift == shift ]
for m in matching_duties:
yield m
def duty_permutations(shifts, duties):
from itertools import product
# build a list of shifts
shift_perms = []
for shift in shifts:
shift_duty_perms = []
for slot in range(shift.max_coverage):
slot_duties = [ d for d in duties if d.shift == shift and d.slot == (slot+1) ]
shift_duty_perms.append(slot_duties)
shift_perms.append(shift_duty_perms)
all_perms = ( shift_perms, shift_duty_perms )
# generate all possible duties for all shifts
perms = list(product(*shift_perms))
return perms
def solutions_for_duty_permutations(permutations):
from models import Solution
res = []
for duties in permutations:
sol = Solution(duties)
res.append(sol)
return res
def find_clashing_duties(duty, duties):
"""Find duties for the same worker that are too close together"""
from datetime import timedelta
one_day = timedelta(days=1)
one_day_before = duty.shift.start - one_day
one_day_after = duty.shift.end + one_day
for d in [ ds for ds in duties if ds.worker == duty.worker ]:
# skip the duty we're considering, as it can't clash with itself
if duty == d:
continue
clashes = False
# check if dates are too close to another shift
if d.shift.start >= one_day_before and d.shift.start <= one_day_after:
clashes = True
# check if slots collide with another shift
if d.slot == duty.slot:
clashes = True
if clashes:
yield d
def filter_unwanted_shifts(solutions):
from models import Solution
print "possibly unwanted:", solutions
new_solutions = []
new_duties = []
for sol in solutions:
for duty in sol.duties():
duty_ok = True
if not duty.worker.available_for_shift(duty.shift):
duty_ok = False
if duty_ok:
print "duty OK:"
duty.dump(depth=1)
new_duties.append(duty)
else:
print "duty **NOT** OK:"
duty.dump(depth=1)
shifts = set([ d.shift for d in new_duties ])
shift_lists = []
for s in shifts:
shift_duties = [ d for d in new_duties if d.shift == s ]
shift_lists.append(shift_duties)
new_solutions.append(Solution(shift_lists))
return new_solutions
def filter_clashing_duties(solutions):
new_solutions = []
for sol in solutions:
solution_ok = True
for duty in sol.duties():
num_clashing_duties = len(set(find_clashing_duties(duty, sol.duties())))
# check if many duties collide with this one (and thus we should delete this one
if num_clashing_duties > 0:
solution_ok = False
break
if solution_ok:
new_solutions.append(sol)
return new_solutions
def filter_incomplete_shifts(solutions):
new_solutions = []
shift_duty_count = {}
for sol in solutions:
solution_ok = True
for shift in set([ duty.shift for duty in sol.duties() ]):
shift_duties = [ d for d in sol.duties() if d.shift == shift ]
num_workers = len(set([ d.worker for d in shift_duties ]))
if num_workers < shift.min_coverage:
solution_ok = False
if solution_ok:
new_solutions.append(sol)
return new_solutions
def filter_solutions(solutions, workers):
# filter permutations ############################
# for each solution
solutions = filter_unwanted_shifts(solutions)
solutions = filter_clashing_duties(solutions)
solutions = filter_incomplete_shifts(solutions)
return solutions
def prioritise_solutions(solutions):
# TODO: not implemented!
return solutions
# prioritise solutions ############################
# for all solutions
# score according to number of staff on a duty
# score according to male/female staff
# score according to skill/background diversity
# score according to when staff last on shift
# sort all solutions by score
def solve_duties(shifts, duties, workers):
# ramify all possible duties #########################
perms = duty_permutations(shifts, duties)
solutions = solutions_for_duty_permutations(perms)
solutions = filter_solutions(solutions, workers)
solutions = prioritise_solutions(solutions)
return solutions
def load_shifts():
from models import Shift
shifts = [
Shift(am2, am8, 2, 3),
Shift(am8, pm12, 2, 3),
]
return shifts
def load_workers():
from models import Avail, Worker
joe_avail = ( Avail(am2, am8), )
sam_avail = ( Avail(am2, am8), )
ned_avail = ( Avail(am2, am8), )
bob_avail = ( Avail(am8, pm12), )
max_avail = ( Avail(am8, pm12), )
joe = Worker("joe", joe_avail)
sam = Worker("sam", sam_avail)
ned = Worker("ned", sam_avail)
bob = Worker("bob", bob_avail)
max = Worker("max", max_avail)
return (joe, sam, ned, bob, max)
def main():
import sys
shifts = load_shifts()
workers = load_workers()
duties = duties_for_all_workers(shifts, workers)
solutions = solve_duties(shifts, duties, workers)
if len(solutions) == 0:
print "Sorry, can't solve this. Perhaps you need more staff available, or"
print "simpler duty constraints?"
sys.exit(20)
else:
print "Solved. Solutions found:"
for sol in solutions:
sol.dump()
if __name__ == "__main__":
main()
</code></pre>
<p>Snipping the debugging output before the result, this currently gives:</p>
<pre><code>Solved. Solutions found:
<Solution
<ShiftList
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker joe
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker sam
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker ned
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
>
<ShiftList
<Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1
<Worker bob
<2009-10-01 08:00:00 to 2009-10-01 12:00:00>
>
>
<Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1
<Worker max
<2009-10-01 08:00:00 to 2009-10-01 12:00:00>
>
>
>
>
</code></pre>
| 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 from that point forward. You probably want to avoid that, people like to know their schedules well in advance.</p>
<p>You can deal with some cancellations without rerunning the algorithm because it can pre-schedule the next available person or two. </p>
<p>It might not be possible or desirable to always generate the most optimal solution, but you can keep a running count of "less-than-optimal" events per worker, and always choose the worker with the lowest count when you have to assign another "bad choice". That's what people generally care about (several "bad" scheduling decisions frequently/unfairly).</p>
| 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 as good. Just... please don't suggest random timetabling stuff such as the ones for booking classrooms, as I don't think they can do this.</p>
<p>Thanks in advance for reading; I know it's a big post. I'm trying to do my best to document this clearly though, and to show that I've made efforts on my own.</p>
<h2>Problem</h2>
<p>I need a worker/timeslot scheduling algorithm which generates shifts for workers, which meets the following criteria:</p>
<p><strong>Input Data</strong></p>
<pre><code>import datetime.datetime as dt
class DateRange:
def __init__(self, start, end):
self.start = start
self.end = end
class Shift:
def __init__(self, range, min, max):
self.range = range
self.min_workers = min
self.max_workers = max
tue_9th_10pm = dt(2009, 1, 9, 22, 0)
wed_10th_4am = dt(2009, 1, 10, 4, 0)
wed_10th_10am = dt(2009, 1, 10, 10, 0)
shift_1_times = Range(tue_9th_10pm, wed_10th_4am)
shift_2_times = Range(wed_10th_4am, wed_10th_10am)
shift_3_times = Range(wed_10th_10am, wed_10th_2pm)
shift_1 = Shift(shift_1_times, 2,3) # allows 3, requires 2, but only 2 available
shift_2 = Shift(shift_2_times, 2,2) # allows 2
shift_3 = Shift(shift_3_times, 2,3) # allows 3, requires 2, 3 available
shifts = ( shift_1, shift_2, shift_3 )
joe_avail = [ shift_1, shift_2 ]
bob_avail = [ shift_1, shift_3 ]
sam_avail = [ shift_2 ]
amy_avail = [ shift_2 ]
ned_avail = [ shift_2, shift_3 ]
max_avail = [ shift_3 ]
jim_avail = [ shift_3 ]
joe = Worker('joe', joe_avail)
bob = Worker('bob', bob_avail)
sam = Worker('sam', sam_avail)
ned = Worker('ned', ned_avail)
max = Worker('max', max_avail)
amy = Worker('amy', amy_avail)
jim = Worker('jim', jim_avail)
workers = ( joe, bob, sam, ned, max, amy, jim )
</code></pre>
<h2>Processing</h2>
<p>From above, <em>shifts</em> and <em>workers</em> are the two main input variables to process</p>
<p>Each shift has a minimum and maximum number of workers needed. Filling the minimum requirements for a shift is crucial to success, but if all else fails, a rota with gaps to be filled manually is better than "error" :) The main algorithmic issue is that there shouldn't be unnecessary gaps, when enough workers are available.</p>
<p>Ideally, the maximum number of workers for a shift would be filled, but this is the lowest priority relative to other constraints, so if anything has to give, it should be this.</p>
<p><strong>Flexible constraints</strong></p>
<p>These are a little flexible, and their boundaries can be pushed a little if a "perfect" solution can't be found. This flexibility should be a last resort though, rather than being exploited randomly. Ideally, the flexibility would be configurable with a "fudge_factor" variable, or similar.</p>
<ul>
<li>There is a minimum time period
between two shifts. So, a worker
shouldn't be scheduled for two shifts
in the same day, for instance.</li>
<li>There are a maximum number of shifts a
worker can do in a given time period
(say, a month)</li>
<li>There are a maximum number of certain
shifts that can be done in a month
(say, overnight shifts)</li>
</ul>
<p><strong>Nice to have, but not necessary</strong></p>
<p>If you can come up with an algorithm which does the above and includes any/all of these, I'll be seriously impressed and grateful. Even an add-on script to do these bits separately would be great too.</p>
<ul>
<li><p>Overlapping shifts. For instance,
it would be good to be able to specify
a "front desk" shift and a "back office"
shift that both occur at the same time.
This could be done with separate invocations
of the program with different shift data,
except that the constraints about scheduling
people for multiple shifts in a given time
period would be missed.</p></li>
<li><p>Minimum reschedule time period for workers specifiable
on a per-worker (rather than global) basis. For instance,
if Joe is feeling overworked or is dealing with personal issues,
or is a beginner learning the ropes, we might want to schedule him
less often than other workers.</p></li>
<li><p>Some automated/random/fair way of selecting staff to fill minimum
shift numbers when no available workers fit.</p></li>
<li><p>Some way of handling sudden cancellations, and just filling the gaps
without rearranging other shifts.</p></li>
</ul>
<h2>Output Test</h2>
<p>Probably, the algorithm should generate as many matching Solutions as possible, where each Solution looks like this:</p>
<pre><code>class Solution:
def __init__(self, shifts_workers):
"""shifts_workers -- a dictionary of shift objects as keys, and a
a lists of workers filling the shift as values."""
assert isinstance(dict, shifts_workers)
self.shifts_workers = shifts_workers
</code></pre>
<p>Here's a test function for an individual solution, given the above data. I <em>think</em> this is right, but I'd appreciate some peer review on it too.</p>
<pre><code>def check_solution(solution):
assert isinstance(Solution, solution)
def shift_check(shift, workers, workers_allowed):
assert isinstance(Shift, shift):
assert isinstance(list, workers):
assert isinstance(list, workers_allowed)
num_workers = len(workers)
assert num_workers >= shift.min_workers
assert num_workers <= shift.max_workers
for w in workers_allowed:
assert w in workers
shifts_workers = solution.shifts_workers
# all shifts should be covered
assert len(shifts_workers.keys()) == 3
assert shift1 in shifts_workers.keys()
assert shift2 in shifts_workers.keys()
assert shift3 in shifts_workers.keys()
# shift_1 should be covered by 2 people - joe, and bob
shift_check(shift_1, shifts_workers[shift_1], (joe, bob))
# shift_2 should be covered by 2 people - sam and amy
shift_check(shift_2, shifts_workers[shift_2], (sam, amy))
# shift_3 should be covered by 3 people - ned, max, and jim
shift_check(shift_3, shifts_workers[shift_3], (ned,max,jim))
</code></pre>
<h2>Attempts</h2>
<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>
<p>My latest attempt is to generate every possible permutation as a solution, then whittle down the permutations that don't meet the constraints. This seems to work much more quickly, and has gotten me further, but I'm using python 2.6's itertools.product() to help generate the permutations, and I can't quite get it right. It wouldn't surprise me if there are many bugs as, honestly, the problem doesn't fit in my head that well :)</p>
<p>Currently my code for this is in two files: models.py and rota.py. models.py looks like:</p>
<pre><code># -*- coding: utf-8 -*-
class Shift:
def __init__(self, start_datetime, end_datetime, min_coverage, max_coverage):
self.start = start_datetime
self.end = end_datetime
self.duration = self.end - self.start
self.min_coverage = min_coverage
self.max_coverage = max_coverage
def __repr__(self):
return "<Shift %s--%s (%r<x<%r)" % (self.start, self.end, self.min_coverage, self.max_coverage)
class Duty:
def __init__(self, worker, shift, slot):
self.worker = worker
self.shift = shift
self.slot = slot
def __repr__(self):
return "<Duty worker=%r shift=%r slot=%d>" % (self.worker, self.shift, self.slot)
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Duty shift=%s slot=%s" % (self.shift, self.slot)
self.worker.dump(indent=indent, depth=depth+1)
print ind + ">"
class Avail:
def __init__(self, start_time, end_time):
self.start = start_time
self.end = end_time
def __repr__(self):
return "<%s to %s>" % (self.start, self.end)
class Worker:
def __init__(self, name, availabilities):
self.name = name
self.availabilities = availabilities
def __repr__(self):
return "<Worker %s Avail=%r>" % (self.name, self.availabilities)
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Worker %s" % self.name
for avail in self.availabilities:
print ind + " " * indent + repr(avail)
print ind + ">"
def available_for_shift(self, shift):
for a in self.availabilities:
if shift.start >= a.start and shift.end <= a.end:
return True
print "Worker %s not available for %r (Availability: %r)" % (self.name, shift, self.availabilities)
return False
class Solution:
def __init__(self, shifts):
self._shifts = list(shifts)
def __repr__(self):
return "<Solution: shifts=%r>" % self._shifts
def duties(self):
d = []
for s in self._shifts:
for x in s:
yield x
def shifts(self):
return list(set([ d.shift for d in self.duties() ]))
def dump_shift(self, s, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<ShiftList"
for duty in s:
duty.dump(indent=indent, depth=depth+1)
print ind + ">"
def dump(self, indent=4, depth=1):
ind = " " * (indent * depth)
print ind + "<Solution"
for s in self._shifts:
self.dump_shift(s, indent=indent, depth=depth+1)
print ind + ">"
class Env:
def __init__(self, shifts, workers):
self.shifts = shifts
self.workers = workers
self.fittest = None
self.generation = 0
class DisplayContext:
def __init__(self, env):
self.env = env
def status(self, msg, *args):
raise NotImplementedError()
def cleanup(self):
pass
def update(self):
pass
</code></pre>
<p>and rota.py looks like:</p>
<pre><code>#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
from datetime import datetime as dt
am2 = dt(2009, 10, 1, 2, 0)
am8 = dt(2009, 10, 1, 8, 0)
pm12 = dt(2009, 10, 1, 12, 0)
def duties_for_all_workers(shifts, workers):
from models import Duty
duties = []
# for all shifts
for shift in shifts:
# for all slots
for cov in range(shift.min_coverage, shift.max_coverage):
for slot in range(cov):
# for all workers
for worker in workers:
# generate a duty
duty = Duty(worker, shift, slot+1)
duties.append(duty)
return duties
def filter_duties_for_shift(duties, shift):
matching_duties = [ d for d in duties if d.shift == shift ]
for m in matching_duties:
yield m
def duty_permutations(shifts, duties):
from itertools import product
# build a list of shifts
shift_perms = []
for shift in shifts:
shift_duty_perms = []
for slot in range(shift.max_coverage):
slot_duties = [ d for d in duties if d.shift == shift and d.slot == (slot+1) ]
shift_duty_perms.append(slot_duties)
shift_perms.append(shift_duty_perms)
all_perms = ( shift_perms, shift_duty_perms )
# generate all possible duties for all shifts
perms = list(product(*shift_perms))
return perms
def solutions_for_duty_permutations(permutations):
from models import Solution
res = []
for duties in permutations:
sol = Solution(duties)
res.append(sol)
return res
def find_clashing_duties(duty, duties):
"""Find duties for the same worker that are too close together"""
from datetime import timedelta
one_day = timedelta(days=1)
one_day_before = duty.shift.start - one_day
one_day_after = duty.shift.end + one_day
for d in [ ds for ds in duties if ds.worker == duty.worker ]:
# skip the duty we're considering, as it can't clash with itself
if duty == d:
continue
clashes = False
# check if dates are too close to another shift
if d.shift.start >= one_day_before and d.shift.start <= one_day_after:
clashes = True
# check if slots collide with another shift
if d.slot == duty.slot:
clashes = True
if clashes:
yield d
def filter_unwanted_shifts(solutions):
from models import Solution
print "possibly unwanted:", solutions
new_solutions = []
new_duties = []
for sol in solutions:
for duty in sol.duties():
duty_ok = True
if not duty.worker.available_for_shift(duty.shift):
duty_ok = False
if duty_ok:
print "duty OK:"
duty.dump(depth=1)
new_duties.append(duty)
else:
print "duty **NOT** OK:"
duty.dump(depth=1)
shifts = set([ d.shift for d in new_duties ])
shift_lists = []
for s in shifts:
shift_duties = [ d for d in new_duties if d.shift == s ]
shift_lists.append(shift_duties)
new_solutions.append(Solution(shift_lists))
return new_solutions
def filter_clashing_duties(solutions):
new_solutions = []
for sol in solutions:
solution_ok = True
for duty in sol.duties():
num_clashing_duties = len(set(find_clashing_duties(duty, sol.duties())))
# check if many duties collide with this one (and thus we should delete this one
if num_clashing_duties > 0:
solution_ok = False
break
if solution_ok:
new_solutions.append(sol)
return new_solutions
def filter_incomplete_shifts(solutions):
new_solutions = []
shift_duty_count = {}
for sol in solutions:
solution_ok = True
for shift in set([ duty.shift for duty in sol.duties() ]):
shift_duties = [ d for d in sol.duties() if d.shift == shift ]
num_workers = len(set([ d.worker for d in shift_duties ]))
if num_workers < shift.min_coverage:
solution_ok = False
if solution_ok:
new_solutions.append(sol)
return new_solutions
def filter_solutions(solutions, workers):
# filter permutations ############################
# for each solution
solutions = filter_unwanted_shifts(solutions)
solutions = filter_clashing_duties(solutions)
solutions = filter_incomplete_shifts(solutions)
return solutions
def prioritise_solutions(solutions):
# TODO: not implemented!
return solutions
# prioritise solutions ############################
# for all solutions
# score according to number of staff on a duty
# score according to male/female staff
# score according to skill/background diversity
# score according to when staff last on shift
# sort all solutions by score
def solve_duties(shifts, duties, workers):
# ramify all possible duties #########################
perms = duty_permutations(shifts, duties)
solutions = solutions_for_duty_permutations(perms)
solutions = filter_solutions(solutions, workers)
solutions = prioritise_solutions(solutions)
return solutions
def load_shifts():
from models import Shift
shifts = [
Shift(am2, am8, 2, 3),
Shift(am8, pm12, 2, 3),
]
return shifts
def load_workers():
from models import Avail, Worker
joe_avail = ( Avail(am2, am8), )
sam_avail = ( Avail(am2, am8), )
ned_avail = ( Avail(am2, am8), )
bob_avail = ( Avail(am8, pm12), )
max_avail = ( Avail(am8, pm12), )
joe = Worker("joe", joe_avail)
sam = Worker("sam", sam_avail)
ned = Worker("ned", sam_avail)
bob = Worker("bob", bob_avail)
max = Worker("max", max_avail)
return (joe, sam, ned, bob, max)
def main():
import sys
shifts = load_shifts()
workers = load_workers()
duties = duties_for_all_workers(shifts, workers)
solutions = solve_duties(shifts, duties, workers)
if len(solutions) == 0:
print "Sorry, can't solve this. Perhaps you need more staff available, or"
print "simpler duty constraints?"
sys.exit(20)
else:
print "Solved. Solutions found:"
for sol in solutions:
sol.dump()
if __name__ == "__main__":
main()
</code></pre>
<p>Snipping the debugging output before the result, this currently gives:</p>
<pre><code>Solved. Solutions found:
<Solution
<ShiftList
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker joe
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker sam
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
<Duty shift=<Shift 2009-10-01 02:00:00--2009-10-01 08:00:00 (2<x<3) slot=1
<Worker ned
<2009-10-01 02:00:00 to 2009-10-01 08:00:00>
>
>
>
<ShiftList
<Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1
<Worker bob
<2009-10-01 08:00:00 to 2009-10-01 12:00:00>
>
>
<Duty shift=<Shift 2009-10-01 08:00:00--2009-10-01 12:00:00 (2<x<3) slot=1
<Worker max
<2009-10-01 08:00:00 to 2009-10-01 12:00:00>
>
>
>
>
</code></pre>
| 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 way to compare two solutions), but I would recommend evaluation.</p>
<p>What would be real good is if you could obtain a score for a shorter timespan, for example daily, it is really helpful with algorithms if you can 'predict' the range of the final score from a partial solution (eg, just the first 3 days out of 7). This way you can interrupt the computation based on this partial solution if it's already too low to meet your expectations.</p>
<p><strong>Symmetry</strong></p>
<p>It is likely that among those 200 people you have similar profiles: ie people sharing the same characteristics (availability, experience, willingness, ...). If you take two persons with the same profile, they are going to be interchangeable:</p>
<ul>
<li>Solution 1: (shift 1: Joe)(shift 2: Jim) ...other workers only...</li>
<li>Solution 2: (shift 1: Jim)(shift 2: Joe) ...other workers only...</li>
</ul>
<p>are actually the same solution from your point of view.</p>
<p>The good thing is that usually, you have less profiles than persons, which helps tremendously with the time spent in computation!</p>
<p>For example, imagine that you generated all the solutions based on Solution 1, then there is no need to compute anything based on Solution 2.</p>
<p><strong>Iterative</strong></p>
<p>Instead of generating the whole schedule at once, you may consider generating it incrementally (say 1 week at a time). The net gain is that the complexity for a week is reduced (there are less possibilities).</p>
<p>Then, once you have this week, you compute the second one, being careful of taking the first into account the first for your constraints of course.</p>
<p>The advantage is that you explicitly design you algorithm to take into account an already used solution, this way for the next schedule generation it will make sure not to make a person work 24hours straight!</p>
<p><strong>Serialization</strong></p>
<p>You should consider the serialization of your solution objects (pick up your choice, pickle is quite good for Python). You will need the previous schedule when generating a new one, and I bet you'd rather not enter it manually for the 200 people.</p>
<p><strong>Exhaustive</strong></p>
<p>Now, after all that, I would actually favor an exhaustive search since using symmetry and evaluation the possibilities might not be so numerous (the problem remains NP-complete though, there is no silver bullet).</p>
<p>You may be willing to try your hand at the <a href="http://en.wikipedia.org/wiki/Backtracking" rel="nofollow">Backtracking Algorithm</a>.</p>
<p>Also, you should take a look at the following links which deal with similar kind of problems:</p>
<ul>
<li><a href="http://norvig.com/sudoku.html" rel="nofollow">Python Sudoku Solver</a></li>
<li><a href="http://www.ocf.berkeley.edu/~jchu/publicportal/sudoku/sudoku.paper.html" rel="nofollow">Java Sudoku Solver using Knuth Dancing Links</a> (uses the backtracking algorithm)</li>
</ul>
<p>Both discuss the problems encountered during the implementation, so checking them out should help you.</p>
| 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 import ParseResponse
response = urlopen("http://www.wegottickets.com/")
forms = ParseResponse(response, backwards_compat=False)
form = forms[0]
form.set_value("Live music", name="unified_query")
form.set_all_readonly(False)
control = form.find_control(type="submit")
print control.disabled
print control.readonly
#print form
request2 = form.click()
try:
response2 = urlopen(request2)
except:
print "Unsccessful query"
print response2.geturl()
print response2.info()
print response.read()
response2.close()
</code></pre>
<p>Thank you very much!</p>
| 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' instead". Not helpful for debugging. The exception will stop the program and print a useful error message, if you don't get in its way.</p>
| 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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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 on, you decide that you do need a setter, as you want to do something clever at the same time. But you don't want to have to change all the code that uses your class - so you wrap the setter in the <code>@property</code> decorator, and it all just works.</p>
| 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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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. Just doing document.title = 'something' is nicer. You know that a lot is happening behind the scenes anyway.</p>
| 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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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 single CPU instructions. To read simplicity into an assignment is to read things that aren't there.</p>
<p>When you say x.b = c, probably all you should think is that "whatever just happened, x.b should now be c".</p>
| 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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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 amount of internal work is needed to make <code>x.getB()</code> return <code>2</code>.</p>
<p>However, there are no language-imposed <em>guarantees</em> about this expected behavior, i.e., compiler-enforced constraints on the body of methods whose names start with <code>get</code> or <code>set</code>: rather, it's left up to common sense, social convention, "style guides", and testing.</p>
<p>The behavior of <code>x.b</code> accesses, and assignments such as <code>x.b = 2</code>, in languages which do have properties (a set of languages which includes but is not limited to Python) is <em>exactly</em> the same as for getter and setter methods in, e.g., Java: the same expectations, the same lack of language-enforced guarantees.</p>
<p>The first win for properties is syntax and readability. Having to write, e.g.,</p>
<pre><code>x.setB(x.getB() + 1)
</code></pre>
<p>instead of the obvious</p>
<pre><code>x.b += 1
</code></pre>
<p>cries out for vengeance to the gods. In languages which support properties, there is absolutely no good reason to force users of the class to go through the gyrations of such Byzantine boilerplate, impacting their code's readability with no upside whatsoever.</p>
<p>In Python specifically, there's one more great upside to using properties (or other descriptors) in lieu of getters and setters: if and when you reorganize your class so that the underlying setter and getter are not needed anymore, you can (without breaking the class's published API) simply eliminate those methods and the property that relies on them, making <code>b</code> a normal "stored" attribute of <code>x</code>'s class rather than a "logical" one obtained and set computationally.</p>
<p>In Python, doing things directly (when feasible) instead of via methods is an important optimization, and systematically using properties enables you to perform this optimization whenever feasible (always exposing "normal stored attributes" directly, and only ones which do need computation upon access and/or setting via methods and properties).</p>
<p>So, if you use getters and setters instead of properties, beyond impacting the readability of your users' code, you are <em>also</em> gratuitously wasting machine cycles (and the energy that goes to their computer during those cycles;-), <strong>again</strong> for no good reason whatsoever.</p>
<p>Your only argument against properties is e.g. that "an outside user wouldn't expect any side effects as a result of an assignment, usually"; but you miss the fact that the same user (in a language such as Java where getters and setters are pervasive) wouldn't expect (observable) "side effects" as a result of calling a setter, either (and even less for a getter;-). They're reasonable expectations and it's up to you, as the class author, to try and accommodate them -- whether your setter and getter are used directly or through a property, makes no difference. If you have methods with important observable side effects, do <strong>not</strong> name them <code>getThis</code>, <code>setThat</code>, and do not use them via properties.</p>
<p>The complaint that properties "hide the implementation" is wholly unjustified: most <em>all</em> of OOP is about implementing information hiding -- making a class responsible for presenting a logical interface to the outside world and implementing it internally as best it can. Getters and setters, exactly like properties, are tools towards this goal. Properties just do a better job at it (in languages that support them;-).</p>
| 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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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><code>class Atom(object):
def __init__(self, handle):
self.handle = handle
def _get_charge(self):
return dt_getcharge(self.handle)
def _set_charge(self, charge):
dt_setcharge(self.handle, charge)
charge = property(_get_charge, _set_charge)
</code></pre>
<p>10 years ago, when I wrote this package, I had to use __getattr__ and __setattr__ which made it possible, but the implementation was a lot more error prone.</p>
<pre><code>class Atom:
def __init__(self, handle):
self.handle = handle
def __getattr__(self, name):
if name == "charge":
return dt_getcharge(self.handle)
raise AttributeError(name)
def __setattr__(self, name, value):
if name == "charge":
dt_setcharge(self.handle, value)
else:
self.__dict__[name] = value
</code></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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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 very popular.</p>
<p>You identify that Foo is causing a bottleneck. Perhaps it is possible to add some caching to Foo to speed it up. Using properties will let you do that without changing any code or tests outside of Foo.</p>
<p>Yes of course this is problematic code, but you just saved a lot of $$ fixing it quickly.</p>
<p>What if Foo is in a library that you have hundreds or thousands of users for? Well you saved yourself having to tell them to do an expensive refactor when they upgrade to the newest version of Foo.</p>
<p>The release notes have a lineitem about Foo instead of a paragraph porting guide.</p>
<p>Experienced Python programmers don't expect much from <code>a.b=2</code> other than <code>a.b==2</code>, but they know even that may not be true. What happens inside the class is it's own business.</p>
| 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 can happen, such as <code>a.b=2</code> actually causes <code>a.b</code> to be <code>1</code>. Or an exception is raised. Or a performance problem. Or just being confusing.</p>
<p>Can you give me a concrete example for a good usage of it? (using it to patch problematic code doesn't count ;-)</p>
| 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 procedures, like validating a min or max value, like triggering an event because the height changed, automatically setting other values in function of the new height value, all that may occur at the moment Something.height value was assigned. Remember, you don't need to call them in your code, they are auto executed at the moment you read or write the property value. In some way they are like event procedures, when the property X changes value and when the property X value is read.</p>
| 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 property P ends with X</p>
<p>Thanks, Matt</p>
| 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 property P ends with X</p>
<p>Thanks, Matt</p>
| 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 >=', prefix).filter('prop <', 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 configuration:</p>
<pre><code>NameVirtualHost *
<VirtualHost *>
DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride all
</Directory>
<Directory "/var/www/auction-in-europe.com/aie">
Options Indexes FollowSymLinks MultiViews
#AddHandler mod_python .py
PythonOption mod_python.legacy.importer *
SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On
AllowOverride all
Order allow,deny
allow from all
# This directive allows us to have apache2's default start page
# in /apache2-default/, but still have / go to the right place
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ScriptAlias /bin/ /home/www/auction-in-europe.com/aie/bin/
ServerAdmin teamwork19@gmail.com
ErrorLog /home/logs/auction-in-europe.com/error_log
CustomLog /home/logs/auction-in-europe.com/access_log combined
ServerName auction-in-europe.com
ServerAlias www.auction-in-europe.com antique-in-europe.com www.antique-in-europe.com art-in-europe.com www.art-in-europe.com en.art-in-europe.com
ServerAlias en.antique-in-europe.com en.auction-in-europe.com fr.antique-in-europe.com fr.art-in-europe.com fr.auction-in-europe.com auction.tinyerp.org
#RewriteEngine on
#RewriteRule ^/(.*)\.html /index.py [E=pg:$1]
ErrorLog /var/log/apache2/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature On
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
<Directory /home/www/postfixadmin>
</Directory>
</VirtualHost>
</code></pre>
<p>Logs are quite empty:</p>
<pre><code>[Mon Oct 12 13:25:58 2009] [notice] mod_python: (Re)importing module 'mod_python.publisher'
[Mon Oct 12 13:25:58 2009] [notice] [client 212.166.58.166] Publisher loading page /home/www/auction-in-europe.com/aie/index.py
</code></pre>
<p>I really have no idea where to start.</p>
<p>Please help!</p>
| 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
class AppContext(albatross.SessionFileAppContext):
def __init__(self, app):
albatross.SessionFileAppContext.__init__(self, app)
# path = os.environ.get('PATH_INFO','').split('/')
# path = filter(lambda x: x, path)
# self.module = path.pop(0)
# self.path = {}
# while path:
# val = path.pop()
# self.path[ path.pop() ] = val
def load_template_once(self, template):
new_template = os.path.join(self.lang_get(),template)
return albatross.SessionFileAppContext.load_template_once(new_template)
def load_template(self, template):
new_template = os.path.join(self.lang_get(),template)
return albatross.SessionFileAppContext.load_template(self,new_template)
def run_template_once(self, template):
new_template = os.path.join(self.lang_get(), template)
return albatross.SessionFileAppContext.run_template_once(self,new_template)
def run_template(self, template):
new_template = os.path.join(self.lang_get(), template)
return albatross.SessionFileAppContext.run_template(self,new_template)
def req_get(self):
return self.current_url()[len(self.base_url())+1:]
def args_calc(self):
path = self.current_url()[len(self.base_url())+1:].split('/')
path = filter(lambda x: x, path)
if not len(path):
path=['index']
self.module = path.pop(0)
self.path = {}
while path:
val = path.pop()
self.path[ path.pop() ] = val
def lang_get(self):
if self.request.get_header('host')[:3] in ('fr.','en.'):
return self.request.get_header('host')[:2]
try:
language = self.request.get_header('Accept-Language')
if language:
new_lang = language[:2]
if new_lang in ('fr','en'):
return new_lang
except:
return 'en'
return 'en'
def hostname_get(self):
if self.request.get_header('host')[-17:]=='art-in-europe.com':
return 'art'
elif self.request.get_header('host')[-21:]=='antique-in-europe.com':
return 'antique'
else:
return 'auction'
def module_get(self):
self.args_calc()
return self.module
def path_get(self, key):
self.args_calc()
return self.path[key]
class App(albatross.ModularSessionFileApp):
def __init__(self):
albatross.ModularSessionFileApp.__init__(self,
base_url = '/index.py',
module_path = os.path.join(base_dir, 'modules'),
template_path = os.path.join(base_dir, 'template'),
start_page = 'index',
secret = '(=-AiE-)',
session_appid='A-i-E',
session_dir='/var/tmp/albatross/')
def create_context(self):
return AppContext(self)
class alx_a(albatross.EnclosingTag):
name = 'alx-a'
def to_html(self, ctx):
ctx.write_content('')
albatross.EnclosingTag.to_html(self, ctx)
ctx.write_content('')
# Escape text for attribute values
def escape_br(text):
text = str(text)
text = string.replace(text, '&', '&')
text = string.replace(text, '', '>',)
text = string.replace(text, '"', '"')
text = string.replace(text, "'", '')
text = string.replace(text, "\n", '<br>')
return text
class alx_value(EmptyTag):
name = 'alx-value'
def __init__(self, ctx, filename, line_num, attribs):
EmptyTag.__init__(self, ctx, filename, line_num, attribs)
#self.compile_expr()
def to_html(self, ctx):
value = ctx.eval_expr(self.get_attrib('expr'))
format = self.get_attrib('date')
if format:
value = time.strftime(format, time.localtime(value))
ctx.write_content(value)
return
lookup_name = self.get_attrib('lookup')
if lookup_name:
lookup = ctx.get_lookup(lookup_name)
if not lookup:
self.raise_error('undefined lookup "%s"' % lookup_name)
lookup.lookup_html(ctx, value)
return
if self.has_attrib('noescape'):
ctx.write_content(str(value))
else:
ctx.write_content(escape_br(value))
app = App()
app.register_tagclasses(alx_a)
app.register_tagclasses(alx_value)
def handler(req):
return app.run(apacheapp.Request(req)) </code></pre>
| 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 configuration:</p>
<pre><code>NameVirtualHost *
<VirtualHost *>
DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride all
</Directory>
<Directory "/var/www/auction-in-europe.com/aie">
Options Indexes FollowSymLinks MultiViews
#AddHandler mod_python .py
PythonOption mod_python.legacy.importer *
SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On
AllowOverride all
Order allow,deny
allow from all
# This directive allows us to have apache2's default start page
# in /apache2-default/, but still have / go to the right place
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ScriptAlias /bin/ /home/www/auction-in-europe.com/aie/bin/
ServerAdmin teamwork19@gmail.com
ErrorLog /home/logs/auction-in-europe.com/error_log
CustomLog /home/logs/auction-in-europe.com/access_log combined
ServerName auction-in-europe.com
ServerAlias www.auction-in-europe.com antique-in-europe.com www.antique-in-europe.com art-in-europe.com www.art-in-europe.com en.art-in-europe.com
ServerAlias en.antique-in-europe.com en.auction-in-europe.com fr.antique-in-europe.com fr.art-in-europe.com fr.auction-in-europe.com auction.tinyerp.org
#RewriteEngine on
#RewriteRule ^/(.*)\.html /index.py [E=pg:$1]
ErrorLog /var/log/apache2/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature On
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
<Directory /home/www/postfixadmin>
</Directory>
</VirtualHost>
</code></pre>
<p>Logs are quite empty:</p>
<pre><code>[Mon Oct 12 13:25:58 2009] [notice] mod_python: (Re)importing module 'mod_python.publisher'
[Mon Oct 12 13:25:58 2009] [notice] [client 212.166.58.166] Publisher loading page /home/www/auction-in-europe.com/aie/index.py
</code></pre>
<p>I really have no idea where to start.</p>
<p>Please help!</p>
| 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 is rather difficult to trouble-shoot but I believe your apache config should be closer to this:</p>
<pre><code> <Directory "/var/www/auction-in-europe.com/aie">
Order allow,deny
Allow from all
SetHandler python-program .py
PythonHandler index ## or what ever the above file is called without the .py
PythonDebug On
</Directory>
</code></pre>
<p>This will make all requests to "/var/www/auction-in-europe.com/aie" get handled by index.py.</p>
| 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=cookiejar#cookielib.CookieJar" rel="nofollow">cookiejar</a> and login over http</li>
<li>there are many more auth schemes, so find out which you need.</li>
</ul>
| 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 "<stdin>", line 1, in <module>
File "C:\Python25\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 387, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 425, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 360, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 506, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Authorization Required
</code></pre>
<p>You will have to catch this exception, create a urllib2.HTTPPasswordManager object, add the username and password to the HTTPPasswordManager, create a urllib2.HTTPBasicAuthHandler object, create an opener object and finally fetch the url using the opener. Code and a tutorial is available here: <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#id5" rel="nofollow">http://www.voidspace.org.uk/python/articles/urllib2.shtml#id5</a></p>
| 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">pygame.midi.Input</a>:</p>
<pre><code> Input is used to get midi input from midi devices.
Input(device_id)
Input(device_id, buffer_size)
Input.close - closes a midi stream, flushing any pending buffers. closes a midi stream, flushing any pending buffers.
Input.poll - returns true if there's data, or false if not. returns true if there's data, or false if not.
Input.read - reads num_events midi events from the buffer. reads num_events midi events from the buffer.
</code></pre>
<p>If you're looking for an alternative, have a look at <a href="http://wiki.python.org/moin/PythonInMusic">PythonInMusic</a> in the Python wiki.</p>
<p>There are various different projects related to MIDI input and output there, some for Windows as well. (Click the little > sign after each project to follow the link to the project homepage)</p>
<p>I have not used any of them personally, but I'm sure it will help you get started.</p>
| 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), rather than the code that emits the
signal. Disabling signals is just a quick fix that will work when you
know exactly what handlers are attached to a signal, and it hides the
underlying problem by putting the fix in the wrong place.</p>
</blockquote>
| 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 testing frameworks is that they launch instances of browsers; I just want a script I can schedule to run daily to retrieve the page I want. Any way to do this?</p>
| 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 methods)
# to the selected HTMLForm (from ClientForm).
br["cheeses"] = ["mozzarella", "caerphilly"] # (the method here is __setitem__)
response = br.submit() # submit current form
</code></pre>
| 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 testing frameworks is that they launch instances of browsers; I just want a script I can schedule to run daily to retrieve the page I want. Any way to do this?</p>
| 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 testing frameworks is that they launch instances of browsers; I just want a script I can schedule to run daily to retrieve the page I want. Any way to do this?</p>
| 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>print response.read()
</code></pre>
| 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 testing frameworks is that they launch instances of browsers; I just want a script I can schedule to run daily to retrieve the page I want. Any way to do this?</p>
| 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 home page, saving the response
br.open( "http://google.com" )
# Select the search box and search for 'foo'
br.select_form( 'f' )
br.form[ 'q' ] = 'foo'
# Get the search results
br.submit()
# Find the link to foofighters.com; why did we run a search?
resp = None
for link in br.links():
siteMatch = re.compile( 'www.foofighters.com' ).search( link.url )
if siteMatch:
resp = br.follow_link( link )
break
# Print the site
content = resp.get_data()
print content
</code></pre>
| 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 front end. It starts the web application with the following:</p>
<pre><code>try:
client = webbrowser.get("firefox")
client.open(url)
return
except:
try:
client = webbrowser.get()
client.open(url)
return
except:
print('Please open %s in Firefox.' % url)
</code></pre>
<p>I have Safari on my Mac as the default, but I also have Firefox installed and running. The above code started the new URL (on localhost) in Safari. Crunchy does not work well in Safari. I want to see it in Firefox, since I do have Firefox. Under Python 2.5, 2.6, and 2.7 (from version control) I get this:</p>
<pre><code>>>> import webbrowser
>>> webbrowser.get("firefox")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/webbrowser.py", line 46, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
</code></pre>
<p>Firefox is there. I tried using webbrowser.get("/Applications/Firefox.app/Contents/MacOS/firefox %s") which starts up a new instance of Firefox then complains that another instance of Firefox is already running.</p>
<p>I really would like webbrowser to open up the URL in an existing tab/window of Firefox, if it's already running, or in a new Firefox is not already running.</p>
<p>I looked at webbrowser.py and it looks like there is no 'firefox' support for MacOSX. That's okay, I can add that. But I don't know how to open the URL in Firefox in the way I want to.</p>
<p>Ideas? And for now, I can force Crunchy to give me the URL, which I can manually paste into Firefox.</p>
| 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>client = webbrowser.get("open -a /Applications/Firefox.app %s")
</code></pre>
<p>Following Nicholas Riley 's comment</p>
<p>If Firefox is on the list of Applications then you can get away with open -a Firefox.app %s</p>
| 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 front end. It starts the web application with the following:</p>
<pre><code>try:
client = webbrowser.get("firefox")
client.open(url)
return
except:
try:
client = webbrowser.get()
client.open(url)
return
except:
print('Please open %s in Firefox.' % url)
</code></pre>
<p>I have Safari on my Mac as the default, but I also have Firefox installed and running. The above code started the new URL (on localhost) in Safari. Crunchy does not work well in Safari. I want to see it in Firefox, since I do have Firefox. Under Python 2.5, 2.6, and 2.7 (from version control) I get this:</p>
<pre><code>>>> import webbrowser
>>> webbrowser.get("firefox")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/webbrowser.py", line 46, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
</code></pre>
<p>Firefox is there. I tried using webbrowser.get("/Applications/Firefox.app/Contents/MacOS/firefox %s") which starts up a new instance of Firefox then complains that another instance of Firefox is already running.</p>
<p>I really would like webbrowser to open up the URL in an existing tab/window of Firefox, if it's already running, or in a new Firefox is not already running.</p>
<p>I looked at webbrowser.py and it looks like there is no 'firefox' support for MacOSX. That's okay, I can add that. But I don't know how to open the URL in Firefox in the way I want to.</p>
<p>Ideas? And for now, I can force Crunchy to give me the URL, which I can manually paste into Firefox.</p>
| 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>
<pre><code>% open -b org.mozilla.firefox http://www.stackoverflow.com/
</code></pre>
<p>(or, of course, the equivalent in Python with <code>subprocess</code> or similar) should do what you want.</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"'
'engine.autoreload_on : True'
'engine.autoreload_frequency = 5 '
'server.socket_host': '0.0.0.0',
'server.socket_port': 8080}
}
cherrypy.config.update(global_conf)
cherrypy.tree.mount(home, '/', config = application_conf)
cherrypy.engine.start()
</code></pre>
| 2 | 2009-10-12T15:46:01Z | 1,555,656 | <p>huh, you're doing something wrong with your dict:</p>
<pre><code>>>> global_conf = {
... 'global': { 'server.environment= "production"'
... 'engine.autoreload_on : True'
... 'engine.autoreload_frequency = 5 '
... 'server.socket_host': '0.0.0.0',
... 'server.socket_port': 8080}
... }
>>> print global_conf
{'global':
{'server.environment= "production"engine.autoreload_on : Trueengine.autoreload_frequency = 5 server.socket_host': '0.0.0.0',
'server.socket_port': 8080}
}
</code></pre>
<p>More specifically, there are commas and colons missing from your dict definiton. Each key/value pair must have a colon, and they are separated with commas. Something like this might work:</p>
<pre><code>global_conf = {
'global': { 'server.environment': 'production',
'engine.autoreload_on': True,
'engine.autoreload_frequency': 5,
'server.socket_host': '0.0.0.0',
'server.socket_port': 8080,
}
}
</code></pre>
<p>Check python <a href="http://docs.python.org/library/stdtypes.html#mapping-types-dict">dictionary documentation</a> for more info.</p>
| 6 | 2009-10-12T16:44:13Z | [
"python",
"cherrypy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.