Return the absolute time-distance string for two datetime objects,
ints or any combination you can dream of.

If times are integers, they are interpreted as seconds from now.

granularity dictates where the string calculation is stopped.
If set to seconds (default) you will receive the full string. If
another accuracy is supplied you will receive an approximation.
Available granularities are:
‘century’, ‘decade’, ‘year’, ‘month’, ‘day’, ‘hour’, ‘minute’,
‘second’

Setting round to true will increase the result by 1 if the fractional
value is greater than 50% of the granularity unit.

You can pass the desired Markdown module as the markdown
argument, or the helper will try to import markdown. If neither is
available, it will fall back to webhelpers.markdown, which is
Freewisdom’s Markdown 1.7 without extensions.

IMPORTANT:
If your source text is untrusted and may contain malicious HTML markup,
pass safe_mode="escape" to escape it, safe_mode="replace" to
replace it with a scolding message, or safe_mode="remove" to strip it.

Most helpers have an **attrs argument to specify additional HTML
attributes. A trailing underscore in the name will be deleted; this is
especially important for attributes that are identical to Python keywords;
e.g., class_. Some helpers handle certain keywords specially; these are
noted in the helpers’ docstrings.

To create your own custom tags, see webhelpers.html.builder.

A set of CSS styles complementing these helpers is in
webhelpers/public/stylesheets/webhelpers.css.

id is the HTML ID attribute, and should be passed as a keyword
argument. By default the ID is the same as the name filtered through
_make_safe_id_component(). Pass None to suppress the
ID attribute entirely.

The following HTML attributes may be set by keyword argument:

disabled - If true, checkbox will be grayed out.

readonly - If true, the user will not be able to modify the checkbox.

To arrange multiple checkboxes in a group, see
webhelpers.containers.distribute().

You must close the form yourself by calling end_form() or outputting
</form>.

Options:

method

The method to use when submitting the form, usually either
“GET” or “POST”. If “PUT”, “DELETE”, or another verb is used, a
hidden input with name _method is added to simulate the verb
over POST.

multipart

If set to True, the enctype is set to “multipart/form-data”.
You must set it to true when uploading files, or the browser will
submit the filename rather than the file.

hidden_fields

Additional hidden fields to add to the beginning of the form. It may
be a dict or an iterable of key-value tuples. This is implemented by
calling the object’s .items() method if it has one, or just
iterating the object. (This will successfuly get multiple values for
the same key in WebOb MultiDict objects.)

Because input tags must be placed in a block tag rather than directly
inside the form, all hidden fields will be put in a
‘<div style=”display:none”>’. The style prevents the <div> from being
displayed or affecting the layout.

selected_values – a string or list of strings or integers giving
the value(s) that should be preselected.

options – an Options object or iterable of (value,label)
pairs. The label will be shown on the form; the option will be returned
to the application if that option is chosen. If you pass a string or int
instead of a 2-tuple, it will be used for both the value and the label.
If the value is a tuple or a list, it will be added as an optgroup,
with label as label.

id is the HTML ID attribute, and should be passed as a keyword
argument. By default the ID is the same as the name. filtered through
_make_safe_id_component(). Pass None to suppress the
ID attribute entirely.

CAUTION: the old rails helper options_for_select had the label first.
The order was reversed because most real-life collections have the value
first, including dicts of the form {value:label}. For those dicts
you can simply pass D.items() as this argument.

HINT: You can sort options alphabetically by label via:
sorted(my_options,key=lambdax:x[1])

The following options may only be keyword arguments:

multiple – if true, this control will allow multiple

selections.

prompt – if specified, an extra option will be prepended to the
list: (“”, prompt). This is intended for those “Please choose ...”
pseudo-options. Its value is “”, equivalent to not making a selection.

id is the HTML ID attribute, and should be passed as a keyword
argument. By default the ID is the same as the name filtered through
_make_safe_id_component(). Pass None to suppress the
ID attribute entirely.

type is the input field type, normally “text”. You can override it
for HTML 5 input fields that don’t have their own helper; e.g.,
“search”, “email”, “date”.

Options:

disabled - If set to True, the user will not be able to use

this input.

size - The number of visible characters that will fit in the

input.

maxlength - The maximum number of characters that the browser

will allow the user to enter.

The remaining keyword args will be standard HTML attributes for the tag.

ModelTags allows you to build a create/update form easily. (This is the
C and U in CRUD.) The constructor takes a database record, which can be
a SQLAlchemy mapped class, or any object with attributes or keys for the
field values. Its methods shadow the the form field helpers, but it
automatically fills in the value attribute based on the current value in
the record. (It also knows about the ‘checked’ and ‘selected’ attributes
for certain tags.)

You can also use the same form to input a new record. Pass None or
"" instead of a record, and it will set all the current values to a
default value, which is either the default keyword arg to the method, or
“” if not specified.

(Hint: in Pylons you can put mt=ModelTags(c.record) in your template,
and then if the record doesn’t exist you can either set c.record=None
or not set it at all. That’s because nonexistent c attributes resolve
to “” unless you’ve set config["pylons.strict_c"]=True. However,
having a c attribute that’s sometimes set and sometimes not is
arguably bad programming style.)

record is the database record to lookup values in. It may be
any object with attributes or keys, including a SQLAlchemy mapped
instance. It may also be None or "" to indicate that a new
record is being created. (The class attribute undefined_values
tells which values indicate a new record.)

If use_keys is true, values will be looked up by key. If false
(default), values will be looked up by attribute.

date_format is a strftime-compatible string used by the .date
method. The default is American format (MM/DD/YYYY), which is
most often seen in text fields paired with popup calendars.
European format (DD/MM/YYYY) is “%d/%m/%Y”. ISO format (YYYY-MM-DD)
is “%Y-%m-%d”.

id_format is a formatting-operator format for the HTML ‘id’ attribute.
It should contain one “%s” where the tag’s name will be embedded.

The value can be a datetime.date, datetime.datetime, None,
or “”. The former two are converted to a string using the
date format passed to the constructor. The latter two are converted
to “”.

If there’s no database record, consult keyword arg default. It it’s
the string “today”, use todays’s date. Otherwise it can be any of the
values allowed above. If no default is specified, the text field is
initialized to “”.

The radio button will initially be selected if the database value
equals checked_value. On form submission the value will be
checked_value if the button was selected, or "" otherwise.

In case of a ModelTags object that is created from scratch
(e.g. new_employee=ModelTags(None)) the option that should
be checked can be set by the ‘default’ parameter. As in:
new_employee.radio('status',checked_value=7,default=7)

The control’s ‘id’ attribute will be modified as follows:

If not specified but an ‘id_format’ was given to the constructor,
generate an ID based on the format.

If an ID was passed in or was generated by step (1), append an
underscore and the checked value. Before appending the checked
value, lowercase it, change any spaces to "_", and remove any
non-alphanumeric characters except underscores and hyphens.

If no ID was passed or generated by step (1), the radio button
will not have an ‘id’ attribute.

To display multiple radio buttons in a group, see
webhelper.containers.distribute().

If the corresponding database value is not a list or tuple, it’s
wrapped in a one-element list. But if it’s “” or None, an empty
list is substituted. This is to accommodate multiselect lists, which
may have multiple values selected.

The URL of the image. (This must be the exact URL desired. A
previous version of this helper added magic prefixes; this is
no longer the case.)

alt

The img’s alt tag. Non-graphical browsers and screen readers will
output this instead of the image. If the image is pure decoration
and uninteresting to non-graphical users, pass “”. To omit the
alt tag completely, pass None.

width

The width of the image, default is not included.

height

The height of the image, default is not included.

path

Calculate the width and height based on the image file at path if
possible. May not be specified if width or height is
specified. The results are also written to the debug log for
troubleshooting.

use_pil

If true, calcuate the image dimensions using the Python Imaging
Library, which must be installed. Otherwise use a pure Python
algorithm which understands fewer image formats and may be less
accurate. This flag controls whether
webhelpers.media.get_dimensions_pil or
webhelpers.media.get_dimensions is called. It has no effect if
path is not specified.

The auto-detection of feed for the current page is only for
browsers and news readers that support it.

url

The URL of the feed. (This should be the exact URLs desired. A
previous version of this helper added magic prefixes; this is no longer
the case.)

feed_type

The type of feed. Specifying ‘rss’ or ‘atom’ automatically
translates to a type of ‘application/rss+xml’ or
‘application/atom+xml’, respectively. Otherwise the type is
used as specified. Defaults to ‘rss’.

For every element in bool_attrs, I look for a corresponding key in
attrs. If its value is true, I change the value to match the key.
For example, I convert selected=True into selected="selected". If
the value is false, I delete the key.

Used to determine what to link. Options are “all”,
“email_addresses”, or “urls”

href_attrs

Additional attributes for generated <a> tags.

Example:

>>> auto_link("Go to http://www.planetpython.com and say hello to guido@python.org")literal(u'Go to <a href="http://www.planetpython.com">http://www.planetpython.com</a> and say hello to <a href="mailto:guido@python.org">guido@python.org</a>')

This method generates HTML code that represents a form. Forms
are “block” content, which means that you should not try to
insert them into your HTML where only inline content is
expected. For example, you can legally insert a form inside of
a div or td element or in between p elements, but
not in the middle of a run of text, nor can you place a form
within another form.
(Bottom line: Always validate your HTML before going public.)

This inserts “<strong class=”highlight”>...</strong>” around every
occurrence.

Arguments:

text:

The full text.

phrase:

A phrase to find in the text. This may be a string, a list of strings,
or a compiled regular expression. If a string, it’s regex-escaped and
compiled. If a list, all of the strings will be highlighted. This is
done by regex-escaping all elements and then joining them using the
regex “|” token.

highlighter:

Deprecated. A replacement expression for the regex substitution.
This was deprecated because it bypasses the HTML builder and creates
tags via string mangling. The previous default was ‘<strong
class=”highlight”>1</strong>’, which mimics the normal behavior of
this function. phrase must be a string if highlighter is
specified. Overrides class_ and attrs_ arguments.

case_sensitive:

If false (default), the phrases are searched in a case-insensitive
manner. No effect if phrase is a regex object.

class_:

CSS class for the <strong> tag.

**attrs:

Additional HTML attributes for the <strong> tag.

Changed in WebHelpers 1.0b2: new implementation using HTML builder.
Allow phrase to be list or regex. Deprecate highlighter and
change its default value to None. Add case_sensitive, class_,
and **attrs arguments.

You can also specify the cc address, bcc address, subject, and body
parts of the message header to create a complex e-mail using the
corresponding cc, bcc, subject, and body keyword
arguments. Each of these options are URI escaped and then appended
to the email_address before being output. Be aware that
javascript keywords will not be escaped and may break this feature
when encoding with javascript.

Examples:

>>> mail_to("me@domain.com","My email",cc="ccaddress@domain.com",bcc="bccaddress@domain.com",subject="This is an example email",body="This is the body of the message.")literal(u'<a href="mailto:me@domain.com?cc=ccaddress%40domain.com&amp;bcc=bccaddress%40domain.com&amp;subject=This%20is%20an%20example%20email&amp;body=This%20is%20the%20body%20of%20the%20message.">My email</a>')

The MIMEType helper assists in delivering appropriate content types
for a single action in a controller, based on several requirements:

Does the URL end in a specific extension? (.html, .xml, etc.)

Can the client accept HTML?

What Accept headers did the client send?

If the URL ends in an extension, the mime-type associated with that is
given the highest preference. Since some browsers fail to properly set
their Accept headers to indicate they should be served HTML, the next
check looks to see if its at least in the list. This way those
browsers will still get the HTML they are expecting.

Finally, if the client didn’t include an extension, and doesn’t have
HTML in the list of Accept headers, than the desired mime-type is
returned if the server can send it.

The MIMETypes object class provides a single point to hold onto all
the registered mimetypes, and their association extensions. It’s
used by the mimetypes method to determine the appropriate content
type to return to a client.

Check the PATH_INFO of the current request and client’s HTTP Accept
to attempt to use the appropriate mime-type.

If a content-type is matched, return the appropriate response
content type, and if running under Pylons, set the response content
type directly. If a content-type is not matched, return False.

This works best with URLs that end in extensions that differentiate
content-type. Examples: http://example.com/example,
http://example.com/example.xml, http://example.com/example.csv

Since browsers generally allow for any content-type, but should be
sent HTML when possible, the html mimetype check should always come
first, as shown in the example below.

Example:

# some code likely in environment.pyMIMETypes.init()MIMETypes.add_alias('html','text/html')MIMETypes.add_alias('xml','application/xml')MIMETypes.add_alias('csv','text/csv')# code in a Pylons controllerdefsomeaction(self):# prepare a bunch of data# ......# prepare MIMETypes objectm=MIMETypes(request.environ)ifm.mimetype('html'):returnrender('/some/template.html')elifm.mimetype('atom'):returnrender('/some/xml_template.xml')elifm.mimetype('csv'):# write the data to a csv filereturncsvfileelse:abort(404)# Code in a non-Pylons controller.m=MIMETypes(environ)response_type=m.mimetype('html')# ``response_type`` is a MIME type or ``False``.

The median is the point at which half the numbers are lower than it and
half the numbers are higher. This gives a better sense of the majority
level than the mean (average) does, because the mean can be skewed by a few
extreme numbers at either end. For instance, say you want to calculate
the typical household income in a community and you’ve sampled four
households:

Standard deviation shows the variability within a sequence of numbers.
A small standard deviation means the numbers are close to each other. A
large standard deviation shows they are widely different. In fact it
shows how far the numbers tend to deviate from the average. This can be
used to detect whether the average has been skewed by a few extremely high
or extremely low values.

Most natural and random phenomena follow the normal distribution (aka the
bell curve), which says that most values are close to average but a few are
extreme. E.g., most people are close to 5‘9” tall but a few are very tall
or very short. If the data does follow the bell curve, 68% of the values
will be within 1 standard deviation (stdev) of the average, and 95% will be
within 2 standard deviations. So a university professor grading exams on a
curve might give a “C” (mediocre) grade to students within 1 stdev of the
average score, “B” (better than average) to those within 2 stdevs above,
and “A” (perfect) to the 0.25% higher than 2 stdevs. Those between 1 and 2
stdevs below get a “D” (poor), and those below 2 stdevs... we won’t talk
about them.

By default the helper computes the unbiased estimate
for the population standard deviation, by applying an unbiasing
factor of sqrt(N/(N-1)).

If you’d rather have the function compute the population standard
deviation, pass sample=False.

This class extends SimpleStats by calculating additional statistics,
and by storing all data seen. All values must be numeric (int,
long, and/or float), and you must call .finish() to generate
the additional statistics. That’s because the statistics here cannot be
calculated incrementally, but only after all data is known.

The stat attributes are None until you call .finish(). It’s
permissible – though not recommended – to add data after calling
.finish() and then call .finish() again. This recalculates the
stats over the entire data set.

In addition to the hook methods provided by SimpleStats, subclasses
can override ._finish-stats to provide additional statistics.

Subclasses can override ._init_stats and ._update_stats to add
additional statistics.

The constructor accepts one optional argument, numeric. If true, the
instance accepts only values that are int, long, or float.
The default is false, which accepts any value. This is meant for instances
or subclasses that don’t want non-numeric values.

category is the message’s category. If not specified, the default
category will be used. Raise ValueError if the category is not
in the list of allowed categories.

If ignore_duplicate is true, don’t add the message if another
message with identical text has already been added. If the new
message has a different category than the original message, change the
original message to the new category.

If text exceeds the length, this string will replace
the end of the string

whole_word

If true, shorten the string further to avoid breaking a word in the
middle. A word is defined as any string not containing whitespace.
If the entire text before the break is a single word, it will have to
be broken.

Example:

>>> truncate('Once upon a time in a world far far away',14)'Once upon a...'