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 |
|---|---|---|---|---|---|---|---|---|---|---|
etcher-be/elib_config | elib_config/_validate.py | validate_config | def validate_config(raise_=True):
"""
Verifies that all configuration values have a valid setting
"""
ELIBConfig.check()
known_paths = set()
duplicate_values = set()
missing_values = set()
for config_value in ConfigValue.config_values:
if config_value.path not in known_paths:
... | python | def validate_config(raise_=True):
"""
Verifies that all configuration values have a valid setting
"""
ELIBConfig.check()
known_paths = set()
duplicate_values = set()
missing_values = set()
for config_value in ConfigValue.config_values:
if config_value.path not in known_paths:
... | [
"def",
"validate_config",
"(",
"raise_",
"=",
"True",
")",
":",
"ELIBConfig",
".",
"check",
"(",
")",
"known_paths",
"=",
"set",
"(",
")",
"duplicate_values",
"=",
"set",
"(",
")",
"missing_values",
"=",
"set",
"(",
")",
"for",
"config_value",
"in",
"Con... | Verifies that all configuration values have a valid setting | [
"Verifies",
"that",
"all",
"configuration",
"values",
"have",
"a",
"valid",
"setting"
] | train | https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_validate.py#L13-L35 |
alexandershov/mess | mess/dicts.py | groupby | def groupby(iterable, key=None):
"""
Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and... | python | def groupby(iterable, key=None):
"""
Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and... | [
"def",
"groupby",
"(",
"iterable",
",",
"key",
"=",
"None",
")",
":",
"groups",
"=",
"{",
"}",
"for",
"item",
"in",
"iterable",
":",
"if",
"key",
"is",
"None",
":",
"key_value",
"=",
"item",
"else",
":",
"key_value",
"=",
"key",
"(",
"item",
")",
... | Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and
returns the element unchanged.
:E... | [
"Group",
"items",
"from",
"iterable",
"by",
"key",
"and",
"return",
"a",
"dictionary",
"where",
"values",
"are",
"the",
"lists",
"of",
"items",
"from",
"the",
"iterable",
"having",
"the",
"same",
"key",
"."
] | train | https://github.com/alexandershov/mess/blob/7b0d956c1fd39cca2e4adcd5dc35952ec3ed3fd5/mess/dicts.py#L1-L21 |
corydodt/Crosscap | crosscap/tree.py | enter | def enter(clsQname):
"""
Delegate a rule to another class which instantiates a Klein app
This also memoizes the resource instance on the handler function itself
"""
def wrapper(routeHandler):
@functools.wraps(routeHandler)
def inner(self, request, *a, **kw):
if getattr(i... | python | def enter(clsQname):
"""
Delegate a rule to another class which instantiates a Klein app
This also memoizes the resource instance on the handler function itself
"""
def wrapper(routeHandler):
@functools.wraps(routeHandler)
def inner(self, request, *a, **kw):
if getattr(i... | [
"def",
"enter",
"(",
"clsQname",
")",
":",
"def",
"wrapper",
"(",
"routeHandler",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"routeHandler",
")",
"def",
"inner",
"(",
"self",
",",
"request",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"if",
... | Delegate a rule to another class which instantiates a Klein app
This also memoizes the resource instance on the handler function itself | [
"Delegate",
"a",
"rule",
"to",
"another",
"class",
"which",
"instantiates",
"a",
"Klein",
"app"
] | train | https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/tree.py#L35-L50 |
corydodt/Crosscap | crosscap/tree.py | openAPIDoc | def openAPIDoc(**kwargs):
"""
Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object
"""
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The ... | python | def openAPIDoc(**kwargs):
"""
Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object
"""
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The ... | [
"def",
"openAPIDoc",
"(",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"yaml",
".",
"dump",
"(",
"kwargs",
",",
"default_flow_style",
"=",
"False",
")",
"def",
"deco",
"(",
"routeHandler",
")",
":",
"# Wrap routeHandler, retaining name and __doc__, then edit __doc__.",... | Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object | [
"Update",
"a",
"function",
"s",
"docstring",
"to",
"include",
"the",
"OpenAPI",
"Yaml",
"generated",
"by",
"running",
"the",
"openAPIGraph",
"object"
] | train | https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/tree.py#L53-L69 |
tBaxter/tango-comments | build/lib/tango_comments/models.py | Comment.get_as_text | def get_as_text(self):
"""
Return this comment as plain text. Useful for emails.
"""
d = {
'user': self.user or self.name,
'date': self.post_date,
'comment': self.text,
'domain': self.site.domain,
'url': self.get_absolute_url()... | python | def get_as_text(self):
"""
Return this comment as plain text. Useful for emails.
"""
d = {
'user': self.user or self.name,
'date': self.post_date,
'comment': self.text,
'domain': self.site.domain,
'url': self.get_absolute_url()... | [
"def",
"get_as_text",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'user'",
":",
"self",
".",
"user",
"or",
"self",
".",
"name",
",",
"'date'",
":",
"self",
".",
"post_date",
",",
"'comment'",
":",
"self",
".",
"text",
",",
"'domain'",
":",
"self",
".",
... | Return this comment as plain text. Useful for emails. | [
"Return",
"this",
"comment",
"as",
"plain",
"text",
".",
"Useful",
"for",
"emails",
"."
] | train | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/models.py#L78-L89 |
artisanofcode/python-broadway | broadway/errors.py | handle_http_exception | def handle_http_exception(error):
"""
Attempts to render a template based on the `code` of a `HTTPException`. The
format string `errors/{code}.html` is used to generate the filename of
the template.
e.g. A `NotFound` exception will attempt to render `errors/404.html`.
If no template is found t... | python | def handle_http_exception(error):
"""
Attempts to render a template based on the `code` of a `HTTPException`. The
format string `errors/{code}.html` is used to generate the filename of
the template.
e.g. A `NotFound` exception will attempt to render `errors/404.html`.
If no template is found t... | [
"def",
"handle_http_exception",
"(",
"error",
")",
":",
"template",
"=",
"TEMPLATE",
".",
"format",
"(",
"code",
"=",
"error",
".",
"code",
")",
"try",
":",
"return",
"flask",
".",
"render_template",
"(",
"template",
",",
"exception",
"=",
"error",
")",
... | Attempts to render a template based on the `code` of a `HTTPException`. The
format string `errors/{code}.html` is used to generate the filename of
the template.
e.g. A `NotFound` exception will attempt to render `errors/404.html`.
If no template is found the standard flask error response is returned. | [
"Attempts",
"to",
"render",
"a",
"template",
"based",
"on",
"the",
"code",
"of",
"a",
"HTTPException",
".",
"The",
"format",
"string",
"errors",
"/",
"{",
"code",
"}",
".",
"html",
"is",
"used",
"to",
"generate",
"the",
"filename",
"of",
"the",
"template... | train | https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/errors.py#L20-L37 |
artisanofcode/python-broadway | broadway/errors.py | init_app | def init_app(application):
"""
Associates the error handler
"""
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) | python | def init_app(application):
"""
Associates the error handler
"""
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) | [
"def",
"init_app",
"(",
"application",
")",
":",
"for",
"code",
"in",
"werkzeug",
".",
"exceptions",
".",
"default_exceptions",
":",
"application",
".",
"register_error_handler",
"(",
"code",
",",
"handle_http_exception",
")"
] | Associates the error handler | [
"Associates",
"the",
"error",
"handler"
] | train | https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/errors.py#L40-L45 |
mixmastamyk/out | out/__init__.py | _find_palettes | def _find_palettes(stream):
''' Need to configure palettes manually, since we are checking stderr. '''
chosen = choose_palette(stream=stream)
palettes = get_available_palettes(chosen)
fg = ForegroundPalette(palettes=palettes)
fx = EffectsPalette(palettes=palettes)
return fg, fx, chosen | python | def _find_palettes(stream):
''' Need to configure palettes manually, since we are checking stderr. '''
chosen = choose_palette(stream=stream)
palettes = get_available_palettes(chosen)
fg = ForegroundPalette(palettes=palettes)
fx = EffectsPalette(palettes=palettes)
return fg, fx, chosen | [
"def",
"_find_palettes",
"(",
"stream",
")",
":",
"chosen",
"=",
"choose_palette",
"(",
"stream",
"=",
"stream",
")",
"palettes",
"=",
"get_available_palettes",
"(",
"chosen",
")",
"fg",
"=",
"ForegroundPalette",
"(",
"palettes",
"=",
"palettes",
")",
"fx",
... | Need to configure palettes manually, since we are checking stderr. | [
"Need",
"to",
"configure",
"palettes",
"manually",
"since",
"we",
"are",
"checking",
"stderr",
"."
] | train | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L22-L28 |
mixmastamyk/out | out/__init__.py | add_logging_level | def add_logging_level(name, value, method_name=None):
''' Comprehensively adds a new logging level to the ``logging`` module and
the currently configured logging class.
Derived from: https://stackoverflow.com/a/35804945/450917
'''
if not method_name:
method_name = name.lower()
... | python | def add_logging_level(name, value, method_name=None):
''' Comprehensively adds a new logging level to the ``logging`` module and
the currently configured logging class.
Derived from: https://stackoverflow.com/a/35804945/450917
'''
if not method_name:
method_name = name.lower()
... | [
"def",
"add_logging_level",
"(",
"name",
",",
"value",
",",
"method_name",
"=",
"None",
")",
":",
"if",
"not",
"method_name",
":",
"method_name",
"=",
"name",
".",
"lower",
"(",
")",
"# set levels",
"logging",
".",
"addLevelName",
"(",
"value",
",",
"name"... | Comprehensively adds a new logging level to the ``logging`` module and
the currently configured logging class.
Derived from: https://stackoverflow.com/a/35804945/450917 | [
"Comprehensively",
"adds",
"a",
"new",
"logging",
"level",
"to",
"the",
"logging",
"module",
"and",
"the",
"currently",
"configured",
"logging",
"class",
"."
] | train | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L153-L182 |
mixmastamyk/out | out/__init__.py | Logger.configure | def configure(self, **kwargs):
''' Convenience function to set a number of parameters on this logger
and associated handlers and formatters.
'''
for kwarg in kwargs:
value = kwargs[kwarg]
if kwarg == 'level':
self.set_level(value)
... | python | def configure(self, **kwargs):
''' Convenience function to set a number of parameters on this logger
and associated handlers and formatters.
'''
for kwarg in kwargs:
value = kwargs[kwarg]
if kwarg == 'level':
self.set_level(value)
... | [
"def",
"configure",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"kwarg",
"in",
"kwargs",
":",
"value",
"=",
"kwargs",
"[",
"kwarg",
"]",
"if",
"kwarg",
"==",
"'level'",
":",
"self",
".",
"set_level",
"(",
"value",
")",
"elif",
"kwarg",
"... | Convenience function to set a number of parameters on this logger
and associated handlers and formatters. | [
"Convenience",
"function",
"to",
"set",
"a",
"number",
"of",
"parameters",
"on",
"this",
"logger",
"and",
"associated",
"handlers",
"and",
"formatters",
"."
] | train | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L59-L115 |
mixmastamyk/out | out/__init__.py | Logger.log_config | def log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s... | python | def log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s... | [
"def",
"log_config",
"(",
"self",
")",
":",
"level",
"=",
"self",
".",
"level",
"debug",
"=",
"self",
".",
"debug",
"debug",
"(",
"'Logging config:'",
")",
"debug",
"(",
"'/ name: {}, id: {}'",
",",
"self",
".",
"name",
",",
"id",
"(",
"self",
")",
")"... | Log the current logging configuration. | [
"Log",
"the",
"current",
"logging",
"configuration",
"."
] | train | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L117-L139 |
adminMesfix/validations | validations/dsl.py | is_valid_timestamp | def is_valid_timestamp(date, unit='millis'):
"""
Checks that a number that represents a date as milliseconds is correct.
"""
assert isinstance(date, int), "Input is not instance of int"
if unit is 'millis':
return is_positive(date) and len(str(date)) == 13
elif unit is 'seconds':
... | python | def is_valid_timestamp(date, unit='millis'):
"""
Checks that a number that represents a date as milliseconds is correct.
"""
assert isinstance(date, int), "Input is not instance of int"
if unit is 'millis':
return is_positive(date) and len(str(date)) == 13
elif unit is 'seconds':
... | [
"def",
"is_valid_timestamp",
"(",
"date",
",",
"unit",
"=",
"'millis'",
")",
":",
"assert",
"isinstance",
"(",
"date",
",",
"int",
")",
",",
"\"Input is not instance of int\"",
"if",
"unit",
"is",
"'millis'",
":",
"return",
"is_positive",
"(",
"date",
")",
"... | Checks that a number that represents a date as milliseconds is correct. | [
"Checks",
"that",
"a",
"number",
"that",
"represents",
"a",
"date",
"as",
"milliseconds",
"is",
"correct",
"."
] | train | https://github.com/adminMesfix/validations/blob/a2fe04514c7aa1894b20eddbb1e848678ca08861/validations/dsl.py#L66-L77 |
chartbeat-labs/swailing | swailing/logger.py | Logger.debug | def debug(self, msg=None, *args, **kwargs):
"""Write log at DEBUG level. Same arguments as Python's built-in
Logger.
"""
return self._log(logging.DEBUG, msg, args, kwargs) | python | def debug(self, msg=None, *args, **kwargs):
"""Write log at DEBUG level. Same arguments as Python's built-in
Logger.
"""
return self._log(logging.DEBUG, msg, args, kwargs) | [
"def",
"debug",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Write log at DEBUG level. Same arguments as Python's built-in
Logger. | [
"Write",
"log",
"at",
"DEBUG",
"level",
".",
"Same",
"arguments",
"as",
"Python",
"s",
"built",
"-",
"in",
"Logger",
"."
] | train | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L67-L73 |
chartbeat-labs/swailing | swailing/logger.py | Logger.info | def info(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at INFO level."""
return self._log(logging.INFO, msg, args, kwargs) | python | def info(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at INFO level."""
return self._log(logging.INFO, msg, args, kwargs) | [
"def",
"info",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Similar to DEBUG but at INFO level. | [
"Similar",
"to",
"DEBUG",
"but",
"at",
"INFO",
"level",
"."
] | train | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L75-L78 |
chartbeat-labs/swailing | swailing/logger.py | Logger.exception | def exception(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at ERROR level with exc_info set.
https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472
"""
kwargs['exc_info'] = 1
return self._log(logging.ERROR, msg, args, kwargs) | python | def exception(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at ERROR level with exc_info set.
https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472
"""
kwargs['exc_info'] = 1
return self._log(logging.ERROR, msg, args, kwargs) | [
"def",
"exception",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'exc_info'",
"]",
"=",
"1",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"ERROR",
",",
"msg",
",",
"args",
",",
... | Similar to DEBUG but at ERROR level with exc_info set.
https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472 | [
"Similar",
"to",
"DEBUG",
"but",
"at",
"ERROR",
"level",
"with",
"exc_info",
"set",
"."
] | train | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L90-L96 |
chartbeat-labs/swailing | swailing/logger.py | Logger.log | def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs) | python | def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs) | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log",
"(",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Writes log out at any arbitray level. | [
"Writes",
"log",
"out",
"at",
"any",
"arbitray",
"level",
"."
] | train | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L103-L106 |
chartbeat-labs/swailing | swailing/logger.py | Logger._log | def _log(self, level, msg, args, kwargs):
"""Throttled log output."""
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_an... | python | def _log(self, level, msg, args, kwargs):
"""Throttled log output."""
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_an... | [
"def",
"_log",
"(",
"self",
",",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")",
":",
"with",
"self",
".",
"_tb_lock",
":",
"if",
"self",
".",
"_tb",
"is",
"None",
":",
"throttled",
"=",
"0",
"should_log",
"=",
"True",
"else",
":",
"throttled... | Throttled log output. | [
"Throttled",
"log",
"output",
"."
] | train | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L112-L142 |
shaypal5/utilitime | utilitime/timestamp/timestamp.py | timestamp_to_local_time | def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------... | python | def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------... | [
"def",
"timestamp_to_local_time",
"(",
"timestamp",
",",
"timezone_name",
")",
":",
"# first convert timestamp to UTC",
"utc_time",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"float",
"(",
"timestamp",
")",
")",
"delo",
"=",
"Delorean",
"(",
"utc_time",
",",
"... | Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime o... | [
"Convert",
"epoch",
"timestamp",
"to",
"a",
"localized",
"Delorean",
"datetime",
"object",
"."
] | train | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L12-L32 |
shaypal5/utilitime | utilitime/timestamp/timestamp.py | timestamp_to_local_time_str | def timestamp_to_local_time_str(
timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local... | python | def timestamp_to_local_time_str(
timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local... | [
"def",
"timestamp_to_local_time_str",
"(",
"timestamp",
",",
"timezone_name",
",",
"fmt",
"=",
"\"yyyy-MM-dd HH:mm:ss\"",
")",
":",
"localized_d",
"=",
"timestamp_to_local_time",
"(",
"timestamp",
",",
"timezone_name",
")",
"localized_datetime_str",
"=",
"localized_d",
... | Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
fmt : str
The format of the output string.
Returns
-------
str
... | [
"Convert",
"epoch",
"timestamp",
"to",
"a",
"localized",
"datetime",
"string",
"."
] | train | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L35-L55 |
shaypal5/utilitime | utilitime/timestamp/timestamp.py | get_timestamp | def get_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute."""
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
... | python | def get_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute."""
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
... | [
"def",
"get_timestamp",
"(",
"timezone_name",
",",
"year",
",",
"month",
",",
"day",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"timezone_name",
")",
"tz_datetime",
"=",
"tz",
".",
"localize",
"... | Epoch timestamp from timezone, year, month, day, hour and minute. | [
"Epoch",
"timestamp",
"from",
"timezone",
"year",
"month",
"day",
"hour",
"and",
"minute",
"."
] | train | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L58-L63 |
bruth/restlib2 | restlib2/mimeparse.py | parse_media_range | def parse_media_range(range):
"""Carves up a media range and returns a tuple of the
(type, subtype, params) where 'params' is a dictionary
of all the parameters for the media range.
For example, the media range 'application/*;q=0.5' would
get parsed into:
('application', '*', {'q... | python | def parse_media_range(range):
"""Carves up a media range and returns a tuple of the
(type, subtype, params) where 'params' is a dictionary
of all the parameters for the media range.
For example, the media range 'application/*;q=0.5' would
get parsed into:
('application', '*', {'q... | [
"def",
"parse_media_range",
"(",
"range",
")",
":",
"(",
"type",
",",
"subtype",
",",
"params",
")",
"=",
"parse_mime_type",
"(",
"range",
")",
"if",
"'q'",
"not",
"in",
"params",
"or",
"not",
"params",
"[",
"'q'",
"]",
"or",
"float",
"(",
"params",
... | Carves up a media range and returns a tuple of the
(type, subtype, params) where 'params' is a dictionary
of all the parameters for the media range.
For example, the media range 'application/*;q=0.5' would
get parsed into:
('application', '*', {'q', '0.5'})
In addition this f... | [
"Carves",
"up",
"a",
"media",
"range",
"and",
"returns",
"a",
"tuple",
"of",
"the",
"(",
"type",
"subtype",
"params",
")",
"where",
"params",
"is",
"a",
"dictionary",
"of",
"all",
"the",
"parameters",
"for",
"the",
"media",
"range",
".",
"For",
"example"... | train | https://github.com/bruth/restlib2/blob/cb147527496ddf08263364f1fb52e7c48f215667/restlib2/mimeparse.py#L47-L64 |
bruth/restlib2 | restlib2/mimeparse.py | fitness_and_quality_parsed | def fitness_and_quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a given mime-type against
a list of media_ranges that have already been
parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality
parameter of the best match,... | python | def fitness_and_quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a given mime-type against
a list of media_ranges that have already been
parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality
parameter of the best match,... | [
"def",
"fitness_and_quality_parsed",
"(",
"mime_type",
",",
"parsed_ranges",
")",
":",
"best_fitness",
"=",
"-",
"1",
"best_fit_q",
"=",
"0",
"(",
"target_type",
",",
"target_subtype",
",",
"target_params",
")",
"=",
"parse_media_range",
"(",
"mime_type",
")",
"... | Find the best match for a given mime-type against
a list of media_ranges that have already been
parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality
parameter of the best match, or (-1, 0) if no match
was found. Just as for quality_par... | [
"Find",
"the",
"best",
"match",
"for",
"a",
"given",
"mime",
"-",
"type",
"against",
"a",
"list",
"of",
"media_ranges",
"that",
"have",
"already",
"been",
"parsed",
"by",
"parse_media_range",
"()",
".",
"Returns",
"a",
"tuple",
"of",
"the",
"fitness",
"val... | train | https://github.com/bruth/restlib2/blob/cb147527496ddf08263364f1fb52e7c48f215667/restlib2/mimeparse.py#L66-L91 |
klmitch/vobj | vobj/decorators.py | upgrader | def upgrader(version=None):
"""
A decorator for marking a method as an upgrader from an older
version of a given object. Can be used in two different ways:
``@upgrader``
In this usage, the decorated method updates from the previous
schema version to this schema version.
``@upgrade... | python | def upgrader(version=None):
"""
A decorator for marking a method as an upgrader from an older
version of a given object. Can be used in two different ways:
``@upgrader``
In this usage, the decorated method updates from the previous
schema version to this schema version.
``@upgrade... | [
"def",
"upgrader",
"(",
"version",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"# Save the version to update from",
"func",
".",
"__vers_upgrader__",
"=",
"version",
"return",
"func",
"# What is version? It can be None, an int, or a callable,",
"#... | A decorator for marking a method as an upgrader from an older
version of a given object. Can be used in two different ways:
``@upgrader``
In this usage, the decorated method updates from the previous
schema version to this schema version.
``@upgrader(number)``
In this usage, the d... | [
"A",
"decorator",
"for",
"marking",
"a",
"method",
"as",
"an",
"upgrader",
"from",
"an",
"older",
"version",
"of",
"a",
"given",
"object",
".",
"Can",
"be",
"used",
"in",
"two",
"different",
"ways",
":"
] | train | https://github.com/klmitch/vobj/blob/4952658dc0914fe92afb2ef6e5ccca2829de6cb2/vobj/decorators.py#L19-L70 |
klmitch/vobj | vobj/decorators.py | downgrader | def downgrader(version):
"""
A decorator for marking a method as a downgrader to an older
version of a given object. Note that downgrader methods are
implicitly class methods. Also note that downgraders take a
single argument--a dictionary of attributes--and must return a
dictionary. Downgrad... | python | def downgrader(version):
"""
A decorator for marking a method as a downgrader to an older
version of a given object. Note that downgrader methods are
implicitly class methods. Also note that downgraders take a
single argument--a dictionary of attributes--and must return a
dictionary. Downgrad... | [
"def",
"downgrader",
"(",
"version",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"# Save the version to downgrade to",
"func",
".",
"__vers_downgrader__",
"=",
"version",
"return",
"func",
"# Sanity-check the version number",
"if",
"not",
"isinstance",
"(",
... | A decorator for marking a method as a downgrader to an older
version of a given object. Note that downgrader methods are
implicitly class methods. Also note that downgraders take a
single argument--a dictionary of attributes--and must return a
dictionary. Downgraders may modify the argument in place,... | [
"A",
"decorator",
"for",
"marking",
"a",
"method",
"as",
"a",
"downgrader",
"to",
"an",
"older",
"version",
"of",
"a",
"given",
"object",
".",
"Note",
"that",
"downgrader",
"methods",
"are",
"implicitly",
"class",
"methods",
".",
"Also",
"note",
"that",
"d... | train | https://github.com/klmitch/vobj/blob/4952658dc0914fe92afb2ef6e5ccca2829de6cb2/vobj/decorators.py#L73-L97 |
nir0s/serv | serv/init/systemd.py | SystemD.generate | def generate(self, overwrite=False):
"""Generate service files and returns a list of them.
Note that env var names will be capitalized using a Jinja filter.
This is template dependent.
Even though a param might be named `key` and have value `value`,
it will be rendered as `KEY=v... | python | def generate(self, overwrite=False):
"""Generate service files and returns a list of them.
Note that env var names will be capitalized using a Jinja filter.
This is template dependent.
Even though a param might be named `key` and have value `value`,
it will be rendered as `KEY=v... | [
"def",
"generate",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"super",
"(",
"SystemD",
",",
"self",
")",
".",
"generate",
"(",
"overwrite",
"=",
"overwrite",
")",
"self",
".",
"_validate_init_system_specific_params",
"(",
")",
"svc_file_template",
... | Generate service files and returns a list of them.
Note that env var names will be capitalized using a Jinja filter.
This is template dependent.
Even though a param might be named `key` and have value `value`,
it will be rendered as `KEY=value`.
We retrieve the names of the tem... | [
"Generate",
"service",
"files",
"and",
"returns",
"a",
"list",
"of",
"them",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L35-L70 |
nir0s/serv | serv/init/systemd.py | SystemD.install | def install(self):
"""Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed.
"""
super(SystemD, self).install()
... | python | def install(self):
"""Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed.
"""
super(SystemD, self).install()
... | [
"def",
"install",
"(",
"self",
")",
":",
"super",
"(",
"SystemD",
",",
"self",
")",
".",
"install",
"(",
")",
"self",
".",
"deploy_service_file",
"(",
"self",
".",
"svc_file_path",
",",
"self",
".",
"svc_file_dest",
")",
"self",
".",
"deploy_service_file",... | Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed. | [
"Install",
"the",
"service",
"on",
"the",
"local",
"machine"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L72-L84 |
nir0s/serv | serv/init/systemd.py | SystemD.stop | def stop(self):
"""Stop the service.
"""
try:
sh.systemctl.stop(self.name)
except sh.ErrorReturnCode_5:
self.logger.debug('Service not running.') | python | def stop(self):
"""Stop the service.
"""
try:
sh.systemctl.stop(self.name)
except sh.ErrorReturnCode_5:
self.logger.debug('Service not running.') | [
"def",
"stop",
"(",
"self",
")",
":",
"try",
":",
"sh",
".",
"systemctl",
".",
"stop",
"(",
"self",
".",
"name",
")",
"except",
"sh",
".",
"ErrorReturnCode_5",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Service not running.'",
")"
] | Stop the service. | [
"Stop",
"the",
"service",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L91-L97 |
nir0s/serv | serv/init/systemd.py | SystemD.uninstall | def uninstall(self):
"""Uninstall the service.
This is supposed to perform any cleanup operations required to
remove the service. Files, links, whatever else should be removed.
This method should also run when implementing cleanup in case of
failures. As such, idempotence should... | python | def uninstall(self):
"""Uninstall the service.
This is supposed to perform any cleanup operations required to
remove the service. Files, links, whatever else should be removed.
This method should also run when implementing cleanup in case of
failures. As such, idempotence should... | [
"def",
"uninstall",
"(",
"self",
")",
":",
"sh",
".",
"systemctl",
".",
"disable",
"(",
"self",
".",
"name",
")",
"sh",
".",
"systemctl",
"(",
"'daemon-reload'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"svc_file_dest",
")",
":"... | Uninstall the service.
This is supposed to perform any cleanup operations required to
remove the service. Files, links, whatever else should be removed.
This method should also run when implementing cleanup in case of
failures. As such, idempotence should be considered. | [
"Uninstall",
"the",
"service",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L101-L114 |
nir0s/serv | serv/init/systemd.py | SystemD.status | def status(self, name=''):
"""Return a list of the statuses of the `name` service, or
if name is omitted, a list of the status of all services for this
specific init system.
There should be a standardization around the status fields.
There currently isn't.
`self.service... | python | def status(self, name=''):
"""Return a list of the statuses of the `name` service, or
if name is omitted, a list of the status of all services for this
specific init system.
There should be a standardization around the status fields.
There currently isn't.
`self.service... | [
"def",
"status",
"(",
"self",
",",
"name",
"=",
"''",
")",
":",
"super",
"(",
"SystemD",
",",
"self",
")",
".",
"status",
"(",
"name",
"=",
"name",
")",
"svc_list",
"=",
"sh",
".",
"systemctl",
"(",
"'--no-legend'",
",",
"'--no-pager'",
",",
"t",
"... | Return a list of the statuses of the `name` service, or
if name is omitted, a list of the status of all services for this
specific init system.
There should be a standardization around the status fields.
There currently isn't.
`self.services` is set in `base.py` | [
"Return",
"a",
"list",
"of",
"the",
"statuses",
"of",
"the",
"name",
"service",
"or",
"if",
"name",
"is",
"omitted",
"a",
"list",
"of",
"the",
"status",
"of",
"all",
"services",
"for",
"this",
"specific",
"init",
"system",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L116-L135 |
totokaka/pySpaceGDN | pyspacegdn/requests/find_request.py | FindRequest.sort | def sort(self, *sort):
""" Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API.... | python | def sort(self, *sort):
""" Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API.... | [
"def",
"sort",
"(",
"self",
",",
"*",
"sort",
")",
":",
"self",
".",
"add_get_param",
"(",
"'sort'",
",",
"FILTER_DELIMITER",
".",
"join",
"(",
"[",
"ELEMENT_DELIMITER",
".",
"join",
"(",
"elements",
")",
"for",
"elements",
"in",
"sort",
"]",
")",
")",... | Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API. See also the API documentation on
... | [
"Sort",
"the",
"results",
"."
] | train | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L73-L91 |
totokaka/pySpaceGDN | pyspacegdn/requests/find_request.py | FindRequest.where | def where(self, *where):
""" Filter the results.
Filter the results by provided rules. The rules should be tuples that
look like this::
('<key>', '<operator>', '<value>')
For example::
('name', '$eq', 'Vanilla Minecraft')
This is also covered in the d... | python | def where(self, *where):
""" Filter the results.
Filter the results by provided rules. The rules should be tuples that
look like this::
('<key>', '<operator>', '<value>')
For example::
('name', '$eq', 'Vanilla Minecraft')
This is also covered in the d... | [
"def",
"where",
"(",
"self",
",",
"*",
"where",
")",
":",
"filters",
"=",
"list",
"(",
")",
"for",
"key",
",",
"operator",
",",
"value",
"in",
"where",
":",
"filters",
".",
"append",
"(",
"ELEMENT_DELIMITER",
".",
"join",
"(",
"(",
"key",
",",
"ope... | Filter the results.
Filter the results by provided rules. The rules should be tuples that
look like this::
('<key>', '<operator>', '<value>')
For example::
('name', '$eq', 'Vanilla Minecraft')
This is also covered in the documentation_ of the SpaceGDN API.
... | [
"Filter",
"the",
"results",
"."
] | train | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L93-L114 |
totokaka/pySpaceGDN | pyspacegdn/requests/find_request.py | FindRequest.fetch | def fetch(self):
""" Run the request and fetch the results.
This method will compile the request, send it to the SpaceGDN endpoint
defined with the `SpaceGDN` object and wrap the results in a
:class:`pyspacegdn.Response` object.
Returns a :class:`pyspacegdn.Response` object.
... | python | def fetch(self):
""" Run the request and fetch the results.
This method will compile the request, send it to the SpaceGDN endpoint
defined with the `SpaceGDN` object and wrap the results in a
:class:`pyspacegdn.Response` object.
Returns a :class:`pyspacegdn.Response` object.
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"response",
"=",
"Response",
"(",
")",
"has_next",
"=",
"True",
"while",
"has_next",
":",
"resp",
"=",
"self",
".",
"_fetch",
"(",
"default_path",
"=",
"'v2'",
")",
"results",
"=",
"None",
"if",
"resp",
".",
"su... | Run the request and fetch the results.
This method will compile the request, send it to the SpaceGDN endpoint
defined with the `SpaceGDN` object and wrap the results in a
:class:`pyspacegdn.Response` object.
Returns a :class:`pyspacegdn.Response` object. | [
"Run",
"the",
"request",
"and",
"fetch",
"the",
"results",
"."
] | train | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L116-L137 |
kalekundert/nonstdlib | nonstdlib/meta.py | singleton | def singleton(cls):
""" Decorator function that turns a class into a singleton. """
import inspect
# Create a structure to store instances of any singletons that get
# created.
instances = {}
# Make sure that the constructor for this class doesn't take any
# arguments. Since singletons ca... | python | def singleton(cls):
""" Decorator function that turns a class into a singleton. """
import inspect
# Create a structure to store instances of any singletons that get
# created.
instances = {}
# Make sure that the constructor for this class doesn't take any
# arguments. Since singletons ca... | [
"def",
"singleton",
"(",
"cls",
")",
":",
"import",
"inspect",
"# Create a structure to store instances of any singletons that get",
"# created.",
"instances",
"=",
"{",
"}",
"# Make sure that the constructor for this class doesn't take any",
"# arguments. Since singletons can only be... | Decorator function that turns a class into a singleton. | [
"Decorator",
"function",
"that",
"turns",
"a",
"class",
"into",
"a",
"singleton",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/meta.py#L40-L75 |
heikomuller/sco-engine | scoengine/model.py | ModelOutputFile.from_dict | def from_dict(doc):
"""Create a model output file object from a dictionary.
"""
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) | python | def from_dict(doc):
"""Create a model output file object from a dictionary.
"""
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) | [
"def",
"from_dict",
"(",
"doc",
")",
":",
"if",
"'path'",
"in",
"doc",
":",
"path",
"=",
"doc",
"[",
"'path'",
"]",
"else",
":",
"path",
"=",
"None",
"return",
"ModelOutputFile",
"(",
"doc",
"[",
"'filename'",
"]",
",",
"doc",
"[",
"'mimeType'",
"]",... | Create a model output file object from a dictionary. | [
"Create",
"a",
"model",
"output",
"file",
"object",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L61-L73 |
heikomuller/sco-engine | scoengine/model.py | ModelOutputFile.to_dict | def to_dict(self):
"""Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict
"""
doc = {
'filename' : self.filename,
'mimeType' : self.mime_type
}
# Add path if present
if s... | python | def to_dict(self):
"""Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict
"""
doc = {
'filename' : self.filename,
'mimeType' : self.mime_type
}
# Add path if present
if s... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"doc",
"=",
"{",
"'filename'",
":",
"self",
".",
"filename",
",",
"'mimeType'",
":",
"self",
".",
"mime_type",
"}",
"# Add path if present",
"if",
"self",
".",
"filename",
"!=",
"self",
".",
"path",
":",
"doc",
... | Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict | [
"Get",
"a",
"dictionary",
"serialization",
"of",
"the",
"object",
"to",
"convert",
"into",
"a",
"Json",
"object",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L75-L90 |
heikomuller/sco-engine | scoengine/model.py | ModelOutputs.from_dict | def from_dict(doc):
"""Create a model output object from a dictionary.
"""
return ModelOutputs(
ModelOutputFile.from_dict(doc['prediction']),
[ModelOutputFile.from_dict(a) for a in doc['attachments']]
) | python | def from_dict(doc):
"""Create a model output object from a dictionary.
"""
return ModelOutputs(
ModelOutputFile.from_dict(doc['prediction']),
[ModelOutputFile.from_dict(a) for a in doc['attachments']]
) | [
"def",
"from_dict",
"(",
"doc",
")",
":",
"return",
"ModelOutputs",
"(",
"ModelOutputFile",
".",
"from_dict",
"(",
"doc",
"[",
"'prediction'",
"]",
")",
",",
"[",
"ModelOutputFile",
".",
"from_dict",
"(",
"a",
")",
"for",
"a",
"in",
"doc",
"[",
"'attachm... | Create a model output object from a dictionary. | [
"Create",
"a",
"model",
"output",
"object",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L131-L138 |
heikomuller/sco-engine | scoengine/model.py | ModelOutputs.to_dict | def to_dict(self):
"""Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict
"""
return {
'prediction' : self.prediction_file.to_dict(),
'attachments' : [a.to_dict() for a in self.attachments]
... | python | def to_dict(self):
"""Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict
"""
return {
'prediction' : self.prediction_file.to_dict(),
'attachments' : [a.to_dict() for a in self.attachments]
... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'prediction'",
":",
"self",
".",
"prediction_file",
".",
"to_dict",
"(",
")",
",",
"'attachments'",
":",
"[",
"a",
".",
"to_dict",
"(",
")",
"for",
"a",
"in",
"self",
".",
"attachments",
"]",
"... | Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict | [
"Get",
"a",
"dictionary",
"serialization",
"of",
"the",
"object",
"to",
"convert",
"into",
"a",
"Json",
"object",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L140-L151 |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.delete_model | def delete_model(self, model_id, erase=False):
"""Delete the model with given identifier in the database. Returns the
handle for the deleted model or None if object identifier is unknown.
Parameters
----------
model_id : string
Unique model identifier
erase :... | python | def delete_model(self, model_id, erase=False):
"""Delete the model with given identifier in the database. Returns the
handle for the deleted model or None if object identifier is unknown.
Parameters
----------
model_id : string
Unique model identifier
erase :... | [
"def",
"delete_model",
"(",
"self",
",",
"model_id",
",",
"erase",
"=",
"False",
")",
":",
"return",
"self",
".",
"delete_object",
"(",
"model_id",
",",
"erase",
"=",
"erase",
")"
] | Delete the model with given identifier in the database. Returns the
handle for the deleted model or None if object identifier is unknown.
Parameters
----------
model_id : string
Unique model identifier
erase : Boolean, optinal
If true, the record will be ... | [
"Delete",
"the",
"model",
"with",
"given",
"identifier",
"in",
"the",
"database",
".",
"Returns",
"the",
"handle",
"for",
"the",
"deleted",
"model",
"or",
"None",
"if",
"object",
"identifier",
"is",
"unknown",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L239-L255 |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.register_model | def register_model(self, model_id, properties, parameters, outputs, connector):
"""Create an experiment object for the subject and image group. Objects
are referenced by their identifier. The reference to a functional data
object is optional.
Raises ValueError if no valid experiment nam... | python | def register_model(self, model_id, properties, parameters, outputs, connector):
"""Create an experiment object for the subject and image group. Objects
are referenced by their identifier. The reference to a functional data
object is optional.
Raises ValueError if no valid experiment nam... | [
"def",
"register_model",
"(",
"self",
",",
"model_id",
",",
"properties",
",",
"parameters",
",",
"outputs",
",",
"connector",
")",
":",
"# Create object handle and store it in database before returning it",
"obj",
"=",
"ModelHandle",
"(",
"model_id",
",",
"properties",... | Create an experiment object for the subject and image group. Objects
are referenced by their identifier. The reference to a functional data
object is optional.
Raises ValueError if no valid experiment name is given in property list.
Parameters
----------
model_id : stri... | [
"Create",
"an",
"experiment",
"object",
"for",
"the",
"subject",
"and",
"image",
"group",
".",
"Objects",
"are",
"referenced",
"by",
"their",
"identifier",
".",
"The",
"reference",
"to",
"a",
"functional",
"data",
"object",
"is",
"optional",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L339-L367 |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.to_dict | def to_dict(self, model):
"""Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model
"""
# Get the basic Json object from the super class
... | python | def to_dict(self, model):
"""Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model
"""
# Get the basic Json object from the super class
... | [
"def",
"to_dict",
"(",
"self",
",",
"model",
")",
":",
"# Get the basic Json object from the super class",
"obj",
"=",
"super",
"(",
"ModelRegistry",
",",
"self",
")",
".",
"to_dict",
"(",
"model",
")",
"# Add model parameter",
"obj",
"[",
"'parameters'",
"]",
"... | Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model | [
"Create",
"a",
"dictionary",
"serialization",
"for",
"a",
"model",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L369-L389 |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.update_connector | def update_connector(self, model_id, connector):
"""Update the connector information for a given model.
Returns None if the specified model not exist.
Parameters
----------
model_id : string
Unique model identifier
connector : dict
New connection... | python | def update_connector(self, model_id, connector):
"""Update the connector information for a given model.
Returns None if the specified model not exist.
Parameters
----------
model_id : string
Unique model identifier
connector : dict
New connection... | [
"def",
"update_connector",
"(",
"self",
",",
"model_id",
",",
"connector",
")",
":",
"model",
"=",
"self",
".",
"get_model",
"(",
"model_id",
")",
"if",
"model",
"is",
"None",
":",
"return",
"None",
"model",
".",
"connector",
"=",
"connector",
"self",
".... | Update the connector information for a given model.
Returns None if the specified model not exist.
Parameters
----------
model_id : string
Unique model identifier
connector : dict
New connection information
Returns
-------
ModelH... | [
"Update",
"the",
"connector",
"information",
"for",
"a",
"given",
"model",
"."
] | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L391-L412 |
bmweiner/skillful | skillful/interface.py | _snake_to_camel | def _snake_to_camel(name, strict=False):
"""Converts parameter names from snake_case to camelCase.
Args:
name, str. Snake case.
strict: bool, default True. If True, will set name to lowercase before
converting, otherwise assumes original name is proper camel case.
Set to... | python | def _snake_to_camel(name, strict=False):
"""Converts parameter names from snake_case to camelCase.
Args:
name, str. Snake case.
strict: bool, default True. If True, will set name to lowercase before
converting, otherwise assumes original name is proper camel case.
Set to... | [
"def",
"_snake_to_camel",
"(",
"name",
",",
"strict",
"=",
"False",
")",
":",
"if",
"strict",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"terms",
"=",
"name",
".",
"split",
"(",
"'_'",
")",
"return",
"terms",
"[",
"0",
"]",
"+",
"''",
".",... | Converts parameter names from snake_case to camelCase.
Args:
name, str. Snake case.
strict: bool, default True. If True, will set name to lowercase before
converting, otherwise assumes original name is proper camel case.
Set to False if name may already be in camelCase.
... | [
"Converts",
"parameter",
"names",
"from",
"snake_case",
"to",
"camelCase",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L565-L580 |
bmweiner/skillful | skillful/interface.py | DefaultAttrMixin._set_default_attr | def _set_default_attr(self, default_attr):
"""Sets default attributes when None.
Args:
default_attr: dict. Key-val of attr, default-value.
"""
for attr, val in six.iteritems(default_attr):
if getattr(self, attr, None) is None:
setattr(self, attr, ... | python | def _set_default_attr(self, default_attr):
"""Sets default attributes when None.
Args:
default_attr: dict. Key-val of attr, default-value.
"""
for attr, val in six.iteritems(default_attr):
if getattr(self, attr, None) is None:
setattr(self, attr, ... | [
"def",
"_set_default_attr",
"(",
"self",
",",
"default_attr",
")",
":",
"for",
"attr",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"default_attr",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"attr",
",",
"None",
")",
"is",
"None",
":",
"setattr",
... | Sets default attributes when None.
Args:
default_attr: dict. Key-val of attr, default-value. | [
"Sets",
"default",
"attributes",
"when",
"None",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L10-L18 |
bmweiner/skillful | skillful/interface.py | Body.to_json | def to_json(self, drop_null=True, camel=False, indent=None, sort_keys=False):
"""Serialize self as JSON
Args:
drop_null: bool, default True. Remove 'empty' attributes. See
to_dict.
camel: bool, default True. Convert keys to camelCase.
indent: int, def... | python | def to_json(self, drop_null=True, camel=False, indent=None, sort_keys=False):
"""Serialize self as JSON
Args:
drop_null: bool, default True. Remove 'empty' attributes. See
to_dict.
camel: bool, default True. Convert keys to camelCase.
indent: int, def... | [
"def",
"to_json",
"(",
"self",
",",
"drop_null",
"=",
"True",
",",
"camel",
"=",
"False",
",",
"indent",
"=",
"None",
",",
"sort_keys",
"=",
"False",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
"drop_null",
",",
"camel... | Serialize self as JSON
Args:
drop_null: bool, default True. Remove 'empty' attributes. See
to_dict.
camel: bool, default True. Convert keys to camelCase.
indent: int, default None. See json built-in.
sort_keys: bool, default False. See json built-... | [
"Serialize",
"self",
"as",
"JSON"
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L29-L43 |
bmweiner/skillful | skillful/interface.py | Body.to_dict | def to_dict(self, drop_null=True, camel=False):
"""Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params.
"""
#return _to_dict... | python | def to_dict(self, drop_null=True, camel=False):
"""Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params.
"""
#return _to_dict... | [
"def",
"to_dict",
"(",
"self",
",",
"drop_null",
"=",
"True",
",",
"camel",
"=",
"False",
")",
":",
"#return _to_dict(self, drop_null, camel)",
"def",
"to_dict",
"(",
"obj",
",",
"drop_null",
",",
"camel",
")",
":",
"\"\"\"Recursively constructs the dict.\"\"\"",
... | Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params. | [
"Serialize",
"self",
"as",
"dict",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L45-L80 |
bmweiner/skillful | skillful/interface.py | RequestBody.parse | def parse(self, body):
"""Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self
"""
if isinstance(body, six.string_types):
body = json.loads(body)
# version
version = body... | python | def parse(self, body):
"""Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self
"""
if isinstance(body, six.string_types):
body = json.loads(body)
# version
version = body... | [
"def",
"parse",
"(",
"self",
",",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"six",
".",
"string_types",
")",
":",
"body",
"=",
"json",
".",
"loads",
"(",
"body",
")",
"# version",
"version",
"=",
"body",
"[",
"'version'",
"]",
"self",
... | Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self | [
"Parse",
"JSON",
"request",
"storing",
"content",
"in",
"object",
"attributes",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L112-L170 |
bmweiner/skillful | skillful/interface.py | ResponseBody.set_speech_text | def set_speech_text(self, text):
"""Set response output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot exceed
8,000 characters.
"""
self.response.outputSpeech.type = 'PlainText'
self.response.outputSp... | python | def set_speech_text(self, text):
"""Set response output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot exceed
8,000 characters.
"""
self.response.outputSpeech.type = 'PlainText'
self.response.outputSp... | [
"def",
"set_speech_text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"response",
".",
"outputSpeech",
".",
"type",
"=",
"'PlainText'",
"self",
".",
"response",
".",
"outputSpeech",
".",
"text",
"=",
"text"
] | Set response output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot exceed
8,000 characters. | [
"Set",
"response",
"output",
"speech",
"as",
"plain",
"text",
"type",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L365-L373 |
bmweiner/skillful | skillful/interface.py | ResponseBody.set_speech_ssml | def set_speech_ssml(self, ssml):
"""Set response output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters.
"""
self.respons... | python | def set_speech_ssml(self, ssml):
"""Set response output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters.
"""
self.respons... | [
"def",
"set_speech_ssml",
"(",
"self",
",",
"ssml",
")",
":",
"self",
".",
"response",
".",
"outputSpeech",
".",
"type",
"=",
"'SSML'",
"self",
".",
"response",
".",
"outputSpeech",
".",
"ssml",
"=",
"ssml"
] | Set response output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters. | [
"Set",
"response",
"output",
"speech",
"as",
"SSML",
"type",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L375-L384 |
bmweiner/skillful | skillful/interface.py | ResponseBody.set_card_simple | def set_card_simple(self, title, content):
"""Set response card as simple type.
title and content cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card.
"""
self.response.card.t... | python | def set_card_simple(self, title, content):
"""Set response card as simple type.
title and content cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card.
"""
self.response.card.t... | [
"def",
"set_card_simple",
"(",
"self",
",",
"title",
",",
"content",
")",
":",
"self",
".",
"response",
".",
"card",
".",
"type",
"=",
"'Simple'",
"self",
".",
"response",
".",
"card",
".",
"title",
"=",
"title",
"self",
".",
"response",
".",
"card",
... | Set response card as simple type.
title and content cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card. | [
"Set",
"response",
"card",
"as",
"simple",
"type",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L386-L397 |
bmweiner/skillful | skillful/interface.py | ResponseBody.set_card_standard | def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
"""Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. ... | python | def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
"""Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. ... | [
"def",
"set_card_standard",
"(",
"self",
",",
"title",
",",
"text",
",",
"smallImageUrl",
"=",
"None",
",",
"largeImageUrl",
"=",
"None",
")",
":",
"self",
".",
"response",
".",
"card",
".",
"type",
"=",
"'Standard'",
"self",
".",
"response",
".",
"card"... | Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. Content of Standard type card.
smallImageUrl: str. URL of small image. Cannot exceed 2,000
... | [
"Set",
"response",
"card",
"as",
"standard",
"type",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L399-L419 |
bmweiner/skillful | skillful/interface.py | ResponseBody.set_reprompt_text | def set_reprompt_text(self, text):
"""Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters.
"""
self.response.reprompt.outputSpeech.type = 'PlainText'
se... | python | def set_reprompt_text(self, text):
"""Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters.
"""
self.response.reprompt.outputSpeech.type = 'PlainText'
se... | [
"def",
"set_reprompt_text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"response",
".",
"reprompt",
".",
"outputSpeech",
".",
"type",
"=",
"'PlainText'",
"self",
".",
"response",
".",
"reprompt",
".",
"outputSpeech",
".",
"text",
"=",
"text"
] | Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters. | [
"Set",
"response",
"reprompt",
"output",
"speech",
"as",
"plain",
"text",
"type",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L425-L433 |
bmweiner/skillful | skillful/interface.py | ResponseBody.set_reprompt_ssml | def set_reprompt_ssml(self, ssml):
"""Set response reprompt output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters.
"""
s... | python | def set_reprompt_ssml(self, ssml):
"""Set response reprompt output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters.
"""
s... | [
"def",
"set_reprompt_ssml",
"(",
"self",
",",
"ssml",
")",
":",
"self",
".",
"response",
".",
"reprompt",
".",
"outputSpeech",
".",
"type",
"=",
"'SSML'",
"self",
".",
"response",
".",
"reprompt",
".",
"outputSpeech",
".",
"ssml",
"=",
"ssml"
] | Set response reprompt output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters. | [
"Set",
"response",
"reprompt",
"output",
"speech",
"as",
"SSML",
"type",
"."
] | train | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L435-L444 |
salimm/httpoutpustream | httpoutputstream/stream.py | HttpBufferedOutstream.writelines | def writelines(self, lines):
'''
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
:param lines:
'''
if self.__closed:
raise OSError()
for line in lines:
... | python | def writelines(self, lines):
'''
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
:param lines:
'''
if self.__closed:
raise OSError()
for line in lines:
... | [
"def",
"writelines",
"(",
"self",
",",
"lines",
")",
":",
"if",
"self",
".",
"__closed",
":",
"raise",
"OSError",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"self",
".",
"write",
"(",
"line",
")"
] | Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
:param lines: | [
"Write",
"a",
"list",
"of",
"lines",
"to",
"the",
"stream",
".",
"Line",
"separators",
"are",
"not",
"added",
"so",
"it",
"is",
"usual",
"for",
"each",
"of",
"the",
"lines",
"provided",
"to",
"have",
"a",
"line",
"separator",
"at",
"the",
"end",
".",
... | train | https://github.com/salimm/httpoutpustream/blob/c3c785e3c6faf6348494b742669cd8025659f763/httpoutputstream/stream.py#L28-L36 |
salimm/httpoutpustream | httpoutputstream/stream.py | HttpBufferedOutstream.__save | def __save(self, b):
'''
saves the given data to the buffer
:param b:
'''
newbufferidx = (self.__bufferidx + len(b))
self.__buffer[self.__bufferidx:newbufferidx] = b
#update buffer index
self.__bufferidx = newbufferidx | python | def __save(self, b):
'''
saves the given data to the buffer
:param b:
'''
newbufferidx = (self.__bufferidx + len(b))
self.__buffer[self.__bufferidx:newbufferidx] = b
#update buffer index
self.__bufferidx = newbufferidx | [
"def",
"__save",
"(",
"self",
",",
"b",
")",
":",
"newbufferidx",
"=",
"(",
"self",
".",
"__bufferidx",
"+",
"len",
"(",
"b",
")",
")",
"self",
".",
"__buffer",
"[",
"self",
".",
"__bufferidx",
":",
"newbufferidx",
"]",
"=",
"b",
"#update buffer index"... | saves the given data to the buffer
:param b: | [
"saves",
"the",
"given",
"data",
"to",
"the",
"buffer",
":",
"param",
"b",
":"
] | train | https://github.com/salimm/httpoutpustream/blob/c3c785e3c6faf6348494b742669cd8025659f763/httpoutputstream/stream.py#L81-L89 |
salimm/httpoutpustream | httpoutputstream/stream.py | HttpBufferedOutstream.flush | def flush(self):
'''
Flushes the buffer to socket. Only call when the write is done. Calling flush after each write will prevent the buffer to act as efficiently as possible
'''
# return if empty
if self.__bufferidx == 0:
return
# send here the data
s... | python | def flush(self):
'''
Flushes the buffer to socket. Only call when the write is done. Calling flush after each write will prevent the buffer to act as efficiently as possible
'''
# return if empty
if self.__bufferidx == 0:
return
# send here the data
s... | [
"def",
"flush",
"(",
"self",
")",
":",
"# return if empty",
"if",
"self",
".",
"__bufferidx",
"==",
"0",
":",
"return",
"# send here the data",
"self",
".",
"conn",
".",
"send",
"(",
"\"%s\\r\\n\"",
"%",
"hex",
"(",
"self",
".",
"__bufferidx",
")",
"[",
... | Flushes the buffer to socket. Only call when the write is done. Calling flush after each write will prevent the buffer to act as efficiently as possible | [
"Flushes",
"the",
"buffer",
"to",
"socket",
".",
"Only",
"call",
"when",
"the",
"write",
"is",
"done",
".",
"Calling",
"flush",
"after",
"each",
"write",
"will",
"prevent",
"the",
"buffer",
"to",
"act",
"as",
"efficiently",
"as",
"possible"
] | train | https://github.com/salimm/httpoutpustream/blob/c3c785e3c6faf6348494b742669cd8025659f763/httpoutputstream/stream.py#L92-L103 |
salimm/httpoutpustream | httpoutputstream/stream.py | HttpBufferedOutstream.close | def close(self):
'''
Closes the stream to output. It destroys the buffer and the buffer pointer. However, it will not close the the client connection
'''
#write all that is remained in buffer
self.flush()
# delete buffer
self.__buffer = None
#reset buffer ... | python | def close(self):
'''
Closes the stream to output. It destroys the buffer and the buffer pointer. However, it will not close the the client connection
'''
#write all that is remained in buffer
self.flush()
# delete buffer
self.__buffer = None
#reset buffer ... | [
"def",
"close",
"(",
"self",
")",
":",
"#write all that is remained in buffer",
"self",
".",
"flush",
"(",
")",
"# delete buffer",
"self",
".",
"__buffer",
"=",
"None",
"#reset buffer index to -1 to indicate no where",
"self",
".",
"__bufferidx",
"=",
"-",
"1",
"#wr... | Closes the stream to output. It destroys the buffer and the buffer pointer. However, it will not close the the client connection | [
"Closes",
"the",
"stream",
"to",
"output",
".",
"It",
"destroys",
"the",
"buffer",
"and",
"the",
"buffer",
"pointer",
".",
"However",
"it",
"will",
"not",
"close",
"the",
"the",
"client",
"connection"
] | train | https://github.com/salimm/httpoutpustream/blob/c3c785e3c6faf6348494b742669cd8025659f763/httpoutputstream/stream.py#L106-L121 |
cfobel/clutter-webcam-viewer | clutter_webcam_viewer/warp_control.py | WarpControl.create_ui | def create_ui(self):
'''
Create UI elements and connect signals.
'''
box = Gtk.Box()
rotate_left = Gtk.Button('Rotate left')
rotate_right = Gtk.Button('Rotate right')
flip_horizontal = Gtk.Button('Flip horizontal')
flip_vertical = Gtk.Button('Flip vertical... | python | def create_ui(self):
'''
Create UI elements and connect signals.
'''
box = Gtk.Box()
rotate_left = Gtk.Button('Rotate left')
rotate_right = Gtk.Button('Rotate right')
flip_horizontal = Gtk.Button('Flip horizontal')
flip_vertical = Gtk.Button('Flip vertical... | [
"def",
"create_ui",
"(",
"self",
")",
":",
"box",
"=",
"Gtk",
".",
"Box",
"(",
")",
"rotate_left",
"=",
"Gtk",
".",
"Button",
"(",
"'Rotate left'",
")",
"rotate_right",
"=",
"Gtk",
".",
"Button",
"(",
"'Rotate right'",
")",
"flip_horizontal",
"=",
"Gtk",... | Create UI elements and connect signals. | [
"Create",
"UI",
"elements",
"and",
"connect",
"signals",
"."
] | train | https://github.com/cfobel/clutter-webcam-viewer/blob/b227d2ae02d750194e65c13bcf178550755c3afc/clutter_webcam_viewer/warp_control.py#L15-L55 |
cfobel/clutter-webcam-viewer | clutter_webcam_viewer/warp_control.py | WarpControl.save | def save(self):
'''
Save warp projection settings to HDF file.
'''
response = pu.open(title='Save perspective warp', patterns=['*.h5'])
if response is not None:
self.warp_actor.save(response) | python | def save(self):
'''
Save warp projection settings to HDF file.
'''
response = pu.open(title='Save perspective warp', patterns=['*.h5'])
if response is not None:
self.warp_actor.save(response) | [
"def",
"save",
"(",
"self",
")",
":",
"response",
"=",
"pu",
".",
"open",
"(",
"title",
"=",
"'Save perspective warp'",
",",
"patterns",
"=",
"[",
"'*.h5'",
"]",
")",
"if",
"response",
"is",
"not",
"None",
":",
"self",
".",
"warp_actor",
".",
"save",
... | Save warp projection settings to HDF file. | [
"Save",
"warp",
"projection",
"settings",
"to",
"HDF",
"file",
"."
] | train | https://github.com/cfobel/clutter-webcam-viewer/blob/b227d2ae02d750194e65c13bcf178550755c3afc/clutter_webcam_viewer/warp_control.py#L57-L63 |
cfobel/clutter-webcam-viewer | clutter_webcam_viewer/warp_control.py | WarpControl.load | def load(self):
'''
Load warp projection settings from HDF file.
'''
response = pu.open(title='Load perspective warp', patterns=['*.h5'])
if response is not None:
self.warp_actor.load(response) | python | def load(self):
'''
Load warp projection settings from HDF file.
'''
response = pu.open(title='Load perspective warp', patterns=['*.h5'])
if response is not None:
self.warp_actor.load(response) | [
"def",
"load",
"(",
"self",
")",
":",
"response",
"=",
"pu",
".",
"open",
"(",
"title",
"=",
"'Load perspective warp'",
",",
"patterns",
"=",
"[",
"'*.h5'",
"]",
")",
"if",
"response",
"is",
"not",
"None",
":",
"self",
".",
"warp_actor",
".",
"load",
... | Load warp projection settings from HDF file. | [
"Load",
"warp",
"projection",
"settings",
"from",
"HDF",
"file",
"."
] | train | https://github.com/cfobel/clutter-webcam-viewer/blob/b227d2ae02d750194e65c13bcf178550755c3afc/clutter_webcam_viewer/warp_control.py#L65-L71 |
Bystroushaak/zeo_connector | src/zeo_connector/transaction_manager.py | transaction_manager | def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manager_decorator(*args, **kwargs):
with transaction.manager:
return fn(*args, **kwargs)
return transaction_manager_decorator | python | def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manager_decorator(*args, **kwargs):
with transaction.manager:
return fn(*args, **kwargs)
return transaction_manager_decorator | [
"def",
"transaction_manager",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"transaction_manager_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"transaction",
".",
"manager",
":",
"return",
"fn",
"(",
"*",
"args",
... | Decorator which wraps whole function into ``with transaction.manager:``. | [
"Decorator",
"which",
"wraps",
"whole",
"function",
"into",
"with",
"transaction",
".",
"manager",
":",
"."
] | train | https://github.com/Bystroushaak/zeo_connector/blob/93f86447204efc8e33d3112907cd221daf6bce3b/src/zeo_connector/transaction_manager.py#L13-L22 |
tbobm/devscripts | devscripts/logs.py | simple_logger | def simple_logger(**kwargs):
"""
Creates a simple logger
:param str name: The logger's name ('api', 'back'...)
:param int base_level: Lowest level allowed to log (Default: DEBUG)
:param str log_format: Logging format used for STDOUT
(Default: logs.FORMAT)
:param bool... | python | def simple_logger(**kwargs):
"""
Creates a simple logger
:param str name: The logger's name ('api', 'back'...)
:param int base_level: Lowest level allowed to log (Default: DEBUG)
:param str log_format: Logging format used for STDOUT
(Default: logs.FORMAT)
:param bool... | [
"def",
"simple_logger",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Args",
"logger_name",
"=",
"kwargs",
".",
"get",
"(",
"'name'",
")",
"base_level",
"=",
"kwargs",
".",
"get",
"(",
"'base_level'",
",",
"logging",
".",
"DEBUG",
")",
"should_stdout",
"=",
"kwa... | Creates a simple logger
:param str name: The logger's name ('api', 'back'...)
:param int base_level: Lowest level allowed to log (Default: DEBUG)
:param str log_format: Logging format used for STDOUT
(Default: logs.FORMAT)
:param bool should_stdout: Allows to log to stdout (... | [
"Creates",
"a",
"simple",
"logger"
] | train | https://github.com/tbobm/devscripts/blob/beb23371ba80739afb5474766e8049ead3837925/devscripts/logs.py#L12-L49 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | compare_dicts | def compare_dicts(d1, d2):
"""
Returns a diff string of the two dicts.
"""
a = json.dumps(d1, indent=4, sort_keys=True)
b = json.dumps(d2, indent=4, sort_keys=True)
# stolen from cpython
# https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1... | python | def compare_dicts(d1, d2):
"""
Returns a diff string of the two dicts.
"""
a = json.dumps(d1, indent=4, sort_keys=True)
b = json.dumps(d2, indent=4, sort_keys=True)
# stolen from cpython
# https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1... | [
"def",
"compare_dicts",
"(",
"d1",
",",
"d2",
")",
":",
"a",
"=",
"json",
".",
"dumps",
"(",
"d1",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
"b",
"=",
"json",
".",
"dumps",
"(",
"d2",
",",
"indent",
"=",
"4",
",",
"sort_keys"... | Returns a diff string of the two dicts. | [
"Returns",
"a",
"diff",
"string",
"of",
"the",
"two",
"dicts",
"."
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L13-L24 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | stringer | def stringer(x):
"""
Takes an object and makes it stringy
>>> print(stringer({'a': 1, 2: 3, 'b': [1, 'c', 2.5]}))
{'b': ['1', 'c', '2.5'], 'a': '1', '2': '3'}
"""
if isinstance(x, string_types):
return x
if isinstance(x, (list, tuple)):
return [stringer(y) for y in x]
if ... | python | def stringer(x):
"""
Takes an object and makes it stringy
>>> print(stringer({'a': 1, 2: 3, 'b': [1, 'c', 2.5]}))
{'b': ['1', 'c', '2.5'], 'a': '1', '2': '3'}
"""
if isinstance(x, string_types):
return x
if isinstance(x, (list, tuple)):
return [stringer(y) for y in x]
if ... | [
"def",
"stringer",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"string_types",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"stringer",
"(",
"y",
")",
"for",
"y",
... | Takes an object and makes it stringy
>>> print(stringer({'a': 1, 2: 3, 'b': [1, 'c', 2.5]}))
{'b': ['1', 'c', '2.5'], 'a': '1', '2': '3'} | [
"Takes",
"an",
"object",
"and",
"makes",
"it",
"stringy",
">>>",
"print",
"(",
"stringer",
"(",
"{",
"a",
":",
"1",
"2",
":",
"3",
"b",
":",
"[",
"1",
"c",
"2",
".",
"5",
"]",
"}",
"))",
"{",
"b",
":",
"[",
"1",
"c",
"2",
".",
"5",
"]",
... | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L27-L39 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | diff_analysis | def diff_analysis(using):
"""
Returns a diff string comparing the analysis defined in ES, with
the analysis defined in Python land for the connection `using`
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
return compare_dicts(es_analysis, python_analysis... | python | def diff_analysis(using):
"""
Returns a diff string comparing the analysis defined in ES, with
the analysis defined in Python land for the connection `using`
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
return compare_dicts(es_analysis, python_analysis... | [
"def",
"diff_analysis",
"(",
"using",
")",
":",
"python_analysis",
"=",
"collect_analysis",
"(",
"using",
")",
"es_analysis",
"=",
"existing_analysis",
"(",
"using",
")",
"return",
"compare_dicts",
"(",
"es_analysis",
",",
"python_analysis",
")"
] | Returns a diff string comparing the analysis defined in ES, with
the analysis defined in Python land for the connection `using` | [
"Returns",
"a",
"diff",
"string",
"comparing",
"the",
"analysis",
"defined",
"in",
"ES",
"with",
"the",
"analysis",
"defined",
"in",
"Python",
"land",
"for",
"the",
"connection",
"using"
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L42-L49 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | collect_analysis | def collect_analysis(using):
"""
generate the analysis settings from Python land
"""
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) | python | def collect_analysis(using):
"""
generate the analysis settings from Python land
"""
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) | [
"def",
"collect_analysis",
"(",
"using",
")",
":",
"python_analysis",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"index",
"in",
"registry",
".",
"indexes_for_connection",
"(",
"using",
")",
":",
"python_analysis",
".",
"update",
"(",
"index",
".",
"_doc_type... | generate the analysis settings from Python land | [
"generate",
"the",
"analysis",
"settings",
"from",
"Python",
"land"
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L52-L60 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | existing_analysis | def existing_analysis(using):
"""
Get the existing analysis for the `using` Elasticsearch connection
"""
es = connections.get_connection(using)
index_name = settings.ELASTICSEARCH_CONNECTIONS[using]['index_name']
if es.indices.exists(index=index_name):
return stringer(es.indices.get_sett... | python | def existing_analysis(using):
"""
Get the existing analysis for the `using` Elasticsearch connection
"""
es = connections.get_connection(using)
index_name = settings.ELASTICSEARCH_CONNECTIONS[using]['index_name']
if es.indices.exists(index=index_name):
return stringer(es.indices.get_sett... | [
"def",
"existing_analysis",
"(",
"using",
")",
":",
"es",
"=",
"connections",
".",
"get_connection",
"(",
"using",
")",
"index_name",
"=",
"settings",
".",
"ELASTICSEARCH_CONNECTIONS",
"[",
"using",
"]",
"[",
"'index_name'",
"]",
"if",
"es",
".",
"indices",
... | Get the existing analysis for the `using` Elasticsearch connection | [
"Get",
"the",
"existing",
"analysis",
"for",
"the",
"using",
"Elasticsearch",
"connection"
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L63-L71 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | is_analysis_compatible | def is_analysis_compatible(using):
"""
Returns True if the analysis defined in Python land and ES for the connection `using` are compatible
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return True
# we want to... | python | def is_analysis_compatible(using):
"""
Returns True if the analysis defined in Python land and ES for the connection `using` are compatible
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return True
# we want to... | [
"def",
"is_analysis_compatible",
"(",
"using",
")",
":",
"python_analysis",
"=",
"collect_analysis",
"(",
"using",
")",
"es_analysis",
"=",
"existing_analysis",
"(",
"using",
")",
"if",
"es_analysis",
"==",
"DOES_NOT_EXIST",
":",
"return",
"True",
"# we want to ensu... | Returns True if the analysis defined in Python land and ES for the connection `using` are compatible | [
"Returns",
"True",
"if",
"the",
"analysis",
"defined",
"in",
"Python",
"land",
"and",
"ES",
"for",
"the",
"connection",
"using",
"are",
"compatible"
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L74-L102 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | combined_analysis | def combined_analysis(using):
"""
Combine the analysis in ES with the analysis defined in Python. The one in
Python takes precedence
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return python_analysis
# we... | python | def combined_analysis(using):
"""
Combine the analysis in ES with the analysis defined in Python. The one in
Python takes precedence
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return python_analysis
# we... | [
"def",
"combined_analysis",
"(",
"using",
")",
":",
"python_analysis",
"=",
"collect_analysis",
"(",
"using",
")",
"es_analysis",
"=",
"existing_analysis",
"(",
"using",
")",
"if",
"es_analysis",
"==",
"DOES_NOT_EXIST",
":",
"return",
"python_analysis",
"# we want t... | Combine the analysis in ES with the analysis defined in Python. The one in
Python takes precedence | [
"Combine",
"the",
"analysis",
"in",
"ES",
"with",
"the",
"analysis",
"defined",
"in",
"Python",
".",
"The",
"one",
"in",
"Python",
"takes",
"precedence"
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L105-L126 |
xethorn/oto | oto/adaptors/flask.py | flaskify | def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Arg... | python | def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Arg... | [
"def",
"flaskify",
"(",
"response",
",",
"headers",
"=",
"None",
",",
"encoder",
"=",
"None",
")",
":",
"status_code",
"=",
"response",
".",
"status",
"data",
"=",
"response",
".",
"errors",
"or",
"response",
".",
"message",
"mimetype",
"=",
"'text/plain'"... | Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Args:
response (Response): The dictionary object to co... | [
"Format",
"the",
"response",
"to",
"be",
"consumeable",
"by",
"flask",
"."
] | train | https://github.com/xethorn/oto/blob/2a76d374ccc4c85fdf81ae1c43698a94c0594d7b/oto/adaptors/flask.py#L6-L34 |
hitchtest/hitchserve | hitchserve/service_handle.py | ServiceHandle.stop | def stop(self):
"""Ask politely, first, with SIGINT and SIGQUIT."""
if hasattr(self, 'process'):
if self.process is not None:
try:
is_running = self.process.poll() is None
except AttributeError:
is_running = False
... | python | def stop(self):
"""Ask politely, first, with SIGINT and SIGQUIT."""
if hasattr(self, 'process'):
if self.process is not None:
try:
is_running = self.process.poll() is None
except AttributeError:
is_running = False
... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'process'",
")",
":",
"if",
"self",
".",
"process",
"is",
"not",
"None",
":",
"try",
":",
"is_running",
"=",
"self",
".",
"process",
".",
"poll",
"(",
")",
"is",
"None",
"e... | Ask politely, first, with SIGINT and SIGQUIT. | [
"Ask",
"politely",
"first",
"with",
"SIGINT",
"and",
"SIGQUIT",
"."
] | train | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_handle.py#L101-L133 |
hitchtest/hitchserve | hitchserve/service_handle.py | ServiceHandle.kill | def kill(self):
"""Murder the children of this service in front of it, and then murder the service itself."""
if not self.is_dead():
self.bundle_engine.warnline("{0} did not shut down cleanly, killing.".format(self.service.name))
try:
if hasattr(self.process, 'pid... | python | def kill(self):
"""Murder the children of this service in front of it, and then murder the service itself."""
if not self.is_dead():
self.bundle_engine.warnline("{0} did not shut down cleanly, killing.".format(self.service.name))
try:
if hasattr(self.process, 'pid... | [
"def",
"kill",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_dead",
"(",
")",
":",
"self",
".",
"bundle_engine",
".",
"warnline",
"(",
"\"{0} did not shut down cleanly, killing.\"",
".",
"format",
"(",
"self",
".",
"service",
".",
"name",
")",
")",
... | Murder the children of this service in front of it, and then murder the service itself. | [
"Murder",
"the",
"children",
"of",
"this",
"service",
"in",
"front",
"of",
"it",
"and",
"then",
"murder",
"the",
"service",
"itself",
"."
] | train | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_handle.py#L144-L154 |
abe-winter/pg13-py | pg13/pgmock.py | TablesDict.tempkeys | def tempkeys(self):
"""Add a new level to make new keys temporary. Used instead of copy in sqex.
This may *seem* similar to a transaction but the tables are not being duplicated, just referenced.
At __exit__, old dict is restored (but changes to Tables remain).
"""
self.levels.append(dict(self.... | python | def tempkeys(self):
"""Add a new level to make new keys temporary. Used instead of copy in sqex.
This may *seem* similar to a transaction but the tables are not being duplicated, just referenced.
At __exit__, old dict is restored (but changes to Tables remain).
"""
self.levels.append(dict(self.... | [
"def",
"tempkeys",
"(",
"self",
")",
":",
"self",
".",
"levels",
".",
"append",
"(",
"dict",
"(",
"self",
".",
"levels",
"[",
"-",
"1",
"]",
")",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"levels",
".",
"pop",
"(",
")"
] | Add a new level to make new keys temporary. Used instead of copy in sqex.
This may *seem* similar to a transaction but the tables are not being duplicated, just referenced.
At __exit__, old dict is restored (but changes to Tables remain). | [
"Add",
"a",
"new",
"level",
"to",
"make",
"new",
"keys",
"temporary",
".",
"Used",
"instead",
"of",
"copy",
"in",
"sqex",
".",
"This",
"may",
"*",
"seem",
"*",
"similar",
"to",
"a",
"transaction",
"but",
"the",
"tables",
"are",
"not",
"being",
"duplica... | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock.py#L28-L35 |
abe-winter/pg13-py | pg13/pgmock.py | TablesDict.cascade_delete | def cascade_delete(self, name):
"this fails under diamond inheritance"
for child in self[name].child_tables:
self.cascade_delete(child.name)
del self[name] | python | def cascade_delete(self, name):
"this fails under diamond inheritance"
for child in self[name].child_tables:
self.cascade_delete(child.name)
del self[name] | [
"def",
"cascade_delete",
"(",
"self",
",",
"name",
")",
":",
"for",
"child",
"in",
"self",
"[",
"name",
"]",
".",
"child_tables",
":",
"self",
".",
"cascade_delete",
"(",
"child",
".",
"name",
")",
"del",
"self",
"[",
"name",
"]"
] | this fails under diamond inheritance | [
"this",
"fails",
"under",
"diamond",
"inheritance"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock.py#L66-L70 |
abe-winter/pg13-py | pg13/pgmock.py | TablesDict.create | def create(self, ex):
"helper for apply_sql in CreateX case"
if ex.name in self:
if ex.nexists: return
raise ValueError('table_exists',ex.name)
if any(c.pkey for c in ex.cols):
if ex.pkey:
raise sqparse2.SQLSyntaxError("don't mix table-level and column-level pkeys",ex)
... | python | def create(self, ex):
"helper for apply_sql in CreateX case"
if ex.name in self:
if ex.nexists: return
raise ValueError('table_exists',ex.name)
if any(c.pkey for c in ex.cols):
if ex.pkey:
raise sqparse2.SQLSyntaxError("don't mix table-level and column-level pkeys",ex)
... | [
"def",
"create",
"(",
"self",
",",
"ex",
")",
":",
"if",
"ex",
".",
"name",
"in",
"self",
":",
"if",
"ex",
".",
"nexists",
":",
"return",
"raise",
"ValueError",
"(",
"'table_exists'",
",",
"ex",
".",
"name",
")",
"if",
"any",
"(",
"c",
".",
"pkey... | helper for apply_sql in CreateX case | [
"helper",
"for",
"apply_sql",
"in",
"CreateX",
"case"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock.py#L72-L90 |
abe-winter/pg13-py | pg13/pgmock.py | TablesDict.drop | def drop(self, ex):
"helper for apply_sql in DropX case"
# todo: factor out inheritance logic (for readability)
if ex.name not in self:
if ex.ifexists: return
raise KeyError(ex.name)
table_ = self[ex.name]
parent = table_.parent_table
if table_.child_tables:
if not ex.... | python | def drop(self, ex):
"helper for apply_sql in DropX case"
# todo: factor out inheritance logic (for readability)
if ex.name not in self:
if ex.ifexists: return
raise KeyError(ex.name)
table_ = self[ex.name]
parent = table_.parent_table
if table_.child_tables:
if not ex.... | [
"def",
"drop",
"(",
"self",
",",
"ex",
")",
":",
"# todo: factor out inheritance logic (for readability)\r",
"if",
"ex",
".",
"name",
"not",
"in",
"self",
":",
"if",
"ex",
".",
"ifexists",
":",
"return",
"raise",
"KeyError",
"(",
"ex",
".",
"name",
")",
"t... | helper for apply_sql in DropX case | [
"helper",
"for",
"apply_sql",
"in",
"DropX",
"case"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock.py#L92-L105 |
abe-winter/pg13-py | pg13/pgmock.py | TablesDict.apply_sql | def apply_sql(self, ex, values, lockref):
"""call the stmt in tree with values subbed on the tables in t_d.
ex is a parsed statement returned by parse_expression.
values is the tuple of %s replacements.
lockref can be anything as long as it stays the same; it's used for assigning tranaction ownershi... | python | def apply_sql(self, ex, values, lockref):
"""call the stmt in tree with values subbed on the tables in t_d.
ex is a parsed statement returned by parse_expression.
values is the tuple of %s replacements.
lockref can be anything as long as it stays the same; it's used for assigning tranaction ownershi... | [
"def",
"apply_sql",
"(",
"self",
",",
"ex",
",",
"values",
",",
"lockref",
")",
":",
"sqex",
".",
"depth_first_sub",
"(",
"ex",
",",
"values",
")",
"with",
"self",
".",
"lock_db",
"(",
"lockref",
",",
"isinstance",
"(",
"ex",
",",
"sqparse2",
".",
"S... | call the stmt in tree with values subbed on the tables in t_d.
ex is a parsed statement returned by parse_expression.
values is the tuple of %s replacements.
lockref can be anything as long as it stays the same; it's used for assigning tranaction ownership.
(safest is to make it a pgmock_dbapi2.Co... | [
"call",
"the",
"stmt",
"in",
"tree",
"with",
"values",
"subbed",
"on",
"the",
"tables",
"in",
"t_d",
".",
"ex",
"is",
"a",
"parsed",
"statement",
"returned",
"by",
"parse_expression",
".",
"values",
"is",
"the",
"tuple",
"of",
"%s",
"replacements",
".",
... | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock.py#L107-L129 |
amcfague/webunit2 | webunit2/framework.py | Framework._prepare_basicauth | def _prepare_basicauth(self, username, password):
"""
Handles BasicAuth preparation and error handling. Either both
``username`` and ``password`` must be defined, or neither. Defining
one but not the other will result in an :class:`AssertionError`.
``username``
``passw... | python | def _prepare_basicauth(self, username, password):
"""
Handles BasicAuth preparation and error handling. Either both
``username`` and ``password`` must be defined, or neither. Defining
one but not the other will result in an :class:`AssertionError`.
``username``
``passw... | [
"def",
"_prepare_basicauth",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"if",
"username",
"and",
"password",
":",
"enc_str",
"=",
"base64",
".",
"b64encode",
"(",
"\":\"",
".",
"join",
"(",
"(",
"username",
",",
"password",
")",
")",
")",
... | Handles BasicAuth preparation and error handling. Either both
``username`` and ``password`` must be defined, or neither. Defining
one but not the other will result in an :class:`AssertionError`.
``username``
``password``
Returns a tuple of ``(header_key, header_value)`` which... | [
"Handles",
"BasicAuth",
"preparation",
"and",
"error",
"handling",
".",
"Either",
"both",
"username",
"and",
"password",
"must",
"be",
"defined",
"or",
"neither",
".",
"Defining",
"one",
"but",
"not",
"the",
"other",
"will",
"result",
"in",
"an",
":",
"class... | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/framework.py#L49-L67 |
amcfague/webunit2 | webunit2/framework.py | Framework._prepare_uri | def _prepare_uri(self, path, query_params={}):
"""
Prepares a full URI with the selected information.
``path``:
Path can be in one of two formats:
- If :attr:`server` was defined, the ``path`` will be appended
to the existing host, or
... | python | def _prepare_uri(self, path, query_params={}):
"""
Prepares a full URI with the selected information.
``path``:
Path can be in one of two formats:
- If :attr:`server` was defined, the ``path`` will be appended
to the existing host, or
... | [
"def",
"_prepare_uri",
"(",
"self",
",",
"path",
",",
"query_params",
"=",
"{",
"}",
")",
":",
"query_str",
"=",
"urllib",
".",
"urlencode",
"(",
"query_params",
")",
"# If we have a relative path (as opposed to a full URL), build it of",
"# the connection info",
"if",
... | Prepares a full URI with the selected information.
``path``:
Path can be in one of two formats:
- If :attr:`server` was defined, the ``path`` will be appended
to the existing host, or
- an absolute URL
``query_params``:
Used to ... | [
"Prepares",
"a",
"full",
"URI",
"with",
"the",
"selected",
"information",
"."
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/framework.py#L69-L97 |
amcfague/webunit2 | webunit2/framework.py | Framework._make_request | def _make_request(self, uri, method, body, headers={}):
"""
Wraps the response and content returned by :mod:`httplib2` into a
:class:`~webunit2.response.HttpResponse` object.
``uri``:
Absolute URI to the resource.
``method``:
Any supported HTTP methods de... | python | def _make_request(self, uri, method, body, headers={}):
"""
Wraps the response and content returned by :mod:`httplib2` into a
:class:`~webunit2.response.HttpResponse` object.
``uri``:
Absolute URI to the resource.
``method``:
Any supported HTTP methods de... | [
"def",
"_make_request",
"(",
"self",
",",
"uri",
",",
"method",
",",
"body",
",",
"headers",
"=",
"{",
"}",
")",
":",
"response",
",",
"content",
"=",
"self",
".",
"_httpobj",
".",
"request",
"(",
"uri",
",",
"method",
"=",
"method",
",",
"body",
"... | Wraps the response and content returned by :mod:`httplib2` into a
:class:`~webunit2.response.HttpResponse` object.
``uri``:
Absolute URI to the resource.
``method``:
Any supported HTTP methods defined in :rfc:`2616`.
``body``:
In the case of POST and ... | [
"Wraps",
"the",
"response",
"and",
"content",
"returned",
"by",
":",
"mod",
":",
"httplib2",
"into",
"a",
":",
"class",
":",
"~webunit2",
".",
"response",
".",
"HttpResponse",
"object",
"."
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/framework.py#L99-L120 |
amcfague/webunit2 | webunit2/framework.py | Framework.retrieve_page | def retrieve_page(self, method, path, post_params={}, headers={},
status=200, username=None, password=None,
*args, **kwargs):
"""
Makes the actual request. This will also go through and generate the
needed steps to make the request, i.e. basic auth.
... | python | def retrieve_page(self, method, path, post_params={}, headers={},
status=200, username=None, password=None,
*args, **kwargs):
"""
Makes the actual request. This will also go through and generate the
needed steps to make the request, i.e. basic auth.
... | [
"def",
"retrieve_page",
"(",
"self",
",",
"method",
",",
"path",
",",
"post_params",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"status",
"=",
"200",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"args",
",",
"*",
... | Makes the actual request. This will also go through and generate the
needed steps to make the request, i.e. basic auth.
``method``:
Any supported HTTP methods defined in :rfc:`2616`.
``path``:
Absolute or relative path. See :meth:`_prepare_uri` for more
deta... | [
"Makes",
"the",
"actual",
"request",
".",
"This",
"will",
"also",
"go",
"through",
"and",
"generate",
"the",
"needed",
"steps",
"to",
"make",
"the",
"request",
"i",
".",
"e",
".",
"basic",
"auth",
"."
] | train | https://github.com/amcfague/webunit2/blob/3157e5837aad0810800628c1383f1fe11ee3e513/webunit2/framework.py#L122-L179 |
ojake/django-tracked-model | tracked_model/control.py | create_track_token | def create_track_token(request):
"""Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called fro... | python | def create_track_token(request):
"""Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called fro... | [
"def",
"create_track_token",
"(",
"request",
")",
":",
"from",
"tracked_model",
".",
"models",
"import",
"RequestInfo",
"request_pk",
"=",
"RequestInfo",
".",
"create_or_get_from_request",
"(",
"request",
")",
".",
"pk",
"user_pk",
"=",
"None",
"if",
"request",
... | Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called from celery task. | [
"Returns",
"TrackToken",
".",
"TrackToken",
"contains",
"request",
"and",
"user",
"making",
"changes",
"."
] | train | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/control.py#L7-L21 |
ojake/django-tracked-model | tracked_model/control.py | TrackedModelMixin.save | def save(self, *args, **kwargs):
"""Saves changes made on model instance if ``request`` or
``track_token`` keyword are provided.
"""
from tracked_model.models import History, RequestInfo
if self.pk:
action = ActionType.UPDATE
changes = None
else:
... | python | def save(self, *args, **kwargs):
"""Saves changes made on model instance if ``request`` or
``track_token`` keyword are provided.
"""
from tracked_model.models import History, RequestInfo
if self.pk:
action = ActionType.UPDATE
changes = None
else:
... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"tracked_model",
".",
"models",
"import",
"History",
",",
"RequestInfo",
"if",
"self",
".",
"pk",
":",
"action",
"=",
"ActionType",
".",
"UPDATE",
"changes",
"=",
... | Saves changes made on model instance if ``request`` or
``track_token`` keyword are provided. | [
"Saves",
"changes",
"made",
"on",
"model",
"instance",
"if",
"request",
"or",
"track_token",
"keyword",
"are",
"provided",
"."
] | train | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/control.py#L38-L76 |
ojake/django-tracked-model | tracked_model/control.py | TrackedModelMixin._tracked_model_diff | def _tracked_model_diff(self):
"""Returns changes made to model instance.
Returns None if no changes were made.
"""
initial_state = self._tracked_model_initial_state
current_state = serializer.dump_model(self)
if current_state == initial_state:
return None
... | python | def _tracked_model_diff(self):
"""Returns changes made to model instance.
Returns None if no changes were made.
"""
initial_state = self._tracked_model_initial_state
current_state = serializer.dump_model(self)
if current_state == initial_state:
return None
... | [
"def",
"_tracked_model_diff",
"(",
"self",
")",
":",
"initial_state",
"=",
"self",
".",
"_tracked_model_initial_state",
"current_state",
"=",
"serializer",
".",
"dump_model",
"(",
"self",
")",
"if",
"current_state",
"==",
"initial_state",
":",
"return",
"None",
"c... | Returns changes made to model instance.
Returns None if no changes were made. | [
"Returns",
"changes",
"made",
"to",
"model",
"instance",
".",
"Returns",
"None",
"if",
"no",
"changes",
"were",
"made",
"."
] | train | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/control.py#L103-L124 |
ojake/django-tracked-model | tracked_model/control.py | TrackedModelMixin.tracked_model_history | def tracked_model_history(self):
"""Returns history of a tracked object"""
from tracked_model.models import History
return History.objects.filter(
table_name=self._meta.db_table, table_id=self.pk) | python | def tracked_model_history(self):
"""Returns history of a tracked object"""
from tracked_model.models import History
return History.objects.filter(
table_name=self._meta.db_table, table_id=self.pk) | [
"def",
"tracked_model_history",
"(",
"self",
")",
":",
"from",
"tracked_model",
".",
"models",
"import",
"History",
"return",
"History",
".",
"objects",
".",
"filter",
"(",
"table_name",
"=",
"self",
".",
"_meta",
".",
"db_table",
",",
"table_id",
"=",
"self... | Returns history of a tracked object | [
"Returns",
"history",
"of",
"a",
"tracked",
"object"
] | train | https://github.com/ojake/django-tracked-model/blob/19bc48874dd2e5fb5defedc6b8c5c3915cce1424/tracked_model/control.py#L126-L130 |
foliant-docs/foliantcontrib.init | foliant/cli/init/__init__.py | replace_placeholders | def replace_placeholders(path: Path, properties: Dict[str, str]):
'''Replace placeholders in a file with the values from the mapping.'''
with open(path, encoding='utf8') as file:
file_content = Template(file.read())
with open(path, 'w', encoding='utf8') as file:
file.write(file_content.saf... | python | def replace_placeholders(path: Path, properties: Dict[str, str]):
'''Replace placeholders in a file with the values from the mapping.'''
with open(path, encoding='utf8') as file:
file_content = Template(file.read())
with open(path, 'w', encoding='utf8') as file:
file.write(file_content.saf... | [
"def",
"replace_placeholders",
"(",
"path",
":",
"Path",
",",
"properties",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
":",
"with",
"open",
"(",
"path",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"file",
":",
"file_content",
"=",
"Template",
"(",
... | Replace placeholders in a file with the values from the mapping. | [
"Replace",
"placeholders",
"in",
"a",
"file",
"with",
"the",
"values",
"from",
"the",
"mapping",
"."
] | train | https://github.com/foliant-docs/foliantcontrib.init/blob/39aa38949b6270a750c800b79b4e71dd827f28d8/foliant/cli/init/__init__.py#L41-L48 |
foliant-docs/foliantcontrib.init | foliant/cli/init/__init__.py | BuiltinTemplateValidator.validate | def validate(self, document):
'''Check if the selected template exists.'''
template = document.text
if template not in self.builtin_templates:
raise ValidationError(
message=f'Template {template} not found. '
+ f'Available templates are: {", ".join(s... | python | def validate(self, document):
'''Check if the selected template exists.'''
template = document.text
if template not in self.builtin_templates:
raise ValidationError(
message=f'Template {template} not found. '
+ f'Available templates are: {", ".join(s... | [
"def",
"validate",
"(",
"self",
",",
"document",
")",
":",
"template",
"=",
"document",
".",
"text",
"if",
"template",
"not",
"in",
"self",
".",
"builtin_templates",
":",
"raise",
"ValidationError",
"(",
"message",
"=",
"f'Template {template} not found. '",
"+",... | Check if the selected template exists. | [
"Check",
"if",
"the",
"selected",
"template",
"exists",
"."
] | train | https://github.com/foliant-docs/foliantcontrib.init/blob/39aa38949b6270a750c800b79b4e71dd827f28d8/foliant/cli/init/__init__.py#L28-L38 |
foliant-docs/foliantcontrib.init | foliant/cli/init/__init__.py | Cli.init | def init(self, project_name='', template='base', quiet=False, debug=False):
'''Generate new Foliant project.'''
self.logger.setLevel(DEBUG if debug else WARNING)
self.logger.info('Project creation started.')
self.logger.debug(f'Template: {template}')
template_path = Path(temp... | python | def init(self, project_name='', template='base', quiet=False, debug=False):
'''Generate new Foliant project.'''
self.logger.setLevel(DEBUG if debug else WARNING)
self.logger.info('Project creation started.')
self.logger.debug(f'Template: {template}')
template_path = Path(temp... | [
"def",
"init",
"(",
"self",
",",
"project_name",
"=",
"''",
",",
"template",
"=",
"'base'",
",",
"quiet",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"self",
".",
"logger",
".",
"setLevel",
"(",
"DEBUG",
"if",
"debug",
"else",
"WARNING",
")",... | Generate new Foliant project. | [
"Generate",
"new",
"Foliant",
"project",
"."
] | train | https://github.com/foliant-docs/foliantcontrib.init/blob/39aa38949b6270a750c800b79b4e71dd827f28d8/foliant/cli/init/__init__.py#L62-L161 |
aptiko/simpletail | simpletail/__init__.py | ropen.get_start_of_line | def get_start_of_line(self):
"""Return index of start of last line stored in self.buf.
This function never fetches more data from the file; therefore,
if it returns zero, meaning the line starts at the beginning of the
buffer, the caller should then fetch more data and retry.
"""... | python | def get_start_of_line(self):
"""Return index of start of last line stored in self.buf.
This function never fetches more data from the file; therefore,
if it returns zero, meaning the line starts at the beginning of the
buffer, the caller should then fetch more data and retry.
"""... | [
"def",
"get_start_of_line",
"(",
"self",
")",
":",
"if",
"self",
".",
"newline",
"in",
"(",
"'\\r'",
",",
"'\\n'",
",",
"'\\r\\n'",
")",
":",
"return",
"self",
".",
"buf",
".",
"rfind",
"(",
"self",
".",
"newline",
".",
"encode",
"(",
"'ascii'",
")",... | Return index of start of last line stored in self.buf.
This function never fetches more data from the file; therefore,
if it returns zero, meaning the line starts at the beginning of the
buffer, the caller should then fetch more data and retry. | [
"Return",
"index",
"of",
"start",
"of",
"last",
"line",
"stored",
"in",
"self",
".",
"buf",
".",
"This",
"function",
"never",
"fetches",
"more",
"data",
"from",
"the",
"file",
";",
"therefore",
"if",
"it",
"returns",
"zero",
"meaning",
"the",
"line",
"st... | train | https://github.com/aptiko/simpletail/blob/4ebe31950c9a3b7fac243dc83afd915894ce678f/simpletail/__init__.py#L59-L76 |
aptiko/simpletail | simpletail/__init__.py | ropen.read_next_into_buf | def read_next_into_buf(self):
"""Read data from the file in self.bufsize chunks until we're
certain we have a full line in the buffer.
"""
file_pos = self.fileobject.tell()
if (file_pos == 0) and (self.buf == b''):
raise StopIteration
while file_pos and (se... | python | def read_next_into_buf(self):
"""Read data from the file in self.bufsize chunks until we're
certain we have a full line in the buffer.
"""
file_pos = self.fileobject.tell()
if (file_pos == 0) and (self.buf == b''):
raise StopIteration
while file_pos and (se... | [
"def",
"read_next_into_buf",
"(",
"self",
")",
":",
"file_pos",
"=",
"self",
".",
"fileobject",
".",
"tell",
"(",
")",
"if",
"(",
"file_pos",
"==",
"0",
")",
"and",
"(",
"self",
".",
"buf",
"==",
"b''",
")",
":",
"raise",
"StopIteration",
"while",
"f... | Read data from the file in self.bufsize chunks until we're
certain we have a full line in the buffer. | [
"Read",
"data",
"from",
"the",
"file",
"in",
"self",
".",
"bufsize",
"chunks",
"until",
"we",
"re",
"certain",
"we",
"have",
"a",
"full",
"line",
"in",
"the",
"buffer",
"."
] | train | https://github.com/aptiko/simpletail/blob/4ebe31950c9a3b7fac243dc83afd915894ce678f/simpletail/__init__.py#L78-L91 |
jimklo/pyiso8601plus | iso8601/iso8601.py | parse_timezone | def parse_timezone(tzstring, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if tzstring == "Z":
return default_timezone
# This isn't strictly correct, but it's common to encounter dates without
# timezones so I'll assume the default (which defaults to ... | python | def parse_timezone(tzstring, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if tzstring == "Z":
return default_timezone
# This isn't strictly correct, but it's common to encounter dates without
# timezones so I'll assume the default (which defaults to ... | [
"def",
"parse_timezone",
"(",
"tzstring",
",",
"default_timezone",
"=",
"UTC",
")",
":",
"if",
"tzstring",
"==",
"\"Z\"",
":",
"return",
"default_timezone",
"# This isn't strictly correct, but it's common to encounter dates without",
"# timezones so I'll assume the default (which... | Parses ISO 8601 time zone specs into tzinfo offsets | [
"Parses",
"ISO",
"8601",
"time",
"zone",
"specs",
"into",
"tzinfo",
"offsets"
] | train | https://github.com/jimklo/pyiso8601plus/blob/b1bd0741d15a14aecbce8ccafc21625405cef6fc/iso8601/iso8601.py#L64-L81 |
jimklo/pyiso8601plus | iso8601/iso8601.py | parse_date | def parse_date(datestring, default_timezone=UTC):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used. ... | python | def parse_date(datestring, default_timezone=UTC):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used. ... | [
"def",
"parse_date",
"(",
"datestring",
",",
"default_timezone",
"=",
"UTC",
")",
":",
"if",
"not",
"isinstance",
"(",
"datestring",
",",
"basestring",
")",
":",
"raise",
"ParseError",
"(",
"\"Expecting a string %r\"",
"%",
"datestring",
")",
"m",
"=",
"ISO860... | Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used. This is UTC by
default. | [
"Parses",
"ISO",
"8601",
"dates",
"into",
"datetime",
"objects",
"The",
"timezone",
"is",
"parsed",
"from",
"the",
"date",
"string",
".",
"However",
"it",
"is",
"quite",
"common",
"to",
"have",
"dates",
"without",
"a",
"timezone",
"(",
"not",
"strictly",
"... | train | https://github.com/jimklo/pyiso8601plus/blob/b1bd0741d15a14aecbce8ccafc21625405cef6fc/iso8601/iso8601.py#L83-L108 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | tree_handler | def tree_handler(*args, **kwargs):
"""
Singleton `TreeHandler` generator. Any arguments are given to
:class:`TreeHandler`, when it is first created.
Returns:
obj: :class:`TreeHandler` instance.
"""
global _TREE_HANDLER
if not _TREE_HANDLER:
_TREE_HANDLER = TreeHandler(*args... | python | def tree_handler(*args, **kwargs):
"""
Singleton `TreeHandler` generator. Any arguments are given to
:class:`TreeHandler`, when it is first created.
Returns:
obj: :class:`TreeHandler` instance.
"""
global _TREE_HANDLER
if not _TREE_HANDLER:
_TREE_HANDLER = TreeHandler(*args... | [
"def",
"tree_handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_TREE_HANDLER",
"if",
"not",
"_TREE_HANDLER",
":",
"_TREE_HANDLER",
"=",
"TreeHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_TREE_HANDLER"
] | Singleton `TreeHandler` generator. Any arguments are given to
:class:`TreeHandler`, when it is first created.
Returns:
obj: :class:`TreeHandler` instance. | [
"Singleton",
"TreeHandler",
"generator",
".",
"Any",
"arguments",
"are",
"given",
"to",
":",
"class",
":",
"TreeHandler",
"when",
"it",
"is",
"first",
"created",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L281-L294 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler._add_to | def _add_to(self, db, index, item, default=OOSet):
"""
Add `item` to `db` under `index`. If `index` is not yet in `db`, create
it using `default`.
Args:
db (dict-obj): Dict-like object used to connect to database.
index (str): Index used to look in `db`.
... | python | def _add_to(self, db, index, item, default=OOSet):
"""
Add `item` to `db` under `index`. If `index` is not yet in `db`, create
it using `default`.
Args:
db (dict-obj): Dict-like object used to connect to database.
index (str): Index used to look in `db`.
... | [
"def",
"_add_to",
"(",
"self",
",",
"db",
",",
"index",
",",
"item",
",",
"default",
"=",
"OOSet",
")",
":",
"row",
"=",
"db",
".",
"get",
"(",
"index",
",",
"None",
")",
"if",
"row",
"is",
"None",
":",
"row",
"=",
"default",
"(",
")",
"db",
... | Add `item` to `db` under `index`. If `index` is not yet in `db`, create
it using `default`.
Args:
db (dict-obj): Dict-like object used to connect to database.
index (str): Index used to look in `db`.
item (obj): Persistent object, which may be stored in DB.
... | [
"Add",
"item",
"to",
"db",
"under",
"index",
".",
"If",
"index",
"is",
"not",
"yet",
"in",
"db",
"create",
"it",
"using",
"default",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L73-L92 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler.add_tree | def add_tree(self, tree, parent=None):
"""
Add `tree` into database.
Args:
tree (obj): :class:`.Tree` instance.
parent (ref, default None): Reference to parent tree. This is used
for all sub-trees in recursive call.
"""
if tree.path in sel... | python | def add_tree(self, tree, parent=None):
"""
Add `tree` into database.
Args:
tree (obj): :class:`.Tree` instance.
parent (ref, default None): Reference to parent tree. This is used
for all sub-trees in recursive call.
"""
if tree.path in sel... | [
"def",
"add_tree",
"(",
"self",
",",
"tree",
",",
"parent",
"=",
"None",
")",
":",
"if",
"tree",
".",
"path",
"in",
"self",
".",
"path_db",
":",
"self",
".",
"remove_tree_by_path",
"(",
"tree",
".",
"path",
")",
"# index all indexable attributes",
"for",
... | Add `tree` into database.
Args:
tree (obj): :class:`.Tree` instance.
parent (ref, default None): Reference to parent tree. This is used
for all sub-trees in recursive call. | [
"Add",
"tree",
"into",
"database",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L95-L126 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler.remove_tree_by_path | def remove_tree_by_path(self, path):
"""
Remove the tree from database by given `path`.
Args:
path (str): Path of the tree.
"""
with transaction.manager:
trees = self.path_db.get(path, None)
if not trees:
return
for tree in t... | python | def remove_tree_by_path(self, path):
"""
Remove the tree from database by given `path`.
Args:
path (str): Path of the tree.
"""
with transaction.manager:
trees = self.path_db.get(path, None)
if not trees:
return
for tree in t... | [
"def",
"remove_tree_by_path",
"(",
"self",
",",
"path",
")",
":",
"with",
"transaction",
".",
"manager",
":",
"trees",
"=",
"self",
".",
"path_db",
".",
"get",
"(",
"path",
",",
"None",
")",
"if",
"not",
"trees",
":",
"return",
"for",
"tree",
"in",
"... | Remove the tree from database by given `path`.
Args:
path (str): Path of the tree. | [
"Remove",
"the",
"tree",
"from",
"database",
"by",
"given",
"path",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L128-L142 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler._remove_from | def _remove_from(self, db, index, item):
"""
Remove `item` from `db` at `index`.
Note:
This function is inverse to :meth:`._add_to`.
Args:
db (dict-obj): Dict-like object used to connect to database.
index (str): Index used to look in `db`.
... | python | def _remove_from(self, db, index, item):
"""
Remove `item` from `db` at `index`.
Note:
This function is inverse to :meth:`._add_to`.
Args:
db (dict-obj): Dict-like object used to connect to database.
index (str): Index used to look in `db`.
... | [
"def",
"_remove_from",
"(",
"self",
",",
"db",
",",
"index",
",",
"item",
")",
":",
"with",
"transaction",
".",
"manager",
":",
"row",
"=",
"db",
".",
"get",
"(",
"index",
",",
"None",
")",
"if",
"row",
"is",
"None",
":",
"return",
"with",
"transac... | Remove `item` from `db` at `index`.
Note:
This function is inverse to :meth:`._add_to`.
Args:
db (dict-obj): Dict-like object used to connect to database.
index (str): Index used to look in `db`.
item (obj): Persistent object, which may be stored in DB. | [
"Remove",
"item",
"from",
"db",
"at",
"index",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L153-L177 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler._remove_tree | def _remove_tree(self, tree, parent=None):
"""
Really remove the tree identified by `tree` instance from all indexes
from database.
Args:
tree (obj): :class:`.Tree` instance.
parent (obj, default None): Reference to parent.
"""
# remove sub-trees
... | python | def _remove_tree(self, tree, parent=None):
"""
Really remove the tree identified by `tree` instance from all indexes
from database.
Args:
tree (obj): :class:`.Tree` instance.
parent (obj, default None): Reference to parent.
"""
# remove sub-trees
... | [
"def",
"_remove_tree",
"(",
"self",
",",
"tree",
",",
"parent",
"=",
"None",
")",
":",
"# remove sub-trees",
"for",
"sub_tree",
"in",
"tree",
".",
"sub_trees",
":",
"self",
".",
"_remove_tree",
"(",
"sub_tree",
",",
"parent",
"=",
"tree",
")",
"# remove it... | Really remove the tree identified by `tree` instance from all indexes
from database.
Args:
tree (obj): :class:`.Tree` instance.
parent (obj, default None): Reference to parent. | [
"Really",
"remove",
"the",
"tree",
"identified",
"by",
"tree",
"instance",
"from",
"all",
"indexes",
"from",
"database",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L180-L207 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler.trees_by_issn | def trees_by_issn(self, issn):
"""
Search trees by `issn`.
Args:
issn (str): :attr:`.Tree.issn` property of :class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances.
"""
return set(
self.issn_db.get(issn, OOSet()).keys()
... | python | def trees_by_issn(self, issn):
"""
Search trees by `issn`.
Args:
issn (str): :attr:`.Tree.issn` property of :class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances.
"""
return set(
self.issn_db.get(issn, OOSet()).keys()
... | [
"def",
"trees_by_issn",
"(",
"self",
",",
"issn",
")",
":",
"return",
"set",
"(",
"self",
".",
"issn_db",
".",
"get",
"(",
"issn",
",",
"OOSet",
"(",
")",
")",
".",
"keys",
"(",
")",
")"
] | Search trees by `issn`.
Args:
issn (str): :attr:`.Tree.issn` property of :class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances. | [
"Search",
"trees",
"by",
"issn",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L210-L222 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler.trees_by_path | def trees_by_path(self, path):
"""
Search trees by `path`.
Args:
path (str): :attr:`.Tree.path` property of :class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances.
"""
return set(
self.path_db.get(path, OOSet()).keys()
... | python | def trees_by_path(self, path):
"""
Search trees by `path`.
Args:
path (str): :attr:`.Tree.path` property of :class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances.
"""
return set(
self.path_db.get(path, OOSet()).keys()
... | [
"def",
"trees_by_path",
"(",
"self",
",",
"path",
")",
":",
"return",
"set",
"(",
"self",
".",
"path_db",
".",
"get",
"(",
"path",
",",
"OOSet",
"(",
")",
")",
".",
"keys",
"(",
")",
")"
] | Search trees by `path`.
Args:
path (str): :attr:`.Tree.path` property of :class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances. | [
"Search",
"trees",
"by",
"path",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L225-L237 |
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler.trees_by_subpath | def trees_by_subpath(self, sub_path):
"""
Search trees by `sub_path` using ``Tree.path.startswith(sub_path)``
comparison.
Args:
sub_path (str): Part of the :attr:`.Tree.path` property of
:class:`.Tree`.
Returns:
set: Set of matching :clas... | python | def trees_by_subpath(self, sub_path):
"""
Search trees by `sub_path` using ``Tree.path.startswith(sub_path)``
comparison.
Args:
sub_path (str): Part of the :attr:`.Tree.path` property of
:class:`.Tree`.
Returns:
set: Set of matching :clas... | [
"def",
"trees_by_subpath",
"(",
"self",
",",
"sub_path",
")",
":",
"matches",
"=",
"(",
"self",
".",
"path_db",
"[",
"tree_path",
"]",
".",
"keys",
"(",
")",
"for",
"tree_path",
"in",
"self",
".",
"path_db",
".",
"iterkeys",
"(",
")",
"if",
"tree_path"... | Search trees by `sub_path` using ``Tree.path.startswith(sub_path)``
comparison.
Args:
sub_path (str): Part of the :attr:`.Tree.path` property of
:class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances. | [
"Search",
"trees",
"by",
"sub_path",
"using",
"Tree",
".",
"path",
".",
"startswith",
"(",
"sub_path",
")",
"comparison",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L240-L258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.