repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
hasgeek/coaster
coaster/app.py
init_app
def init_app(app, env=None): """ Configure an app depending on the environment. Loads settings from a file named ``settings.py`` in the instance folder, followed by additional settings from one of ``development.py``, ``production.py`` or ``testing.py``. Typical usage:: from flask import Fla...
python
def init_app(app, env=None): """ Configure an app depending on the environment. Loads settings from a file named ``settings.py`` in the instance folder, followed by additional settings from one of ``development.py``, ``production.py`` or ``testing.py``. Typical usage:: from flask import Fla...
[ "def", "init_app", "(", "app", ",", "env", "=", "None", ")", ":", "# Make current_auth available to app templates", "app", ".", "jinja_env", ".", "globals", "[", "'current_auth'", "]", "=", "current_auth", "# Make the current view available to app templates", "app", "."...
Configure an app depending on the environment. Loads settings from a file named ``settings.py`` in the instance folder, followed by additional settings from one of ``development.py``, ``production.py`` or ``testing.py``. Typical usage:: from flask import Flask import coaster.app ap...
[ "Configure", "an", "app", "depending", "on", "the", "environment", ".", "Loads", "settings", "from", "a", "file", "named", "settings", ".", "py", "in", "the", "instance", "folder", "followed", "by", "additional", "settings", "from", "one", "of", "development",...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L84-L121
hasgeek/coaster
coaster/app.py
load_config_from_file
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not fi...
python
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not fi...
[ "def", "load_config_from_file", "(", "app", ",", "filepath", ")", ":", "try", ":", "app", ".", "config", ".", "from_pyfile", "(", "filepath", ")", "return", "True", "except", "IOError", ":", "# TODO: Can we print to sys.stderr in production? Should this go to", "# log...
Helper function to load config from a specified file
[ "Helper", "function", "to", "load", "config", "from", "a", "specified", "file" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L124-L133
hasgeek/coaster
coaster/app.py
SandboxedFlask.create_jinja_environment
def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. """ ...
python
def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. """ ...
[ "def", "create_jinja_environment", "(", "self", ")", ":", "options", "=", "dict", "(", "self", ".", "jinja_options", ")", "if", "'autoescape'", "not", "in", "options", ":", "options", "[", "'autoescape'", "]", "=", "self", ".", "select_jinja_autoescape", "rv",...
Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior.
[ "Creates", "the", "Jinja2", "environment", "based", "on", ":", "attr", ":", "jinja_options", "and", ":", "meth", ":", "select_jinja_autoescape", ".", "Since", "0", ".", "7", "this", "also", "adds", "the", "Jinja2", "globals", "and", "filters", "after", "init...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L59-L81
hasgeek/coaster
coaster/utils/tsquery.py
for_tsquery
def for_tsquery(text): r""" Tokenize text into a valid PostgreSQL to_tsquery query. >>> for_tsquery(" ") '' >>> for_tsquery("This is a test") "'This is a test'" >>> for_tsquery('Match "this AND phrase"') "'Match this'&'phrase'" >>> for_tsquery('Match "this & phrase"') "'Match th...
python
def for_tsquery(text): r""" Tokenize text into a valid PostgreSQL to_tsquery query. >>> for_tsquery(" ") '' >>> for_tsquery("This is a test") "'This is a test'" >>> for_tsquery('Match "this AND phrase"') "'Match this'&'phrase'" >>> for_tsquery('Match "this & phrase"') "'Match th...
[ "def", "for_tsquery", "(", "text", ")", ":", "tokens", "=", "[", "_token_map", ".", "get", "(", "t", ",", "t", ")", "for", "t", "in", "_tsquery_tokens_re", ".", "split", "(", "_whitespace_re", ".", "sub", "(", "' '", ",", "text", ".", "replace", "(",...
r""" Tokenize text into a valid PostgreSQL to_tsquery query. >>> for_tsquery(" ") '' >>> for_tsquery("This is a test") "'This is a test'" >>> for_tsquery('Match "this AND phrase"') "'Match this'&'phrase'" >>> for_tsquery('Match "this & phrase"') "'Match this'&'phrase'" >>> for_t...
[ "r", "Tokenize", "text", "into", "a", "valid", "PostgreSQL", "to_tsquery", "query", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/tsquery.py#L19-L137
hasgeek/coaster
coaster/sqlalchemy/mixins.py
IdMixin.id
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immut...
python
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immut...
[ "def", "id", "(", "cls", ")", ":", "if", "cls", ".", "__uuid_primary_key__", ":", "return", "immutable", "(", "Column", "(", "UUIDType", "(", "binary", "=", "False", ")", ",", "default", "=", "uuid_", ".", "uuid4", ",", "primary_key", "=", "True", ",",...
Database identity for this model, used for foreign key references from other models
[ "Database", "identity", "for", "this", "model", "used", "for", "foreign", "key", "references", "from", "other", "models" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L61-L68
hasgeek/coaster
coaster/sqlalchemy/mixins.py
IdMixin.url_id
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) ...
python
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) ...
[ "def", "url_id", "(", "cls", ")", ":", "if", "cls", ".", "__uuid_primary_key__", ":", "def", "url_id_func", "(", "self", ")", ":", "\"\"\"The URL id, UUID primary key rendered as a hex string\"\"\"", "return", "self", ".", "id", ".", "hex", "def", "url_id_is", "("...
The URL id
[ "The", "URL", "id" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L71-L97
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UuidMixin.uuid
def uuid(cls): """UUID column, or synonym to existing :attr:`id` column if that is a UUID""" if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_primary_key__: return synonym('id') else: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, unique=True, ...
python
def uuid(cls): """UUID column, or synonym to existing :attr:`id` column if that is a UUID""" if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_primary_key__: return synonym('id') else: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, unique=True, ...
[ "def", "uuid", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'__uuid_primary_key__'", ")", "and", "cls", ".", "__uuid_primary_key__", ":", "return", "synonym", "(", "'id'", ")", "else", ":", "return", "immutable", "(", "Column", "(", "UUIDType",...
UUID column, or synonym to existing :attr:`id` column if that is a UUID
[ "UUID", "column", "or", "synonym", "to", "existing", ":", "attr", ":", "id", "column", "if", "that", "is", "a", "UUID" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L112-L117
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.url_for
def url_for(self, action='view', **kwargs): """ Return public URL to this instance for a given action (default 'view') """ app = current_app._get_current_object() if current_app else None if app is not None and action in self.url_for_endpoints.get(app, {}): endpoint, ...
python
def url_for(self, action='view', **kwargs): """ Return public URL to this instance for a given action (default 'view') """ app = current_app._get_current_object() if current_app else None if app is not None and action in self.url_for_endpoints.get(app, {}): endpoint, ...
[ "def", "url_for", "(", "self", ",", "action", "=", "'view'", ",", "*", "*", "kwargs", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "if", "current_app", "else", "None", "if", "app", "is", "not", "None", "and", "action", "in...
Return public URL to this instance for a given action (default 'view')
[ "Return", "public", "URL", "to", "this", "instance", "for", "a", "given", "action", "(", "default", "view", ")" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L213-L248
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.is_url_for
def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs): """ View decorator that registers the view as a :meth:`url_for` target. """ def decorator(f): if 'url_for_endpoints' not in cls.__dict__: cls.url_for_endpoints = {None: {}} ...
python
def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs): """ View decorator that registers the view as a :meth:`url_for` target. """ def decorator(f): if 'url_for_endpoints' not in cls.__dict__: cls.url_for_endpoints = {None: {}} ...
[ "def", "is_url_for", "(", "cls", ",", "_action", ",", "_endpoint", "=", "None", ",", "_app", "=", "None", ",", "_external", "=", "None", ",", "*", "*", "paramattrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "'url_for_endpoints'", "not", ...
View decorator that registers the view as a :meth:`url_for` target.
[ "View", "decorator", "that", "registers", "the", "view", "as", "a", ":", "meth", ":", "url_for", "target", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L258-L272
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.register_view_for
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, ...
python
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, ...
[ "def", "register_view_for", "(", "cls", ",", "app", ",", "action", ",", "classview", ",", "attr", ")", ":", "if", "'view_for_endpoints'", "not", "in", "cls", ".", "__dict__", ":", "cls", ".", "view_for_endpoints", "=", "{", "}", "cls", ".", "view_for_endpo...
Register a classview and viewhandler for a given app and action
[ "Register", "a", "classview", "and", "viewhandler", "for", "a", "given", "app", "and", "action" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L275-L281
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.view_for
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
python
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
[ "def", "view_for", "(", "self", ",", "action", "=", "'view'", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "view", ",", "attr", "=", "self", ".", "view_for_endpoints", "[", "app", "]", "[", "action", "]", "return", "getattr"...
Return the classview viewhandler that handles the specified action
[ "Return", "the", "classview", "viewhandler", "that", "handles", "the", "specified", "action" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L283-L289
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.classview_for
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """ app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
python
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """ app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
[ "def", "classview_for", "(", "self", ",", "action", "=", "'view'", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "return", "self", ".", "view_for_endpoints", "[", "app", "]", "[", "action", "]", "[", "0", "]", "(", "self", ...
Return the classview that contains the viewhandler for the specified action
[ "Return", "the", "classview", "that", "contains", "the", "viewhandler", "for", "the", "specified", "action" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L291-L296
hasgeek/coaster
coaster/sqlalchemy/mixins.py
NoIdMixin._set_fields
def _set_fields(self, fields): """Helper method for :meth:`upsert` in the various subclasses""" for f in fields: if hasattr(self, f): setattr(self, f, fields[f]) else: raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=...
python
def _set_fields(self, fields): """Helper method for :meth:`upsert` in the various subclasses""" for f in fields: if hasattr(self, f): setattr(self, f, fields[f]) else: raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=...
[ "def", "_set_fields", "(", "self", ",", "fields", ")", ":", "for", "f", "in", "fields", ":", "if", "hasattr", "(", "self", ",", "f", ")", ":", "setattr", "(", "self", ",", "f", ",", "fields", "[", "f", "]", ")", "else", ":", "raise", "TypeError",...
Helper method for :meth:`upsert` in the various subclasses
[ "Helper", "method", "for", ":", "meth", ":", "upsert", "in", "the", "various", "subclasses" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L305-L311
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.name
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column...
python
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column...
[ "def", "name", "(", "cls", ")", ":", "if", "cls", ".", "__name_length__", "is", "None", ":", "column_type", "=", "UnicodeText", "(", ")", "else", ":", "column_type", "=", "Unicode", "(", "cls", ".", "__name_length__", ")", "if", "cls", ".", "__name_blank...
The URL name of this object, unique across all instances of this model
[ "The", "URL", "name", "of", "this", "object", "unique", "across", "all", "instances", "of", "this", "model" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L347-L356
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.title
def title(cls): """The title of this object""" if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
python
def title(cls): """The title of this object""" if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
[ "def", "title", "(", "cls", ")", ":", "if", "cls", ".", "__title_length__", "is", "None", ":", "column_type", "=", "UnicodeText", "(", ")", "else", ":", "column_type", "=", "Unicode", "(", "cls", ".", "__title_length__", ")", "return", "Column", "(", "co...
The title of this object
[ "The", "title", "of", "this", "object" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L359-L365
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.upsert
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) ret...
python
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) ret...
[ "def", "upsert", "(", "cls", ",", "name", ",", "*", "*", "fields", ")", ":", "instance", "=", "cls", ".", "get", "(", "name", ")", "if", "instance", ":", "instance", ".", "_set_fields", "(", "fields", ")", "else", ":", "instance", "=", "cls", "(", ...
Insert or update an instance
[ "Insert", "or", "update", "an", "instance" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L386-L394
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.make_name
def make_name(self, reserved=[]): """ Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2 until an available name is found. :param reserved: List or se...
python
def make_name(self, reserved=[]): """ Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2 until an available name is found. :param reserved: List or se...
[ "def", "make_name", "(", "self", ",", "reserved", "=", "[", "]", ")", ":", "if", "self", ".", "title", ":", "if", "inspect", "(", "self", ")", ".", "has_identity", ":", "def", "checkused", "(", "c", ")", ":", "return", "bool", "(", "c", "in", "re...
Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2 until an available name is found. :param reserved: List or set of reserved names unavailable for use
[ "Autogenerates", "a", ":", "attr", ":", "name", "from", "the", ":", "attr", ":", "title", ".", "If", "the", "auto", "-", "generated", "name", "is", "already", "in", "use", "in", "this", "model", ":", "meth", ":", "make_name", "tries", "again", "by", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L396-L414
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.get
def get(cls, parent, name): """Get an instance matching the parent and name""" return cls.query.filter_by(parent=parent, name=name).one_or_none()
python
def get(cls, parent, name): """Get an instance matching the parent and name""" return cls.query.filter_by(parent=parent, name=name).one_or_none()
[ "def", "get", "(", "cls", ",", "parent", ",", "name", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "parent", "=", "parent", ",", "name", "=", "name", ")", ".", "one_or_none", "(", ")" ]
Get an instance matching the parent and name
[ "Get", "an", "instance", "matching", "the", "parent", "and", "name" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L483-L485
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.short_title
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): ...
python
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): ...
[ "def", "short_title", "(", "self", ")", ":", "if", "self", ".", "title", "and", "self", ".", "parent", "is", "not", "None", "and", "hasattr", "(", "self", ".", "parent", ",", "'title'", ")", "and", "self", ".", "parent", ".", "title", ":", "if", "s...
Generates an abbreviated title by subtracting the parent's title from this instance's title.
[ "Generates", "an", "abbreviated", "title", "by", "subtracting", "the", "parent", "s", "title", "from", "this", "instance", "s", "title", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L517-L529
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.permissions
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
python
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
[ "def", "permissions", "(", "self", ",", "actor", ",", "inherited", "=", "None", ")", ":", "if", "inherited", "is", "not", "None", ":", "return", "inherited", "|", "super", "(", "BaseScopedNameMixin", ",", "self", ")", ".", "permissions", "(", "actor", ")...
Permissions for this model, plus permissions inherited from the parent.
[ "Permissions", "for", "this", "model", "plus", "permissions", "inherited", "from", "the", "parent", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L536-L545
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseIdNameMixin.make_name
def make_name(self): """Autogenerates a :attr:`name` from :attr:`title_for_name`""" if self.title: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__))
python
def make_name(self): """Autogenerates a :attr:`name` from :attr:`title_for_name`""" if self.title: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__))
[ "def", "make_name", "(", "self", ")", ":", "if", "self", ".", "title", ":", "self", ".", "name", "=", "six", ".", "text_type", "(", "make_name", "(", "self", ".", "title_for_name", ",", "maxlength", "=", "self", ".", "__name_length__", ")", ")" ]
Autogenerates a :attr:`name` from :attr:`title_for_name`
[ "Autogenerates", "a", ":", "attr", ":", "name", "from", ":", "attr", ":", "title_for_name" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L605-L608
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedIdMixin.get
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
python
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
[ "def", "get", "(", "cls", ",", "parent", ",", "url_id", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "parent", "=", "parent", ",", "url_id", "=", "url_id", ")", ".", "one_or_none", "(", ")" ]
Get an instance matching the parent and url_id
[ "Get", "an", "instance", "matching", "the", "parent", "and", "url_id" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L673-L675
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedIdMixin.make_id
def make_id(self): """Create a new URL id that is unique to the parent container""" if self.url_id is None: # Set id only if empty self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)], self.__class__.parent == self.parent)
python
def make_id(self): """Create a new URL id that is unique to the parent container""" if self.url_id is None: # Set id only if empty self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)], self.__class__.parent == self.parent)
[ "def", "make_id", "(", "self", ")", ":", "if", "self", ".", "url_id", "is", "None", ":", "# Set id only if empty", "self", ".", "url_id", "=", "select", "(", "[", "func", ".", "coalesce", "(", "func", ".", "max", "(", "self", ".", "__class__", ".", "...
Create a new URL id that is unique to the parent container
[ "Create", "a", "new", "URL", "id", "that", "is", "unique", "to", "the", "parent", "container" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L677-L681
hasgeek/coaster
coaster/sqlalchemy/functions.py
make_timestamp_columns
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
python
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
[ "def", "make_timestamp_columns", "(", ")", ":", "return", "(", "Column", "(", "'created_at'", ",", "DateTime", ",", "default", "=", "func", ".", "utcnow", "(", ")", ",", "nullable", "=", "False", ")", ",", "Column", "(", "'updated_at'", ",", "DateTime", ...
Return two columns, created_at and updated_at, with appropriate defaults
[ "Return", "two", "columns", "created_at", "and", "updated_at", "with", "appropriate", "defaults" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L49-L54
hasgeek/coaster
coaster/sqlalchemy/functions.py
failsafe_add
def failsafe_add(_session, _instance, **filters): """ Add and commit a new instance in a nested transaction (using SQL SAVEPOINT), gracefully handling failure in case a conflicting entry is already in the database (which may occur due to parallel requests causing race conditions in a production envi...
python
def failsafe_add(_session, _instance, **filters): """ Add and commit a new instance in a nested transaction (using SQL SAVEPOINT), gracefully handling failure in case a conflicting entry is already in the database (which may occur due to parallel requests causing race conditions in a production envi...
[ "def", "failsafe_add", "(", "_session", ",", "_instance", ",", "*", "*", "filters", ")", ":", "if", "_instance", "in", "_session", ":", "# This instance is already in the session, most likely due to a", "# save-update cascade. SQLAlchemy will flush before beginning a", "# neste...
Add and commit a new instance in a nested transaction (using SQL SAVEPOINT), gracefully handling failure in case a conflicting entry is already in the database (which may occur due to parallel requests causing race conditions in a production environment with multiple workers). Returns the instance save...
[ "Add", "and", "commit", "a", "new", "instance", "in", "a", "nested", "transaction", "(", "using", "SQL", "SAVEPOINT", ")", "gracefully", "handling", "failure", "in", "case", "a", "conflicting", "entry", "is", "already", "in", "the", "database", "(", "which",...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L57-L105
hasgeek/coaster
coaster/sqlalchemy/functions.py
add_primary_relationship
def add_primary_relationship(parent, childrel, child, parentrel, parentcol): """ When a parent-child relationship is defined as one-to-many, :func:`add_primary_relationship` lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a tr...
python
def add_primary_relationship(parent, childrel, child, parentrel, parentcol): """ When a parent-child relationship is defined as one-to-many, :func:`add_primary_relationship` lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a tr...
[ "def", "add_primary_relationship", "(", "parent", ",", "childrel", ",", "child", ",", "parentrel", ",", "parentcol", ")", ":", "parent_table_name", "=", "parent", ".", "__tablename__", "child_table_name", "=", "child", ".", "__tablename__", "primary_table_name", "="...
When a parent-child relationship is defined as one-to-many, :func:`add_primary_relationship` lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a trigger is added as well to ensure foreign key integrity. A SQLAlchemy relationship na...
[ "When", "a", "parent", "-", "child", "relationship", "is", "defined", "as", "one", "-", "to", "-", "many", ":", "func", ":", "add_primary_relationship", "lets", "the", "parent", "refer", "to", "one", "child", "as", "the", "primary", "by", "creating", "a", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L108-L210
hasgeek/coaster
coaster/sqlalchemy/functions.py
auto_init_default
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column...
python
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column...
[ "def", "auto_init_default", "(", "column", ")", ":", "if", "isinstance", "(", "column", ",", "ColumnProperty", ")", ":", "default", "=", "column", ".", "columns", "[", "0", "]", ".", "default", "else", ":", "default", "=", "column", ".", "default", "@", ...
Set the default value for a column when it's first accessed rather than first committed to the database.
[ "Set", "the", "default", "value", "for", "a", "column", "when", "it", "s", "first", "accessed", "rather", "than", "first", "committed", "to", "the", "database", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L213-L234
hasgeek/coaster
coaster/views/decorators.py
requestargs
def requestargs(*vars, **config): """ Decorator that loads parameters from request.values if not specified in the function's keyword arguments. Usage:: @requestargs('param1', ('param2', int), 'param3[]', ...) def function(param1, param2=0, param3=None): ... requestargs take...
python
def requestargs(*vars, **config): """ Decorator that loads parameters from request.values if not specified in the function's keyword arguments. Usage:: @requestargs('param1', ('param2', int), 'param3[]', ...) def function(param1, param2=0, param3=None): ... requestargs take...
[ "def", "requestargs", "(", "*", "vars", ",", "*", "*", "config", ")", ":", "if", "config", "and", "list", "(", "config", ".", "keys", "(", ")", ")", "!=", "[", "'source'", "]", ":", "raise", "TypeError", "(", "\"Unrecognised parameters: %s\"", "%", "re...
Decorator that loads parameters from request.values if not specified in the function's keyword arguments. Usage:: @requestargs('param1', ('param2', int), 'param3[]', ...) def function(param1, param2=0, param3=None): ... requestargs takes a list of parameters to pass to the wrapped ...
[ "Decorator", "that", "loads", "parameters", "from", "request", ".", "values", "if", "not", "specified", "in", "the", "function", "s", "keyword", "arguments", ".", "Usage", "::" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L42-L130
hasgeek/coaster
coaster/views/decorators.py
load_model
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[]): """ Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def pro...
python
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[]): """ Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def pro...
[ "def", "load_model", "(", "model", ",", "attributes", "=", "None", ",", "parameter", "=", "None", ",", "kwargs", "=", "False", ",", "permission", "=", "None", ",", "addlperms", "=", "None", ",", "urlcheck", "=", "[", "]", ")", ":", "return", "load_mode...
Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def profile_view(profileob): # 'profileob' is now a Profile model instance. The load_model decorator replaced this: # p...
[ "Decorator", "to", "load", "a", "model", "given", "a", "query", "parameter", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L147-L203
hasgeek/coaster
coaster/views/decorators.py
load_models
def load_models(*chain, **kwargs): """ Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). ...
python
def load_models(*chain, **kwargs): """ Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). ...
[ "def", "load_models", "(", "*", "chain", ",", "*", "*", "kwargs", ")", ":", "def", "inner", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated_function", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "permissions", "=", "None",...
Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). Lists and tuples can be used interchangeably. A...
[ "Decorator", "to", "load", "a", "chain", "of", "models", "from", "the", "given", "parameters", ".", "This", "works", "just", "like", ":", "func", ":", "load_model", "and", "accepts", "the", "same", "parameters", "with", "some", "small", "differences", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L206-L323
hasgeek/coaster
coaster/views/decorators.py
dict_jsonify
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonify(param)
python
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonify(param)
[ "def", "dict_jsonify", "(", "param", ")", ":", "if", "not", "isinstance", "(", "param", ",", "dict", ")", ":", "param", "=", "dict", "(", "param", ")", "return", "jsonify", "(", "param", ")" ]
Convert the parameter into a dictionary before calling jsonify, if it's not already one
[ "Convert", "the", "parameter", "into", "a", "dictionary", "before", "calling", "jsonify", "if", "it", "s", "not", "already", "one" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L334-L338
hasgeek/coaster
coaster/views/decorators.py
dict_jsonp
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
python
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
[ "def", "dict_jsonp", "(", "param", ")", ":", "if", "not", "isinstance", "(", "param", ",", "dict", ")", ":", "param", "=", "dict", "(", "param", ")", "return", "jsonp", "(", "param", ")" ]
Convert the parameter into a dictionary before calling jsonp, if it's not already one
[ "Convert", "the", "parameter", "into", "a", "dictionary", "before", "calling", "jsonp", "if", "it", "s", "not", "already", "one" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L341-L345
hasgeek/coaster
coaster/views/decorators.py
render_with
def render_with(template=None, json=False, jsonp=False): """ Decorator to render the wrapped function with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The function's return value must be ...
python
def render_with(template=None, json=False, jsonp=False): """ Decorator to render the wrapped function with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The function's return value must be ...
[ "def", "render_with", "(", "template", "=", "None", ",", "json", "=", "False", ",", "jsonp", "=", "False", ")", ":", "if", "jsonp", ":", "templates", "=", "{", "'application/json'", ":", "dict_jsonp", ",", "'application/javascript'", ":", "dict_jsonp", ",", ...
Decorator to render the wrapped function with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The function's return value must be a dictionary and is passed to the template as parameters. Callable...
[ "Decorator", "to", "render", "the", "wrapped", "function", "with", "the", "given", "template", "(", "or", "dictionary", "of", "mimetype", "keys", "to", "templates", "where", "the", "template", "is", "a", "string", "name", "of", "a", "template", "file", "or",...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L348-L510
hasgeek/coaster
coaster/views/decorators.py
cors
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None): """ Adds CORS headers to the decorated view function. :param origins: Allowed origins...
python
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None): """ Adds CORS headers to the decorated view function. :param origins: Allowed origins...
[ "def", "cors", "(", "origins", ",", "methods", "=", "[", "'HEAD'", ",", "'OPTIONS'", ",", "'GET'", ",", "'POST'", ",", "'PUT'", ",", "'PATCH'", ",", "'DELETE'", "]", ",", "headers", "=", "[", "'Accept'", ",", "'Accept-Language'", ",", "'Content-Language'",...
Adds CORS headers to the decorated view function. :param origins: Allowed origins (see below) :param methods: A list of allowed HTTP methods :param headers: A list of allowed HTTP headers :param max_age: Duration in seconds for which the CORS response may be cached The :obj:`origins` parameter may...
[ "Adds", "CORS", "headers", "to", "the", "decorated", "view", "function", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L513-L598
hasgeek/coaster
coaster/views/decorators.py
requires_permission
def requires_permission(permission): """ View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method tha...
python
def requires_permission(permission): """ View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method tha...
[ "def", "requires_permission", "(", "permission", ")", ":", "def", "inner", "(", "f", ")", ":", "def", "is_available_here", "(", ")", ":", "if", "not", "hasattr", "(", "current_auth", ",", "'permissions'", ")", ":", "return", "False", "elif", "is_collection",...
View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method that can be called to perform the same test. ...
[ "View", "decorator", "that", "requires", "a", "certain", "permission", "to", "be", "present", "in", "current_auth", ".", "permissions", "before", "the", "view", "is", "allowed", "to", "proceed", ".", "Aborts", "with", "403", "Forbidden", "if", "the", "permissi...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L601-L639
hasgeek/coaster
coaster/utils/misc.py
is_collection
def is_collection(item): """ Returns True if the item is a collection class: list, tuple, set, frozenset or any other class that resembles one of these (using abstract base classes). >>> is_collection(0) False >>> is_collection(0.1) False >>> is_collection('') False >>> is_colle...
python
def is_collection(item): """ Returns True if the item is a collection class: list, tuple, set, frozenset or any other class that resembles one of these (using abstract base classes). >>> is_collection(0) False >>> is_collection(0.1) False >>> is_collection('') False >>> is_colle...
[ "def", "is_collection", "(", "item", ")", ":", "return", "not", "isinstance", "(", "item", ",", "six", ".", "string_types", ")", "and", "isinstance", "(", "item", ",", "(", "collections", ".", "Set", ",", "collections", ".", "Sequence", ")", ")" ]
Returns True if the item is a collection class: list, tuple, set, frozenset or any other class that resembles one of these (using abstract base classes). >>> is_collection(0) False >>> is_collection(0.1) False >>> is_collection('') False >>> is_collection({}) False >>> is_collec...
[ "Returns", "True", "if", "the", "item", "is", "a", "collection", "class", ":", "list", "tuple", "set", "frozenset", "or", "any", "other", "class", "that", "resembles", "one", "of", "these", "(", "using", "abstract", "base", "classes", ")", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L48-L75
hasgeek/coaster
coaster/utils/misc.py
buid
def buid(): """ Return a new random id that is exactly 22 characters long, by encoding a UUID4 in URL-safe Base64. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table >>> len(buid()) 22 >>> buid() == buid() False >>> isinstance(buid(), six.text_type) True """ ...
python
def buid(): """ Return a new random id that is exactly 22 characters long, by encoding a UUID4 in URL-safe Base64. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table >>> len(buid()) 22 >>> buid() == buid() False >>> isinstance(buid(), six.text_type) True """ ...
[ "def", "buid", "(", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "return", "urlsafe_b64encode", "(", "uuid", ".", "uuid4", "(", ")", ".", "bytes", ")", ".", "decode", "(", "'utf-8'", ")", ".", "rstrip", "(", "'='", ")", "else", ":", ...
Return a new random id that is exactly 22 characters long, by encoding a UUID4 in URL-safe Base64. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table >>> len(buid()) 22 >>> buid() == buid() False >>> isinstance(buid(), six.text_type) True
[ "Return", "a", "new", "random", "id", "that", "is", "exactly", "22", "characters", "long", "by", "encoding", "a", "UUID4", "in", "URL", "-", "safe", "Base64", ".", "See", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Base6...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L78-L94
hasgeek/coaster
coaster/utils/misc.py
uuid1mc_from_datetime
def uuid1mc_from_datetime(dt): """ Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled con...
python
def uuid1mc_from_datetime(dt): """ Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled con...
[ "def", "uuid1mc_from_datetime", "(", "dt", ")", ":", "fields", "=", "list", "(", "uuid1mc", "(", ")", ".", "fields", ")", "if", "isinstance", "(", "dt", ",", "datetime", ")", ":", "timeval", "=", "time", ".", "mktime", "(", "dt", ".", "timetuple", "(...
Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled conditions only. >>> dt = datetime.now() ...
[ "Return", "a", "UUID1", "with", "a", "random", "multicast", "MAC", "id", "and", "with", "a", "timestamp", "matching", "the", "given", "datetime", "object", "or", "timestamp", "value", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L104-L145
hasgeek/coaster
coaster/utils/misc.py
uuid2buid
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else...
python
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else...
[ "def", "uuid2buid", "(", "value", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "return", "urlsafe_b64encode", "(", "value", ".", "bytes", ")", ".", "decode", "(", "'utf-8'", ")", ".", "rstrip", "(", "'='", ")", "else", ":", "return", "...
Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ'
[ "Convert", "a", "UUID", "object", "to", "a", "22", "-", "char", "BUID", "string" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L148-L159
hasgeek/coaster
coaster/utils/misc.py
newpin
def newpin(digits=4): """ Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True """ randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randin...
python
def newpin(digits=4): """ Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True """ randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randin...
[ "def", "newpin", "(", "digits", "=", "4", ")", ":", "randnum", "=", "randint", "(", "0", ",", "10", "**", "digits", ")", "while", "len", "(", "str", "(", "randnum", ")", ")", ">", "digits", ":", "randnum", "=", "randint", "(", "0", ",", "10", "...
Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True
[ "Return", "a", "random", "numeric", "string", "with", "the", "specified", "number", "of", "digits", "default", "4", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L186-L201
hasgeek/coaster
coaster/utils/misc.py
make_name
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param str...
python
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param str...
[ "def", "make_name", "(", "text", ",", "delim", "=", "u'-'", ",", "maxlength", "=", "50", ",", "checkused", "=", "None", ",", "counter", "=", "2", ")", ":", "name", "=", "text", ".", "replace", "(", "'@'", ",", "delim", ")", "name", "=", "unidecode"...
u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param string delim: Delimiter between words, default '-' :param int maxlength: Maxi...
[ "u", "Generate", "an", "ASCII", "name", "slug", ".", "If", "a", "checkused", "filter", "is", "provided", "it", "will", "be", "called", "with", "the", "candidate", ".", "If", "it", "returns", "True", "make_name", "will", "add", "counter", "numbers", "starti...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L204-L291
hasgeek/coaster
coaster/utils/misc.py
make_password
def make_password(password, encoding='BCRYPT'): """ Make a password with PLAIN, SSHA or BCRYPT (default) encoding. >>> make_password('foo', encoding='PLAIN') '{PLAIN}foo' >>> make_password(u're-foo', encoding='SSHA')[:6] '{SSHA}' >>> make_password(u're-foo')[:8] '{BCRYPT}' >>> make_...
python
def make_password(password, encoding='BCRYPT'): """ Make a password with PLAIN, SSHA or BCRYPT (default) encoding. >>> make_password('foo', encoding='PLAIN') '{PLAIN}foo' >>> make_password(u're-foo', encoding='SSHA')[:6] '{SSHA}' >>> make_password(u're-foo')[:8] '{BCRYPT}' >>> make_...
[ "def", "make_password", "(", "password", ",", "encoding", "=", "'BCRYPT'", ")", ":", "if", "encoding", "not", "in", "[", "'PLAIN'", ",", "'SSHA'", ",", "'BCRYPT'", "]", ":", "raise", "ValueError", "(", "\"Unknown encoding %s\"", "%", "encoding", ")", "if", ...
Make a password with PLAIN, SSHA or BCRYPT (default) encoding. >>> make_password('foo', encoding='PLAIN') '{PLAIN}foo' >>> make_password(u're-foo', encoding='SSHA')[:6] '{SSHA}' >>> make_password(u're-foo')[:8] '{BCRYPT}' >>> make_password('foo') == make_password('foo') False
[ "Make", "a", "password", "with", "PLAIN", "SSHA", "or", "BCRYPT", "(", "default", ")", "encoding", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L294-L338
hasgeek/coaster
coaster/utils/misc.py
check_password
def check_password(reference, attempt): """ Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encodin...
python
def check_password(reference, attempt): """ Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encodin...
[ "def", "check_password", "(", "reference", ",", "attempt", ")", ":", "if", "reference", ".", "startswith", "(", "u'{PLAIN}'", ")", ":", "if", "reference", "[", "7", ":", "]", "==", "attempt", ":", "return", "True", "elif", "reference", ".", "startswith", ...
Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encoding') False >>> check_password(u'{SSHA}q/uVU8r...
[ "Compare", "a", "reference", "password", "with", "the", "user", "attempt", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L341-L398
hasgeek/coaster
coaster/utils/misc.py
format_currency
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> form...
python
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> form...
[ "def", "format_currency", "(", "value", ",", "decimals", "=", "2", ")", ":", "number", ",", "decimal", "=", "(", "(", "u'%%.%df'", "%", "decimals", ")", "%", "value", ")", ".", "split", "(", "u'.'", ")", "parts", "=", "[", "]", "while", "len", "(",...
Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> format_currency(99.95) '99.95' >>> format_curren...
[ "Return", "a", "number", "suitably", "formatted", "for", "display", "as", "currency", "with", "thousands", "separated", "by", "commas", "and", "up", "to", "two", "decimal", "points", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L401-L437
hasgeek/coaster
coaster/utils/misc.py
md5sum
def md5sum(data): """ Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32 """ if six.PY3: # pragma: no cover return h...
python
def md5sum(data): """ Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32 """ if six.PY3: # pragma: no cover return h...
[ "def", "md5sum", "(", "data", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "return", "hashlib", ".", "md5", "(", "data", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "else", ":", "# pragma: no cover", "return", ...
Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32
[ "Return", "md5sum", "of", "data", "as", "a", "32", "-", "character", "string", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L440-L454
hasgeek/coaster
coaster/utils/misc.py
isoweek_datetime
def isoweek_datetime(year, week, timezone='UTC', naive=False): """ Returns a datetime matching the starting point of a specified ISO week in the specified timezone (default UTC). Returns a naive datetime in UTC if requested (default False). >>> isoweek_datetime(2017, 1) datetime.datetime(2017, ...
python
def isoweek_datetime(year, week, timezone='UTC', naive=False): """ Returns a datetime matching the starting point of a specified ISO week in the specified timezone (default UTC). Returns a naive datetime in UTC if requested (default False). >>> isoweek_datetime(2017, 1) datetime.datetime(2017, ...
[ "def", "isoweek_datetime", "(", "year", ",", "week", ",", "timezone", "=", "'UTC'", ",", "naive", "=", "False", ")", ":", "naivedt", "=", "datetime", ".", "combine", "(", "isoweek", ".", "Week", "(", "year", ",", "week", ")", ".", "day", "(", "0", ...
Returns a datetime matching the starting point of a specified ISO week in the specified timezone (default UTC). Returns a naive datetime in UTC if requested (default False). >>> isoweek_datetime(2017, 1) datetime.datetime(2017, 1, 2, 0, 0, tzinfo=<UTC>) >>> isoweek_datetime(2017, 1, 'Asia/Kolkata')...
[ "Returns", "a", "datetime", "matching", "the", "starting", "point", "of", "a", "specified", "ISO", "week", "in", "the", "specified", "timezone", "(", "default", "UTC", ")", ".", "Returns", "a", "naive", "datetime", "in", "UTC", "if", "requested", "(", "def...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L464-L488
hasgeek/coaster
coaster/utils/misc.py
midnight_to_utc
def midnight_to_utc(dt, timezone=None, naive=False): """ Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia...
python
def midnight_to_utc(dt, timezone=None, naive=False): """ Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia...
[ "def", "midnight_to_utc", "(", "dt", ",", "timezone", "=", "None", ",", "naive", "=", "False", ")", ":", "if", "timezone", ":", "if", "isinstance", "(", "timezone", ",", "six", ".", "string_types", ")", ":", "tz", "=", "pytz", ".", "timezone", "(", "...
Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1))) datetime.datetime(...
[ "Returns", "a", "UTC", "datetime", "matching", "the", "midnight", "for", "the", "given", "date", "or", "datetime", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L491-L528
hasgeek/coaster
coaster/utils/misc.py
getbool
def getbool(value): """ Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2...
python
def getbool(value): """ Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2...
[ "def", "getbool", "(", "value", ")", ":", "value", "=", "str", "(", "value", ")", ".", "lower", "(", ")", "if", "value", "in", "[", "'1'", ",", "'t'", ",", "'true'", ",", "'y'", ",", "'yes'", "]", ":", "return", "True", "elif", "value", "in", "...
Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2) >>> getbool(0) False ...
[ "Returns", "a", "boolean", "from", "any", "of", "a", "range", "of", "values", ".", "Returns", "None", "for", "unrecognized", "values", ".", "Numbers", "other", "than", "0", "and", "1", "are", "considered", "unrecognized", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L531-L558
hasgeek/coaster
coaster/utils/misc.py
require_one_of
def require_one_of(_return=False, **kwargs): """ Validator that raises :exc:`TypeError` unless one and only one parameter is not ``None``. Use this inside functions that take multiple parameters, but allow only one of them to be specified:: def my_func(this=None, that=None, other=None): ...
python
def require_one_of(_return=False, **kwargs): """ Validator that raises :exc:`TypeError` unless one and only one parameter is not ``None``. Use this inside functions that take multiple parameters, but allow only one of them to be specified:: def my_func(this=None, that=None, other=None): ...
[ "def", "require_one_of", "(", "_return", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Two ways to count number of non-None parameters:", "#", "# 1. sum([1 if v is not None else 0 for v in kwargs.values()])", "#", "# Using a list comprehension instead of a generator comprehe...
Validator that raises :exc:`TypeError` unless one and only one parameter is not ``None``. Use this inside functions that take multiple parameters, but allow only one of them to be specified:: def my_func(this=None, that=None, other=None): # Require one and only one of `this` or `that` ...
[ "Validator", "that", "raises", ":", "exc", ":", "TypeError", "unless", "one", "and", "only", "one", "parameter", "is", "not", "None", ".", "Use", "this", "inside", "functions", "that", "take", "multiple", "parameters", "but", "allow", "only", "one", "of", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L592-L642
hasgeek/coaster
coaster/utils/misc.py
unicode_http_header
def unicode_http_header(value): r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6...
python
def unicode_http_header(value): r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6...
[ "def", "unicode_http_header", "(", "value", ")", ":", "if", "six", ".", "PY3", ":", "# pragma: no cover", "# email.header.decode_header expects strings, not bytes. Your input data may be in bytes.", "# Since these bytes are almost always ASCII, calling `.decode()` on it without specifying"...
r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True ...
[ "r", "Convert", "an", "ASCII", "HTTP", "header", "string", "into", "a", "unicode", "string", "with", "the", "appropriate", "encoding", "applied", ".", "Expects", "headers", "to", "be", "RFC", "2047", "compliant", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L645-L664
hasgeek/coaster
coaster/utils/misc.py
get_email_domain
def get_email_domain(emailaddr): """ Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_...
python
def get_email_domain(emailaddr): """ Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_...
[ "def", "get_email_domain", "(", "emailaddr", ")", ":", "realname", ",", "address", "=", "email", ".", "utils", ".", "parseaddr", "(", "emailaddr", ")", "try", ":", "username", ",", "domain", "=", "address", ".", "split", "(", "'@'", ")", "if", "not", "...
Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_email_domain('Example Address <test@example.c...
[ "Return", "the", "domain", "component", "of", "an", "email", "address", ".", "Returns", "None", "if", "the", "provided", "string", "cannot", "be", "parsed", "as", "an", "email", "address", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L667-L691
hasgeek/coaster
coaster/utils/misc.py
sorted_timezones
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = di...
python
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = di...
[ "def", "sorted_timezones", "(", ")", ":", "def", "hourmin", "(", "delta", ")", ":", "if", "delta", ".", "days", "<", "0", ":", "hours", ",", "remaining", "=", "divmod", "(", "86400", "-", "delta", ".", "seconds", ",", "3600", ")", "else", ":", "hou...
Return a list of timezones sorted by offset from UTC.
[ "Return", "a", "list", "of", "timezones", "sorted", "by", "offset", "from", "UTC", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L714-L746
hasgeek/coaster
coaster/utils/misc.py
namespace_from_url
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname...
python
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname...
[ "def", "namespace_from_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "if", "parsed", ".", "hostname", "is", "None", "or", "parsed", ".", "hostname", "in", "[", "'localhost'", ",", "'localhost.localdomain'", "]", "or", "(", "_ipv4_...
Construct a dotted namespace string from a URL.
[ "Construct", "a", "dotted", "namespace", "string", "from", "a", "URL", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L749-L764
hasgeek/coaster
coaster/utils/misc.py
base_domain_matches
def base_domain_matches(d1, d2): """ Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co'...
python
def base_domain_matches(d1, d2): """ Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co'...
[ "def", "base_domain_matches", "(", "d1", ",", "d2", ")", ":", "r1", "=", "tldextract", ".", "extract", "(", "d1", ")", "r2", "=", "tldextract", ".", "extract", "(", "d2", ")", "# r1 and r2 contain subdomain, domain and suffix.", "# We want to confirm that domain and...
Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co') False >>> base_domain_matches('stat...
[ "Check", "if", "two", "domains", "have", "the", "same", "base", "domain", "using", "the", "Public", "Suffix", "List", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L767-L788
hasgeek/coaster
coaster/sqlalchemy/columns.py
MarkdownColumn
def MarkdownColumn(name, deferred=False, group=None, **kwargs): """ Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes. """ return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwar...
python
def MarkdownColumn(name, deferred=False, group=None, **kwargs): """ Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes. """ return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwar...
[ "def", "MarkdownColumn", "(", "name", ",", "deferred", "=", "False", ",", "group", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "composite", "(", "MarkdownComposite", ",", "Column", "(", "name", "+", "'_text'", ",", "UnicodeText", ",", "*", ...
Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes.
[ "Create", "a", "composite", "column", "that", "autogenerates", "HTML", "from", "Markdown", "text", "storing", "data", "in", "db", "columns", "named", "with", "_html", "and", "_text", "prefixes", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/columns.py#L177-L186
hasgeek/coaster
coaster/sqlalchemy/columns.py
MutableDict.coerce
def coerce(cls, key, value): """Convert plain dictionaries to MutableDict.""" if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) elif isinstance(value, six.string_types): # Assume JSON string ...
python
def coerce(cls, key, value): """Convert plain dictionaries to MutableDict.""" if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) elif isinstance(value, six.string_types): # Assume JSON string ...
[ "def", "coerce", "(", "cls", ",", "key", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "MutableDict", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "MutableDict", "(", "value", ")", "elif", "isin...
Convert plain dictionaries to MutableDict.
[ "Convert", "plain", "dictionaries", "to", "MutableDict", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/columns.py#L79-L95
hasgeek/coaster
coaster/assets.py
VersionedAssets.require
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if not n.startswith('!')] return Bundle(*[bundle for name, version, bundle ...
python
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if not n.startswith('!')] return Bundle(*[bundle for name, version, bundle ...
[ "def", "require", "(", "self", ",", "*", "namespecs", ")", ":", "blacklist", "=", "set", "(", "[", "n", "[", "1", ":", "]", "for", "n", "in", "namespecs", "if", "n", ".", "startswith", "(", "'!'", ")", "]", ")", "not_blacklist", "=", "[", "n", ...
Return a bundle of the requested assets and their dependencies.
[ "Return", "a", "bundle", "of", "the", "requested", "assets", "and", "their", "dependencies", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/assets.py#L165-L170
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateTransitionWrapper._state_invalid
def _state_invalid(self): """ If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state) """ for statemanager, conditions in self.statetransition.transitions.items(): curre...
python
def _state_invalid(self): """ If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state) """ for statemanager, conditions in self.statetransition.transitions.items(): curre...
[ "def", "_state_invalid", "(", "self", ")", ":", "for", "statemanager", ",", "conditions", "in", "self", ".", "statetransition", ".", "transitions", ".", "items", "(", ")", ":", "current_state", "=", "getattr", "(", "self", ".", "obj", ",", "statemanager", ...
If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state)
[ "If", "the", "state", "is", "invalid", "for", "the", "transition", "return", "details", "on", "what", "didn", "t", "match" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L538-L554
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager._set
def _set(self, obj, value): """Internal method to set state, called by meth:`StateTransition.__call__`""" if value not in self.lenum: raise ValueError("Not a valid value: %s" % value) type(obj).__dict__[self.propname].__set__(obj, value)
python
def _set(self, obj, value): """Internal method to set state, called by meth:`StateTransition.__call__`""" if value not in self.lenum: raise ValueError("Not a valid value: %s" % value) type(obj).__dict__[self.propname].__set__(obj, value)
[ "def", "_set", "(", "self", ",", "obj", ",", "value", ")", ":", "if", "value", "not", "in", "self", ".", "lenum", ":", "raise", "ValueError", "(", "\"Not a valid value: %s\"", "%", "value", ")", "type", "(", "obj", ")", ".", "__dict__", "[", "self", ...
Internal method to set state, called by meth:`StateTransition.__call__`
[ "Internal", "method", "to", "set", "state", "called", "by", "meth", ":", "StateTransition", ".", "__call__" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L662-L667
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.add_state_group
def add_state_group(self, name, *states): """ Add a group of managed states. Groups can be specified directly in the :class:`~coaster.utils.classes.LabeledEnum`. This method is only useful for grouping a conditional state with existing states. It cannot be used to form a group of...
python
def add_state_group(self, name, *states): """ Add a group of managed states. Groups can be specified directly in the :class:`~coaster.utils.classes.LabeledEnum`. This method is only useful for grouping a conditional state with existing states. It cannot be used to form a group of...
[ "def", "add_state_group", "(", "self", ",", "name", ",", "*", "states", ")", ":", "# See `_add_state_internal` for explanation of the following", "if", "hasattr", "(", "self", ",", "name", ")", ":", "raise", "AttributeError", "(", "\"State group name %s conflicts with e...
Add a group of managed states. Groups can be specified directly in the :class:`~coaster.utils.classes.LabeledEnum`. This method is only useful for grouping a conditional state with existing states. It cannot be used to form a group of groups. :param str name: Name of this group ...
[ "Add", "a", "group", "of", "managed", "states", ".", "Groups", "can", "be", "specified", "directly", "in", "the", ":", "class", ":", "~coaster", ".", "utils", ".", "classes", ".", "LabeledEnum", ".", "This", "method", "is", "only", "useful", "for", "grou...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L690-L707
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.add_conditional_state
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): """ Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. ...
python
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): """ Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. ...
[ "def", "add_conditional_state", "(", "self", ",", "name", ",", "state", ",", "validator", ",", "class_validator", "=", "None", ",", "cache_for", "=", "None", ",", "label", "=", "None", ")", ":", "# We'll accept a ManagedState with grouped values, but not a ManagedStat...
Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. :param str name: Name of the new state :param ManagedState state: Existing state that this is based on ...
[ "Add", "a", "conditional", "state", "that", "combines", "an", "existing", "state", "with", "a", "validator", "that", "must", "also", "pass", ".", "The", "validator", "receives", "the", "object", "on", "which", "the", "property", "is", "present", "as", "a", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L709-L738
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.transition
def transition(self, from_, to, if_=None, **data): """ Decorates a method to transition from one state to another. The decorated method can accept any necessary parameters and perform additional processing, or raise an exception to abort the transition. If it returns without an e...
python
def transition(self, from_, to, if_=None, **data): """ Decorates a method to transition from one state to another. The decorated method can accept any necessary parameters and perform additional processing, or raise an exception to abort the transition. If it returns without an e...
[ "def", "transition", "(", "self", ",", "from_", ",", "to", ",", "if_", "=", "None", ",", "*", "*", "data", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "isinstance", "(", "f", ",", "StateTransition", ")", ":", "f", ".", "add_transition",...
Decorates a method to transition from one state to another. The decorated method can accept any necessary parameters and perform additional processing, or raise an exception to abort the transition. If it returns without an error, the state value is updated automatically. Transitions may...
[ "Decorates", "a", "method", "to", "transition", "from", "one", "state", "to", "another", ".", "The", "decorated", "method", "can", "accept", "any", "necessary", "parameters", "and", "perform", "additional", "processing", "or", "raise", "an", "exception", "to", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L740-L763
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.requires
def requires(self, from_, if_=None, **data): """ Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Val...
python
def requires(self, from_, if_=None, **data): """ Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Val...
[ "def", "requires", "(", "self", ",", "from_", ",", "if_", "=", "None", ",", "*", "*", "data", ")", ":", "return", "self", ".", "transition", "(", "from_", ",", "None", ",", "if_", ",", "*", "*", "data", ")" ]
Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Validator(s) that, given the object, must all return True for the ca...
[ "Decorates", "a", "method", "that", "may", "be", "called", "if", "the", "given", "state", "is", "currently", "active", ".", "Registers", "a", "transition", "internally", "but", "does", "not", "change", "the", "state", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L765-L774
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager._value
def _value(self, obj, cls=None): """The state value (called from the wrapper)""" if obj is not None: return getattr(obj, self.propname) else: return getattr(cls, self.propname)
python
def _value(self, obj, cls=None): """The state value (called from the wrapper)""" if obj is not None: return getattr(obj, self.propname) else: return getattr(cls, self.propname)
[ "def", "_value", "(", "self", ",", "obj", ",", "cls", "=", "None", ")", ":", "if", "obj", "is", "not", "None", ":", "return", "getattr", "(", "obj", ",", "self", ".", "propname", ")", "else", ":", "return", "getattr", "(", "cls", ",", "self", "."...
The state value (called from the wrapper)
[ "The", "state", "value", "(", "called", "from", "the", "wrapper", ")" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L776-L781
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.check_constraint
def check_constraint(column, lenum, **kwargs): """ Returns a SQL CHECK constraint string given a column name and a :class:`~coaster.utils.classes.LabeledEnum`. Alembic may not detect the CHECK constraint when autogenerating migrations, so you may need to do this manually using t...
python
def check_constraint(column, lenum, **kwargs): """ Returns a SQL CHECK constraint string given a column name and a :class:`~coaster.utils.classes.LabeledEnum`. Alembic may not detect the CHECK constraint when autogenerating migrations, so you may need to do this manually using t...
[ "def", "check_constraint", "(", "column", ",", "lenum", ",", "*", "*", "kwargs", ")", ":", "return", "CheckConstraint", "(", "str", "(", "column_constructor", "(", "column", ")", ".", "in_", "(", "lenum", ".", "keys", "(", ")", ")", ".", "compile", "("...
Returns a SQL CHECK constraint string given a column name and a :class:`~coaster.utils.classes.LabeledEnum`. Alembic may not detect the CHECK constraint when autogenerating migrations, so you may need to do this manually using the Python console to extract the SQL string:: ...
[ "Returns", "a", "SQL", "CHECK", "constraint", "string", "given", "a", "column", "name", "and", "a", ":", "class", ":", "~coaster", ".", "utils", ".", "classes", ".", "LabeledEnum", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L784-L804
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.bestmatch
def bestmatch(self): """ Best matching current scalar state (direct or conditional), only applicable when accessed via an instance. """ if self.obj is not None: for mstate in self.statemanager.all_states_by_value[self.value]: msw = mstate(self.obj, sel...
python
def bestmatch(self): """ Best matching current scalar state (direct or conditional), only applicable when accessed via an instance. """ if self.obj is not None: for mstate in self.statemanager.all_states_by_value[self.value]: msw = mstate(self.obj, sel...
[ "def", "bestmatch", "(", "self", ")", ":", "if", "self", ".", "obj", "is", "not", "None", ":", "for", "mstate", "in", "self", ".", "statemanager", ".", "all_states_by_value", "[", "self", ".", "value", "]", ":", "msw", "=", "mstate", "(", "self", "."...
Best matching current scalar state (direct or conditional), only applicable when accessed via an instance.
[ "Best", "matching", "current", "scalar", "state", "(", "direct", "or", "conditional", ")", "only", "applicable", "when", "accessed", "via", "an", "instance", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L832-L841
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.current
def current(self): """ All states and state groups that are currently active. """ if self.obj is not None: return {name: mstate(self.obj, self.cls) for name, mstate in self.statemanager.states.items() if mstate(self.obj, self.cls)}
python
def current(self): """ All states and state groups that are currently active. """ if self.obj is not None: return {name: mstate(self.obj, self.cls) for name, mstate in self.statemanager.states.items() if mstate(self.obj, self.cls)}
[ "def", "current", "(", "self", ")", ":", "if", "self", ".", "obj", "is", "not", "None", ":", "return", "{", "name", ":", "mstate", "(", "self", ".", "obj", ",", "self", ".", "cls", ")", "for", "name", ",", "mstate", "in", "self", ".", "statemanag...
All states and state groups that are currently active.
[ "All", "states", "and", "state", "groups", "that", "are", "currently", "active", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L843-L850
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.transitions
def transitions(self, current=True): """ Returns available transitions for the current state, as a dictionary of name: :class:`StateTransitionWrapper`. :param bool current: Limit to transitions available in ``obj.`` :meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access` ...
python
def transitions(self, current=True): """ Returns available transitions for the current state, as a dictionary of name: :class:`StateTransitionWrapper`. :param bool current: Limit to transitions available in ``obj.`` :meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access` ...
[ "def", "transitions", "(", "self", ",", "current", "=", "True", ")", ":", "if", "current", "and", "isinstance", "(", "self", ".", "obj", ",", "RoleMixin", ")", ":", "proxy", "=", "self", ".", "obj", ".", "current_access", "(", ")", "else", ":", "prox...
Returns available transitions for the current state, as a dictionary of name: :class:`StateTransitionWrapper`. :param bool current: Limit to transitions available in ``obj.`` :meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access`
[ "Returns", "available", "transitions", "for", "the", "current", "state", "as", "a", "dictionary", "of", "name", ":", ":", "class", ":", "StateTransitionWrapper", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L852-L868
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.transitions_for
def transitions_for(self, roles=None, actor=None, anchors=[]): """ For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes: returns currently available transitions for the specified roles or actor as a dictionary of name: :class:`StateTransitionWrapper`. """ prox...
python
def transitions_for(self, roles=None, actor=None, anchors=[]): """ For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes: returns currently available transitions for the specified roles or actor as a dictionary of name: :class:`StateTransitionWrapper`. """ prox...
[ "def", "transitions_for", "(", "self", ",", "roles", "=", "None", ",", "actor", "=", "None", ",", "anchors", "=", "[", "]", ")", ":", "proxy", "=", "self", ".", "obj", ".", "access_for", "(", "roles", ",", "actor", ",", "anchors", ")", "return", "{...
For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes: returns currently available transitions for the specified roles or actor as a dictionary of name: :class:`StateTransitionWrapper`.
[ "For", "use", "on", ":", "class", ":", "~coaster", ".", "sqlalchemy", ".", "mixins", ".", "RoleMixin", "classes", ":", "returns", "currently", "available", "transitions", "for", "the", "specified", "roles", "or", "actor", "as", "a", "dictionary", "of", "name...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L870-L878
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.group
def group(self, items, keep_empty=False): """ Given an iterable of instances, groups them by state using :class:`ManagedState` instances as dictionary keys. Returns an `OrderedDict` that preserves the order of states from the source :class:`~coaster.utils.classes.LabeledEnum`. :...
python
def group(self, items, keep_empty=False): """ Given an iterable of instances, groups them by state using :class:`ManagedState` instances as dictionary keys. Returns an `OrderedDict` that preserves the order of states from the source :class:`~coaster.utils.classes.LabeledEnum`. :...
[ "def", "group", "(", "self", ",", "items", ",", "keep_empty", "=", "False", ")", ":", "cls", "=", "self", ".", "cls", "if", "self", ".", "cls", "is", "not", "None", "else", "type", "(", "self", ".", "obj", ")", "# Class of the item being managed", "gro...
Given an iterable of instances, groups them by state using :class:`ManagedState` instances as dictionary keys. Returns an `OrderedDict` that preserves the order of states from the source :class:`~coaster.utils.classes.LabeledEnum`. :param bool keep_empty: If ``True``, empty states are included ...
[ "Given", "an", "iterable", "of", "instances", "groups", "them", "by", "state", "using", ":", "class", ":", "ManagedState", "instances", "as", "dictionary", "keys", ".", "Returns", "an", "OrderedDict", "that", "preserves", "the", "order", "of", "states", "from"...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L880-L906
hasgeek/coaster
coaster/gfm.py
gfm
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last lin...
python
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last lin...
[ "def", "gfm", "(", "text", ")", ":", "def", "indent_code", "(", "matchobj", ")", ":", "syntax", "=", "matchobj", ".", "group", "(", "1", ")", "code", "=", "matchobj", ".", "group", "(", "2", ")", "if", "syntax", ":", "result", "=", "' :::'", "+"...
Prepare text for rendering by a regular Markdown processor.
[ "Prepare", "text", "for", "rendering", "by", "a", "regular", "Markdown", "processor", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/gfm.py#L111-L169
hasgeek/coaster
coaster/gfm.py
markdown
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid...
python
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid...
[ "def", "markdown", "(", "text", ",", "html", "=", "False", ",", "valid_tags", "=", "GFM_TAGS", ")", ":", "if", "text", "is", "None", ":", "return", "None", "if", "html", ":", "return", "Markup", "(", "sanitize_html", "(", "markdown_convert_html", "(", "g...
Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled.
[ "Return", "Markdown", "rendered", "text", "using", "GitHub", "Flavoured", "Markdown", "with", "HTML", "escaped", "and", "syntax", "-", "highlighting", "enabled", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/gfm.py#L172-L182
hasgeek/coaster
coaster/views/classview.py
rulejoin
def rulejoin(class_rule, method_rule): """ Join class and method rules. Used internally by :class:`ClassView` to combine rules from the :func:`route` decorators on the class and on the individual view handler methods:: >>> rulejoin('/', '') '/' >>> rulejoin('/', 'first') ...
python
def rulejoin(class_rule, method_rule): """ Join class and method rules. Used internally by :class:`ClassView` to combine rules from the :func:`route` decorators on the class and on the individual view handler methods:: >>> rulejoin('/', '') '/' >>> rulejoin('/', 'first') ...
[ "def", "rulejoin", "(", "class_rule", ",", "method_rule", ")", ":", "if", "method_rule", ".", "startswith", "(", "'/'", ")", ":", "return", "method_rule", "else", ":", "return", "class_rule", "+", "(", "''", "if", "class_rule", ".", "endswith", "(", "'/'",...
Join class and method rules. Used internally by :class:`ClassView` to combine rules from the :func:`route` decorators on the class and on the individual view handler methods:: >>> rulejoin('/', '') '/' >>> rulejoin('/', 'first') '/first' >>> rulejoin('/first', '/second')...
[ "Join", "class", "and", "method", "rules", ".", "Used", "internally", "by", ":", "class", ":", "ClassView", "to", "combine", "rules", "from", "the", ":", "func", ":", "route", "decorators", "on", "the", "class", "and", "on", "the", "individual", "view", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L56-L80
hasgeek/coaster
coaster/views/classview.py
requires_roles
def requires_roles(roles): """ Decorator for :class:`ModelView` views that limits access to the specified roles. """ def inner(f): def is_available_here(context): return bool(roles.intersection(context.obj.current_roles)) def is_available(context): result = i...
python
def requires_roles(roles): """ Decorator for :class:`ModelView` views that limits access to the specified roles. """ def inner(f): def is_available_here(context): return bool(roles.intersection(context.obj.current_roles)) def is_available(context): result = i...
[ "def", "requires_roles", "(", "roles", ")", ":", "def", "inner", "(", "f", ")", ":", "def", "is_available_here", "(", "context", ")", ":", "return", "bool", "(", "roles", ".", "intersection", "(", "context", ".", "obj", ".", "current_roles", ")", ")", ...
Decorator for :class:`ModelView` views that limits access to the specified roles.
[ "Decorator", "for", ":", "class", ":", "ModelView", "views", "that", "limits", "access", "to", "the", "specified", "roles", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L568-L594
hasgeek/coaster
coaster/views/classview.py
url_change_check
def url_change_check(f): """ View method decorator that checks the URL of the loaded object in ``self.obj`` against the URL in the request (using ``self.obj.url_for(__name__)``). If the URLs do not match, and the request is a ``GET``, it issues a redirect to the correct URL. Usage:: @ro...
python
def url_change_check(f): """ View method decorator that checks the URL of the loaded object in ``self.obj`` against the URL in the request (using ``self.obj.url_for(__name__)``). If the URLs do not match, and the request is a ``GET``, it issues a redirect to the correct URL. Usage:: @ro...
[ "def", "url_change_check", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "method", "==", "'GET'", "and", "self", ".", "obj", "is", "not",...
View method decorator that checks the URL of the loaded object in ``self.obj`` against the URL in the request (using ``self.obj.url_for(__name__)``). If the URLs do not match, and the request is a ``GET``, it issues a redirect to the correct URL. Usage:: @route('/doc/<document>') class ...
[ "View", "method", "decorator", "that", "checks", "the", "URL", "of", "the", "loaded", "object", "in", "self", ".", "obj", "against", "the", "URL", "in", "the", "request", "(", "using", "self", ".", "obj", ".", "url_for", "(", "__name__", ")", ")", ".",...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L634-L665
hasgeek/coaster
coaster/views/classview.py
ViewHandler.init_app
def init_app(self, app, cls, callback=None): """ Register routes for a given app and :class:`ClassView` class. At the time of this call, we will always be in the view class even if we were originally defined in a base class. :meth:`ClassView.init_app` ensures this. :meth:`init_ap...
python
def init_app(self, app, cls, callback=None): """ Register routes for a given app and :class:`ClassView` class. At the time of this call, we will always be in the view class even if we were originally defined in a base class. :meth:`ClassView.init_app` ensures this. :meth:`init_ap...
[ "def", "init_app", "(", "self", ",", "app", ",", "cls", ",", "callback", "=", "None", ")", ":", "def", "view_func", "(", "*", "*", "view_args", ")", ":", "# view_func does not make any reference to variables from init_app to avoid creating", "# a closure. Instead, the c...
Register routes for a given app and :class:`ClassView` class. At the time of this call, we will always be in the view class even if we were originally defined in a base class. :meth:`ClassView.init_app` ensures this. :meth:`init_app` therefore takes the liberty of adding additional attri...
[ "Register", "routes", "for", "a", "given", "app", "and", ":", "class", ":", "ClassView", "class", ".", "At", "the", "time", "of", "this", "call", "we", "will", "always", "be", "in", "the", "view", "class", "even", "if", "we", "were", "originally", "def...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L149-L226
hasgeek/coaster
coaster/views/classview.py
ViewHandlerWrapper.is_available
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
python
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
[ "def", "is_available", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_viewh", ".", "wrapped_func", ",", "'is_available'", ")", ":", "return", "self", ".", "_viewh", ".", "wrapped_func", ".", "is_available", "(", "self", ".", "_obj", ")", "re...
Indicates whether this view is available in the current context
[ "Indicates", "whether", "this", "view", "is", "available", "in", "the", "current", "context" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L254-L258
hasgeek/coaster
coaster/views/classview.py
ClassView.dispatch_request
def dispatch_request(self, view, view_args): """ View dispatcher that calls before_request, the view, and then after_request. Subclasses may override this to provide a custom flow. :class:`ModelView` does this to insert a model loading phase. :param view: View method wrapped in ...
python
def dispatch_request(self, view, view_args): """ View dispatcher that calls before_request, the view, and then after_request. Subclasses may override this to provide a custom flow. :class:`ModelView` does this to insert a model loading phase. :param view: View method wrapped in ...
[ "def", "dispatch_request", "(", "self", ",", "view", ",", "view_args", ")", ":", "# Call the :meth:`before_request` method", "resp", "=", "self", ".", "before_request", "(", ")", "if", "resp", ":", "return", "self", ".", "after_request", "(", "make_response", "(...
View dispatcher that calls before_request, the view, and then after_request. Subclasses may override this to provide a custom flow. :class:`ModelView` does this to insert a model loading phase. :param view: View method wrapped in specified decorators. The dispatcher must call this ...
[ "View", "dispatcher", "that", "calls", "before_request", "the", "view", "and", "then", "after_request", ".", "Subclasses", "may", "override", "this", "to", "provide", "a", "custom", "flow", ".", ":", "class", ":", "ModelView", "does", "this", "to", "insert", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L342-L357
hasgeek/coaster
coaster/views/classview.py
ClassView.is_available
def is_available(self): """ Returns `True` if *any* view handler in the class is currently available via its `is_available` method. """ if self.is_always_available: return True for viewname in self.__views__: if getattr(self, viewname).is_available...
python
def is_available(self): """ Returns `True` if *any* view handler in the class is currently available via its `is_available` method. """ if self.is_always_available: return True for viewname in self.__views__: if getattr(self, viewname).is_available...
[ "def", "is_available", "(", "self", ")", ":", "if", "self", ".", "is_always_available", ":", "return", "True", "for", "viewname", "in", "self", ".", "__views__", ":", "if", "getattr", "(", "self", ",", "viewname", ")", ".", "is_available", "(", ")", ":",...
Returns `True` if *any* view handler in the class is currently available via its `is_available` method.
[ "Returns", "True", "if", "*", "any", "*", "view", "handler", "in", "the", "class", "is", "currently", "available", "via", "its", "is_available", "method", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L387-L397
hasgeek/coaster
coaster/views/classview.py
ClassView.add_route_for
def add_route_for(cls, _name, rule, **options): """ Add a route for an existing method or view. Useful for modifying routes that a subclass inherits from a base class:: class BaseView(ClassView): def latent_view(self): return 'latent-view' ...
python
def add_route_for(cls, _name, rule, **options): """ Add a route for an existing method or view. Useful for modifying routes that a subclass inherits from a base class:: class BaseView(ClassView): def latent_view(self): return 'latent-view' ...
[ "def", "add_route_for", "(", "cls", ",", "_name", ",", "rule", ",", "*", "*", "options", ")", ":", "setattr", "(", "cls", ",", "_name", ",", "route", "(", "rule", ",", "*", "*", "options", ")", "(", "cls", ".", "__get_raw_attr", "(", "_name", ")", ...
Add a route for an existing method or view. Useful for modifying routes that a subclass inherits from a base class:: class BaseView(ClassView): def latent_view(self): return 'latent-view' @route('other') def other_view(self): ...
[ "Add", "a", "route", "for", "an", "existing", "method", "or", "view", ".", "Useful", "for", "modifying", "routes", "that", "a", "subclass", "inherits", "from", "a", "base", "class", "::" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L407-L437
hasgeek/coaster
coaster/views/classview.py
ClassView.init_app
def init_app(cls, app, callback=None): """ Register views on an app. If :attr:`callback` is specified, it will be called after ``app.``:meth:`~flask.Flask.add_url_rule`, with the same parameters. """ processed = set() cls.__views__ = set() cls.is_always_av...
python
def init_app(cls, app, callback=None): """ Register views on an app. If :attr:`callback` is specified, it will be called after ``app.``:meth:`~flask.Flask.add_url_rule`, with the same parameters. """ processed = set() cls.__views__ = set() cls.is_always_av...
[ "def", "init_app", "(", "cls", ",", "app", ",", "callback", "=", "None", ")", ":", "processed", "=", "set", "(", ")", "cls", ".", "__views__", "=", "set", "(", ")", "cls", ".", "is_always_available", "=", "False", "for", "base", "in", "cls", ".", "...
Register views on an app. If :attr:`callback` is specified, it will be called after ``app.``:meth:`~flask.Flask.add_url_rule`, with the same parameters.
[ "Register", "views", "on", "an", "app", ".", "If", ":", "attr", ":", "callback", "is", "specified", "it", "will", "be", "called", "after", "app", ".", ":", "meth", ":", "~flask", ".", "Flask", ".", "add_url_rule", "with", "the", "same", "parameters", "...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L440-L464
hasgeek/coaster
coaster/views/classview.py
ModelView.dispatch_request
def dispatch_request(self, view, view_args): """ View dispatcher that calls :meth:`before_request`, :meth:`loader`, :meth:`after_loader`, the view, and then :meth:`after_request`. :param view: View method wrapped in specified decorators. :param dict view_args: View arguments, to...
python
def dispatch_request(self, view, view_args): """ View dispatcher that calls :meth:`before_request`, :meth:`loader`, :meth:`after_loader`, the view, and then :meth:`after_request`. :param view: View method wrapped in specified decorators. :param dict view_args: View arguments, to...
[ "def", "dispatch_request", "(", "self", ",", "view", ",", "view_args", ")", ":", "# Call the :meth:`before_request` method", "resp", "=", "self", ".", "before_request", "(", ")", "if", "resp", ":", "return", "self", ".", "after_request", "(", "make_response", "(...
View dispatcher that calls :meth:`before_request`, :meth:`loader`, :meth:`after_loader`, the view, and then :meth:`after_request`. :param view: View method wrapped in specified decorators. :param dict view_args: View arguments, to be passed on to the view method
[ "View", "dispatcher", "that", "calls", ":", "meth", ":", "before_request", ":", "meth", ":", "loader", ":", "meth", ":", "after_loader", "the", "view", "and", "then", ":", "meth", ":", "after_request", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L518-L537
hasgeek/coaster
coaster/sqlalchemy/roles.py
with_roles
def with_roles(obj=None, rw=None, call=None, read=None, write=None): """ Convenience function and decorator to define roles on an attribute. Only works with :class:`RoleMixin`, which reads the annotations made by this function and populates :attr:`~RoleMixin.__roles__`. Examples:: id = db....
python
def with_roles(obj=None, rw=None, call=None, read=None, write=None): """ Convenience function and decorator to define roles on an attribute. Only works with :class:`RoleMixin`, which reads the annotations made by this function and populates :attr:`~RoleMixin.__roles__`. Examples:: id = db....
[ "def", "with_roles", "(", "obj", "=", "None", ",", "rw", "=", "None", ",", "call", "=", "None", ",", "read", "=", "None", ",", "write", "=", "None", ")", ":", "# Convert lists and None values to sets", "rw", "=", "set", "(", "rw", ")", "if", "rw", "e...
Convenience function and decorator to define roles on an attribute. Only works with :class:`RoleMixin`, which reads the annotations made by this function and populates :attr:`~RoleMixin.__roles__`. Examples:: id = db.Column(Integer, primary_key=True) with_roles(id, read={'all'}) @...
[ "Convenience", "function", "and", "decorator", "to", "define", "roles", "on", "an", "attribute", ".", "Only", "works", "with", ":", "class", ":", "RoleMixin", "which", "reads", "the", "annotations", "made", "by", "this", "function", "and", "populates", ":", ...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L210-L277
hasgeek/coaster
coaster/sqlalchemy/roles.py
declared_attr_roles
def declared_attr_roles(rw=None, call=None, read=None, write=None): """ Equivalent of :func:`with_roles` for use with ``@declared_attr``:: @declared_attr @declared_attr_roles(read={'all'}) def my_column(cls): return Column(Integer) While :func:`with_roles` is always the...
python
def declared_attr_roles(rw=None, call=None, read=None, write=None): """ Equivalent of :func:`with_roles` for use with ``@declared_attr``:: @declared_attr @declared_attr_roles(read={'all'}) def my_column(cls): return Column(Integer) While :func:`with_roles` is always the...
[ "def", "declared_attr_roles", "(", "rw", "=", "None", ",", "call", "=", "None", ",", "read", "=", "None", ",", "write", "=", "None", ")", ":", "def", "inner", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "attr", "(", "cls", ")", ":",...
Equivalent of :func:`with_roles` for use with ``@declared_attr``:: @declared_attr @declared_attr_roles(read={'all'}) def my_column(cls): return Column(Integer) While :func:`with_roles` is always the outermost decorator on properties and functions, :func:`declared_attr_roles...
[ "Equivalent", "of", ":", "func", ":", "with_roles", "for", "use", "with", "@declared_attr", "::" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L285-L312
hasgeek/coaster
coaster/sqlalchemy/roles.py
__configure_roles
def __configure_roles(mapper, cls): """ Run through attributes of the class looking for role decorations from :func:`with_roles` and add them to :attr:`cls.__roles__` """ # Don't mutate ``__roles__`` in the base class. # The subclass must have its own. # Since classes may specify ``__roles__...
python
def __configure_roles(mapper, cls): """ Run through attributes of the class looking for role decorations from :func:`with_roles` and add them to :attr:`cls.__roles__` """ # Don't mutate ``__roles__`` in the base class. # The subclass must have its own. # Since classes may specify ``__roles__...
[ "def", "__configure_roles", "(", "mapper", ",", "cls", ")", ":", "# Don't mutate ``__roles__`` in the base class.", "# The subclass must have its own.", "# Since classes may specify ``__roles__`` directly without", "# using :func:`with_roles`, we must preserve existing content.", "if", "'_...
Run through attributes of the class looking for role decorations from :func:`with_roles` and add them to :attr:`cls.__roles__`
[ "Run", "through", "attributes", "of", "the", "class", "looking", "for", "role", "decorations", "from", ":", "func", ":", "with_roles", "and", "add", "them", "to", ":", "attr", ":", "cls", ".", "__roles__" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L414-L456
hasgeek/coaster
coaster/sqlalchemy/roles.py
RoleMixin.current_roles
def current_roles(self): """ :class:`~coaster.utils.classes.InspectableSet` containing currently available roles on this object, using :obj:`~coaster.auth.current_auth`. Use in the view layer to inspect for a role being present: if obj.current_roles.editor: ...
python
def current_roles(self): """ :class:`~coaster.utils.classes.InspectableSet` containing currently available roles on this object, using :obj:`~coaster.auth.current_auth`. Use in the view layer to inspect for a role being present: if obj.current_roles.editor: ...
[ "def", "current_roles", "(", "self", ")", ":", "return", "InspectableSet", "(", "self", ".", "roles_for", "(", "actor", "=", "current_auth", ".", "actor", ",", "anchors", "=", "current_auth", ".", "anchors", ")", ")" ]
:class:`~coaster.utils.classes.InspectableSet` containing currently available roles on this object, using :obj:`~coaster.auth.current_auth`. Use in the view layer to inspect for a role being present: if obj.current_roles.editor: pass {% if obj.current_ro...
[ ":", "class", ":", "~coaster", ".", "utils", ".", "classes", ".", "InspectableSet", "containing", "currently", "available", "roles", "on", "this", "object", "using", ":", "obj", ":", "~coaster", ".", "auth", ".", "current_auth", ".", "Use", "in", "the", "v...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L363-L377
hasgeek/coaster
coaster/sqlalchemy/roles.py
RoleMixin.access_for
def access_for(self, roles=None, actor=None, anchors=[]): """ Return a proxy object that limits read and write access to attributes based on the actor's roles. If the ``roles`` parameter isn't provided, :meth:`roles_for` is called with the other parameters:: # This typical c...
python
def access_for(self, roles=None, actor=None, anchors=[]): """ Return a proxy object that limits read and write access to attributes based on the actor's roles. If the ``roles`` parameter isn't provided, :meth:`roles_for` is called with the other parameters:: # This typical c...
[ "def", "access_for", "(", "self", ",", "roles", "=", "None", ",", "actor", "=", "None", ",", "anchors", "=", "[", "]", ")", ":", "if", "roles", "is", "None", ":", "roles", "=", "self", ".", "roles_for", "(", "actor", "=", "actor", ",", "anchors", ...
Return a proxy object that limits read and write access to attributes based on the actor's roles. If the ``roles`` parameter isn't provided, :meth:`roles_for` is called with the other parameters:: # This typical call: obj.access_for(actor=current_auth.actor) # Is sho...
[ "Return", "a", "proxy", "object", "that", "limits", "read", "and", "write", "access", "to", "attributes", "based", "on", "the", "actor", "s", "roles", ".", "If", "the", "roles", "parameter", "isn", "t", "provided", ":", "meth", ":", "roles_for", "is", "c...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L388-L403
hasgeek/coaster
coaster/sqlalchemy/roles.py
RoleMixin.current_access
def current_access(self): """ Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user. """ return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)
python
def current_access(self): """ Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user. """ return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)
[ "def", "current_access", "(", "self", ")", ":", "return", "self", ".", "access_for", "(", "actor", "=", "current_auth", ".", "actor", ",", "anchors", "=", "current_auth", ".", "anchors", ")" ]
Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user.
[ "Wraps", ":", "meth", ":", "access_for", "with", ":", "obj", ":", "~coaster", ".", "auth", ".", "current_auth", "to", "return", "a", "proxy", "for", "the", "currently", "authenticated", "user", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L405-L410
hasgeek/coaster
coaster/views/misc.py
get_current_url
def get_current_url(): """ Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':...
python
def get_current_url(): """ Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':...
[ "def", "get_current_url", "(", ")", ":", "if", "current_app", ".", "config", ".", "get", "(", "'SERVER_NAME'", ")", "and", "(", "# Check current hostname against server name, ignoring port numbers, if any (split on ':')", "request", ".", "environ", "[", "'HTTP_HOST'", "]"...
Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path
[ "Return", "the", "current", "URL", "including", "the", "query", "string", "as", "a", "relative", "path", ".", "If", "the", "app", "uses", "subdomains", "return", "an", "absolute", "path" ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L43-L58
hasgeek/coaster
coaster/views/misc.py
get_next_url
def get_next_url(referrer=False, external=False, session=False, default=__marker): """ Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This functio...
python
def get_next_url(referrer=False, external=False, session=False, default=__marker): """ Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This functio...
[ "def", "get_next_url", "(", "referrer", "=", "False", ",", "external", "=", "False", ",", "session", "=", "False", ",", "default", "=", "__marker", ")", ":", "if", "session", ":", "next_url", "=", "request_session", ".", "pop", "(", "'next'", ",", "None"...
Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This function looks for a ``next`` parameter in the request or in the session (depending on whether par...
[ "Get", "the", "next", "URL", "to", "redirect", "to", ".", "Don", "t", "return", "external", "URLs", "unless", "explicitly", "asked", "for", ".", "This", "is", "to", "protect", "the", "site", "from", "being", "an", "unwitting", "redirector", "to", "external...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L64-L96
hasgeek/coaster
coaster/views/misc.py
jsonp
def jsonp(*args, **kw): """ Returns a JSON response with a callback wrapper, if asked for. Consider using CORS instead, as JSONP makes the client app insecure. See the :func:`~coaster.views.decorators.cors` decorator. """ data = json.dumps(dict(*args, **kw), indent=2) callback = request.args...
python
def jsonp(*args, **kw): """ Returns a JSON response with a callback wrapper, if asked for. Consider using CORS instead, as JSONP makes the client app insecure. See the :func:`~coaster.views.decorators.cors` decorator. """ data = json.dumps(dict(*args, **kw), indent=2) callback = request.args...
[ "def", "jsonp", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "data", "=", "json", ".", "dumps", "(", "dict", "(", "*", "args", ",", "*", "*", "kw", ")", ",", "indent", "=", "2", ")", "callback", "=", "request", ".", "args", ".", "get", ...
Returns a JSON response with a callback wrapper, if asked for. Consider using CORS instead, as JSONP makes the client app insecure. See the :func:`~coaster.views.decorators.cors` decorator.
[ "Returns", "a", "JSON", "response", "with", "a", "callback", "wrapper", "if", "asked", "for", ".", "Consider", "using", "CORS", "instead", "as", "JSONP", "makes", "the", "client", "app", "insecure", ".", "See", "the", ":", "func", ":", "~coaster", ".", "...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L99-L112
hasgeek/coaster
coaster/views/misc.py
endpoint_for
def endpoint_for(url, method=None, return_rule=False, follow_redirects=True): """ Given an absolute URL, retrieve the matching endpoint name (or rule) and view arguments. Requires a current request context to determine runtime environment. :param str method: HTTP method to use (defaults to GET) ...
python
def endpoint_for(url, method=None, return_rule=False, follow_redirects=True): """ Given an absolute URL, retrieve the matching endpoint name (or rule) and view arguments. Requires a current request context to determine runtime environment. :param str method: HTTP method to use (defaults to GET) ...
[ "def", "endpoint_for", "(", "url", ",", "method", "=", "None", ",", "return_rule", "=", "False", ",", "follow_redirects", "=", "True", ")", ":", "parsed_url", "=", "urlsplit", "(", "url", ")", "if", "not", "parsed_url", ".", "netloc", ":", "# We require an...
Given an absolute URL, retrieve the matching endpoint name (or rule) and view arguments. Requires a current request context to determine runtime environment. :param str method: HTTP method to use (defaults to GET) :param bool return_rule: Return the URL rule instead of the endpoint name :param bool...
[ "Given", "an", "absolute", "URL", "retrieve", "the", "matching", "endpoint", "name", "(", "or", "rule", ")", "and", "view", "arguments", ".", "Requires", "a", "current", "request", "context", "to", "determine", "runtime", "environment", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L115-L172
hasgeek/coaster
coaster/docflow.py
DocumentWorkflow.permissions
def permissions(self): """ Permissions for this workflow. Plays nice with :meth:`coaster.views.load_models` and :class:`coaster.sqlalchemy.PermissionMixin` to determine the available permissions to the current user. """ perms = set(super(DocumentWorkflow, self).pe...
python
def permissions(self): """ Permissions for this workflow. Plays nice with :meth:`coaster.views.load_models` and :class:`coaster.sqlalchemy.PermissionMixin` to determine the available permissions to the current user. """ perms = set(super(DocumentWorkflow, self).pe...
[ "def", "permissions", "(", "self", ")", ":", "perms", "=", "set", "(", "super", "(", "DocumentWorkflow", ",", "self", ")", ".", "permissions", "(", ")", ")", "if", "g", ":", "if", "hasattr", "(", "g", ",", "'permissions'", ")", ":", "perms", ".", "...
Permissions for this workflow. Plays nice with :meth:`coaster.views.load_models` and :class:`coaster.sqlalchemy.PermissionMixin` to determine the available permissions to the current user.
[ "Permissions", "for", "this", "workflow", ".", "Plays", "nice", "with", ":", "meth", ":", "coaster", ".", "views", ".", "load_models", "and", ":", "class", ":", "coaster", ".", "sqlalchemy", ".", "PermissionMixin", "to", "determine", "the", "available", "per...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/docflow.py#L71-L84
hasgeek/coaster
coaster/sqlalchemy/annotations.py
__configure_annotations
def __configure_annotations(mapper, cls): """ Run through attributes of the class looking for annotations from :func:`annotation_wrapper` and add them to :attr:`cls.__annotations__` and :attr:`cls.__annotations_by_attr__` """ annotations = {} annotations_by_attr = {} # An attribute may ...
python
def __configure_annotations(mapper, cls): """ Run through attributes of the class looking for annotations from :func:`annotation_wrapper` and add them to :attr:`cls.__annotations__` and :attr:`cls.__annotations_by_attr__` """ annotations = {} annotations_by_attr = {} # An attribute may ...
[ "def", "__configure_annotations", "(", "mapper", ",", "cls", ")", ":", "annotations", "=", "{", "}", "annotations_by_attr", "=", "{", "}", "# An attribute may be defined more than once in base classes. Only handle the first", "processed", "=", "set", "(", ")", "# Loop thr...
Run through attributes of the class looking for annotations from :func:`annotation_wrapper` and add them to :attr:`cls.__annotations__` and :attr:`cls.__annotations_by_attr__`
[ "Run", "through", "attributes", "of", "the", "class", "looking", "for", "annotations", "from", ":", "func", ":", "annotation_wrapper", "and", "add", "them", "to", ":", "attr", ":", "cls", ".", "__annotations__", "and", ":", "attr", ":", "cls", ".", "__anno...
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/annotations.py#L62-L103
hasgeek/coaster
coaster/sqlalchemy/annotations.py
annotation_wrapper
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the obj...
python
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the obj...
[ "def", "annotation_wrapper", "(", "annotation", ",", "doc", "=", "None", ")", ":", "def", "decorator", "(", "attr", ")", ":", "__cache__", ".", "setdefault", "(", "attr", ",", "[", "]", ")", ".", "append", "(", "annotation", ")", "# Also mark the annotatio...
Defines an annotation, which can be applied to attributes in a database model.
[ "Defines", "an", "annotation", "which", "can", "be", "applied", "to", "attributes", "in", "a", "database", "model", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/annotations.py#L114-L135
hasgeek/coaster
coaster/auth.py
add_auth_attribute
def add_auth_attribute(attr, value, actor=False): """ Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute i...
python
def add_auth_attribute(attr, value, actor=False): """ Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute i...
[ "def", "add_auth_attribute", "(", "attr", ",", "value", ",", "actor", "=", "False", ")", ":", "if", "attr", "in", "(", "'actor'", ",", "'anchors'", ",", "'is_anonymous'", ",", "'not_anonymous'", ",", "'is_authenticated'", ",", "'not_authenticated'", ")", ":", ...
Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute is an actor (user or client app accessing own data) ...
[ "Helper", "function", "for", "login", "managers", ".", "Adds", "authorization", "attributes", "to", ":", "obj", ":", "current_auth", "for", "the", "duration", "of", "the", "request", "." ]
train
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/auth.py#L29-L66
dnephin/PyStaticConfiguration
staticconf/schema.py
SchemaMeta.build_attributes
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): ...
python
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): ...
[ "def", "build_attributes", "(", "cls", ",", "attributes", ",", "namespace", ")", ":", "config_path", "=", "attributes", ".", "get", "(", "'config_path'", ")", "tokens", "=", "{", "}", "def", "build_config_key", "(", "value_def", ",", "config_key", ")", ":", ...
Return an attributes dictionary with ValueTokens replaced by a property which returns the config value.
[ "Return", "an", "attributes", "dictionary", "with", "ValueTokens", "replaced", "by", "a", "property", "which", "returns", "the", "config", "value", "." ]
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/schema.py#L166-L193
dnephin/PyStaticConfiguration
staticconf/proxy.py
cache_as_field
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: ...
python
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: ...
[ "def", "cache_as_field", "(", "cache_name", ")", ":", "def", "cache_wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "inner_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", ...
Cache a functions return value as the field 'cache_name'.
[ "Cache", "a", "functions", "return", "value", "as", "the", "field", "cache_name", "." ]
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L74-L87
dnephin/PyStaticConfiguration
staticconf/proxy.py
extract_value
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is mi...
python
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is mi...
[ "def", "extract_value", "(", "proxy", ")", ":", "value", "=", "proxy", ".", "namespace", ".", "get", "(", "proxy", ".", "config_key", ",", "proxy", ".", "default", ")", "if", "value", "is", "UndefToken", ":", "raise", "errors", ".", "ConfigurationError", ...
Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate.
[ "Given", "a", "value", "proxy", "type", "Retrieve", "a", "value", "from", "a", "namespace", "raising", "exception", "if", "no", "value", "is", "found", "or", "the", "value", "does", "not", "validate", "." ]
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L90-L103
dnephin/PyStaticConfiguration
staticconf/readers.py
build_reader
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to ...
python
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to ...
[ "def", "build_reader", "(", "validator", ",", "reader_namespace", "=", "config", ".", "DEFAULT", ")", ":", "def", "reader", "(", "config_key", ",", "default", "=", "UndefToken", ",", "namespace", "=", "None", ")", ":", "config_namespace", "=", "config", ".",...
A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to the appropriate type. :param reader_namespace: the d...
[ "A", "factory", "method", "for", "creating", "a", "custom", "config", "reader", "from", "a", "validation", "function", "." ]
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/readers.py#L103-L116