code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def po_to_json(po_file, locale=None, domain=None): """Convert *.po file to a json-like data structure.""" with open(po_file, 'rb') as f: po_data = read_po(f, locale=locale, domain=domain) messages = dict(_message_to_json(msg) for msg in po_data) messages[''] = { 'domain': po_data.domai...
Convert *.po file to a json-like data structure.
po_to_json
python
indico/indico
indico/util/i18n.py
https://github.com/indico/indico/blob/master/indico/util/i18n.py
MIT
def square(image): """Return a squared image. :param image: a `PIL.Image` object """ width, height = image.size if width == height: return image side = min(width, height) overflow = max(width, height) - side margin = overflow / 2 if width > height: box = (margin, 0, ...
Return a squared image. :param image: a `PIL.Image` object
square
python
indico/indico
indico/util/images.py
https://github.com/indico/indico/blob/master/indico/util/images.py
MIT
def materialize_iterable(type_=list): """Decorator that materializes an iterable. Iterates over the result of the decorated function and stores the returned values into a collection. This makes most sense on functions that use `yield` for simplicity but should return a collection instead of a gene...
Decorator that materializes an iterable. Iterates over the result of the decorated function and stores the returned values into a collection. This makes most sense on functions that use `yield` for simplicity but should return a collection instead of a generator. :param type_: The collection type...
materialize_iterable
python
indico/indico
indico/util/iterables.py
https://github.com/indico/indico/blob/master/indico/util/iterables.py
MIT
def window(seq, n=2): """ Return a sliding window (of width n) over data from the iterable. s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... """ it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = (*result[1:], elem) ...
Return a sliding window (of width n) over data from the iterable. s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
window
python
indico/indico
indico/util/iterables.py
https://github.com/indico/indico/blob/master/indico/util/iterables.py
MIT
def get_locator(obj): """Retrieve the locator data from an object. The object may be a dictionary (in case a locator is passed) or an object with a ``locator`` property. """ # note: we use explicit hasattr checks since we don't want to end # up with an AttributeError raised from inside the loca...
Retrieve the locator data from an object. The object may be a dictionary (in case a locator is passed) or an object with a ``locator`` property.
get_locator
python
indico/indico
indico/util/locators.py
https://github.com/indico/indico/blob/master/indico/util/locators.py
MIT
def validate_with_message(fn, reason): """Create a validation function with a custom error message.""" def validate(args): if not fn(args): # cast to str since ValidationError only wraps the message in a list # if it's a string, but the babel lazy i18n string isn't a string ...
Create a validation function with a custom error message.
validate_with_message
python
indico/indico
indico/util/marshmallow.py
https://github.com/indico/indico/blob/master/indico/util/marshmallow.py
MIT
def not_empty(value): """Validator which ensures the value is not empty. Any falsy value is considered empty. """ if not value: raise ValidationError(_('This field cannot be empty.'))
Validator which ensures the value is not empty. Any falsy value is considered empty.
not_empty
python
indico/indico
indico/util/marshmallow.py
https://github.com/indico/indico/blob/master/indico/util/marshmallow.py
MIT
def no_relative_urls(value): """Validator that checks links/images use absolute URLs.""" if value and has_relative_links(value): raise ValidationError(_('Links and images may not use relative URLs.'))
Validator that checks links/images use absolute URLs.
no_relative_urls
python
indico/indico
indico/util/marshmallow.py
https://github.com/indico/indico/blob/master/indico/util/marshmallow.py
MIT
def validate_format_placeholders(format_string, valid_placeholders, required_placeholders=None): """Validate that a string contains only the correct format placeholders. This MUST ALWAYS be used when accepting format strings from users or other untrustworthy sources. """ try: placeholders =...
Validate that a string contains only the correct format placeholders. This MUST ALWAYS be used when accepting format strings from users or other untrustworthy sources.
validate_format_placeholders
python
indico/indico
indico/util/marshmallow.py
https://github.com/indico/indico/blob/master/indico/util/marshmallow.py
MIT
def make_validate_indico_placeholders(context, /, **kwargs): """Create a marshmallow validator for missing placeholders. This uses the generic signal-based placeholder system. """ def _validate_indico_placeholders(value): if missing := get_missing_placeholders(context, value, **kwargs): ...
Create a marshmallow validator for missing placeholders. This uses the generic signal-based placeholder system.
make_validate_indico_placeholders
python
indico/indico
indico/util/marshmallow.py
https://github.com/indico/indico/blob/master/indico/util/marshmallow.py
MIT
def file_extension(*exts): """Validator which checks the file extension.""" exts = frozenset('.' + ext.lstrip('.') for ext in exts) def validate(file): if not file: return ext = os.path.splitext(file.filename)[1].lower() if ext not in exts: raise ValidationEr...
Validator which checks the file extension.
file_extension
python
indico/indico
indico/util/marshmallow.py
https://github.com/indico/indico/blob/master/indico/util/marshmallow.py
MIT
def latex_render_error(message): """Generate nice error box in LaTeX document. :param message: The error message :returns: LaTeX code for error box """ return textwrap.dedent(r''' \begin{tcolorbox}[width=\textwidth,colback=red!5!white,colframe=red!75!black,title={Indico rendering error}] ...
Generate nice error box in LaTeX document. :param message: The error message :returns: LaTeX code for error box
latex_render_error
python
indico/indico
indico/util/mdx_latex.py
https://github.com/indico/indico/blob/master/indico/util/mdx_latex.py
MIT
def latex_render_image(src, alt, tmpdir, strict=False): """Generate LaTeX code that includes an arbitrary image from a URL. This involves fetching the image from a web server and figuring out its MIME type. A temporary file will be created, which is not immediately deleted since it has to be included i...
Generate LaTeX code that includes an arbitrary image from a URL. This involves fetching the image from a web server and figuring out its MIME type. A temporary file will be created, which is not immediately deleted since it has to be included in the LaTeX code. It should be handled by the enclosing cod...
latex_render_image
python
indico/indico
indico/util/mdx_latex.py
https://github.com/indico/indico/blob/master/indico/util/mdx_latex.py
MIT
def run(self, doc): """ Walk the dom converting relevant nodes to text nodes with relevant content. """ latex_text = self.tolatex(doc) doc.clear() doc.text = latex_text
Walk the dom converting relevant nodes to text nodes with relevant content.
run
python
indico/indico
indico/util/mdx_latex.py
https://github.com/indico/indico/blob/master/indico/util/mdx_latex.py
MIT
def icon_from_mimetype(mimetype, default_icon='icon-file-filled'): """Get the most suitable icon for a MIME type.""" mimetype = mimetype.lower() try: return _exact_mapping[mimetype] except KeyError: for pattern, icon in _regex_mapping: if pattern.search(mimetype): ...
Get the most suitable icon for a MIME type.
icon_from_mimetype
python
indico/indico
indico/util/mimetypes.py
https://github.com/indico/indico/blob/master/indico/util/mimetypes.py
MIT
def is_private_url(url): """Check if the provided URL points to a private IP address.""" hostname = urlsplit(url).hostname.strip('[]') if '.' not in hostname and ':' not in hostname: return True try: host_data = socket.getaddrinfo(hostname, None, 0, 0, socket.IPPROTO_TCP) return...
Check if the provided URL points to a private IP address.
is_private_url
python
indico/indico
indico/util/network.py
https://github.com/indico/indico/blob/master/indico/util/network.py
MIT
def package_is_editable(package): """Check whether the Python package is installed in 'editable' mode.""" # based on pip.dist_is_editable dist = distribution(package) for path_item in sys.path: if (Path(path_item) / f'{dist.name}.egg-link').is_file(): # setuptools legacy return True...
Check whether the Python package is installed in 'editable' mode.
package_is_editable
python
indico/indico
indico/util/packaging.py
https://github.com/indico/indico/blob/master/indico/util/packaging.py
MIT
def get_package_root_path(import_name): """Get the root path of a package. Returns ``None`` if the specified import name is invalid or points to a module instead of a package. """ spec = find_spec(import_name) if spec is None or not spec.parent: # no parent if it's not a package (PEP 45...
Get the root path of a package. Returns ``None`` if the specified import name is invalid or points to a module instead of a package.
get_package_root_path
python
indico/indico
indico/util/packaging.py
https://github.com/indico/indico/blob/master/indico/util/packaging.py
MIT
def check_password_pwned(password, *, fast=False): """Check if a password is in the pwned-passwords list. :param password: The plaintext password :param fast: Whether the check should finish quickly, even if that may indicate not being able to check the password. This should ...
Check if a password is in the pwned-passwords list. :param password: The plaintext password :param fast: Whether the check should finish quickly, even if that may indicate not being able to check the password. This should be used during interactive requests :return: A bool...
check_password_pwned
python
indico/indico
indico/util/passwords.py
https://github.com/indico/indico/blob/master/indico/util/passwords.py
MIT
def validate_secure_password(context, password, *, username='', emails=frozenset(), fast=False): """Check if a password is considered secure. A password is considered secure if it: - is at least :data:`LOCAL_PASSWORD_MIN_LENGTH` characters long - does not contain the username unless the username is <5...
Check if a password is considered secure. A password is considered secure if it: - is at least :data:`LOCAL_PASSWORD_MIN_LENGTH` characters long - does not contain the username unless the username is <5 chars and the password is >16 chars long - does not contain the strings 'indico' (or common variati...
validate_secure_password
python
indico/indico
indico/util/passwords.py
https://github.com/indico/indico/blob/master/indico/util/passwords.py
MIT
def replace(cls, text, escape_html=True, **kwargs): """Replace all occurrences of the placeholder in a string. :param text: The text to replace placeholders in :param escape_html: whether HTML escaping should be done :param kwargs: arguments specific to the placeholder's context ...
Replace all occurrences of the placeholder in a string. :param text: The text to replace placeholders in :param escape_html: whether HTML escaping should be done :param kwargs: arguments specific to the placeholder's context
replace
python
indico/indico
indico/util/placeholders.py
https://github.com/indico/indico/blob/master/indico/util/placeholders.py
MIT
def is_empty(cls, text, **kwargs): """Check whether the placeholder renders an empty string. :param text: The text to replace placeholders in :param kwargs: arguments specific to the placeholder's context """ empty = [False] def _replace(m): if not cls.rende...
Check whether the placeholder renders an empty string. :param text: The text to replace placeholders in :param kwargs: arguments specific to the placeholder's context
is_empty
python
indico/indico
indico/util/placeholders.py
https://github.com/indico/indico/blob/master/indico/util/placeholders.py
MIT
def replace_placeholders(context, text, escape_html=True, **kwargs): """Replace placeholders in a string. :param context: the context where the placeholders are used :param text: the text to replace placeholders in :param escape_html: whether HTML escaping should be done :param kwargs: arguments sp...
Replace placeholders in a string. :param context: the context where the placeholders are used :param text: the text to replace placeholders in :param escape_html: whether HTML escaping should be done :param kwargs: arguments specific to the context
replace_placeholders
python
indico/indico
indico/util/placeholders.py
https://github.com/indico/indico/blob/master/indico/util/placeholders.py
MIT
def get_empty_placeholders(context, text, **kwargs): """Get a list of placeholders that evaluate to an empty string. :param context: the context where the placeholders are used :param text: the text containing some placeholders :param kwargs: arguments specific to the context """ return { ...
Get a list of placeholders that evaluate to an empty string. :param context: the context where the placeholders are used :param text: the text containing some placeholders :param kwargs: arguments specific to the context
get_empty_placeholders
python
indico/indico
indico/util/placeholders.py
https://github.com/indico/indico/blob/master/indico/util/placeholders.py
MIT
def get_missing_placeholders(context, text, **kwargs): """Get the set of missing required placeholders. :param context: the context where the placeholders are used :param text: the text to check :param kwargs: arguments specific to the context """ placeholders = {p for p in get_placeholders(con...
Get the set of missing required placeholders. :param context: the context where the placeholders are used :param text: the text to check :param kwargs: arguments specific to the context
get_missing_placeholders
python
indico/indico
indico/util/placeholders.py
https://github.com/indico/indico/blob/master/indico/util/placeholders.py
MIT
def render_placeholder_info(context, **kwargs): """Render the list of available placeholders. :param context: the context where the placeholders are used :param kwargs: arguments specific to the context """ return Markup(render_template('placeholder_info.html', placeholder_kwargs=kwargs, ...
Render the list of available placeholders. :param context: the context where the placeholders are used :param kwargs: arguments specific to the context
render_placeholder_info
python
indico/indico
indico/util/placeholders.py
https://github.com/indico/indico/blob/master/indico/util/placeholders.py
MIT
def check_rule(context, rule, **kwargs): """Check whether a rule matches. :param context: the context where the conditions are used :param rule: the rule to check :param kwargs: arguments specific to the context """ for name, condition in get_conditions(context, **kwargs).items(): if no...
Check whether a rule matches. :param context: the context where the conditions are used :param rule: the rule to check :param kwargs: arguments specific to the context
check_rule
python
indico/indico
indico/util/rules.py
https://github.com/indico/indico/blob/master/indico/util/rules.py
MIT
def get_missing_conditions(context, rule, **kwargs): """Get the set of missing required conditions. :param context: the context where the conditions are used :param rule: the rule to check :param kwargs: arguments specific to the context """ rules = {condition for condition in get_conditions(co...
Get the set of missing required conditions. :param context: the context where the conditions are used :param rule: the rule to check :param kwargs: arguments specific to the context
get_missing_conditions
python
indico/indico
indico/util/rules.py
https://github.com/indico/indico/blob/master/indico/util/rules.py
MIT
def values_from_signal(signal_response, single_value=False, skip_none=True, as_list=False, multi_value_types=GeneratorType, return_plugins=False): """Combine the results from both single-value and multi-value signals. The signal needs to return either a single object (which is not a ...
Combine the results from both single-value and multi-value signals. The signal needs to return either a single object (which is not a generator) or a generator (usually by returning its values using `yield`). :param signal_response: The return value of a Signal's `.send()` method :param single_val...
values_from_signal
python
indico/indico
indico/util/signals.py
https://github.com/indico/indico/blob/master/indico/util/signals.py
MIT
def named_objects_from_signal(signal_response, name_attr='name', plugin_attr=None): """Return a dict of objects based on an unique attribute on each object. The signal needs to return either a single object (which is not a generator) or a generator (usually by returning its values using ``yield``). ...
Return a dict of objects based on an unique attribute on each object. The signal needs to return either a single object (which is not a generator) or a generator (usually by returning its values using ``yield``). :param signal_response: The return value of a Signal's ``.send()`` method :param name...
named_objects_from_signal
python
indico/indico
indico/util/signals.py
https://github.com/indico/indico/blob/master/indico/util/signals.py
MIT
def make_interceptable(func, key=None, ctx=None): """Create a wrapper to make a function call interceptable. The returned wrapper behaves like the original function, but accepting any kwarg and triggering a signal which can modify its call arguments or even override the return value (in which case the ...
Create a wrapper to make a function call interceptable. The returned wrapper behaves like the original function, but accepting any kwarg and triggering a signal which can modify its call arguments or even override the return value (in which case the original function would not get called at all, unless the...
make_interceptable
python
indico/indico
indico/util/signals.py
https://github.com/indico/indico/blob/master/indico/util/signals.py
MIT
def interceptable_sender(func, key=None): """Get the signal sender to intercept a function call. :param func: The function that should be intercepted :param key: An optional key in case using just the function name would be too generic (e.g. most utils) """ name = f'{func.__module__...
Get the signal sender to intercept a function call. :param func: The function that should be intercepted :param key: An optional key in case using just the function name would be too generic (e.g. most utils)
interceptable_sender
python
indico/indico
indico/util/signals.py
https://github.com/indico/indico/blob/master/indico/util/signals.py
MIT
def csv_text_io_wrapper(buf): """IO wrapper to use the csv reader/writer on a byte stream.""" w = TextIOWrapper(buf, encoding='utf-8-sig', newline='') try: yield w except UnicodeDecodeError: raise UserValueError(_('The CSV file must be saved in UTF-8 encoding')) finally: w.de...
IO wrapper to use the csv reader/writer on a byte stream.
csv_text_io_wrapper
python
indico/indico
indico/util/spreadsheets.py
https://github.com/indico/indico/blob/master/indico/util/spreadsheets.py
MIT
def generate_csv(headers, rows, *, include_header=True): """Generate a CSV file from a list of headers and rows. While CSV cells may contain multiline data, we replace linebreaks with spaces in case someone wants to use it in Excel which does *not* handle such cells properly... :param headers: a l...
Generate a CSV file from a list of headers and rows. While CSV cells may contain multiline data, we replace linebreaks with spaces in case someone wants to use it in Excel which does *not* handle such cells properly... :param headers: a list of cell captions :param rows: a list of dicts mapping ca...
generate_csv
python
indico/indico
indico/util/spreadsheets.py
https://github.com/indico/indico/blob/master/indico/util/spreadsheets.py
MIT
def generate_xlsx(headers, rows, tz=None): """Generate an XLSX file from a list of headers and rows. :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :return: an `io.BytesIO` containing the XLSX data """ workbook_options = {'in_memory': True, 'stri...
Generate an XLSX file from a list of headers and rows. :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :return: an `io.BytesIO` containing the XLSX data
generate_xlsx
python
indico/indico
indico/util/spreadsheets.py
https://github.com/indico/indico/blob/master/indico/util/spreadsheets.py
MIT
def send_csv(filename, headers, rows, *, include_header=True): """Send a CSV file to the client. :param filename: The name of the CSV file :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :param include_header: whether to include a header in the data ...
Send a CSV file to the client. :param filename: The name of the CSV file :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :param include_header: whether to include a header in the data :return: a flask response containing the CSV data
send_csv
python
indico/indico
indico/util/spreadsheets.py
https://github.com/indico/indico/blob/master/indico/util/spreadsheets.py
MIT
def send_xlsx(filename, headers, rows, tz=None): """Send an XLSX file to the client. :param filename: The name of the CSV file :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :param tz: the timezone for the values that are datetime objects :return...
Send an XLSX file to the client. :param filename: The name of the CSV file :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :param tz: the timezone for the values that are datetime objects :return: a flask response containing the XLSX data
send_xlsx
python
indico/indico
indico/util/spreadsheets.py
https://github.com/indico/indico/blob/master/indico/util/spreadsheets.py
MIT
def strict_str(value): """Convert a value to unicode or fails if it is None. Useful when converting e.g. IDs to path segments. Usually they should not be ``None`` so we do not want to fail silently (and end up with a literal ``None`` in the path). """ if value is None: raise TypeError(...
Convert a value to unicode or fails if it is None. Useful when converting e.g. IDs to path segments. Usually they should not be ``None`` so we do not want to fail silently (and end up with a literal ``None`` in the path).
strict_str
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def slugify(*args, **kwargs): """Join a series of strings into a URL slug. - normalizes strings to proper ascii repesentations - removes non-alphanumeric characters - replaces whitespace with dashes :param lower: Whether the slug should be all-lowercase :param maxlen: Maximum slug length :...
Join a series of strings into a URL slug. - normalizes strings to proper ascii repesentations - removes non-alphanumeric characters - replaces whitespace with dashes :param lower: Whether the slug should be all-lowercase :param maxlen: Maximum slug length :param fallback: Fallback in case of a...
slugify
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def truncate(text, max_size, ellipsis='...'): """Truncate text if it's too long.""" if len(text) > max_size: text = text[:max_size] + ellipsis return text
Truncate text if it's too long.
truncate
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def render_markdown(text, escape_latex_math=True, md=None, extra_html=False, **kwargs): """Mako markdown to HTML filter. :param text: Markdown source to convert to HTML :param escape_latex_math: Whether math expression should be left untouched or a function that will be called ...
Mako markdown to HTML filter. :param text: Markdown source to convert to HTML :param escape_latex_math: Whether math expression should be left untouched or a function that will be called to replace math-mode segments. :param md: An alternative markdown processor (can be used ...
render_markdown
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def html_to_markdown(html): """Convert basic HTML to Markdown. This util is meant for cases like comments where the text is generally written in Markdown, but can also contain basic HTML tags, and needs to be used in a plaintext context (e.g. text/plain email notification). """ ht = HTML2Text(b...
Convert basic HTML to Markdown. This util is meant for cases like comments where the text is generally written in Markdown, but can also contain basic HTML tags, and needs to be used in a plaintext context (e.g. text/plain email notification).
html_to_markdown
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def sanitize_for_platypus(text): """Sanitize HTML to be used in platypus.""" from indico.core.config import config tags = ['b', 'br', 'em', 'font', 'i', 'img', 'strike', 'strong', 'sub', 'sup', 'u', 'span', 'div', 'p'] attrs = { 'font': ['size', 'face', 'color'], 'img': ['src', 'width', ...
Sanitize HTML to be used in platypus.
sanitize_for_platypus
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def validate_email_verbose(email, *, check_dns=True): """Validate the given email address. This checks both if it looks valid and if it has valid MX (or A/AAAA) records. :return: ``None`` for a valid email address, otherwise ``'invalid'`` or ``'undeliverable'`` depending on whether the em...
Validate the given email address. This checks both if it looks valid and if it has valid MX (or A/AAAA) records. :return: ``None`` for a valid email address, otherwise ``'invalid'`` or ``'undeliverable'`` depending on whether the email address has syntax errors or dns validation ...
validate_email_verbose
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def validate_emails(emails): """Validate a space/semicolon/comma-separated list of email addresses.""" emails = re.split(r'[\s;,]+', emails) return all(validate_email(email) for email in emails if email)
Validate a space/semicolon/comma-separated list of email addresses.
validate_emails
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def strip_whitespace(s): """Remove trailing/leading whitespace if a string was passed. This utility is useful in cases where you might get None or non-string values such as WTForms filters. """ if isinstance(s, str) and not isinstance(s, Enum): s = s.strip() return s
Remove trailing/leading whitespace if a string was passed. This utility is useful in cases where you might get None or non-string values such as WTForms filters.
strip_whitespace
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def make_unique_token(is_unique): """Create a unique UUID4-based token. :param is_unique: a callable invoked with the token which should return a boolean indicating if the token is actually """ token = str(uuid4()) while not is_unique(token): token = str(uuid4()) r...
Create a unique UUID4-based token. :param is_unique: a callable invoked with the token which should return a boolean indicating if the token is actually
make_unique_token
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def text_to_repr(text, html=False, max_length=50): """Convert text to a suitable string for a repr. :param text: A string which might contain html and/or linebreaks :param html: If True, HTML tags are stripped. :param max_length: The maximum length before the string is truncated....
Convert text to a suitable string for a repr. :param text: A string which might contain html and/or linebreaks :param html: If True, HTML tags are stripped. :param max_length: The maximum length before the string is truncated. Use ``None`` to disable. :return: A string that cont...
text_to_repr
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def alpha_enum(value): """Convert integer to ordinal letter code (a, b, c, ... z, aa, bb, ...).""" max_len = len(string.ascii_lowercase) return str(string.ascii_lowercase[value % max_len] * (value // max_len + 1))
Convert integer to ordinal letter code (a, b, c, ... z, aa, bb, ...).
alpha_enum
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def format_repr(obj, *args, **kwargs): """Create a pretty repr string from object attributes. :param obj: The object to show the repr for. :param args: The names of arguments to include in the repr. The arguments are shown in order using their unicode representation. :...
Create a pretty repr string from object attributes. :param obj: The object to show the repr for. :param args: The names of arguments to include in the repr. The arguments are shown in order using their unicode representation. :param kwargs: Each kwarg is included as a ``na...
format_repr
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def crc32(data): """Calculate a CRC32 checksum. When a str is passed, it is encoded as UTF-8. """ if isinstance(data, str): data = data.encode('utf-8') return binascii.crc32(data) & 0xffffffff
Calculate a CRC32 checksum. When a str is passed, it is encoded as UTF-8.
crc32
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def format_full_name(first_name, last_name, title=None, *, last_name_first=True, last_name_upper=True, abbrev_first_name=True): """Return the user's name in the specified notation. :param first_name: The first name :param last_name: The last name :param title: The title :param ...
Return the user's name in the specified notation. :param first_name: The first name :param last_name: The last name :param title: The title :param last_name_first: if "lastname, firstname" instead of "firstname lastname" should be used :param last_name_upper: if the last...
format_full_name
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def html_to_plaintext(string): r"""Convert HTML to plaintext. :param string: The HTML source string <p> and <br> elements are converted into newline characters. Any literal '\n' characters in the HTML source are removed. """ string = string.replace('\n', '') doc = etree.HTML(string) fo...
Convert HTML to plaintext. :param string: The HTML source string <p> and <br> elements are converted into newline characters. Any literal '\n' characters in the HTML source are removed.
html_to_plaintext
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def handle_legacy_description(field, obj, get_render_mode=attrgetter('render_mode'), get_value=attrgetter('_description')): """Check if the object in question is using an HTML description and convert it. The description will be automatically converted to Markdown and a warning wil...
Check if the object in question is using an HTML description and convert it. The description will be automatically converted to Markdown and a warning will be shown next to the field. :param field: the WTForms field to be checked :param obj: the object whose render mode/description will be checked ...
handle_legacy_description
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def format_email_with_name(name, address): """Format an email address and name. This is very similar to email.utils.formataddr but doesn't encode to UTF-8 since it's meant to be used e.g. in CSV files and similar places (ie not when actually sending emails from indico). """ quotes = '' if s...
Format an email address and name. This is very similar to email.utils.formataddr but doesn't encode to UTF-8 since it's meant to be used e.g. in CSV files and similar places (ie not when actually sending emails from indico).
format_email_with_name
python
indico/indico
indico/util/string.py
https://github.com/indico/indico/blob/master/indico/util/string.py
MIT
def iter_acl(acl): """Iterate over an ACL in the most efficient order. This first yields users/emails, then ip networks, then local groups, and eventually multipass groups as a remote group check is much more expensive than checking if two users are the same (``==``), if an ip is in a network (just...
Iterate over an ACL in the most efficient order. This first yields users/emails, then ip networks, then local groups, and eventually multipass groups as a remote group check is much more expensive than checking if two users are the same (``==``), if an ip is in a network (just some math) or if a user ...
iter_acl
python
indico/indico
indico/util/user.py
https://github.com/indico/indico/blob/master/indico/util/user.py
MIT
def _set_list_header_if_not_empty(self, msg, header, values): """ Set msg's header, either from self.extra_headers, if present, or from the values argument. """ if values: try: value = self.extra_headers[header] except KeyError: ...
Set msg's header, either from self.extra_headers, if present, or from the values argument.
_set_list_header_if_not_empty
python
indico/indico
indico/vendor/django_mail/message.py
https://github.com/indico/indico/blob/master/indico/vendor/django_mail/message.py
MIT
def get_connection(backend=None, fail_silently=False, **kwds) -> BaseEmailBackend: """Load an email backend and return an instance of it. If backend is None (default), use ``EMAIL_BACKEND`` from config. Both fail_silently and other keyword arguments are used in the constructor of the backend. """ ...
Load an email backend and return an instance of it. If backend is None (default), use ``EMAIL_BACKEND`` from config. Both fail_silently and other keyword arguments are used in the constructor of the backend.
get_connection
python
indico/indico
indico/vendor/django_mail/__init__.py
https://github.com/indico/indico/blob/master/indico/vendor/django_mail/__init__.py
MIT
def use_args(schema_cls, **kwargs): """Similar to webargs' ``use_args`` but allows passing schema kwargs. This makes it much easier to use ``partial=True`` for PATCH endpoints. :param schema_cls: A marshmallow Schema or an argmap dict. :param kwargs: Any keyword arguments that are supported by ``use_a...
Similar to webargs' ``use_args`` but allows passing schema kwargs. This makes it much easier to use ``partial=True`` for PATCH endpoints. :param schema_cls: A marshmallow Schema or an argmap dict. :param kwargs: Any keyword arguments that are supported by ``use_args`` or the Schema cons...
use_args
python
indico/indico
indico/web/args.py
https://github.com/indico/indico/blob/master/indico/web/args.py
MIT
def use_kwargs(schema_cls, **kwargs): """Like ``use_args``, but using kwargs when calling the decorated function.""" kwargs['as_kwargs'] = True return use_args(schema_cls, **kwargs)
Like ``use_args``, but using kwargs when calling the decorated function.
use_kwargs
python
indico/indico
indico/web/args.py
https://github.com/indico/indico/blob/master/indico/web/args.py
MIT
def use_rh_args(schema_cls, **kwargs): """Similar to ``use_args`` but populates the context from RH attributes. The Schema needs a Meta class with an ``rh_context`` attribute specifying which attributes should be taken from the current RH. :param schema_cls: A marshmallow Schema or an argmap dict. ...
Similar to ``use_args`` but populates the context from RH attributes. The Schema needs a Meta class with an ``rh_context`` attribute specifying which attributes should be taken from the current RH. :param schema_cls: A marshmallow Schema or an argmap dict. :param rh_context: When using an argmap, this...
use_rh_args
python
indico/indico
indico/web/args.py
https://github.com/indico/indico/blob/master/indico/web/args.py
MIT
def use_rh_kwargs(schema_cls, **kwargs): """Like ``use_rh_args``, but using kwargs when calling the decorated function.""" kwargs['as_kwargs'] = True return use_rh_args(schema_cls, **kwargs)
Like ``use_rh_args``, but using kwargs when calling the decorated function.
use_rh_kwargs
python
indico/indico
indico/web/args.py
https://github.com/indico/indico/blob/master/indico/web/args.py
MIT
def render_breadcrumbs(*titles, category=None, event=None, management=False, category_url_factory=None): """Render the breadcrumb navigation. :param titles: A list of titles, either strings or Breadcrumb objects. If present, these will simply create a trail of breadcrumbs. ...
Render the breadcrumb navigation. :param titles: A list of titles, either strings or Breadcrumb objects. If present, these will simply create a trail of breadcrumbs. A 'Home' element is inserted automatically. :param event: Generate the event/category breadcrumb trail star...
render_breadcrumbs
python
indico/indico
indico/web/breadcrumbs.py
https://github.com/indico/indico/blob/master/indico/web/breadcrumbs.py
MIT
def _handle_error_cors(): """Set CORS on error response based on RH's CORS settings.""" if not hasattr(g, 'rh') or (cors_config := getattr(g.rh, '_CORS', None)) is None: return cors_options = get_cors_options(current_app, cors_config) @after_this_request def set_error_cors(resp): s...
Set CORS on error response based on RH's CORS settings.
_handle_error_cors
python
indico/indico
indico/web/errors.py
https://github.com/indico/indico/blob/master/indico/web/errors.py
MIT
def build_menu_structure(menu_id, active_item=None, **kwargs): """Build a menu (list of entries) with sections/items. Information is provided by specific signals and filtered by menu id. This can be used as a very thin framework for menu handling across the app. :param menu_id: menu_id used to...
Build a menu (list of entries) with sections/items. Information is provided by specific signals and filtered by menu id. This can be used as a very thin framework for menu handling across the app. :param menu_id: menu_id used to filter out signal calls :param active_item: ID of currently activ...
build_menu_structure
python
indico/indico
indico/web/menu.py
https://github.com/indico/indico/blob/master/indico/web/menu.py
MIT
def render_sidemenu(menu_id, active_item=None, **kwargs): """Render a sidemenu with sections/items. :param menu_id: The identifier of the menu. :param active_item: The name of the currently-active menu item. :param kwargs: Additional arguments passed to the menu signals. """ items = build_menu_...
Render a sidemenu with sections/items. :param menu_id: The identifier of the menu. :param active_item: The name of the currently-active menu item. :param kwargs: Additional arguments passed to the menu signals.
render_sidemenu
python
indico/indico
indico/web/menu.py
https://github.com/indico/indico/blob/master/indico/web/menu.py
MIT
def validate_json(self, schema, json=None): """Validate the request's JSON payload using a JSON schema. :param schema: The JSON schema used for validation. :param json: The JSON object (defaults to ``request.json``) :raises BadRequest: if the JSON validation failed """ i...
Validate the request's JSON payload using a JSON schema. :param schema: The JSON schema used for validation. :param json: The JSON object (defaults to ``request.json``) :raises BadRequest: if the JSON validation failed
validate_json
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def normalize_url(self, *, late=False): """Perform URL normalization. This uses the :attr:`normalize_url_spec` to check if the URL params are what they should be and redirects or fails depending on the HTTP method used if it's not the case. :return: ``None`` or a redirect respo...
Perform URL normalization. This uses the :attr:`normalize_url_spec` to check if the URL params are what they should be and redirects or fails depending on the HTTP method used if it's not the case. :return: ``None`` or a redirect response
normalize_url
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def _process_args(self): """ This method is called before _check_access and url normalization and is a good place to fetch objects from the database based on variables from request params. """
This method is called before _check_access and url normalization and is a good place to fetch objects from the database based on variables from request params.
_process_args
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def _process(self): """Dispatch to a method named ``_process_<verb>``. Except for RESTful endpoints it is usually best to just override this method, especially when using WTForms. """ method = getattr(self, '_process_' + request.method, None) if method is None: ...
Dispatch to a method named ``_process_<verb>``. Except for RESTful endpoints it is usually best to just override this method, especially when using WTForms.
_process
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def wrap_function(cls, func, *, disable_csrf_check=False): """Decorate a function to run within the RH's framework.""" @wraps(func) def wrapper(*args, **kwargs): rh = cls(partial(func, *args, **kwargs)) if disable_csrf_check: rh.CSRF_ENABLED = False ...
Decorate a function to run within the RH's framework.
wrap_function
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def oauth_scope(scope): """Specify a custom OAuth scope needed to access an RH. By default RHs require one of the ``everything`` OAuth scopes to use them when authenticating with an OAuth token. These scopes are meant as wildcards for things that aren't official APIs though. Any RH that expose actu...
Specify a custom OAuth scope needed to access an RH. By default RHs require one of the ``everything`` OAuth scopes to use them when authenticating with an OAuth token. These scopes are meant as wildcards for things that aren't official APIs though. Any RH that expose actual APIs should use scopes relat...
oauth_scope
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def cors(rh=None, /, **options): """Enable CORS for the decorated RH.""" def decorator(rh): rh._CORS = options return rh if rh is None: # if we used `@cors()` we need to return the inner decorator return decorator # in case of `@cors` we have the RH and can apply the a...
Enable CORS for the decorated RH.
cors
python
indico/indico
indico/web/rh.py
https://github.com/indico/indico/blob/master/indico/web/rh.py
MIT
def inject_js(js): """Inject JavaScript into the current page. :param js: Code wrapped in a ``<script>`` tag. """ if 'injected_js' not in g: g.injected_js = [] g.injected_js.append(Markup(js))
Inject JavaScript into the current page. :param js: Code wrapped in a ``<script>`` tag.
inject_js
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def jsonify_template(template, _render_func=render_template, _success=None, **context): """Return a json response containing a rendered template.""" html = _render_func(template, **context) jsonify_kw = {} if _success is not None: jsonify_kw['success'] = _success return jsonify(html=html, js...
Return a json response containing a rendered template.
jsonify_template
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def jsonify_data(flash=True, **json_data): """Return a json response with some default fields. This behaves similar to :func:`~flask.jsonify`, but includes ``success=True`` and flashed messages by default. :param flash: if the json data should contain flashed messages :param json_data: the data to...
Return a json response with some default fields. This behaves similar to :func:`~flask.jsonify`, but includes ``success=True`` and flashed messages by default. :param flash: if the json data should contain flashed messages :param json_data: the data to include in the json response
jsonify_data
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def get_request_info(hide_passwords=True): """Get various information about the current HTTP request. This is especially useful for logging purposes where you want as many information as possible. :param hide_passwords: Hides the actual value of POST fields if their name con...
Get various information about the current HTTP request. This is especially useful for logging purposes where you want as many information as possible. :param hide_passwords: Hides the actual value of POST fields if their name contains ``password``. :return: a dictionary con...
get_request_info
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def is_legacy_signed_url_valid(user, url): """Check whether a legacy signed URL is valid for a user. This util is deprecated and only exists because people may be actively using URLs using the old style token. Any new code should use the new :func:`signed_url_for_user` and :func:`verify_signed_user_url...
Check whether a legacy signed URL is valid for a user. This util is deprecated and only exists because people may be actively using URLs using the old style token. Any new code should use the new :func:`signed_url_for_user` and :func:`verify_signed_user_url` utils which encode the user id within the si...
is_legacy_signed_url_valid
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def signed_url_for_user(user, endpoint, /, *args, **kwargs): """Get a URL for an endpoint, which is signed using a user's signing secret. The user id, path and query string are encoded within the signature. """ from indico.web.flask.util import url_for _external = kwargs.pop('_external', False) ...
Get a URL for an endpoint, which is signed using a user's signing secret. The user id, path and query string are encoded within the signature.
signed_url_for_user
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def verify_signed_user_url(url, method): """Verify a signed URL and extract the associated user. :param url: the full relative URL of the request, including the query string :param method: the HTTP method of the request :return: the user associated with the signed link or `None` if no token was provid...
Verify a signed URL and extract the associated user. :param url: the full relative URL of the request, including the query string :param method: the HTTP method of the request :return: the user associated with the signed link or `None` if no token was provided :raise Forbidden: if a token is present b...
verify_signed_user_url
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def get_request_user(): """Get the user associated with the current request. This looks up the user using all ways of authentication that are supported on the current endpoint. In most cases that's the user from the active session (via a session cookie), but it may also be set (or even overridden i...
Get the user associated with the current request. This looks up the user using all ways of authentication that are supported on the current endpoint. In most cases that's the user from the active session (via a session cookie), but it may also be set (or even overridden if there is a session as well) t...
get_request_user
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def strip_path_from_url(url): """Strip away the path from a given URL. (e.g. https://foo.bar/baz?qux -> https://foo.bar) """ url = urlsplit(url, allow_fragments=False) if not url.netloc: # return the original URL if it's not a valid URL return url.geturl() return urlunsplit(ur...
Strip away the path from a given URL. (e.g. https://foo.bar/baz?qux -> https://foo.bar)
strip_path_from_url
python
indico/indico
indico/web/util.py
https://github.com/indico/indico/blob/master/indico/web/util.py
MIT
def render_template(cls, template_name_or_list=None, *wp_args, **context): """Render a jinja template inside the WP. :param template_name_or_list: the name of the template - if unsed, the `_template` attribute of the class is used. ...
Render a jinja template inside the WP. :param template_name_or_list: the name of the template - if unsed, the `_template` attribute of the class is used. can also be a list containing multiple temp...
render_template
python
indico/indico
indico/web/views.py
https://github.com/indico/indico/blob/master/indico/web/views.py
MIT
def additional_bundles(cls): """Additional bundle objects that will be included.""" return { 'screen': (), 'print': () }
Additional bundle objects that will be included.
additional_bundles
python
indico/indico
indico/web/views.py
https://github.com/indico/indico/blob/master/indico/web/views.py
MIT
def _resolve_bundles(cls): """Add up all bundles, following the MRO.""" seen_bundles = set() for class_ in reversed(cls.mro()[:-1]): attr = class_.__dict__.get('bundles', ()) if isinstance(attr, classproperty): attr = attr.__get__(None, class_) ...
Add up all bundles, following the MRO.
_resolve_bundles
python
indico/indico
indico/web/views.py
https://github.com/indico/indico/blob/master/indico/web/views.py
MIT
def js_vars_global(): """Provide a JS file with global definitions (all users). Useful for server-wide config options, URLs, etc... """ cache_file = Path(config.CACHE_DIR) / f'assets_global_{indico.__version__}_{config.hash}.js' if config.DEBUG or not cache_file.exists(): data = generate_g...
Provide a JS file with global definitions (all users). Useful for server-wide config options, URLs, etc...
js_vars_global
python
indico/indico
indico/web/assets/blueprint.py
https://github.com/indico/indico/blob/master/indico/web/assets/blueprint.py
MIT
def _get_i18n_locale(locale_name, react=False): """Retrieve a locale in a Jed-compatible format.""" # Ensure we have a valid locale. en_GB is our source locale and thus always considered # valid, even if it doesn't exist (dev setup where the user did not compile any locales) # since otherwise we'd have ...
Retrieve a locale in a Jed-compatible format.
_get_i18n_locale
python
indico/indico
indico/web/assets/blueprint.py
https://github.com/indico/indico/blob/master/indico/web/assets/blueprint.py
MIT
def create_config_form(cls, *args, **kwargs): """Create the WTForm to configure this field.""" bases = (cls.config_form_base, cls.config_form) if cls.config_form is not None else (cls.config_form_base,) form_cls = type('_FieldConfigForm', bases, {}) form = form_cls(*args, **kwargs) ...
Create the WTForm to configure this field.
create_config_form
python
indico/indico
indico/web/fields/base.py
https://github.com/indico/indico/blob/master/indico/web/fields/base.py
MIT
def update_object(self, data): """Update the object containing this field. :param data: A dict containing already validated data from form submission. """ for field in self.common_settings: setattr(self.object, field, data[field]) self.object.fie...
Update the object containing this field. :param data: A dict containing already validated data from form submission.
update_object
python
indico/indico
indico/web/fields/base.py
https://github.com/indico/indico/blob/master/indico/web/fields/base.py
MIT
def _make_wtforms_field(self, field_cls, validators=None, **kwargs): """Util to instantiate a WTForms field. This creates a field with the proper title, description and if applicable a DataRequired validator. :param field_cls: A WTForms field class :param validators: A list of ...
Util to instantiate a WTForms field. This creates a field with the proper title, description and if applicable a DataRequired validator. :param field_cls: A WTForms field class :param validators: A list of additional validators :param kwargs: kwargs passed to the field construc...
_make_wtforms_field
python
indico/indico
indico/web/fields/base.py
https://github.com/indico/indico/blob/master/indico/web/fields/base.py
MIT
def copy_field_data(self): """ Return a copy of the field's configuration data without the IDs used to identify selected options. """ field_data_copy = super().copy_field_data() for option in field_data_copy['options']: del option['id'] return field_da...
Return a copy of the field's configuration data without the IDs used to identify selected options.
copy_field_data
python
indico/indico
indico/web/fields/choices.py
https://github.com/indico/indico/blob/master/indico/web/fields/choices.py
MIT
def set_session_user(self, user): """Set the user logged in via this session.""" if not current_app.testing: # Sanity check since logging in via the session during a request authenticated # via token/oauth never makes sense. Disabled during testing since we usually # ...
Set the user logged in via this session.
set_session_user
python
indico/indico
indico/web/flask/session.py
https://github.com/indico/indico/blob/master/indico/web/flask/session.py
MIT
def get_session_user(self): """Get the user logged in via this session.""" user_id = self.get('_user_id') return User.get(user_id) if user_id is not None else None
Get the user logged in via this session.
get_session_user
python
indico/indico
indico/web/flask/session.py
https://github.com/indico/indico/blob/master/indico/web/flask/session.py
MIT
def hard_expiry(self, dt: datetime): """Set the datetime a session definitely expires at. The datetime is expected to be tz-aware, otherwise a ValueError will be raised """ if dt.tzinfo is None: raise ValueError(f'hard_expiry datetime "{dt}" must be tz-aware') ...
Set the datetime a session definitely expires at. The datetime is expected to be tz-aware, otherwise a ValueError will be raised
hard_expiry
python
indico/indico
indico/web/flask/session.py
https://github.com/indico/indico/blob/master/indico/web/flask/session.py
MIT
def test_session_hard_expiry_dt_without_tz(): """Test that passing an unaware datetime raises an error.""" session = IndicoSession() with pytest.raises(ValueError): session.hard_expiry = datetime(2021, 1, 1, 0, 0, 0)
Test that passing an unaware datetime raises an error.
test_session_hard_expiry_dt_without_tz
python
indico/indico
indico/web/flask/session_test.py
https://github.com/indico/indico/blob/master/indico/web/flask/session_test.py
MIT
def test_get_storage_lifetime_with_hard_expiry(app, freeze_time): """Test the storage lifetime with hard expiry set on the session. The returned value should always be the minimum of the hard expiry and the app's permanent/temporary session lifetime. """ dt_now = datetime.now(UTC) freeze_time(d...
Test the storage lifetime with hard expiry set on the session. The returned value should always be the minimum of the hard expiry and the app's permanent/temporary session lifetime.
test_get_storage_lifetime_with_hard_expiry
python
indico/indico
indico/web/flask/session_test.py
https://github.com/indico/indico/blob/master/indico/web/flask/session_test.py
MIT
def test_save_session_with_hard_expiry(app): """Test that a session with a hard expiry sets the cookie expiry to the hard expiry.""" session = IndicoSession() expiry = datetime.now(UTC) + timedelta(days=2) session.hard_expiry = expiry resp_mock = Mock(spec_set=Response) with app.test_request_co...
Test that a session with a hard expiry sets the cookie expiry to the hard expiry.
test_save_session_with_hard_expiry
python
indico/indico
indico/web/flask/session_test.py
https://github.com/indico/indico/blob/master/indico/web/flask/session_test.py
MIT
def natsort(environment, value, reverse=False, case_sensitive=False, attribute=None): """Sort an iterable in natural order. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to contr...
Sort an iterable in natural order. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. Based on J...
natsort
python
indico/indico
indico/web/flask/templating.py
https://github.com/indico/indico/blob/master/indico/web/flask/templating.py
MIT
def groupby(environment, value, attribute, reverse=False): """Like Jinja's builtin `groupby` filter, but allows reversed order.""" expr = make_attrgetter(environment, attribute) return [_GroupTuple(key, list(values)) for key, values in itertools.groupby(sorted(value, key=expr, reverse=reverse), ...
Like Jinja's builtin `groupby` filter, but allows reversed order.
groupby
python
indico/indico
indico/web/flask/templating.py
https://github.com/indico/indico/blob/master/indico/web/flask/templating.py
MIT
def decodeprincipal(value, **kwargs): """Decode a principal into an actual object.""" from indico.util.user import principal_from_identifier return principal_from_identifier(value, soft_fail=True, **kwargs)
Decode a principal into an actual object.
decodeprincipal
python
indico/indico
indico/web/flask/templating.py
https://github.com/indico/indico/blob/master/indico/web/flask/templating.py
MIT