repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
abilian/abilian-core
abilian/web/views/object.py
ObjectView.prepare_args
def prepare_args(self, args, kwargs): """ :attr:`form` is initialized here. See also :meth:`View.prepare_args`. """ args, kwargs = super().prepare_args(args, kwargs) form_kwargs = self.get_form_kwargs() self.form = self.Form(**form_kwargs) return args, kwargs
python
def prepare_args(self, args, kwargs): """ :attr:`form` is initialized here. See also :meth:`View.prepare_args`. """ args, kwargs = super().prepare_args(args, kwargs) form_kwargs = self.get_form_kwargs() self.form = self.Form(**form_kwargs) return args, kwargs
[ "def", "prepare_args", "(", "self", ",", "args", ",", "kwargs", ")", ":", "args", ",", "kwargs", "=", "super", "(", ")", ".", "prepare_args", "(", "args", ",", "kwargs", ")", "form_kwargs", "=", "self", ".", "get_form_kwargs", "(", ")", "self", ".", ...
:attr:`form` is initialized here. See also :meth:`View.prepare_args`.
[ ":", "attr", ":", "form", "is", "initialized", "here", ".", "See", "also", ":", "meth", ":", "View", ".", "prepare_args", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/object.py#L133-L140
abilian/abilian-core
abilian/web/views/object.py
ObjectEdit.form_valid
def form_valid(self, redirect_to=None): """Save object. Called when form is validated. :param redirect_to: real url (created with url_for) to redirect to, instead of the view by default. """ session = db.session() with session.no_autoflush: self.b...
python
def form_valid(self, redirect_to=None): """Save object. Called when form is validated. :param redirect_to: real url (created with url_for) to redirect to, instead of the view by default. """ session = db.session() with session.no_autoflush: self.b...
[ "def", "form_valid", "(", "self", ",", "redirect_to", "=", "None", ")", ":", "session", "=", "db", ".", "session", "(", ")", "with", "session", ".", "no_autoflush", ":", "self", ".", "before_populate_obj", "(", ")", "self", ".", "form", ".", "populate_ob...
Save object. Called when form is validated. :param redirect_to: real url (created with url_for) to redirect to, instead of the view by default.
[ "Save", "object", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/object.py#L345-L390
abilian/abilian-core
abilian/web/views/object.py
JSONModelSearch.get_item
def get_item(self, obj): """Return a result item. :param obj: Instance object :returns: a dictionnary with at least `id` and `text` values """ return {"id": obj.id, "text": self.get_label(obj), "name": obj.name}
python
def get_item(self, obj): """Return a result item. :param obj: Instance object :returns: a dictionnary with at least `id` and `text` values """ return {"id": obj.id, "text": self.get_label(obj), "name": obj.name}
[ "def", "get_item", "(", "self", ",", "obj", ")", ":", "return", "{", "\"id\"", ":", "obj", ".", "id", ",", "\"text\"", ":", "self", ".", "get_label", "(", "obj", ")", ",", "\"name\"", ":", "obj", ".", "name", "}" ]
Return a result item. :param obj: Instance object :returns: a dictionnary with at least `id` and `text` values
[ "Return", "a", "result", "item", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/object.py#L625-L631
noirbizarre/bumpr
setup.py
pip
def pip(name): '''Parse requirements file''' with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f: return f.readlines()
python
def pip(name): '''Parse requirements file''' with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f: return f.readlines()
[ "def", "pip", "(", "name", ")", ":", "with", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "'requirements'", ",", "'{0}.pip'", ".", "format", "(", "name", ")", ")", ")", "as", "f", ":", "return", "f", ".", "readlines", "(", ")" ]
Parse requirements file
[ "Parse", "requirements", "file" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/setup.py#L19-L22
abilian/abilian-core
abilian/services/conversion/handlers.py
PdfToPpmHandler.convert
def convert(self, blob, size=500): """Size is the maximum horizontal size.""" file_list = [] with make_temp_file(blob) as in_fn, make_temp_file() as out_fn: try: subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn]) file_list = sorted(glob.glob(f...
python
def convert(self, blob, size=500): """Size is the maximum horizontal size.""" file_list = [] with make_temp_file(blob) as in_fn, make_temp_file() as out_fn: try: subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn]) file_list = sorted(glob.glob(f...
[ "def", "convert", "(", "self", ",", "blob", ",", "size", "=", "500", ")", ":", "file_list", "=", "[", "]", "with", "make_temp_file", "(", "blob", ")", "as", "in_fn", ",", "make_temp_file", "(", ")", "as", "out_fn", ":", "try", ":", "subprocess", ".",...
Size is the maximum horizontal size.
[ "Size", "is", "the", "maximum", "horizontal", "size", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/handlers.py#L225-L246
abilian/abilian-core
abilian/services/conversion/handlers.py
UnoconvPdfHandler.convert
def convert(self, blob, **kw): """Convert using unoconv converter.""" timeout = self.run_timeout with make_temp_file(blob) as in_fn, make_temp_file( prefix="tmp-unoconv-", suffix=".pdf" ) as out_fn: args = ["-f", "pdf", "-o", out_fn, in_fn] # Hack for...
python
def convert(self, blob, **kw): """Convert using unoconv converter.""" timeout = self.run_timeout with make_temp_file(blob) as in_fn, make_temp_file( prefix="tmp-unoconv-", suffix=".pdf" ) as out_fn: args = ["-f", "pdf", "-o", out_fn, in_fn] # Hack for...
[ "def", "convert", "(", "self", ",", "blob", ",", "*", "*", "kw", ")", ":", "timeout", "=", "self", ".", "run_timeout", "with", "make_temp_file", "(", "blob", ")", "as", "in_fn", ",", "make_temp_file", "(", "prefix", "=", "\"tmp-unoconv-\"", ",", "suffix"...
Convert using unoconv converter.
[ "Convert", "using", "unoconv", "converter", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/handlers.py#L314-L361
abilian/abilian-core
abilian/services/conversion/handlers.py
LibreOfficePdfHandler.convert
def convert(self, blob, **kw): """Convert using soffice converter.""" timeout = self.run_timeout with make_temp_file(blob) as in_fn: cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn] # # TODO: fix this if needed, or remove if not needed # if o...
python
def convert(self, blob, **kw): """Convert using soffice converter.""" timeout = self.run_timeout with make_temp_file(blob) as in_fn: cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn] # # TODO: fix this if needed, or remove if not needed # if o...
[ "def", "convert", "(", "self", ",", "blob", ",", "*", "*", "kw", ")", ":", "timeout", "=", "self", ".", "run_timeout", "with", "make_temp_file", "(", "blob", ")", "as", "in_fn", ":", "cmd", "=", "[", "self", ".", "soffice", ",", "\"--headless\"", ","...
Convert using soffice converter.
[ "Convert", "using", "soffice", "converter", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/handlers.py#L416-L462
abilian/abilian-core
abilian/web/filters.py
autoescape
def autoescape(filter_func): """Decorator to autoescape result from filters.""" @evalcontextfilter @wraps(filter_func) def _autoescape(eval_ctx, *args, **kwargs): result = filter_func(*args, **kwargs) if eval_ctx.autoescape: result = Markup(result) return result ...
python
def autoescape(filter_func): """Decorator to autoescape result from filters.""" @evalcontextfilter @wraps(filter_func) def _autoescape(eval_ctx, *args, **kwargs): result = filter_func(*args, **kwargs) if eval_ctx.autoescape: result = Markup(result) return result ...
[ "def", "autoescape", "(", "filter_func", ")", ":", "@", "evalcontextfilter", "@", "wraps", "(", "filter_func", ")", "def", "_autoescape", "(", "eval_ctx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "filter_func", "(", "*", "args"...
Decorator to autoescape result from filters.
[ "Decorator", "to", "autoescape", "result", "from", "filters", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L22-L33
abilian/abilian-core
abilian/web/filters.py
paragraphs
def paragraphs(value): """Blank lines delimitates paragraphs.""" result = "\n\n".join( "<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n"))) for p in _PARAGRAPH_RE.split(escape(value)) ) return result
python
def paragraphs(value): """Blank lines delimitates paragraphs.""" result = "\n\n".join( "<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n"))) for p in _PARAGRAPH_RE.split(escape(value)) ) return result
[ "def", "paragraphs", "(", "value", ")", ":", "result", "=", "\"\\n\\n\"", ".", "join", "(", "\"<p>{}</p>\"", ".", "format", "(", "p", ".", "strip", "(", ")", ".", "replace", "(", "\"\\n\"", ",", "Markup", "(", "\"<br />\\n\"", ")", ")", ")", "for", "...
Blank lines delimitates paragraphs.
[ "Blank", "lines", "delimitates", "paragraphs", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L47-L53
abilian/abilian-core
abilian/web/filters.py
roughsize
def roughsize(size, above=20, mod=10): """6 -> '6' 15 -> '15' 134 -> '130+'.""" if size < above: return str(size) return "{:d}+".format(size - size % mod)
python
def roughsize(size, above=20, mod=10): """6 -> '6' 15 -> '15' 134 -> '130+'.""" if size < above: return str(size) return "{:d}+".format(size - size % mod)
[ "def", "roughsize", "(", "size", ",", "above", "=", "20", ",", "mod", "=", "10", ")", ":", "if", "size", "<", "above", ":", "return", "str", "(", "size", ")", "return", "\"{:d}+\"", ".", "format", "(", "size", "-", "size", "%", "mod", ")" ]
6 -> '6' 15 -> '15' 134 -> '130+'.
[ "6", "-", ">", "6", "15", "-", ">", "15", "134", "-", ">", "130", "+", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L86-L91
abilian/abilian-core
abilian/web/filters.py
datetimeparse
def datetimeparse(s): """Parse a string date time to a datetime object. Suitable for dates serialized with .isoformat() :return: None, or an aware datetime instance, tz=UTC. """ try: dt = dateutil.parser.parse(s) except ValueError: return None return utc_dt(dt)
python
def datetimeparse(s): """Parse a string date time to a datetime object. Suitable for dates serialized with .isoformat() :return: None, or an aware datetime instance, tz=UTC. """ try: dt = dateutil.parser.parse(s) except ValueError: return None return utc_dt(dt)
[ "def", "datetimeparse", "(", "s", ")", ":", "try", ":", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "s", ")", "except", "ValueError", ":", "return", "None", "return", "utc_dt", "(", "dt", ")" ]
Parse a string date time to a datetime object. Suitable for dates serialized with .isoformat() :return: None, or an aware datetime instance, tz=UTC.
[ "Parse", "a", "string", "date", "time", "to", "a", "datetime", "object", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L94-L106
abilian/abilian-core
abilian/web/filters.py
age
def age(dt, now=None, add_direction=True, date_threshold=None): """ :param dt: :class:`datetime<datetime.datetime>` instance to format :param now: :class:`datetime<datetime.datetime>` instance to compare to `dt` :param add_direction: if `True`, will add "in" or "ago" (example for `en` locale) t...
python
def age(dt, now=None, add_direction=True, date_threshold=None): """ :param dt: :class:`datetime<datetime.datetime>` instance to format :param now: :class:`datetime<datetime.datetime>` instance to compare to `dt` :param add_direction: if `True`, will add "in" or "ago" (example for `en` locale) t...
[ "def", "age", "(", "dt", ",", "now", "=", "None", ",", "add_direction", "=", "True", ",", "date_threshold", "=", "None", ")", ":", "# Fail silently for now XXX", "if", "not", "dt", ":", "return", "\"\"", "if", "not", "now", ":", "now", "=", "datetime", ...
:param dt: :class:`datetime<datetime.datetime>` instance to format :param now: :class:`datetime<datetime.datetime>` instance to compare to `dt` :param add_direction: if `True`, will add "in" or "ago" (example for `en` locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago" :param da...
[ ":", "param", "dt", ":", ":", "class", ":", "datetime<datetime", ".", "datetime", ">", "instance", "to", "format" ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L109-L160
abilian/abilian-core
abilian/web/filters.py
babel2datepicker
def babel2datepicker(pattern): """Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by bootstrap-datepicker.""" if not isinstance(pattern, DateTimePattern): pattern = parse_pattern(pattern) map_fmt = { # days "d": "dd", ...
python
def babel2datepicker(pattern): """Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by bootstrap-datepicker.""" if not isinstance(pattern, DateTimePattern): pattern = parse_pattern(pattern) map_fmt = { # days "d": "dd", ...
[ "def", "babel2datepicker", "(", "pattern", ")", ":", "if", "not", "isinstance", "(", "pattern", ",", "DateTimePattern", ")", ":", "pattern", "=", "parse_pattern", "(", "pattern", ")", "map_fmt", "=", "{", "# days", "\"d\"", ":", "\"dd\"", ",", "\"dd\"", ":...
Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by bootstrap-datepicker.
[ "Convert", "date", "format", "from", "babel", "(", "http", ":", "//", "babel", ".", "pocoo", ".", "org", "/", "docs", "/", "dates", "/", "#date", "-", "fields", "))", "to", "a", "format", "understood", "by", "bootstrap", "-", "datepicker", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L183-L222
abilian/abilian-core
abilian/services/base.py
Service.start
def start(self, ignore_state=False): """Starts the service.""" self.logger.debug("Start service") self._toggle_running(True, ignore_state)
python
def start(self, ignore_state=False): """Starts the service.""" self.logger.debug("Start service") self._toggle_running(True, ignore_state)
[ "def", "start", "(", "self", ",", "ignore_state", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Start service\"", ")", "self", ".", "_toggle_running", "(", "True", ",", "ignore_state", ")" ]
Starts the service.
[ "Starts", "the", "service", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L51-L54
abilian/abilian-core
abilian/services/base.py
Service.stop
def stop(self, ignore_state=False): """Stops the service.""" self.logger.debug("Stop service") self._toggle_running(False, ignore_state)
python
def stop(self, ignore_state=False): """Stops the service.""" self.logger.debug("Stop service") self._toggle_running(False, ignore_state)
[ "def", "stop", "(", "self", ",", "ignore_state", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Stop service\"", ")", "self", ".", "_toggle_running", "(", "False", ",", "ignore_state", ")" ]
Stops the service.
[ "Stops", "the", "service", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L56-L59
abilian/abilian-core
abilian/services/base.py
Service.app_state
def app_state(self): """Current service state in current application. :raise:RuntimeError if working outside application context. """ try: return current_app.extensions[self.name] except KeyError: raise ServiceNotRegistered(self.name)
python
def app_state(self): """Current service state in current application. :raise:RuntimeError if working outside application context. """ try: return current_app.extensions[self.name] except KeyError: raise ServiceNotRegistered(self.name)
[ "def", "app_state", "(", "self", ")", ":", "try", ":", "return", "current_app", ".", "extensions", "[", "self", ".", "name", "]", "except", "KeyError", ":", "raise", "ServiceNotRegistered", "(", "self", ".", "name", ")" ]
Current service state in current application. :raise:RuntimeError if working outside application context.
[ "Current", "service", "state", "in", "current", "application", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L69-L77
abilian/abilian-core
abilian/services/base.py
Service.if_running
def if_running(meth): """Decorator for service methods that must be ran only if service is in running state.""" @wraps(meth) def check_running(self, *args, **kwargs): if not self.running: return return meth(self, *args, **kwargs) return c...
python
def if_running(meth): """Decorator for service methods that must be ran only if service is in running state.""" @wraps(meth) def check_running(self, *args, **kwargs): if not self.running: return return meth(self, *args, **kwargs) return c...
[ "def", "if_running", "(", "meth", ")", ":", "@", "wraps", "(", "meth", ")", "def", "check_running", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "running", ":", "return", "return", "meth", "(", "self",...
Decorator for service methods that must be ran only if service is in running state.
[ "Decorator", "for", "service", "methods", "that", "must", "be", "ran", "only", "if", "service", "is", "in", "running", "state", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L94-L104
noirbizarre/bumpr
bumpr/releaser.py
Releaser.clean
def clean(self): '''Clean the workspace''' if self.config.clean: logger.info('Cleaning') self.execute(self.config.clean)
python
def clean(self): '''Clean the workspace''' if self.config.clean: logger.info('Cleaning') self.execute(self.config.clean)
[ "def", "clean", "(", "self", ")", ":", "if", "self", ".", "config", ".", "clean", ":", "logger", ".", "info", "(", "'Cleaning'", ")", "self", ".", "execute", "(", "self", ".", "config", ".", "clean", ")" ]
Clean the workspace
[ "Clean", "the", "workspace" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/releaser.py#L145-L149
noirbizarre/bumpr
bumpr/releaser.py
Releaser.publish
def publish(self): '''Publish the current release to PyPI''' if self.config.publish: logger.info('Publish') self.execute(self.config.publish)
python
def publish(self): '''Publish the current release to PyPI''' if self.config.publish: logger.info('Publish') self.execute(self.config.publish)
[ "def", "publish", "(", "self", ")", ":", "if", "self", ".", "config", ".", "publish", ":", "logger", ".", "info", "(", "'Publish'", ")", "self", ".", "execute", "(", "self", ".", "config", ".", "publish", ")" ]
Publish the current release to PyPI
[ "Publish", "the", "current", "release", "to", "PyPI" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/releaser.py#L174-L178
noirbizarre/bumpr
tasks.py
header
def header(text): '''Display an header''' print(' '.join((blue('>>'), cyan(text)))) sys.stdout.flush()
python
def header(text): '''Display an header''' print(' '.join((blue('>>'), cyan(text)))) sys.stdout.flush()
[ "def", "header", "(", "text", ")", ":", "print", "(", "' '", ".", "join", "(", "(", "blue", "(", "'>>'", ")", ",", "cyan", "(", "text", ")", ")", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Display an header
[ "Display", "an", "header" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L38-L41
noirbizarre/bumpr
tasks.py
info
def info(text, *args, **kwargs): '''Display informations''' text = text.format(*args, **kwargs) print(' '.join((purple('>>>'), text))) sys.stdout.flush()
python
def info(text, *args, **kwargs): '''Display informations''' text = text.format(*args, **kwargs) print(' '.join((purple('>>>'), text))) sys.stdout.flush()
[ "def", "info", "(", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "text", "=", "text", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")", "print", "(", "' '", ".", "join", "(", "(", "purple", "(", "'>>>'", ")", ",",...
Display informations
[ "Display", "informations" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L44-L48
noirbizarre/bumpr
tasks.py
success
def success(text): '''Display a success message''' print(' '.join((green('✔'), white(text)))) sys.stdout.flush()
python
def success(text): '''Display a success message''' print(' '.join((green('✔'), white(text)))) sys.stdout.flush()
[ "def", "success", "(", "text", ")", ":", "print", "(", "' '", ".", "join", "(", "(", "green", "(", "'✔'),", " ", "w", "ite(t", "e", "xt))", ")", ")", "", "", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Display a success message
[ "Display", "a", "success", "message" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L51-L54
noirbizarre/bumpr
tasks.py
error
def error(text): '''Display an error message''' print(red('✘ {0}'.format(text))) sys.stdout.flush()
python
def error(text): '''Display an error message''' print(red('✘ {0}'.format(text))) sys.stdout.flush()
[ "def", "error", "(", "text", ")", ":", "print", "(", "red", "(", "'✘ {0}'.f", "o", "rmat(t", "e", "xt))", ")", "", "", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Display an error message
[ "Display", "an", "error", "message" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L57-L60
noirbizarre/bumpr
tasks.py
clean
def clean(ctx): '''Cleanup all build artifacts''' header(clean.__doc__) with ctx.cd(ROOT): for pattern in CLEAN_PATTERNS: info(pattern) ctx.run('rm -rf {0}'.format(' '.join(CLEAN_PATTERNS)))
python
def clean(ctx): '''Cleanup all build artifacts''' header(clean.__doc__) with ctx.cd(ROOT): for pattern in CLEAN_PATTERNS: info(pattern) ctx.run('rm -rf {0}'.format(' '.join(CLEAN_PATTERNS)))
[ "def", "clean", "(", "ctx", ")", ":", "header", "(", "clean", ".", "__doc__", ")", "with", "ctx", ".", "cd", "(", "ROOT", ")", ":", "for", "pattern", "in", "CLEAN_PATTERNS", ":", "info", "(", "pattern", ")", "ctx", ".", "run", "(", "'rm -rf {0}'", ...
Cleanup all build artifacts
[ "Cleanup", "all", "build", "artifacts" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L70-L76
noirbizarre/bumpr
tasks.py
deps
def deps(ctx): '''Install or update development dependencies''' header(deps.__doc__) with ctx.cd(ROOT): ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True)
python
def deps(ctx): '''Install or update development dependencies''' header(deps.__doc__) with ctx.cd(ROOT): ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True)
[ "def", "deps", "(", "ctx", ")", ":", "header", "(", "deps", ".", "__doc__", ")", "with", "ctx", ".", "cd", "(", "ROOT", ")", ":", "ctx", ".", "run", "(", "'pip install -r requirements/develop.pip -r requirements/doc.pip'", ",", "pty", "=", "True", ")" ]
Install or update development dependencies
[ "Install", "or", "update", "development", "dependencies" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L80-L84
noirbizarre/bumpr
tasks.py
qa
def qa(ctx): '''Run a quality report''' header(qa.__doc__) with ctx.cd(ROOT): info('Python Static Analysis') flake8_results = ctx.run('flake8 bumpr', pty=True, warn=True) if flake8_results.failed: error('There is some lints to fix') else: success('No l...
python
def qa(ctx): '''Run a quality report''' header(qa.__doc__) with ctx.cd(ROOT): info('Python Static Analysis') flake8_results = ctx.run('flake8 bumpr', pty=True, warn=True) if flake8_results.failed: error('There is some lints to fix') else: success('No l...
[ "def", "qa", "(", "ctx", ")", ":", "header", "(", "qa", ".", "__doc__", ")", "with", "ctx", ".", "cd", "(", "ROOT", ")", ":", "info", "(", "'Python Static Analysis'", ")", "flake8_results", "=", "ctx", ".", "run", "(", "'flake8 bumpr'", ",", "pty", "...
Run a quality report
[ "Run", "a", "quality", "report" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L123-L142
noirbizarre/bumpr
tasks.py
doc
def doc(ctx): '''Build the documentation''' header(doc.__doc__) with ctx.cd(os.path.join(ROOT, 'doc')): ctx.run('make html', pty=True) success('Documentation available in doc/_build/html')
python
def doc(ctx): '''Build the documentation''' header(doc.__doc__) with ctx.cd(os.path.join(ROOT, 'doc')): ctx.run('make html', pty=True) success('Documentation available in doc/_build/html')
[ "def", "doc", "(", "ctx", ")", ":", "header", "(", "doc", ".", "__doc__", ")", "with", "ctx", ".", "cd", "(", "os", ".", "path", ".", "join", "(", "ROOT", ",", "'doc'", ")", ")", ":", "ctx", ".", "run", "(", "'make html'", ",", "pty", "=", "T...
Build the documentation
[ "Build", "the", "documentation" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L153-L158
noirbizarre/bumpr
tasks.py
completion
def completion(ctx): '''Generate bash completion script''' header(completion.__doc__) with ctx.cd(ROOT): ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True) success('Completion generated in bumpr-complete.sh')
python
def completion(ctx): '''Generate bash completion script''' header(completion.__doc__) with ctx.cd(ROOT): ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True) success('Completion generated in bumpr-complete.sh')
[ "def", "completion", "(", "ctx", ")", ":", "header", "(", "completion", ".", "__doc__", ")", "with", "ctx", ".", "cd", "(", "ROOT", ")", ":", "ctx", ".", "run", "(", "'_bumpr_COMPLETE=source bumpr > bumpr-complete.sh'", ",", "pty", "=", "True", ")", "succe...
Generate bash completion script
[ "Generate", "bash", "completion", "script" ]
train
https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L162-L167
abilian/abilian-core
abilian/web/frontend.py
BaseEntityView._check_view_permission
def _check_view_permission(self, view): """ :param view: a :class:`ObjectView` class or instance """ security = get_service("security") return security.has_permission(current_user, view.permission, self.obj)
python
def _check_view_permission(self, view): """ :param view: a :class:`ObjectView` class or instance """ security = get_service("security") return security.has_permission(current_user, view.permission, self.obj)
[ "def", "_check_view_permission", "(", "self", ",", "view", ")", ":", "security", "=", "get_service", "(", "\"security\"", ")", "return", "security", ".", "has_permission", "(", "current_user", ",", "view", ".", "permission", ",", "self", ".", "obj", ")" ]
:param view: a :class:`ObjectView` class or instance
[ ":", "param", "view", ":", "a", ":", "class", ":", "ObjectView", "class", "or", "instance" ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/frontend.py#L178-L183
abilian/abilian-core
abilian/core/models/tag.py
register
def register(cls): """Register an :class:`~.Entity` as a taggable class. Can be used as a class decorator: .. code-block:: python @tag.register class MyContent(Entity): .... """ if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abili...
python
def register(cls): """Register an :class:`~.Entity` as a taggable class. Can be used as a class decorator: .. code-block:: python @tag.register class MyContent(Entity): .... """ if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abili...
[ "def", "register", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Entity", ")", ":", "raise", "ValueError", "(", "\"Class must be a subclass of abilian.core.entities.Entity\"", ")", "SupportTagging", ".", "register", "(", "cls", ")", "return", ...
Register an :class:`~.Entity` as a taggable class. Can be used as a class decorator: .. code-block:: python @tag.register class MyContent(Entity): ....
[ "Register", "an", ":", "class", ":", "~", ".", "Entity", "as", "a", "taggable", "class", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/tag.py#L22-L37
abilian/abilian-core
abilian/core/models/tag.py
supports_tagging
def supports_tagging(obj): """ :param obj: a class or instance """ if isinstance(obj, type): return issubclass(obj, SupportTagging) if not isinstance(obj, SupportTagging): return False if obj.id is None: return False return True
python
def supports_tagging(obj): """ :param obj: a class or instance """ if isinstance(obj, type): return issubclass(obj, SupportTagging) if not isinstance(obj, SupportTagging): return False if obj.id is None: return False return True
[ "def", "supports_tagging", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "type", ")", ":", "return", "issubclass", "(", "obj", ",", "SupportTagging", ")", "if", "not", "isinstance", "(", "obj", ",", "SupportTagging", ")", ":", "return", "Fal...
:param obj: a class or instance
[ ":", "param", "obj", ":", "a", "class", "or", "instance" ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/tag.py#L40-L53
abilian/abilian-core
abilian/core/models/attachment.py
register
def register(cls): """Register an :class:`~.Entity` as a attachmentable class. Can be used as a class decorator: .. code-block:: python @attachment.register class MyContent(Entity): .... """ if not issubclass(cls, Entity): raise ValueError("Class must be a subclass o...
python
def register(cls): """Register an :class:`~.Entity` as a attachmentable class. Can be used as a class decorator: .. code-block:: python @attachment.register class MyContent(Entity): .... """ if not issubclass(cls, Entity): raise ValueError("Class must be a subclass o...
[ "def", "register", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Entity", ")", ":", "raise", "ValueError", "(", "\"Class must be a subclass of abilian.core.entities.Entity\"", ")", "SupportAttachment", ".", "register", "(", "cls", ")", "return...
Register an :class:`~.Entity` as a attachmentable class. Can be used as a class decorator: .. code-block:: python @attachment.register class MyContent(Entity): ....
[ "Register", "an", ":", "class", ":", "~", ".", "Entity", "as", "a", "attachmentable", "class", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/attachment.py#L25-L40
abilian/abilian-core
abilian/core/models/attachment.py
supports_attachments
def supports_attachments(obj): """ :param obj: a class or instance :returns: True is obj supports attachments. """ if isinstance(obj, type): return issubclass(obj, SupportAttachment) if not isinstance(obj, SupportAttachment): return False if obj.id is None: return ...
python
def supports_attachments(obj): """ :param obj: a class or instance :returns: True is obj supports attachments. """ if isinstance(obj, type): return issubclass(obj, SupportAttachment) if not isinstance(obj, SupportAttachment): return False if obj.id is None: return ...
[ "def", "supports_attachments", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "type", ")", ":", "return", "issubclass", "(", "obj", ",", "SupportAttachment", ")", "if", "not", "isinstance", "(", "obj", ",", "SupportAttachment", ")", ":", "retur...
:param obj: a class or instance :returns: True is obj supports attachments.
[ ":", "param", "obj", ":", "a", "class", "or", "instance" ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/attachment.py#L43-L58
abilian/abilian-core
abilian/core/models/attachment.py
for_entity
def for_entity(obj, check_support_attachments=False): """Return attachments on an entity.""" if check_support_attachments and not supports_attachments(obj): return [] return getattr(obj, ATTRIBUTE)
python
def for_entity(obj, check_support_attachments=False): """Return attachments on an entity.""" if check_support_attachments and not supports_attachments(obj): return [] return getattr(obj, ATTRIBUTE)
[ "def", "for_entity", "(", "obj", ",", "check_support_attachments", "=", "False", ")", ":", "if", "check_support_attachments", "and", "not", "supports_attachments", "(", "obj", ")", ":", "return", "[", "]", "return", "getattr", "(", "obj", ",", "ATTRIBUTE", ")"...
Return attachments on an entity.
[ "Return", "attachments", "on", "an", "entity", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/attachment.py#L61-L66
abilian/abilian-core
abilian/services/vocabularies/models.py
strip_label
def strip_label(mapper, connection, target): """Strip labels at ORM level so the unique=True means something.""" if target.label is not None: target.label = target.label.strip()
python
def strip_label(mapper, connection, target): """Strip labels at ORM level so the unique=True means something.""" if target.label is not None: target.label = target.label.strip()
[ "def", "strip_label", "(", "mapper", ",", "connection", ",", "target", ")", ":", "if", "target", ".", "label", "is", "not", "None", ":", "target", ".", "label", "=", "target", ".", "label", ".", "strip", "(", ")" ]
Strip labels at ORM level so the unique=True means something.
[ "Strip", "labels", "at", "ORM", "level", "so", "the", "unique", "=", "True", "means", "something", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L111-L114
abilian/abilian-core
abilian/services/vocabularies/models.py
_before_insert
def _before_insert(mapper, connection, target): """Set item to last position if position not defined.""" if target.position is None: func = sa.sql.func stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)]) target.position = connection.execute(stmt).scalar() + 1
python
def _before_insert(mapper, connection, target): """Set item to last position if position not defined.""" if target.position is None: func = sa.sql.func stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)]) target.position = connection.execute(stmt).scalar() + 1
[ "def", "_before_insert", "(", "mapper", ",", "connection", ",", "target", ")", ":", "if", "target", ".", "position", "is", "None", ":", "func", "=", "sa", ".", "sql", ".", "func", "stmt", "=", "sa", ".", "select", "(", "[", "func", ".", "coalesce", ...
Set item to last position if position not defined.
[ "Set", "item", "to", "last", "position", "if", "position", "not", "defined", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L118-L123
abilian/abilian-core
abilian/services/vocabularies/models.py
VocabularyQuery.by_label
def by_label(self, label): """Like `.get()`, but by label.""" # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(label=label).one() except sa.orm.exc.NoResultFound: return None
python
def by_label(self, label): """Like `.get()`, but by label.""" # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(label=label).one() except sa.orm.exc.NoResultFound: return None
[ "def", "by_label", "(", "self", ",", "label", ")", ":", "# don't use .first(), so that MultipleResultsFound can be raised", "try", ":", "return", "self", ".", "filter_by", "(", "label", "=", "label", ")", ".", "one", "(", ")", "except", "sa", ".", "orm", ".", ...
Like `.get()`, but by label.
[ "Like", ".", "get", "()", "but", "by", "label", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L23-L29
abilian/abilian-core
abilian/services/vocabularies/models.py
VocabularyQuery.by_position
def by_position(self, position): """Like `.get()`, but by position number.""" # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(position=position).one() except sa.orm.exc.NoResultFound: return None
python
def by_position(self, position): """Like `.get()`, but by position number.""" # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(position=position).one() except sa.orm.exc.NoResultFound: return None
[ "def", "by_position", "(", "self", ",", "position", ")", ":", "# don't use .first(), so that MultipleResultsFound can be raised", "try", ":", "return", "self", ".", "filter_by", "(", "position", "=", "position", ")", ".", "one", "(", ")", "except", "sa", ".", "o...
Like `.get()`, but by position number.
[ "Like", ".", "get", "()", "but", "by", "position", "number", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L31-L37
abilian/abilian-core
abilian/web/errors.py
ErrorManagerMixin._remove_session_save_objects
def _remove_session_save_objects(self): """Used during exception handling in case we need to remove() session: keep instances and merge them in the new session. """ if self.testing: return # Before destroying the session, get all instances to be attached to the ...
python
def _remove_session_save_objects(self): """Used during exception handling in case we need to remove() session: keep instances and merge them in the new session. """ if self.testing: return # Before destroying the session, get all instances to be attached to the ...
[ "def", "_remove_session_save_objects", "(", "self", ")", ":", "if", "self", ".", "testing", ":", "return", "# Before destroying the session, get all instances to be attached to the", "# new session. Without this, we get DetachedInstance errors, like when", "# tryin to get user's attribut...
Used during exception handling in case we need to remove() session: keep instances and merge them in the new session.
[ "Used", "during", "exception", "handling", "in", "case", "we", "need", "to", "remove", "()", "session", ":" ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L72-L103
abilian/abilian-core
abilian/web/errors.py
ErrorManagerMixin.log_exception
def log_exception(self, exc_info): """Log exception only if Sentry is not used (this avoids getting error twice in Sentry).""" dsn = self.config.get("SENTRY_DSN") if not dsn: super().log_exception(exc_info)
python
def log_exception(self, exc_info): """Log exception only if Sentry is not used (this avoids getting error twice in Sentry).""" dsn = self.config.get("SENTRY_DSN") if not dsn: super().log_exception(exc_info)
[ "def", "log_exception", "(", "self", ",", "exc_info", ")", ":", "dsn", "=", "self", ".", "config", ".", "get", "(", "\"SENTRY_DSN\"", ")", "if", "not", "dsn", ":", "super", "(", ")", ".", "log_exception", "(", "exc_info", ")" ]
Log exception only if Sentry is not used (this avoids getting error twice in Sentry).
[ "Log", "exception", "only", "if", "Sentry", "is", "not", "used", "(", "this", "avoids", "getting", "error", "twice", "in", "Sentry", ")", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L105-L110
abilian/abilian-core
abilian/web/errors.py
ErrorManagerMixin.init_sentry
def init_sentry(self): """Install Sentry handler if config defines 'SENTRY_DSN'.""" dsn = self.config.get("SENTRY_DSN") if not dsn: return try: import sentry_sdk except ImportError: logger.error( 'SENTRY_DSN is defined in confi...
python
def init_sentry(self): """Install Sentry handler if config defines 'SENTRY_DSN'.""" dsn = self.config.get("SENTRY_DSN") if not dsn: return try: import sentry_sdk except ImportError: logger.error( 'SENTRY_DSN is defined in confi...
[ "def", "init_sentry", "(", "self", ")", ":", "dsn", "=", "self", ".", "config", ".", "get", "(", "\"SENTRY_DSN\"", ")", "if", "not", "dsn", ":", "return", "try", ":", "import", "sentry_sdk", "except", "ImportError", ":", "logger", ".", "error", "(", "'...
Install Sentry handler if config defines 'SENTRY_DSN'.
[ "Install", "Sentry", "handler", "if", "config", "defines", "SENTRY_DSN", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L112-L129
abilian/abilian-core
abilian/web/errors.py
ErrorManagerMixin.install_default_handler
def install_default_handler(self, http_error_code): """Install a default error handler for `http_error_code`. The default error handler renders a template named error404.html for http_error_code 404. """ logger.debug( "Set Default HTTP error handler for status code %...
python
def install_default_handler(self, http_error_code): """Install a default error handler for `http_error_code`. The default error handler renders a template named error404.html for http_error_code 404. """ logger.debug( "Set Default HTTP error handler for status code %...
[ "def", "install_default_handler", "(", "self", ",", "http_error_code", ")", ":", "logger", ".", "debug", "(", "\"Set Default HTTP error handler for status code %d\"", ",", "http_error_code", ")", "handler", "=", "partial", "(", "self", ".", "handle_http_error", ",", "...
Install a default error handler for `http_error_code`. The default error handler renders a template named error404.html for http_error_code 404.
[ "Install", "a", "default", "error", "handler", "for", "http_error_code", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L141-L151
abilian/abilian-core
abilian/web/errors.py
ErrorManagerMixin.handle_http_error
def handle_http_error(self, code, error): """Helper that renders `error{code}.html`. Convenient way to use it:: from functools import partial handler = partial(app.handle_http_error, code) app.errorhandler(code)(handler) """ # 5xx code: error on server ...
python
def handle_http_error(self, code, error): """Helper that renders `error{code}.html`. Convenient way to use it:: from functools import partial handler = partial(app.handle_http_error, code) app.errorhandler(code)(handler) """ # 5xx code: error on server ...
[ "def", "handle_http_error", "(", "self", ",", "code", ",", "error", ")", ":", "# 5xx code: error on server side", "if", "(", "code", "//", "100", ")", "==", "5", ":", "# ensure rollback if needed, else error page may", "# have an error, too, resulting in raw 500 page :-(", ...
Helper that renders `error{code}.html`. Convenient way to use it:: from functools import partial handler = partial(app.handle_http_error, code) app.errorhandler(code)(handler)
[ "Helper", "that", "renders", "error", "{", "code", "}", ".", "html", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L153-L169
abilian/abilian-core
abilian/web/views/registry.py
Registry.register
def register(self, entity, url_func): """Associate a `url_func` with entity's type. :param:entity: an :class:`abilian.core.extensions.db.Model` class or instance. :param:url_func: any callable that accepts an entity instance and return an url for it. """ if not ...
python
def register(self, entity, url_func): """Associate a `url_func` with entity's type. :param:entity: an :class:`abilian.core.extensions.db.Model` class or instance. :param:url_func: any callable that accepts an entity instance and return an url for it. """ if not ...
[ "def", "register", "(", "self", ",", "entity", ",", "url_func", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "entity", ")", ":", "entity", "=", "entity", ".", "__class__", "assert", "issubclass", "(", "entity", ",", "db", ".", "Model", ")", ...
Associate a `url_func` with entity's type. :param:entity: an :class:`abilian.core.extensions.db.Model` class or instance. :param:url_func: any callable that accepts an entity instance and return an url for it.
[ "Associate", "a", "url_func", "with", "entity", "s", "type", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/registry.py#L21-L33
abilian/abilian-core
abilian/web/views/registry.py
Registry.url_for
def url_for(self, entity=None, object_type=None, object_id=None, **kwargs): """Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_...
python
def url_for(self, entity=None, object_type=None, object_id=None, **kwargs): """Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_...
[ "def", "url_for", "(", "self", ",", "entity", "=", "None", ",", "object_type", "=", "None", ",", "object_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "object_type", "is", "None", ":", "assert", "isinstance", "(", "entity", ",", "(", "db...
Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_id=entity.id` to generates an url. :param entity: a instance of a subclass of ...
[ "Return", "canonical", "view", "URL", "for", "given", "entity", "instance", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/registry.py#L35-L69
abilian/abilian-core
abilian/core/models/blob.py
Blob.file
def file(self): """Return :class:`pathlib.Path` object used for storing value.""" from abilian.services.repository import session_repository as repository return repository.get(self, self.uuid)
python
def file(self): """Return :class:`pathlib.Path` object used for storing value.""" from abilian.services.repository import session_repository as repository return repository.get(self, self.uuid)
[ "def", "file", "(", "self", ")", ":", "from", "abilian", ".", "services", ".", "repository", "import", "session_repository", "as", "repository", "return", "repository", ".", "get", "(", "self", ",", "self", ".", "uuid", ")" ]
Return :class:`pathlib.Path` object used for storing value.
[ "Return", ":", "class", ":", "pathlib", ".", "Path", "object", "used", "for", "storing", "value", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L62-L66
abilian/abilian-core
abilian/core/models/blob.py
Blob.value
def value(self): # type: () -> bytes """Binary value content.""" v = self.file return v.open("rb").read() if v is not None else v
python
def value(self): # type: () -> bytes """Binary value content.""" v = self.file return v.open("rb").read() if v is not None else v
[ "def", "value", "(", "self", ")", ":", "# type: () -> bytes", "v", "=", "self", ".", "file", "return", "v", ".", "open", "(", "\"rb\"", ")", ".", "read", "(", ")", "if", "v", "is", "not", "None", "else", "v" ]
Binary value content.
[ "Binary", "value", "content", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L76-L80
abilian/abilian-core
abilian/core/models/blob.py
Blob.value
def value(self, value, encoding="utf-8"): """Store binary content to applications's repository and update `self.meta['md5']`. :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when content is Unicode """ from abilian.ser...
python
def value(self, value, encoding="utf-8"): """Store binary content to applications's repository and update `self.meta['md5']`. :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when content is Unicode """ from abilian.ser...
[ "def", "value", "(", "self", ",", "value", ",", "encoding", "=", "\"utf-8\"", ")", ":", "from", "abilian", ".", "services", ".", "repository", "import", "session_repository", "as", "repository", "repository", ".", "set", "(", "self", ",", "self", ".", "uui...
Store binary content to applications's repository and update `self.meta['md5']`. :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when content is Unicode
[ "Store", "binary", "content", "to", "applications", "s", "repository", "and", "update", "self", ".", "meta", "[", "md5", "]", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L83-L102
abilian/abilian-core
abilian/core/models/blob.py
Blob.value
def value(self): """Remove value from repository.""" from abilian.services.repository import session_repository as repository repository.delete(self, self.uuid)
python
def value(self): """Remove value from repository.""" from abilian.services.repository import session_repository as repository repository.delete(self, self.uuid)
[ "def", "value", "(", "self", ")", ":", "from", "abilian", ".", "services", ".", "repository", "import", "session_repository", "as", "repository", "repository", ".", "delete", "(", "self", ",", "self", ".", "uuid", ")" ]
Remove value from repository.
[ "Remove", "value", "from", "repository", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L105-L109
abilian/abilian-core
abilian/core/models/blob.py
Blob.md5
def md5(self): """Return md5 from meta, or compute it if absent.""" md5 = self.meta.get("md5") if md5 is None: md5 = str(hashlib.md5(self.value).hexdigest()) return md5
python
def md5(self): """Return md5 from meta, or compute it if absent.""" md5 = self.meta.get("md5") if md5 is None: md5 = str(hashlib.md5(self.value).hexdigest()) return md5
[ "def", "md5", "(", "self", ")", ":", "md5", "=", "self", ".", "meta", ".", "get", "(", "\"md5\"", ")", "if", "md5", "is", "None", ":", "md5", "=", "str", "(", "hashlib", ".", "md5", "(", "self", ".", "value", ")", ".", "hexdigest", "(", ")", ...
Return md5 from meta, or compute it if absent.
[ "Return", "md5", "from", "meta", "or", "compute", "it", "if", "absent", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L112-L118
abilian/abilian-core
abilian/services/auth/views.py
forgotten_pw
def forgotten_pw(new_user=False): """Reset password for users who have already activated their accounts.""" email = request.form.get("email", "").lower() action = request.form.get("action") if action == "cancel": return redirect(url_for("login.login_form")) if not email: flash(_("Y...
python
def forgotten_pw(new_user=False): """Reset password for users who have already activated their accounts.""" email = request.form.get("email", "").lower() action = request.form.get("action") if action == "cancel": return redirect(url_for("login.login_form")) if not email: flash(_("Y...
[ "def", "forgotten_pw", "(", "new_user", "=", "False", ")", ":", "email", "=", "request", ".", "form", ".", "get", "(", "\"email\"", ",", "\"\"", ")", ".", "lower", "(", ")", "action", "=", "request", ".", "form", ".", "get", "(", "\"action\"", ")", ...
Reset password for users who have already activated their accounts.
[ "Reset", "password", "for", "users", "who", "have", "already", "activated", "their", "accounts", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L150-L184
abilian/abilian-core
abilian/services/auth/views.py
send_reset_password_instructions
def send_reset_password_instructions(user): # type: (User) -> None """Send the reset password instructions email for the specified user. :param user: The user to send the instructions to """ token = generate_reset_password_token(user) url = url_for("login.reset_password", token=token) reset...
python
def send_reset_password_instructions(user): # type: (User) -> None """Send the reset password instructions email for the specified user. :param user: The user to send the instructions to """ token = generate_reset_password_token(user) url = url_for("login.reset_password", token=token) reset...
[ "def", "send_reset_password_instructions", "(", "user", ")", ":", "# type: (User) -> None", "token", "=", "generate_reset_password_token", "(", "user", ")", "url", "=", "url_for", "(", "\"login.reset_password\"", ",", "token", "=", "token", ")", "reset_link", "=", "...
Send the reset password instructions email for the specified user. :param user: The user to send the instructions to
[ "Send", "the", "reset", "password", "instructions", "email", "for", "the", "specified", "user", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L267-L281
abilian/abilian-core
abilian/services/auth/views.py
generate_reset_password_token
def generate_reset_password_token(user): # type: (User) -> Any """Generate a unique reset password token for the specified user. :param user: The user to work with """ data = [str(user.id), md5(user.password)] return get_serializer("reset").dumps(data)
python
def generate_reset_password_token(user): # type: (User) -> Any """Generate a unique reset password token for the specified user. :param user: The user to work with """ data = [str(user.id), md5(user.password)] return get_serializer("reset").dumps(data)
[ "def", "generate_reset_password_token", "(", "user", ")", ":", "# type: (User) -> Any", "data", "=", "[", "str", "(", "user", ".", "id", ")", ",", "md5", "(", "user", ".", "password", ")", "]", "return", "get_serializer", "(", "\"reset\"", ")", ".", "dumps...
Generate a unique reset password token for the specified user. :param user: The user to work with
[ "Generate", "a", "unique", "reset", "password", "token", "for", "the", "specified", "user", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L284-L291
abilian/abilian-core
abilian/services/auth/views.py
send_mail
def send_mail(subject, recipient, template, **context): """Send an email using the Flask-Mail extension. :param subject: Email subject :param recipient: Email recipient :param template: The name of the email template :param context: The context to render the template with """ config = curr...
python
def send_mail(subject, recipient, template, **context): """Send an email using the Flask-Mail extension. :param subject: Email subject :param recipient: Email recipient :param template: The name of the email template :param context: The context to render the template with """ config = curr...
[ "def", "send_mail", "(", "subject", ",", "recipient", ",", "template", ",", "*", "*", "context", ")", ":", "config", "=", "current_app", ".", "config", "sender", "=", "config", "[", "\"MAIL_SENDER\"", "]", "msg", "=", "Message", "(", "subject", ",", "sen...
Send an email using the Flask-Mail extension. :param subject: Email subject :param recipient: Email recipient :param template: The name of the email template :param context: The context to render the template with
[ "Send", "an", "email", "using", "the", "Flask", "-", "Mail", "extension", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L329-L348
abilian/abilian-core
abilian/app.py
PluginManager.register_plugin
def register_plugin(self, name): """Load and register a plugin given its package name.""" logger.info("Registering plugin: " + name) module = importlib.import_module(name) module.register_plugin(self)
python
def register_plugin(self, name): """Load and register a plugin given its package name.""" logger.info("Registering plugin: " + name) module = importlib.import_module(name) module.register_plugin(self)
[ "def", "register_plugin", "(", "self", ",", "name", ")", ":", "logger", ".", "info", "(", "\"Registering plugin: \"", "+", "name", ")", "module", "=", "importlib", ".", "import_module", "(", "name", ")", "module", ".", "register_plugin", "(", "self", ")" ]
Load and register a plugin given its package name.
[ "Load", "and", "register", "a", "plugin", "given", "its", "package", "name", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L84-L88
abilian/abilian-core
abilian/app.py
PluginManager.register_plugins
def register_plugins(self): """Load plugins listed in config variable 'PLUGINS'.""" registered = set() for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]): if plugin_fqdn not in registered: self.register_plugin(plugin_fqdn) registered.ad...
python
def register_plugins(self): """Load plugins listed in config variable 'PLUGINS'.""" registered = set() for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]): if plugin_fqdn not in registered: self.register_plugin(plugin_fqdn) registered.ad...
[ "def", "register_plugins", "(", "self", ")", ":", "registered", "=", "set", "(", ")", "for", "plugin_fqdn", "in", "chain", "(", "self", ".", "APP_PLUGINS", ",", "self", ".", "config", "[", "\"PLUGINS\"", "]", ")", ":", "if", "plugin_fqdn", "not", "in", ...
Load plugins listed in config variable 'PLUGINS'.
[ "Load", "plugins", "listed", "in", "config", "variable", "PLUGINS", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L90-L96
abilian/abilian-core
abilian/app.py
Application.init_breadcrumbs
def init_breadcrumbs(self): """Insert the first element in breadcrumbs. This happens during `request_started` event, which is triggered before any url_value_preprocessor and `before_request` handlers. """ g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_r...
python
def init_breadcrumbs(self): """Insert the first element in breadcrumbs. This happens during `request_started` event, which is triggered before any url_value_preprocessor and `before_request` handlers. """ g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_r...
[ "def", "init_breadcrumbs", "(", "self", ")", ":", "g", ".", "breadcrumb", ".", "append", "(", "BreadcrumbItem", "(", "icon", "=", "\"home\"", ",", "url", "=", "\"/\"", "+", "request", ".", "script_root", ")", ")" ]
Insert the first element in breadcrumbs. This happens during `request_started` event, which is triggered before any url_value_preprocessor and `before_request` handlers.
[ "Insert", "the", "first", "element", "in", "breadcrumbs", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L217-L223
abilian/abilian-core
abilian/app.py
Application.check_instance_folder
def check_instance_folder(self, create=False): """Verify instance folder exists, is a directory, and has necessary permissions. :param:create: if `True`, creates directory hierarchy :raises: OSError with relevant errno if something is wrong. """ path = Path(self.instanc...
python
def check_instance_folder(self, create=False): """Verify instance folder exists, is a directory, and has necessary permissions. :param:create: if `True`, creates directory hierarchy :raises: OSError with relevant errno if something is wrong. """ path = Path(self.instanc...
[ "def", "check_instance_folder", "(", "self", ",", "create", "=", "False", ")", ":", "path", "=", "Path", "(", "self", ".", "instance_path", ")", "err", "=", "None", "eno", "=", "0", "if", "not", "path", ".", "exists", "(", ")", ":", "if", "create", ...
Verify instance folder exists, is a directory, and has necessary permissions. :param:create: if `True`, creates directory hierarchy :raises: OSError with relevant errno if something is wrong.
[ "Verify", "instance", "folder", "exists", "is", "a", "directory", "and", "has", "necessary", "permissions", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L251-L278
abilian/abilian-core
abilian/app.py
Application.init_extensions
def init_extensions(self): """Initialize flask extensions, helpers and services.""" extensions.redis.init_app(self) extensions.mail.init_app(self) extensions.deferred_js.init_app(self) extensions.upstream_info.extension.init_app(self) actions.init_app(self) # aut...
python
def init_extensions(self): """Initialize flask extensions, helpers and services.""" extensions.redis.init_app(self) extensions.mail.init_app(self) extensions.deferred_js.init_app(self) extensions.upstream_info.extension.init_app(self) actions.init_app(self) # aut...
[ "def", "init_extensions", "(", "self", ")", ":", "extensions", ".", "redis", ".", "init_app", "(", "self", ")", "extensions", ".", "mail", ".", "init_app", "(", "self", ")", "extensions", ".", "deferred_js", ".", "init_app", "(", "self", ")", "extensions",...
Initialize flask extensions, helpers and services.
[ "Initialize", "flask", "extensions", "helpers", "and", "services", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L288-L376
abilian/abilian-core
abilian/app.py
Application.add_url_rule
def add_url_rule(self, rule, endpoint=None, view_func=None, roles=None, **options): """See :meth:`Flask.add_url_rule`. If `roles` parameter is present, it must be a :class:`abilian.service.security.models.Role` instance, or a list of Role instances. """ super().add_url_r...
python
def add_url_rule(self, rule, endpoint=None, view_func=None, roles=None, **options): """See :meth:`Flask.add_url_rule`. If `roles` parameter is present, it must be a :class:`abilian.service.security.models.Role` instance, or a list of Role instances. """ super().add_url_r...
[ "def", "add_url_rule", "(", "self", ",", "rule", ",", "endpoint", "=", "None", ",", "view_func", "=", "None", ",", "roles", "=", "None", ",", "*", "*", "options", ")", ":", "super", "(", ")", ".", "add_url_rule", "(", "rule", ",", "endpoint", ",", ...
See :meth:`Flask.add_url_rule`. If `roles` parameter is present, it must be a :class:`abilian.service.security.models.Role` instance, or a list of Role instances.
[ "See", ":", "meth", ":", "Flask", ".", "add_url_rule", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L378-L390
abilian/abilian-core
abilian/app.py
Application.add_access_controller
def add_access_controller(self, name: str, func: Callable, endpoint: bool = False): """Add an access controller. If `name` is None it is added at application level, else if is considered as a blueprint name. If `endpoint` is True then it is considered as an endpoint. """ ...
python
def add_access_controller(self, name: str, func: Callable, endpoint: bool = False): """Add an access controller. If `name` is None it is added at application level, else if is considered as a blueprint name. If `endpoint` is True then it is considered as an endpoint. """ ...
[ "def", "add_access_controller", "(", "self", ",", "name", ":", "str", ",", "func", ":", "Callable", ",", "endpoint", ":", "bool", "=", "False", ")", ":", "auth_state", "=", "self", ".", "extensions", "[", "auth_service", ".", "name", "]", "adder", "=", ...
Add an access controller. If `name` is None it is added at application level, else if is considered as a blueprint name. If `endpoint` is True then it is considered as an endpoint.
[ "Add", "an", "access", "controller", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L392-L408
abilian/abilian-core
abilian/app.py
Application.add_static_url
def add_static_url(self, url_path, directory, endpoint=None, roles=None): """Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flas...
python
def add_static_url(self, url_path, directory, endpoint=None, roles=None): """Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flas...
[ "def", "add_static_url", "(", "self", ",", "url_path", ",", "directory", ",", "endpoint", "=", "None", ",", "roles", "=", "None", ")", ":", "url_path", "=", "self", ".", "static_url_path", "+", "\"/\"", "+", "url_path", "+", "\"/<path:filename>\"", "self", ...
Add a new url rule for static files. :param url_path: subpath from application static url path. No heading or trailing slash. :param directory: directory to serve content from. :param endpoint: flask endpoint name for this url rule. Example:: app.add_static_url(...
[ "Add", "a", "new", "url", "rule", "for", "static", "files", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L410-L436
abilian/abilian-core
abilian/core/extensions/__init__.py
_message_send
def _message_send(self, connection): """Send a single message instance. If TESTING is True the message will not actually be sent. :param self: a Message instance. """ sender = current_app.config["MAIL_SENDER"] if not self.extra_headers: self.extra_headers = {} self.extra_headers["S...
python
def _message_send(self, connection): """Send a single message instance. If TESTING is True the message will not actually be sent. :param self: a Message instance. """ sender = current_app.config["MAIL_SENDER"] if not self.extra_headers: self.extra_headers = {} self.extra_headers["S...
[ "def", "_message_send", "(", "self", ",", "connection", ")", ":", "sender", "=", "current_app", ".", "config", "[", "\"MAIL_SENDER\"", "]", "if", "not", "self", ".", "extra_headers", ":", "self", ".", "extra_headers", "=", "{", "}", "self", ".", "extra_hea...
Send a single message instance. If TESTING is True the message will not actually be sent. :param self: a Message instance.
[ "Send", "a", "single", "message", "instance", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/extensions/__init__.py#L30-L41
abilian/abilian-core
abilian/core/extensions/__init__.py
_filter_metadata_for_connection
def _filter_metadata_for_connection(target, connection, **kw): """Listener to control what indexes get created. Useful for skipping postgres-specific indexes on a sqlite for example. It's looking for info entry `engines` on an index (`Index(info=dict(engines=['postgresql']))`), an iterable of engine n...
python
def _filter_metadata_for_connection(target, connection, **kw): """Listener to control what indexes get created. Useful for skipping postgres-specific indexes on a sqlite for example. It's looking for info entry `engines` on an index (`Index(info=dict(engines=['postgresql']))`), an iterable of engine n...
[ "def", "_filter_metadata_for_connection", "(", "target", ",", "connection", ",", "*", "*", "kw", ")", ":", "engine", "=", "connection", ".", "engine", ".", "name", "default_engines", "=", "(", "engine", ",", ")", "tables", "=", "target", "if", "isinstance", ...
Listener to control what indexes get created. Useful for skipping postgres-specific indexes on a sqlite for example. It's looking for info entry `engines` on an index (`Index(info=dict(engines=['postgresql']))`), an iterable of engine names.
[ "Listener", "to", "control", "what", "indexes", "get", "created", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/extensions/__init__.py#L58-L73
abilian/abilian-core
abilian/web/util.py
url_for
def url_for(obj, **kw): """Polymorphic variant of Flask's `url_for` function. Behaves like the original function when the first argument is a string. When it's an object, it """ if isinstance(obj, str): return flask_url_for(obj, **kw) try: return current_app.default_view.url_fo...
python
def url_for(obj, **kw): """Polymorphic variant of Flask's `url_for` function. Behaves like the original function when the first argument is a string. When it's an object, it """ if isinstance(obj, str): return flask_url_for(obj, **kw) try: return current_app.default_view.url_fo...
[ "def", "url_for", "(", "obj", ",", "*", "*", "kw", ")", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "return", "flask_url_for", "(", "obj", ",", "*", "*", "kw", ")", "try", ":", "return", "current_app", ".", "default_view", ".", "url_...
Polymorphic variant of Flask's `url_for` function. Behaves like the original function when the first argument is a string. When it's an object, it
[ "Polymorphic", "variant", "of", "Flask", "s", "url_for", "function", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/util.py#L13-L30
abilian/abilian-core
abilian/web/util.py
send_file_from_directory
def send_file_from_directory(filename, directory, app=None): """Helper to add static rules, like in `abilian.app`.app. Example use:: app.add_url_rule( app.static_url_path + '/abilian/<path:filename>', endpoint='abilian_static', view_func=partial(send_file_from_directory, ...
python
def send_file_from_directory(filename, directory, app=None): """Helper to add static rules, like in `abilian.app`.app. Example use:: app.add_url_rule( app.static_url_path + '/abilian/<path:filename>', endpoint='abilian_static', view_func=partial(send_file_from_directory, ...
[ "def", "send_file_from_directory", "(", "filename", ",", "directory", ",", "app", "=", "None", ")", ":", "if", "app", "is", "None", ":", "app", "=", "current_app", "cache_timeout", "=", "app", ".", "get_send_file_max_age", "(", "filename", ")", "return", "se...
Helper to add static rules, like in `abilian.app`.app. Example use:: app.add_url_rule( app.static_url_path + '/abilian/<path:filename>', endpoint='abilian_static', view_func=partial(send_file_from_directory, directory='/path/to/static/files/dir'))
[ "Helper", "to", "add", "static", "rules", "like", "in", "abilian", ".", "app", ".", "app", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/util.py#L39-L53
abilian/abilian-core
abilian/services/audit/service.py
get_model_changes
def get_model_changes( entity_type, year=None, month=None, day=None, hour=None, since=None ): # type: (Text, int, int, int, int, datetime) -> Query """Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware th...
python
def get_model_changes( entity_type, year=None, month=None, day=None, hour=None, since=None ): # type: (Text, int, int, int, int, datetime) -> Query """Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware th...
[ "def", "get_model_changes", "(", "entity_type", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "since", "=", "None", ")", ":", "# type: (Text, int, int, int, int, datetime) -> Query", "query", "=", ...
Get models modified at the given date with the Audit service. :param entity_type: string like "extranet_medicen.apps.crm.models.Compte". Beware the typo, there won't be a warning message. :param since: datetime :param year: int :param month: int :param day: int :param hour: int :retu...
[ "Get", "models", "modified", "at", "the", "given", "date", "with", "the", "Audit", "service", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/audit/service.py#L340-L374
abilian/abilian-core
abilian/services/audit/service.py
get_columns_diff
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: ...
python
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: ...
[ "def", "get_columns_diff", "(", "changes", ")", ":", "for", "change", "in", "changes", ":", "change", ".", "diff", "=", "[", "]", "elt_changes", "=", "change", ".", "get_changes", "(", ")", "if", "elt_changes", ":", "change", ".", "diff", "=", "elt_chang...
Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to [].
[ "Add", "the", "changed", "columns", "as", "a", "diff", "attribute", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/audit/service.py#L377-L391
Ceasar/staticjinja
staticjinja/staticjinja.py
_has_argument
def _has_argument(func): """Test whether a function expects an argument. :param func: The function to be tested for existence of an argument. """ if hasattr(inspect, 'signature'): # New way in python 3.3 sig = inspect.signature(func) return bool(sig.parameters) else:...
python
def _has_argument(func): """Test whether a function expects an argument. :param func: The function to be tested for existence of an argument. """ if hasattr(inspect, 'signature'): # New way in python 3.3 sig = inspect.signature(func) return bool(sig.parameters) else:...
[ "def", "_has_argument", "(", "func", ")", ":", "if", "hasattr", "(", "inspect", ",", "'signature'", ")", ":", "# New way in python 3.3", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "return", "bool", "(", "sig", ".", "parameters", ")", "else"...
Test whether a function expects an argument. :param func: The function to be tested for existence of an argument.
[ "Test", "whether", "a", "function", "expects", "an", "argument", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L23-L35
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.make_site
def make_site(cls, searchpath="templates", outpath=".", contexts=None, rules=None, encoding="utf8", followlinks=True, extensions=None, staticpaths=None, filte...
python
def make_site(cls, searchpath="templates", outpath=".", contexts=None, rules=None, encoding="utf8", followlinks=True, extensions=None, staticpaths=None, filte...
[ "def", "make_site", "(", "cls", ",", "searchpath", "=", "\"templates\"", ",", "outpath", "=", "\".\"", ",", "contexts", "=", "None", ",", "rules", "=", "None", ",", "encoding", "=", "\"utf8\"", ",", "followlinks", "=", "True", ",", "extensions", "=", "No...
Create a :class:`Site <Site>` object. :param searchpath: A string representing the absolute path to the directory that the Site should search to discover templates. Defaults to ``'templates'``. If a relative path is provided, it will be coerced to an absolute ...
[ "Create", "a", ":", "class", ":", "Site", "<Site", ">", "object", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L102-L213
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.get_context
def get_context(self, template): """Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the valu...
python
def get_context(self, template): """Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the valu...
[ "def", "get_context", "(", "self", ",", "template", ")", ":", "context", "=", "{", "}", "for", "regex", ",", "context_generator", "in", "self", ".", "contexts", ":", "if", "re", ".", "match", "(", "regex", ",", "template", ".", "name", ")", ":", "if"...
Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the value is a function. If several matchin...
[ "Get", "the", "context", "for", "a", "template", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L236-L263
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.get_rule
def get_rule(self, template_name): """Find a matching compilation rule for a function. Raises a :exc:`ValueError` if no matching rule can be found. :param template_name: the name of the template """ for regex, render_func in self.rules: if re.match(regex, template_n...
python
def get_rule(self, template_name): """Find a matching compilation rule for a function. Raises a :exc:`ValueError` if no matching rule can be found. :param template_name: the name of the template """ for regex, render_func in self.rules: if re.match(regex, template_n...
[ "def", "get_rule", "(", "self", ",", "template_name", ")", ":", "for", "regex", ",", "render_func", "in", "self", ".", "rules", ":", "if", "re", ".", "match", "(", "regex", ",", "template_name", ")", ":", "return", "render_func", "raise", "ValueError", "...
Find a matching compilation rule for a function. Raises a :exc:`ValueError` if no matching rule can be found. :param template_name: the name of the template
[ "Find", "a", "matching", "compilation", "rule", "for", "a", "function", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L265-L275
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.is_static
def is_static(self, filename): """Check if a file is a static file (which should be copied, rather than compiled using Jinja2). A file is considered static if it lives in any of the directories specified in ``staticpaths``. :param filename: the name of the file to check ...
python
def is_static(self, filename): """Check if a file is a static file (which should be copied, rather than compiled using Jinja2). A file is considered static if it lives in any of the directories specified in ``staticpaths``. :param filename: the name of the file to check ...
[ "def", "is_static", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "staticpaths", "is", "None", ":", "# We're not using static file support", "return", "False", "for", "path", "in", "self", ".", "staticpaths", ":", "if", "filename", ".", "startswit...
Check if a file is a static file (which should be copied, rather than compiled using Jinja2). A file is considered static if it lives in any of the directories specified in ``staticpaths``. :param filename: the name of the file to check
[ "Check", "if", "a", "file", "is", "a", "static", "file", "(", "which", "should", "be", "copied", "rather", "than", "compiled", "using", "Jinja2", ")", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L277-L294
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.is_partial
def is_partial(self, filename): """Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of t...
python
def is_partial(self, filename): """Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of t...
[ "def", "is_partial", "(", "self", ",", "filename", ")", ":", "return", "any", "(", "(", "x", ".", "startswith", "(", "\"_\"", ")", "for", "x", "in", "filename", ".", "split", "(", "os", ".", "path", ".", "sep", ")", ")", ")" ]
Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of the file to check
[ "Check", "if", "a", "file", "is", "a", "partial", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L296-L307
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.is_template
def is_template(self, filename): """Check if a file is a template. A file is a considered a template if it is neither a partial nor ignored. :param filename: the name of the file to check """ if self.is_partial(filename): return False if self.is_ign...
python
def is_template(self, filename): """Check if a file is a template. A file is a considered a template if it is neither a partial nor ignored. :param filename: the name of the file to check """ if self.is_partial(filename): return False if self.is_ign...
[ "def", "is_template", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "is_partial", "(", "filename", ")", ":", "return", "False", "if", "self", ".", "is_ignored", "(", "filename", ")", ":", "return", "False", "if", "self", ".", "is_static", ...
Check if a file is a template. A file is a considered a template if it is neither a partial nor ignored. :param filename: the name of the file to check
[ "Check", "if", "a", "file", "is", "a", "template", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L321-L338
Ceasar/staticjinja
staticjinja/staticjinja.py
Site._ensure_dir
def _ensure_dir(self, template_name): """Ensure the output directory for a template exists.""" head = os.path.dirname(template_name) if head: file_dirpath = os.path.join(self.outpath, head) if not os.path.exists(file_dirpath): os.makedirs(file_dirpath)
python
def _ensure_dir(self, template_name): """Ensure the output directory for a template exists.""" head = os.path.dirname(template_name) if head: file_dirpath = os.path.join(self.outpath, head) if not os.path.exists(file_dirpath): os.makedirs(file_dirpath)
[ "def", "_ensure_dir", "(", "self", ",", "template_name", ")", ":", "head", "=", "os", ".", "path", ".", "dirname", "(", "template_name", ")", "if", "head", ":", "file_dirpath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "outpath", ",", "h...
Ensure the output directory for a template exists.
[ "Ensure", "the", "output", "directory", "for", "a", "template", "exists", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L340-L346
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.render_template
def render_template(self, template, context=None, filepath=None): """Render a single :class:`jinja2.Template` object. If a Rule matching the template is found, the rendering task is delegated to the rule. :param template: A :class:`jinja2.Template` to render. :para...
python
def render_template(self, template, context=None, filepath=None): """Render a single :class:`jinja2.Template` object. If a Rule matching the template is found, the rendering task is delegated to the rule. :param template: A :class:`jinja2.Template` to render. :para...
[ "def", "render_template", "(", "self", ",", "template", ",", "context", "=", "None", ",", "filepath", "=", "None", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Rendering %s...\"", "%", "template", ".", "name", ")", "if", "context", "is", "None",...
Render a single :class:`jinja2.Template` object. If a Rule matching the template is found, the rendering task is delegated to the rule. :param template: A :class:`jinja2.Template` to render. :param context: Optional. A dictionary representing the context to ren...
[ "Render", "a", "single", ":", "class", ":", "jinja2", ".", "Template", "object", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L348-L384
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.render_templates
def render_templates(self, templates, filepath=None): """Render a collection of :class:`jinja2.Template` objects. :param templates: A collection of Templates to render. :param filepath: Optional. A file or file-like object to dump the complete template strea...
python
def render_templates(self, templates, filepath=None): """Render a collection of :class:`jinja2.Template` objects. :param templates: A collection of Templates to render. :param filepath: Optional. A file or file-like object to dump the complete template strea...
[ "def", "render_templates", "(", "self", ",", "templates", ",", "filepath", "=", "None", ")", ":", "for", "template", "in", "templates", ":", "self", ".", "render_template", "(", "template", ",", "filepath", ")" ]
Render a collection of :class:`jinja2.Template` objects. :param templates: A collection of Templates to render. :param filepath: Optional. A file or file-like object to dump the complete template stream into. Defaults to to ``os.path.join(self.outpath, t...
[ "Render", "a", "collection", "of", ":", "class", ":", "jinja2", ".", "Template", "objects", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L386-L399
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.get_dependencies
def get_dependencies(self, filename): """Get a list of files that depends on the file named *filename*. :param filename: the name of the file to find dependencies of """ if self.is_partial(filename): return self.templates elif self.is_template(filename): ...
python
def get_dependencies(self, filename): """Get a list of files that depends on the file named *filename*. :param filename: the name of the file to find dependencies of """ if self.is_partial(filename): return self.templates elif self.is_template(filename): ...
[ "def", "get_dependencies", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "is_partial", "(", "filename", ")", ":", "return", "self", ".", "templates", "elif", "self", ".", "is_template", "(", "filename", ")", ":", "return", "[", "self", ".", ...
Get a list of files that depends on the file named *filename*. :param filename: the name of the file to find dependencies of
[ "Get", "a", "list", "of", "files", "that", "depends", "on", "the", "file", "named", "*", "filename", "*", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L409-L421
Ceasar/staticjinja
staticjinja/staticjinja.py
Site.render
def render(self, use_reloader=False): """Generate the site. :param use_reloader: if given, reload templates on modification """ self.render_templates(self.templates) self.copy_static(self.static_names) if use_reloader: self.logger.info("Watching '%s' for cha...
python
def render(self, use_reloader=False): """Generate the site. :param use_reloader: if given, reload templates on modification """ self.render_templates(self.templates) self.copy_static(self.static_names) if use_reloader: self.logger.info("Watching '%s' for cha...
[ "def", "render", "(", "self", ",", "use_reloader", "=", "False", ")", ":", "self", ".", "render_templates", "(", "self", ".", "templates", ")", "self", ".", "copy_static", "(", "self", ".", "static_names", ")", "if", "use_reloader", ":", "self", ".", "lo...
Generate the site. :param use_reloader: if given, reload templates on modification
[ "Generate", "the", "site", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/staticjinja.py#L423-L435
abilian/abilian-core
abilian/web/jinja.py
JinjaManagerMixin.register_jinja_loaders
def register_jinja_loaders(self, *loaders): """Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered i...
python
def register_jinja_loaders(self, *loaders): """Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered i...
[ "def", "register_jinja_loaders", "(", "self", ",", "*", "loaders", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_jinja_loaders\"", ")", ":", "raise", "ValueError", "(", "\"Cannot register new jinja loaders after first template rendered\"", ")", "self", ".", ...
Register one or many `jinja2.Loader` instances for templates lookup. During application initialization plugins can register a loader so that their templates are available to jinja2 renderer. Order of registration matters: last registered is first looked up (after standard Flask lookup ...
[ "Register", "one", "or", "many", "jinja2", ".", "Loader", "instances", "for", "templates", "lookup", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/jinja.py#L62-L81
abilian/abilian-core
abilian/web/jinja.py
JinjaManagerMixin.jinja_loader
def jinja_loader(self): """Search templates in custom app templates dir (default Flask behaviour), fallback on abilian templates.""" loaders = self._jinja_loaders del self._jinja_loaders loaders.append(Flask.jinja_loader.func(self)) loaders.reverse() return jinja2...
python
def jinja_loader(self): """Search templates in custom app templates dir (default Flask behaviour), fallback on abilian templates.""" loaders = self._jinja_loaders del self._jinja_loaders loaders.append(Flask.jinja_loader.func(self)) loaders.reverse() return jinja2...
[ "def", "jinja_loader", "(", "self", ")", ":", "loaders", "=", "self", ".", "_jinja_loaders", "del", "self", ".", "_jinja_loaders", "loaders", ".", "append", "(", "Flask", ".", "jinja_loader", ".", "func", "(", "self", ")", ")", "loaders", ".", "reverse", ...
Search templates in custom app templates dir (default Flask behaviour), fallback on abilian templates.
[ "Search", "templates", "in", "custom", "app", "templates", "dir", "(", "default", "Flask", "behaviour", ")", "fallback", "on", "abilian", "templates", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/jinja.py#L84-L91
Ceasar/staticjinja
staticjinja/cli.py
render
def render(args): """ Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False,...
python
def render(args): """ Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False,...
[ "def", "render", "(", "args", ")", ":", "srcpath", "=", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'templates'", ")", "if", "args", "[", "'--srcpath'", "]", "is", "None", "else", "args", "[", "'--srcpath'", "]", ...
Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False, 'build': True...
[ "Render", "a", "site", "." ]
train
https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/cli.py#L24-L81
abilian/abilian-core
abilian/services/indexing/schema.py
indexable_role
def indexable_role(principal): """Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`. """ principal = unwrap(principal) if hasattr(principal, "...
python
def indexable_role(principal): """Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`. """ principal = unwrap(principal) if hasattr(principal, "...
[ "def", "indexable_role", "(", "principal", ")", ":", "principal", "=", "unwrap", "(", "principal", ")", "if", "hasattr", "(", "principal", ",", "\"is_anonymous\"", ")", "and", "principal", ".", "is_anonymous", ":", "# transform anonymous user to anonymous role", "pr...
Return a string suitable for query against `allowed_roles_and_users` field. :param principal: It can be :data:`Anonymous`, :data:`Authenticated`, or an instance of :class:`User` or :class:`Group`.
[ "Return", "a", "string", "suitable", "for", "query", "against", "allowed_roles_and_users", "field", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/schema.py#L68-L90
abilian/abilian-core
abilian/services/conversion/service.py
Converter.to_text
def to_text(self, digest, blob, mime_type): """Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = "txt:" + digest text = ...
python
def to_text(self, digest, blob, mime_type): """Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = "txt:" + digest text = ...
[ "def", "to_text", "(", "self", ",", "digest", ",", "blob", ",", "mime_type", ")", ":", "# Special case, for now (XXX).", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "return", "\"\"", "cache_key", "=", "\"txt:\"", "+", "digest", "text", ...
Convert a file to plain text. Useful for full-text indexing. Returns a Unicode string.
[ "Convert", "a", "file", "to", "plain", "text", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L125-L155
abilian/abilian-core
abilian/services/conversion/service.py
Converter.has_image
def has_image(self, digest, mime_type, index, size=500): """Tell if there is a preview image.""" cache_key = f"img:{index}:{size}:{digest}" return mime_type.startswith("image/") or cache_key in self.cache
python
def has_image(self, digest, mime_type, index, size=500): """Tell if there is a preview image.""" cache_key = f"img:{index}:{size}:{digest}" return mime_type.startswith("image/") or cache_key in self.cache
[ "def", "has_image", "(", "self", ",", "digest", ",", "mime_type", ",", "index", ",", "size", "=", "500", ")", ":", "cache_key", "=", "f\"img:{index}:{size}:{digest}\"", "return", "mime_type", ".", "startswith", "(", "\"image/\"", ")", "or", "cache_key", "in", ...
Tell if there is a preview image.
[ "Tell", "if", "there", "is", "a", "preview", "image", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L157-L160
abilian/abilian-core
abilian/services/conversion/service.py
Converter.get_image
def get_image(self, digest, blob, mime_type, index, size=500): """Return an image for the given content, only if it already exists in the image cache.""" # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{dig...
python
def get_image(self, digest, blob, mime_type, index, size=500): """Return an image for the given content, only if it already exists in the image cache.""" # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{dig...
[ "def", "get_image", "(", "self", ",", "digest", ",", "blob", ",", "mime_type", ",", "index", ",", "size", "=", "500", ")", ":", "# Special case, for now (XXX).", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "return", "\"\"", "cache_key"...
Return an image for the given content, only if it already exists in the image cache.
[ "Return", "an", "image", "for", "the", "given", "content", "only", "if", "it", "already", "exists", "in", "the", "image", "cache", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L162-L170
abilian/abilian-core
abilian/services/conversion/service.py
Converter.to_image
def to_image(self, digest, blob, mime_type, index, size=500): """Convert a file to a list of images. Returns image at the given index. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" ...
python
def to_image(self, digest, blob, mime_type, index, size=500): """Convert a file to a list of images. Returns image at the given index. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" ...
[ "def", "to_image", "(", "self", ",", "digest", ",", "blob", ",", "mime_type", ",", "index", ",", "size", "=", "500", ")", ":", "# Special case, for now (XXX).", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "return", "\"\"", "cache_key",...
Convert a file to a list of images. Returns image at the given index.
[ "Convert", "a", "file", "to", "a", "list", "of", "images", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L172-L207
abilian/abilian-core
abilian/services/conversion/service.py
Converter.get_metadata
def get_metadata(self, digest, content, mime_type): """Get a dictionary representing the metadata embedded in the given content.""" # XXX: ad-hoc for now, refactor later if mime_type.startswith("image/"): img = Image.open(BytesIO(content)) ret = {} if...
python
def get_metadata(self, digest, content, mime_type): """Get a dictionary representing the metadata embedded in the given content.""" # XXX: ad-hoc for now, refactor later if mime_type.startswith("image/"): img = Image.open(BytesIO(content)) ret = {} if...
[ "def", "get_metadata", "(", "self", ",", "digest", ",", "content", ",", "mime_type", ")", ":", "# XXX: ad-hoc for now, refactor later", "if", "mime_type", ".", "startswith", "(", "\"image/\"", ")", ":", "img", "=", "Image", ".", "open", "(", "BytesIO", "(", ...
Get a dictionary representing the metadata embedded in the given content.
[ "Get", "a", "dictionary", "representing", "the", "metadata", "embedded", "in", "the", "given", "content", "." ]
train
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/service.py#L209-L244
google/pyu2f
pyu2f/apdu.py
CommandApdu.ToByteArray
def ToByteArray(self): """Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command. """ lc = self.InternalEncodeLc() out =...
python
def ToByteArray(self): """Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command. """ lc = self.InternalEncodeLc() out =...
[ "def", "ToByteArray", "(", "self", ")", ":", "lc", "=", "self", ".", "InternalEncodeLc", "(", ")", "out", "=", "bytearray", "(", "4", ")", "# will extend", "out", "[", "0", "]", "=", "self", ".", "cla", "out", "[", "1", "]", "=", "self", ".", "in...
Serialize the command. Encodes the command as per the U2F specs, using the standard ISO 7816-4 extended encoding. All Commands expect data, so Le is always present. Returns: Python bytearray of the encoded command.
[ "Serialize", "the", "command", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/apdu.py#L56-L79
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator.Authenticate
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # Ensure environment variable is present plugin_cmd = os.environ.get(SK_SIGNING_PLUGIN_ENV_VAR) if plugin_cmd is None: raise errors.PluginError('{} env var is not set' ...
python
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # Ensure environment variable is present plugin_cmd = os.environ.get(SK_SIGNING_PLUGIN_ENV_VAR) if plugin_cmd is None: raise errors.PluginError('{} env var is not set' ...
[ "def", "Authenticate", "(", "self", ",", "app_id", ",", "challenge_data", ",", "print_callback", "=", "sys", ".", "stderr", ".", "write", ")", ":", "# Ensure environment variable is present", "plugin_cmd", "=", "os", ".", "environ", ".", "get", "(", "SK_SIGNING_...
See base class.
[ "See", "base", "class", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L88-L110
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator._BuildPluginRequest
def _BuildPluginRequest(self, app_id, challenge_data, origin): """Builds a JSON request in the form that the plugin expects.""" client_data_map = {} encoded_challenges = [] app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id)) for challenge_item in challenge_data: key = challenge_item...
python
def _BuildPluginRequest(self, app_id, challenge_data, origin): """Builds a JSON request in the form that the plugin expects.""" client_data_map = {} encoded_challenges = [] app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id)) for challenge_item in challenge_data: key = challenge_item...
[ "def", "_BuildPluginRequest", "(", "self", ",", "app_id", ",", "challenge_data", ",", "origin", ")", ":", "client_data_map", "=", "{", "}", "encoded_challenges", "=", "[", "]", "app_id_hash_encoded", "=", "self", ".", "_Base64Encode", "(", "self", ".", "_SHA25...
Builds a JSON request in the form that the plugin expects.
[ "Builds", "a", "JSON", "request", "in", "the", "form", "that", "the", "plugin", "expects", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L116-L154
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator._BuildAuthenticatorResponse
def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response): """Builds the response to return to the caller.""" encoded_client_data = self._Base64Encode(client_data) signature_data = str(plugin_response['signatureData']) key_handle = str(plugin_response['keyHandle']) response = { ...
python
def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response): """Builds the response to return to the caller.""" encoded_client_data = self._Base64Encode(client_data) signature_data = str(plugin_response['signatureData']) key_handle = str(plugin_response['keyHandle']) response = { ...
[ "def", "_BuildAuthenticatorResponse", "(", "self", ",", "app_id", ",", "client_data", ",", "plugin_response", ")", ":", "encoded_client_data", "=", "self", ".", "_Base64Encode", "(", "client_data", ")", "signature_data", "=", "str", "(", "plugin_response", "[", "'...
Builds the response to return to the caller.
[ "Builds", "the", "response", "to", "return", "to", "the", "caller", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L156-L168
google/pyu2f
pyu2f/convenience/customauthenticator.py
CustomAuthenticator._CallPlugin
def _CallPlugin(self, cmd, input_json): """Calls the plugin and validates the response.""" # Calculate length of input input_length = len(input_json) length_bytes_le = struct.pack('<I', input_length) request = length_bytes_le + input_json.encode() # Call plugin sign_process = subprocess.Pop...
python
def _CallPlugin(self, cmd, input_json): """Calls the plugin and validates the response.""" # Calculate length of input input_length = len(input_json) length_bytes_le = struct.pack('<I', input_length) request = length_bytes_le + input_json.encode() # Call plugin sign_process = subprocess.Pop...
[ "def", "_CallPlugin", "(", "self", ",", "cmd", ",", "input_json", ")", ":", "# Calculate length of input", "input_length", "=", "len", "(", "input_json", ")", "length_bytes_le", "=", "struct", ".", "pack", "(", "'<I'", ",", "input_length", ")", "request", "=",...
Calls the plugin and validates the response.
[ "Calls", "the", "plugin", "and", "validates", "the", "response", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/customauthenticator.py#L170-L232
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalInit
def InternalInit(self): """Initializes the device and obtains channel id.""" self.cid = UsbHidTransport.U2FHID_BROADCAST_CID nonce = bytearray(os.urandom(8)) r = self.InternalExchange(UsbHidTransport.U2FHID_INIT, nonce) if len(r) < 17: raise errors.HidError('unexpected init reply len') if ...
python
def InternalInit(self): """Initializes the device and obtains channel id.""" self.cid = UsbHidTransport.U2FHID_BROADCAST_CID nonce = bytearray(os.urandom(8)) r = self.InternalExchange(UsbHidTransport.U2FHID_INIT, nonce) if len(r) < 17: raise errors.HidError('unexpected init reply len') if ...
[ "def", "InternalInit", "(", "self", ")", ":", "self", ".", "cid", "=", "UsbHidTransport", ".", "U2FHID_BROADCAST_CID", "nonce", "=", "bytearray", "(", "os", ".", "urandom", "(", "8", ")", ")", "r", "=", "self", ".", "InternalExchange", "(", "UsbHidTranspor...
Initializes the device and obtains channel id.
[ "Initializes", "the", "device", "and", "obtains", "channel", "id", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L226-L237
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalExchange
def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload)...
python
def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload)...
[ "def", "InternalExchange", "(", "self", ",", "cmd", ",", "payload_in", ")", ":", "# make a copy because we destroy it below", "self", ".", "logger", ".", "debug", "(", "'payload: '", "+", "str", "(", "list", "(", "payload_in", ")", ")", ")", "payload", "=", ...
Sends and receives a message from the device.
[ "Sends", "and", "receives", "a", "message", "from", "the", "device", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L239-L258
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalSend
def InternalSend(self, cmd, payload): """Sends a message to the device, including fragmenting it.""" length_to_send = len(payload) max_payload = self.packet_size - 7 first_frame = payload[0:max_payload] first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd, ...
python
def InternalSend(self, cmd, payload): """Sends a message to the device, including fragmenting it.""" length_to_send = len(payload) max_payload = self.packet_size - 7 first_frame = payload[0:max_payload] first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd, ...
[ "def", "InternalSend", "(", "self", ",", "cmd", ",", "payload", ")", ":", "length_to_send", "=", "len", "(", "payload", ")", "max_payload", "=", "self", ".", "packet_size", "-", "7", "first_frame", "=", "payload", "[", "0", ":", "max_payload", "]", "firs...
Sends a message to the device, including fragmenting it.
[ "Sends", "a", "message", "to", "the", "device", "including", "fragmenting", "it", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L260-L281
google/pyu2f
pyu2f/hidtransport.py
UsbHidTransport.InternalRecv
def InternalRecv(self): """Receives a message from the device, including defragmenting it.""" first_read = self.InternalReadFrame() first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size, first_read) data = first_packet.pay...
python
def InternalRecv(self): """Receives a message from the device, including defragmenting it.""" first_read = self.InternalReadFrame() first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size, first_read) data = first_packet.pay...
[ "def", "InternalRecv", "(", "self", ")", ":", "first_read", "=", "self", ".", "InternalReadFrame", "(", ")", "first_packet", "=", "UsbHidTransport", ".", "InitPacket", ".", "FromWireFormat", "(", "self", ".", "packet_size", ",", "first_read", ")", "data", "=",...
Receives a message from the device, including defragmenting it.
[ "Receives", "a", "message", "from", "the", "device", "including", "defragmenting", "it", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hidtransport.py#L297-L331
google/pyu2f
pyu2f/convenience/localauthenticator.py
LocalAuthenticator.Authenticate
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # If authenticator is not plugged in, prompt try: device = u2f.GetLocalU2FInterface(origin=self.origin) except errors.NoDeviceFoundError: print_callback('Please insert yo...
python
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # If authenticator is not plugged in, prompt try: device = u2f.GetLocalU2FInterface(origin=self.origin) except errors.NoDeviceFoundError: print_callback('Please insert yo...
[ "def", "Authenticate", "(", "self", ",", "app_id", ",", "challenge_data", ",", "print_callback", "=", "sys", ".", "stderr", ".", "write", ")", ":", "# If authenticator is not plugged in, prompt", "try", ":", "device", "=", "u2f", ".", "GetLocalU2FInterface", "(", ...
See base class.
[ "See", "base", "class", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/convenience/localauthenticator.py#L31-L67
google/pyu2f
pyu2f/hid/__init__.py
InternalPlatformSwitch
def InternalPlatformSwitch(funcname, *args, **kwargs): """Determine, on a platform-specific basis, which module to use.""" # pylint: disable=g-import-not-at-top clz = None if sys.platform.startswith('linux'): from pyu2f.hid import linux clz = linux.LinuxHidDevice elif sys.platform.startswith('win32'):...
python
def InternalPlatformSwitch(funcname, *args, **kwargs): """Determine, on a platform-specific basis, which module to use.""" # pylint: disable=g-import-not-at-top clz = None if sys.platform.startswith('linux'): from pyu2f.hid import linux clz = linux.LinuxHidDevice elif sys.platform.startswith('win32'):...
[ "def", "InternalPlatformSwitch", "(", "funcname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=g-import-not-at-top", "clz", "=", "None", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "from", "pyu2f", "....
Determine, on a platform-specific basis, which module to use.
[ "Determine", "on", "a", "platform", "-", "specific", "basis", "which", "module", "to", "use", "." ]
train
https://github.com/google/pyu2f/blob/8742d798027a21cbde0704aac0e93269bad2c3d0/pyu2f/hid/__init__.py#L31-L50