repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
adamalton/django-csp-reports | cspreports/summary.py | collect | def collect(since, to, top=DEFAULT_TOP):
"""Collect the CSP report.
@returntype: CspReportSummary
"""
summary = CspReportSummary(since, to, top=top)
queryset = CSPReport.objects.filter(created__range=(since, to))
valid_queryset = queryset.filter(is_valid=True)
invalid_queryset = queryset.filter(is_valid=False)
summary.total_count = queryset.count()
summary.valid_count = valid_queryset.count()
# Collect sources
sources = {}
for report in valid_queryset:
root_uri = get_root_uri(report.document_uri)
info = sources.setdefault(root_uri, ViolationInfo(root_uri))
info.append(report)
summary.sources = sorted(sources.values(), key=attrgetter('count'), reverse=True)[:top]
# Collect blocks
blocks = {}
for report in valid_queryset:
root_uri = get_root_uri(report.blocked_uri)
info = blocks.setdefault(root_uri, ViolationInfo(root_uri))
info.append(report)
summary.blocks = sorted(blocks.values(), key=attrgetter('count'), reverse=True)[:top]
# Collect invalid reports
summary.invalid_count = invalid_queryset.count()
summary.invalid_reports = tuple(invalid_queryset[:top])
return summary | python | def collect(since, to, top=DEFAULT_TOP):
"""Collect the CSP report.
@returntype: CspReportSummary
"""
summary = CspReportSummary(since, to, top=top)
queryset = CSPReport.objects.filter(created__range=(since, to))
valid_queryset = queryset.filter(is_valid=True)
invalid_queryset = queryset.filter(is_valid=False)
summary.total_count = queryset.count()
summary.valid_count = valid_queryset.count()
# Collect sources
sources = {}
for report in valid_queryset:
root_uri = get_root_uri(report.document_uri)
info = sources.setdefault(root_uri, ViolationInfo(root_uri))
info.append(report)
summary.sources = sorted(sources.values(), key=attrgetter('count'), reverse=True)[:top]
# Collect blocks
blocks = {}
for report in valid_queryset:
root_uri = get_root_uri(report.blocked_uri)
info = blocks.setdefault(root_uri, ViolationInfo(root_uri))
info.append(report)
summary.blocks = sorted(blocks.values(), key=attrgetter('count'), reverse=True)[:top]
# Collect invalid reports
summary.invalid_count = invalid_queryset.count()
summary.invalid_reports = tuple(invalid_queryset[:top])
return summary | [
"def",
"collect",
"(",
"since",
",",
"to",
",",
"top",
"=",
"DEFAULT_TOP",
")",
":",
"summary",
"=",
"CspReportSummary",
"(",
"since",
",",
"to",
",",
"top",
"=",
"top",
")",
"queryset",
"=",
"CSPReport",
".",
"objects",
".",
"filter",
"(",
"created__r... | Collect the CSP report.
@returntype: CspReportSummary | [
"Collect",
"the",
"CSP",
"report",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L124-L157 | train | 26,200 |
adamalton/django-csp-reports | cspreports/summary.py | ViolationInfo.append | def append(self, report):
"""Append a new CSP report."""
assert report not in self.examples
self.count += 1
if len(self.examples) < self.top:
self.examples.append(report) | python | def append(self, report):
"""Append a new CSP report."""
assert report not in self.examples
self.count += 1
if len(self.examples) < self.top:
self.examples.append(report) | [
"def",
"append",
"(",
"self",
",",
"report",
")",
":",
"assert",
"report",
"not",
"in",
"self",
".",
"examples",
"self",
".",
"count",
"+=",
"1",
"if",
"len",
"(",
"self",
".",
"examples",
")",
"<",
"self",
".",
"top",
":",
"self",
".",
"examples",... | Append a new CSP report. | [
"Append",
"a",
"new",
"CSP",
"report",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L35-L40 | train | 26,201 |
adamalton/django-csp-reports | cspreports/summary.py | CspReportSummary.render | def render(self):
"""Render the summary."""
engine = Engine()
return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__)) | python | def render(self):
"""Render the summary."""
engine = Engine()
return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__)) | [
"def",
"render",
"(",
"self",
")",
":",
"engine",
"=",
"Engine",
"(",
")",
"return",
"engine",
".",
"from_string",
"(",
"SUMMARY_TEMPLATE",
")",
".",
"render",
"(",
"Context",
"(",
"self",
".",
"__dict__",
")",
")"
] | Render the summary. | [
"Render",
"the",
"summary",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L118-L121 | train | 26,202 |
adamalton/django-csp-reports | cspreports/management/commands/make_csp_summary.py | _parse_date_input | def _parse_date_input(date_input, default_offset=0):
"""Parses a date input."""
if date_input:
try:
return parse_date_input(date_input)
except ValueError as err:
raise CommandError(force_text(err))
else:
return get_midnight() - timedelta(days=default_offset) | python | def _parse_date_input(date_input, default_offset=0):
"""Parses a date input."""
if date_input:
try:
return parse_date_input(date_input)
except ValueError as err:
raise CommandError(force_text(err))
else:
return get_midnight() - timedelta(days=default_offset) | [
"def",
"_parse_date_input",
"(",
"date_input",
",",
"default_offset",
"=",
"0",
")",
":",
"if",
"date_input",
":",
"try",
":",
"return",
"parse_date_input",
"(",
"date_input",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"CommandError",
"(",
"force_... | Parses a date input. | [
"Parses",
"a",
"date",
"input",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/management/commands/make_csp_summary.py#L13-L21 | train | 26,203 |
adamalton/django-csp-reports | cspreports/models.py | CSPReport.nice_report | def nice_report(self):
"""Return a nicely formatted original report."""
if not self.json:
return '[no CSP report data]'
try:
data = json.loads(self.json)
except ValueError:
return "Invalid CSP report: '{}'".format(self.json)
if 'csp-report' not in data:
return 'Invalid CSP report: ' + json.dumps(data, indent=4, sort_keys=True, separators=(',', ': '))
return json.dumps(data['csp-report'], indent=4, sort_keys=True, separators=(',', ': ')) | python | def nice_report(self):
"""Return a nicely formatted original report."""
if not self.json:
return '[no CSP report data]'
try:
data = json.loads(self.json)
except ValueError:
return "Invalid CSP report: '{}'".format(self.json)
if 'csp-report' not in data:
return 'Invalid CSP report: ' + json.dumps(data, indent=4, sort_keys=True, separators=(',', ': '))
return json.dumps(data['csp-report'], indent=4, sort_keys=True, separators=(',', ': ')) | [
"def",
"nice_report",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"json",
":",
"return",
"'[no CSP report data]'",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"json",
")",
"except",
"ValueError",
":",
"return",
"\"Invalid CSP repo... | Return a nicely formatted original report. | [
"Return",
"a",
"nicely",
"formatted",
"original",
"report",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L87-L97 | train | 26,204 |
adamalton/django-csp-reports | cspreports/models.py | CSPReport.from_message | def from_message(cls, message):
"""Creates an instance from CSP report message.
If the message is not valid, the result will still have as much fields set as possible.
@param message: JSON encoded CSP report.
@type message: text
"""
self = cls(json=message)
try:
decoded_data = json.loads(message)
except ValueError:
# Message is not a valid JSON. Return as invalid.
return self
try:
report_data = decoded_data['csp-report']
except KeyError:
# Message is not a valid CSP report. Return as invalid.
return self
# Extract individual fields
for report_name, field_name in REQUIRED_FIELD_MAP + OPTIONAL_FIELD_MAP:
setattr(self, field_name, report_data.get(report_name))
# Extract integer fields
for report_name, field_name in INTEGER_FIELD_MAP:
value = report_data.get(report_name)
field = self._meta.get_field(field_name)
min_value, max_value = connection.ops.integer_field_range(field.get_internal_type())
if min_value is None:
min_value = 0
# All these fields are possitive. Value can't be negative.
min_value = max(min_value, 0)
if value is not None and min_value <= value and (max_value is None or value <= max_value):
setattr(self, field_name, value)
# Extract disposition
disposition = report_data.get('disposition')
if disposition in dict(DISPOSITIONS).keys():
self.disposition = disposition
# Check if report is valid
is_valid = True
for field_name in dict(REQUIRED_FIELD_MAP).values():
if getattr(self, field_name) is None:
is_valid = False
break
self.is_valid = is_valid
return self | python | def from_message(cls, message):
"""Creates an instance from CSP report message.
If the message is not valid, the result will still have as much fields set as possible.
@param message: JSON encoded CSP report.
@type message: text
"""
self = cls(json=message)
try:
decoded_data = json.loads(message)
except ValueError:
# Message is not a valid JSON. Return as invalid.
return self
try:
report_data = decoded_data['csp-report']
except KeyError:
# Message is not a valid CSP report. Return as invalid.
return self
# Extract individual fields
for report_name, field_name in REQUIRED_FIELD_MAP + OPTIONAL_FIELD_MAP:
setattr(self, field_name, report_data.get(report_name))
# Extract integer fields
for report_name, field_name in INTEGER_FIELD_MAP:
value = report_data.get(report_name)
field = self._meta.get_field(field_name)
min_value, max_value = connection.ops.integer_field_range(field.get_internal_type())
if min_value is None:
min_value = 0
# All these fields are possitive. Value can't be negative.
min_value = max(min_value, 0)
if value is not None and min_value <= value and (max_value is None or value <= max_value):
setattr(self, field_name, value)
# Extract disposition
disposition = report_data.get('disposition')
if disposition in dict(DISPOSITIONS).keys():
self.disposition = disposition
# Check if report is valid
is_valid = True
for field_name in dict(REQUIRED_FIELD_MAP).values():
if getattr(self, field_name) is None:
is_valid = False
break
self.is_valid = is_valid
return self | [
"def",
"from_message",
"(",
"cls",
",",
"message",
")",
":",
"self",
"=",
"cls",
"(",
"json",
"=",
"message",
")",
"try",
":",
"decoded_data",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"ValueError",
":",
"# Message is not a valid JSON. Return... | Creates an instance from CSP report message.
If the message is not valid, the result will still have as much fields set as possible.
@param message: JSON encoded CSP report.
@type message: text | [
"Creates",
"an",
"instance",
"from",
"CSP",
"report",
"message",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L103-L150 | train | 26,205 |
adamalton/django-csp-reports | cspreports/models.py | CSPReport.data | def data(self):
""" Returns self.json loaded as a python object. """
try:
data = self._data
except AttributeError:
data = self._data = json.loads(self.json)
return data | python | def data(self):
""" Returns self.json loaded as a python object. """
try:
data = self._data
except AttributeError:
data = self._data = json.loads(self.json)
return data | [
"def",
"data",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"_data",
"except",
"AttributeError",
":",
"data",
"=",
"self",
".",
"_data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"json",
")",
"return",
"data"
] | Returns self.json loaded as a python object. | [
"Returns",
"self",
".",
"json",
"loaded",
"as",
"a",
"python",
"object",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L153-L159 | train | 26,206 |
adamalton/django-csp-reports | cspreports/models.py | CSPReport.json_as_html | def json_as_html(self):
""" Print out self.json in a nice way. """
# To avoid circular import
from cspreports import utils
formatted_json = utils.format_report(self.json)
return mark_safe("<pre>\n%s</pre>" % escape(formatted_json)) | python | def json_as_html(self):
""" Print out self.json in a nice way. """
# To avoid circular import
from cspreports import utils
formatted_json = utils.format_report(self.json)
return mark_safe("<pre>\n%s</pre>" % escape(formatted_json)) | [
"def",
"json_as_html",
"(",
"self",
")",
":",
"# To avoid circular import",
"from",
"cspreports",
"import",
"utils",
"formatted_json",
"=",
"utils",
".",
"format_report",
"(",
"self",
".",
"json",
")",
"return",
"mark_safe",
"(",
"\"<pre>\\n%s</pre>\"",
"%",
"esca... | Print out self.json in a nice way. | [
"Print",
"out",
"self",
".",
"json",
"in",
"a",
"nice",
"way",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L161-L168 | train | 26,207 |
adamalton/django-csp-reports | cspreports/utils.py | process_report | def process_report(request):
""" Given the HTTP request of a CSP violation report, log it in the required ways. """
if config.EMAIL_ADMINS:
email_admins(request)
if config.LOG:
log_report(request)
if config.SAVE:
save_report(request)
if config.ADDITIONAL_HANDLERS:
run_additional_handlers(request) | python | def process_report(request):
""" Given the HTTP request of a CSP violation report, log it in the required ways. """
if config.EMAIL_ADMINS:
email_admins(request)
if config.LOG:
log_report(request)
if config.SAVE:
save_report(request)
if config.ADDITIONAL_HANDLERS:
run_additional_handlers(request) | [
"def",
"process_report",
"(",
"request",
")",
":",
"if",
"config",
".",
"EMAIL_ADMINS",
":",
"email_admins",
"(",
"request",
")",
"if",
"config",
".",
"LOG",
":",
"log_report",
"(",
"request",
")",
"if",
"config",
".",
"SAVE",
":",
"save_report",
"(",
"r... | Given the HTTP request of a CSP violation report, log it in the required ways. | [
"Given",
"the",
"HTTP",
"request",
"of",
"a",
"CSP",
"violation",
"report",
"log",
"it",
"in",
"the",
"required",
"ways",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L18-L27 | train | 26,208 |
adamalton/django-csp-reports | cspreports/utils.py | get_additional_handlers | def get_additional_handlers():
""" Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS. """
global _additional_handlers
if not isinstance(_additional_handlers, list):
handlers = []
for name in config.ADDITIONAL_HANDLERS:
module_name, function_name = name.rsplit('.', 1)
function = getattr(import_module(module_name), function_name)
handlers.append(function)
_additional_handlers = handlers
return _additional_handlers | python | def get_additional_handlers():
""" Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS. """
global _additional_handlers
if not isinstance(_additional_handlers, list):
handlers = []
for name in config.ADDITIONAL_HANDLERS:
module_name, function_name = name.rsplit('.', 1)
function = getattr(import_module(module_name), function_name)
handlers.append(function)
_additional_handlers = handlers
return _additional_handlers | [
"def",
"get_additional_handlers",
"(",
")",
":",
"global",
"_additional_handlers",
"if",
"not",
"isinstance",
"(",
"_additional_handlers",
",",
"list",
")",
":",
"handlers",
"=",
"[",
"]",
"for",
"name",
"in",
"config",
".",
"ADDITIONAL_HANDLERS",
":",
"module_n... | Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS. | [
"Returns",
"the",
"actual",
"functions",
"from",
"the",
"dotted",
"paths",
"specified",
"in",
"ADDITIONAL_HANDLERS",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L88-L98 | train | 26,209 |
adamalton/django-csp-reports | cspreports/utils.py | parse_date_input | def parse_date_input(value):
"""Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date.
"""
try:
limit = parse_date(value)
except ValueError:
limit = None
if limit is None:
raise ValueError("'{}' is not a valid date.".format(value))
limit = datetime(limit.year, limit.month, limit.day)
if settings.USE_TZ:
limit = make_aware(limit)
return limit | python | def parse_date_input(value):
"""Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date.
"""
try:
limit = parse_date(value)
except ValueError:
limit = None
if limit is None:
raise ValueError("'{}' is not a valid date.".format(value))
limit = datetime(limit.year, limit.month, limit.day)
if settings.USE_TZ:
limit = make_aware(limit)
return limit | [
"def",
"parse_date_input",
"(",
"value",
")",
":",
"try",
":",
"limit",
"=",
"parse_date",
"(",
"value",
")",
"except",
"ValueError",
":",
"limit",
"=",
"None",
"if",
"limit",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"'{}' is not a valid date.\"",
".... | Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date. | [
"Return",
"datetime",
"based",
"on",
"the",
"user",
"s",
"input",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L101-L118 | train | 26,210 |
adamalton/django-csp-reports | cspreports/utils.py | get_midnight | def get_midnight():
"""Return last midnight in localtime as datetime.
@return: Midnight datetime
"""
limit = now()
if settings.USE_TZ:
limit = localtime(limit)
return limit.replace(hour=0, minute=0, second=0, microsecond=0) | python | def get_midnight():
"""Return last midnight in localtime as datetime.
@return: Midnight datetime
"""
limit = now()
if settings.USE_TZ:
limit = localtime(limit)
return limit.replace(hour=0, minute=0, second=0, microsecond=0) | [
"def",
"get_midnight",
"(",
")",
":",
"limit",
"=",
"now",
"(",
")",
"if",
"settings",
".",
"USE_TZ",
":",
"limit",
"=",
"localtime",
"(",
"limit",
")",
"return",
"limit",
".",
"replace",
"(",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second... | Return last midnight in localtime as datetime.
@return: Midnight datetime | [
"Return",
"last",
"midnight",
"in",
"localtime",
"as",
"datetime",
"."
] | 867992c6f535cf6afbf911f92af7eea4c61e4b73 | https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/utils.py#L121-L129 | train | 26,211 |
SpheMakh/Stimela | stimela/recipe.py | StimelaJob.python_job | def python_job(self, function, parameters=None):
"""
Run python function
function : Python callable to execute
name : Name of function (if not given, will used function.__name__)
parameters : Parameters to parse to function
label : Function label; for logging purposes
"""
if not callable(function):
raise utils.StimelaCabRuntimeError('Object given as function is not callable')
if self.name is None:
self.name = function.__name__
self.job = {
'function' : function,
'parameters': parameters,
}
return 0 | python | def python_job(self, function, parameters=None):
"""
Run python function
function : Python callable to execute
name : Name of function (if not given, will used function.__name__)
parameters : Parameters to parse to function
label : Function label; for logging purposes
"""
if not callable(function):
raise utils.StimelaCabRuntimeError('Object given as function is not callable')
if self.name is None:
self.name = function.__name__
self.job = {
'function' : function,
'parameters': parameters,
}
return 0 | [
"def",
"python_job",
"(",
"self",
",",
"function",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"function",
")",
":",
"raise",
"utils",
".",
"StimelaCabRuntimeError",
"(",
"'Object given as function is not callable'",
")",
"if",
"self"... | Run python function
function : Python callable to execute
name : Name of function (if not given, will used function.__name__)
parameters : Parameters to parse to function
label : Function label; for logging purposes | [
"Run",
"python",
"function"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/recipe.py#L105-L126 | train | 26,212 |
SpheMakh/Stimela | stimela/singularity.py | pull | def pull(image, store_path, docker=True):
"""
pull an image
"""
if docker:
fp = "docker://{0:s}".format(image)
else:
fp = image
utils.xrun("singularity", ["pull", "--force", "--name", store_path, fp])
return 0 | python | def pull(image, store_path, docker=True):
"""
pull an image
"""
if docker:
fp = "docker://{0:s}".format(image)
else:
fp = image
utils.xrun("singularity", ["pull", "--force", "--name", store_path, fp])
return 0 | [
"def",
"pull",
"(",
"image",
",",
"store_path",
",",
"docker",
"=",
"True",
")",
":",
"if",
"docker",
":",
"fp",
"=",
"\"docker://{0:s}\"",
".",
"format",
"(",
"image",
")",
"else",
":",
"fp",
"=",
"image",
"utils",
".",
"xrun",
"(",
"\"singularity\"",... | pull an image | [
"pull",
"an",
"image"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L15-L26 | train | 26,213 |
SpheMakh/Stimela | stimela/singularity.py | Container.start | def start(self, *args):
"""
Create a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out))
utils.xrun("singularity instance.start",
list(args) + [volumes,
# "-c",
self.image, self.name])
self.status = "created"
return 0 | python | def start(self, *args):
"""
Create a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out))
utils.xrun("singularity instance.start",
list(args) + [volumes,
# "-c",
self.image, self.name])
self.status = "created"
return 0 | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"volumes",
":",
"volumes",
"=",
"\" --bind \"",
"+",
"\" --bind \"",
".",
"join",
"(",
"self",
".",
"volumes",
")",
"else",
":",
"volumes",
"=",
"\"\"",
"self",
".",
"_print"... | Create a singularity container instance | [
"Create",
"a",
"singularity",
"container",
"instance"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L66-L84 | train | 26,214 |
SpheMakh/Stimela | stimela/singularity.py | Container.run | def run(self, *args):
"""
Run a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Starting container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out))
utils.xrun("singularity run", ["instance://{0:s} {1:s}".format(self.name, self.RUNSCRIPT)],
timeout= self.time_out, kill_callback=self.stop)
self.status = "running"
return 0 | python | def run(self, *args):
"""
Run a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Starting container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out))
utils.xrun("singularity run", ["instance://{0:s} {1:s}".format(self.name, self.RUNSCRIPT)],
timeout= self.time_out, kill_callback=self.stop)
self.status = "running"
return 0 | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"volumes",
":",
"volumes",
"=",
"\" --bind \"",
"+",
"\" --bind \"",
".",
"join",
"(",
"self",
".",
"volumes",
")",
"else",
":",
"volumes",
"=",
"\"\"",
"self",
".",
"_print",
... | Run a singularity container instance | [
"Run",
"a",
"singularity",
"container",
"instance"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L87-L103 | train | 26,215 |
SpheMakh/Stimela | stimela/singularity.py | Container.stop | def stop(self, *args):
"""
Stop a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Stopping container [{}]. The container ID is printed below.".format(self.name))
utils.xrun("singularity", ["instance.stop {0:s}".format(self.name)])
self.status = "exited"
return 0 | python | def stop(self, *args):
"""
Stop a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Stopping container [{}]. The container ID is printed below.".format(self.name))
utils.xrun("singularity", ["instance.stop {0:s}".format(self.name)])
self.status = "exited"
return 0 | [
"def",
"stop",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"volumes",
":",
"volumes",
"=",
"\" --bind \"",
"+",
"\" --bind \"",
".",
"join",
"(",
"self",
".",
"volumes",
")",
"else",
":",
"volumes",
"=",
"\"\"",
"self",
".",
"_print",... | Stop a singularity container instance | [
"Stop",
"a",
"singularity",
"container",
"instance"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/singularity.py#L106-L121 | train | 26,216 |
SpheMakh/Stimela | stimela/docker.py | build | def build(image, build_path, tag=None, build_args=None, fromline=None, args=[]):
""" build a docker image"""
if tag:
image = ":".join([image, tag])
bdir = tempfile.mkdtemp()
os.system('cp -r {0:s}/* {1:s}'.format(build_path, bdir))
if build_args:
stdw = tempfile.NamedTemporaryFile(dir=bdir, mode='w')
with open("{}/Dockerfile".format(bdir)) as std:
dfile = std.readlines()
for line in dfile:
if fromline and line.lower().startswith('from'):
stdw.write('FROM {:s}\n'.format(fromline))
elif line.lower().startswith("cmd"):
for arg in build_args:
stdw.write(arg+"\n")
stdw.write(line)
else:
stdw.write(line)
stdw.flush()
utils.xrun("docker build", args+["--force-rm","-f", stdw.name,
"-t", image,
bdir])
stdw.close()
else:
utils.xrun("docker build", args+["--force-rm", "-t", image,
bdir])
os.system('rm -rf {:s}'.format(bdir)) | python | def build(image, build_path, tag=None, build_args=None, fromline=None, args=[]):
""" build a docker image"""
if tag:
image = ":".join([image, tag])
bdir = tempfile.mkdtemp()
os.system('cp -r {0:s}/* {1:s}'.format(build_path, bdir))
if build_args:
stdw = tempfile.NamedTemporaryFile(dir=bdir, mode='w')
with open("{}/Dockerfile".format(bdir)) as std:
dfile = std.readlines()
for line in dfile:
if fromline and line.lower().startswith('from'):
stdw.write('FROM {:s}\n'.format(fromline))
elif line.lower().startswith("cmd"):
for arg in build_args:
stdw.write(arg+"\n")
stdw.write(line)
else:
stdw.write(line)
stdw.flush()
utils.xrun("docker build", args+["--force-rm","-f", stdw.name,
"-t", image,
bdir])
stdw.close()
else:
utils.xrun("docker build", args+["--force-rm", "-t", image,
bdir])
os.system('rm -rf {:s}'.format(bdir)) | [
"def",
"build",
"(",
"image",
",",
"build_path",
",",
"tag",
"=",
"None",
",",
"build_args",
"=",
"None",
",",
"fromline",
"=",
"None",
",",
"args",
"=",
"[",
"]",
")",
":",
"if",
"tag",
":",
"image",
"=",
"\":\"",
".",
"join",
"(",
"[",
"image",... | build a docker image | [
"build",
"a",
"docker",
"image"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/docker.py#L16-L48 | train | 26,217 |
SpheMakh/Stimela | stimela/docker.py | pull | def pull(image, tag=None):
""" pull a docker image """
if tag:
image = ":".join([image, tag])
utils.xrun("docker pull", [image]) | python | def pull(image, tag=None):
""" pull a docker image """
if tag:
image = ":".join([image, tag])
utils.xrun("docker pull", [image]) | [
"def",
"pull",
"(",
"image",
",",
"tag",
"=",
"None",
")",
":",
"if",
"tag",
":",
"image",
"=",
"\":\"",
".",
"join",
"(",
"[",
"image",
",",
"tag",
"]",
")",
"utils",
".",
"xrun",
"(",
"\"docker pull\"",
",",
"[",
"image",
"]",
")"
] | pull a docker image | [
"pull",
"a",
"docker",
"image"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/docker.py#L50-L55 | train | 26,218 |
SpheMakh/Stimela | stimela/__init__.py | info | def info(cabdir, header=False):
""" prints out help information about a cab """
# First check if cab exists
pfile = "{}/parameters.json".format(cabdir)
if not os.path.exists(pfile):
raise RuntimeError("Cab could not be found at : {}".format(cabdir))
# Get cab info
cab_definition = cab.CabDefinition(parameter_file=pfile)
cab_definition.display(header) | python | def info(cabdir, header=False):
""" prints out help information about a cab """
# First check if cab exists
pfile = "{}/parameters.json".format(cabdir)
if not os.path.exists(pfile):
raise RuntimeError("Cab could not be found at : {}".format(cabdir))
# Get cab info
cab_definition = cab.CabDefinition(parameter_file=pfile)
cab_definition.display(header) | [
"def",
"info",
"(",
"cabdir",
",",
"header",
"=",
"False",
")",
":",
"# First check if cab exists",
"pfile",
"=",
"\"{}/parameters.json\"",
".",
"format",
"(",
"cabdir",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"pfile",
")",
":",
"raise",
... | prints out help information about a cab | [
"prints",
"out",
"help",
"information",
"about",
"a",
"cab"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/__init__.py#L194-L203 | train | 26,219 |
SpheMakh/Stimela | stimela/utils/__init__.py | xrun | def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None):
"""
Run something on command line.
Example: _run("ls", ["-lrt", "../"])
"""
cmd = " ".join([command] + list(map(str, options)) )
def _print_info(msg):
if msg is None: return
if log:
log.info(msg)
else:
print(msg)
def _print_warn(msg):
if msg is None: return
if log:
log.warn(msg)
else:
print(msg)
_print_info(u"Running: {0:s}".format(cmd))
sys.stdout.flush()
starttime = time.time()
process = p = None
try:
foutname = os.path.join("/tmp", "stimela_output_{0:s}_{1:f}".format(hashlib.md5(cmd.encode('utf-8')).hexdigest(), starttime))
with open(foutname, "w+") as fout:
p = process = subprocess.Popen(cmd,
stderr=fout,
stdout=fout,
shell=True)
def clock_killer(p):
while process.poll() is None and (timeout >= 0):
currenttime = time.time()
if (currenttime - starttime < timeout):
DEBUG and _print_warn(u"Clock Reaper: has been running for {0:f}, must finish in {1:f}".format(currenttime - starttime, timeout))
else:
_print_warn(u"Clock Reaper: Timeout reached for '{0:s}'... sending the KILL signal".format(cmd))
(kill_callback is not None) and kill_callback()
time.sleep(INTERRUPT_TIME)
Thread(target=clock_killer, args=tuple([p])).start()
while (process.poll() is None):
currenttime = time.time()
DEBUG and _print_info(u"God mode on: has been running for {0:f}".format(currenttime - starttime))
time.sleep(INTERRUPT_TIME) # this is probably not ideal as it interrupts the process every few seconds,
#check whether there is an alternative with a callback
assert hasattr(process, "returncode"), "No returncode after termination!"
with open(foutname, "r") as fout:
_print_info(fout.read())
finally:
if (process is not None) and process.returncode:
raise StimelaCabRuntimeError('%s: returns errr code %d' % (command, process.returncode)) | python | def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None):
"""
Run something on command line.
Example: _run("ls", ["-lrt", "../"])
"""
cmd = " ".join([command] + list(map(str, options)) )
def _print_info(msg):
if msg is None: return
if log:
log.info(msg)
else:
print(msg)
def _print_warn(msg):
if msg is None: return
if log:
log.warn(msg)
else:
print(msg)
_print_info(u"Running: {0:s}".format(cmd))
sys.stdout.flush()
starttime = time.time()
process = p = None
try:
foutname = os.path.join("/tmp", "stimela_output_{0:s}_{1:f}".format(hashlib.md5(cmd.encode('utf-8')).hexdigest(), starttime))
with open(foutname, "w+") as fout:
p = process = subprocess.Popen(cmd,
stderr=fout,
stdout=fout,
shell=True)
def clock_killer(p):
while process.poll() is None and (timeout >= 0):
currenttime = time.time()
if (currenttime - starttime < timeout):
DEBUG and _print_warn(u"Clock Reaper: has been running for {0:f}, must finish in {1:f}".format(currenttime - starttime, timeout))
else:
_print_warn(u"Clock Reaper: Timeout reached for '{0:s}'... sending the KILL signal".format(cmd))
(kill_callback is not None) and kill_callback()
time.sleep(INTERRUPT_TIME)
Thread(target=clock_killer, args=tuple([p])).start()
while (process.poll() is None):
currenttime = time.time()
DEBUG and _print_info(u"God mode on: has been running for {0:f}".format(currenttime - starttime))
time.sleep(INTERRUPT_TIME) # this is probably not ideal as it interrupts the process every few seconds,
#check whether there is an alternative with a callback
assert hasattr(process, "returncode"), "No returncode after termination!"
with open(foutname, "r") as fout:
_print_info(fout.read())
finally:
if (process is not None) and process.returncode:
raise StimelaCabRuntimeError('%s: returns errr code %d' % (command, process.returncode)) | [
"def",
"xrun",
"(",
"command",
",",
"options",
",",
"log",
"=",
"None",
",",
"_log_container_as_started",
"=",
"False",
",",
"logfile",
"=",
"None",
",",
"timeout",
"=",
"-",
"1",
",",
"kill_callback",
"=",
"None",
")",
":",
"cmd",
"=",
"\" \"",
".",
... | Run something on command line.
Example: _run("ls", ["-lrt", "../"]) | [
"Run",
"something",
"on",
"command",
"line",
"."
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/utils/__init__.py#L52-L110 | train | 26,220 |
SpheMakh/Stimela | stimela/utils/__init__.py | sumcols | def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, suntract=False):
""" add col1 to col2, or sum columns in 'cols' list.
If subtract, subtract col2 from col1
"""
from pyrap.tables import table
tab = table(msname, readonly=False)
if cols:
data = 0
for col in cols:
data += tab.getcol(col)
else:
if subtract:
data = tab.getcol(col1) - tab.getcol(col2)
else:
data = tab.getcol(col1) + tab.getcol(col2)
rowchunk = nrows//10 if nrows > 1000 else nrows
for row0 in range(0, nrows, rowchunk):
nr = min(rowchunk, nrows-row0)
tab.putcol(outcol, data[row0:row0+nr], row0, nr)
tab.close() | python | def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, suntract=False):
""" add col1 to col2, or sum columns in 'cols' list.
If subtract, subtract col2 from col1
"""
from pyrap.tables import table
tab = table(msname, readonly=False)
if cols:
data = 0
for col in cols:
data += tab.getcol(col)
else:
if subtract:
data = tab.getcol(col1) - tab.getcol(col2)
else:
data = tab.getcol(col1) + tab.getcol(col2)
rowchunk = nrows//10 if nrows > 1000 else nrows
for row0 in range(0, nrows, rowchunk):
nr = min(rowchunk, nrows-row0)
tab.putcol(outcol, data[row0:row0+nr], row0, nr)
tab.close() | [
"def",
"sumcols",
"(",
"msname",
",",
"col1",
"=",
"None",
",",
"col2",
"=",
"None",
",",
"outcol",
"=",
"None",
",",
"cols",
"=",
"None",
",",
"suntract",
"=",
"False",
")",
":",
"from",
"pyrap",
".",
"tables",
"import",
"table",
"tab",
"=",
"tabl... | add col1 to col2, or sum columns in 'cols' list.
If subtract, subtract col2 from col1 | [
"add",
"col1",
"to",
"col2",
"or",
"sum",
"columns",
"in",
"cols",
"list",
".",
"If",
"subtract",
"subtract",
"col2",
"from",
"col1"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/utils/__init__.py#L397-L420 | train | 26,221 |
SpheMakh/Stimela | stimela/utils/__init__.py | compute_vis_noise | def compute_vis_noise(msname, sefd, spw_id=0):
"""Computes nominal per-visibility noise"""
from pyrap.tables import table
tab = table(msname)
spwtab = table(msname + "/SPECTRAL_WINDOW")
freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0]
wavelength = 300e+6/freq0
bw = spwtab.getcol("CHAN_WIDTH")[spw_id, 0]
dt = tab.getcol("EXPOSURE", 0, 1)[0]
dtf = (tab.getcol("TIME", tab.nrows()-1, 1)-tab.getcol("TIME", 0, 1))[0]
# close tables properly, else the calls below will hang waiting for a lock...
tab.close()
spwtab.close()
print(">>> %s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(msname, freq0*1e-6, wavelength, bw*1e-3, dt, dtf/3600))
noise = sefd/math.sqrt(abs(2*bw*dt))
print(">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd, noise*1000))
return noise | python | def compute_vis_noise(msname, sefd, spw_id=0):
"""Computes nominal per-visibility noise"""
from pyrap.tables import table
tab = table(msname)
spwtab = table(msname + "/SPECTRAL_WINDOW")
freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0]
wavelength = 300e+6/freq0
bw = spwtab.getcol("CHAN_WIDTH")[spw_id, 0]
dt = tab.getcol("EXPOSURE", 0, 1)[0]
dtf = (tab.getcol("TIME", tab.nrows()-1, 1)-tab.getcol("TIME", 0, 1))[0]
# close tables properly, else the calls below will hang waiting for a lock...
tab.close()
spwtab.close()
print(">>> %s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(msname, freq0*1e-6, wavelength, bw*1e-3, dt, dtf/3600))
noise = sefd/math.sqrt(abs(2*bw*dt))
print(">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd, noise*1000))
return noise | [
"def",
"compute_vis_noise",
"(",
"msname",
",",
"sefd",
",",
"spw_id",
"=",
"0",
")",
":",
"from",
"pyrap",
".",
"tables",
"import",
"table",
"tab",
"=",
"table",
"(",
"msname",
")",
"spwtab",
"=",
"table",
"(",
"msname",
"+",
"\"/SPECTRAL_WINDOW\"",
")"... | Computes nominal per-visibility noise | [
"Computes",
"nominal",
"per",
"-",
"visibility",
"noise"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/utils/__init__.py#L448-L469 | train | 26,222 |
SpheMakh/Stimela | stimela/cargo/cab/specfit/src/addSPI.py | fitsInfo | def fitsInfo(fitsname = None):
"""
Get fits info
"""
hdu = pyfits.open(fitsname)
hdr = hdu[0].header
ra = hdr['CRVAL1']
dra = abs(hdr['CDELT1'])
raPix = hdr['CRPIX1']
dec = hdr['CRVAL2']
ddec = abs(hdr['CDELT2'])
decPix = hdr['CRPIX2']
freq0 = 0
for i in range(1,hdr['NAXIS']+1):
if hdr['CTYPE%d'%i].strip() == 'FREQ':
freq0 = hdr['CRVAL%d'%i]
break
ndim = hdr["NAXIS"]
imslice = np.zeros(ndim, dtype=int).tolist()
imslice[-2:] = slice(None), slice(None)
image = hdu[0].data[imslice]
wcs = WCS(hdr,mode='pyfits')
return {'image':image,'wcs':wcs,'ra':ra,'dec':dec,'dra':dra,'ddec':ddec,'raPix':raPix,'decPix':decPix,'freq0':freq0} | python | def fitsInfo(fitsname = None):
"""
Get fits info
"""
hdu = pyfits.open(fitsname)
hdr = hdu[0].header
ra = hdr['CRVAL1']
dra = abs(hdr['CDELT1'])
raPix = hdr['CRPIX1']
dec = hdr['CRVAL2']
ddec = abs(hdr['CDELT2'])
decPix = hdr['CRPIX2']
freq0 = 0
for i in range(1,hdr['NAXIS']+1):
if hdr['CTYPE%d'%i].strip() == 'FREQ':
freq0 = hdr['CRVAL%d'%i]
break
ndim = hdr["NAXIS"]
imslice = np.zeros(ndim, dtype=int).tolist()
imslice[-2:] = slice(None), slice(None)
image = hdu[0].data[imslice]
wcs = WCS(hdr,mode='pyfits')
return {'image':image,'wcs':wcs,'ra':ra,'dec':dec,'dra':dra,'ddec':ddec,'raPix':raPix,'decPix':decPix,'freq0':freq0} | [
"def",
"fitsInfo",
"(",
"fitsname",
"=",
"None",
")",
":",
"hdu",
"=",
"pyfits",
".",
"open",
"(",
"fitsname",
")",
"hdr",
"=",
"hdu",
"[",
"0",
"]",
".",
"header",
"ra",
"=",
"hdr",
"[",
"'CRVAL1'",
"]",
"dra",
"=",
"abs",
"(",
"hdr",
"[",
"'C... | Get fits info | [
"Get",
"fits",
"info"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/cargo/cab/specfit/src/addSPI.py#L9-L33 | train | 26,223 |
SpheMakh/Stimela | stimela/cargo/cab/specfit/src/addSPI.py | sky2px | def sky2px(wcs,ra,dec,dra,ddec,cell, beam):
"""convert a sky region to pixel positions"""
dra = beam if dra<beam else dra # assume every source is at least as large as the psf
ddec = beam if ddec<beam else ddec
offsetDec = int((ddec/2.)/cell)
offsetRA = int((dra/2.)/cell)
if offsetDec%2==1:
offsetDec += 1
if offsetRA%2==1:
offsetRA += 1
raPix,decPix = map(int, wcs.wcs2pix(ra,dec))
return np.array([raPix-offsetRA,raPix+offsetRA,decPix-offsetDec,decPix+offsetDec]) | python | def sky2px(wcs,ra,dec,dra,ddec,cell, beam):
"""convert a sky region to pixel positions"""
dra = beam if dra<beam else dra # assume every source is at least as large as the psf
ddec = beam if ddec<beam else ddec
offsetDec = int((ddec/2.)/cell)
offsetRA = int((dra/2.)/cell)
if offsetDec%2==1:
offsetDec += 1
if offsetRA%2==1:
offsetRA += 1
raPix,decPix = map(int, wcs.wcs2pix(ra,dec))
return np.array([raPix-offsetRA,raPix+offsetRA,decPix-offsetDec,decPix+offsetDec]) | [
"def",
"sky2px",
"(",
"wcs",
",",
"ra",
",",
"dec",
",",
"dra",
",",
"ddec",
",",
"cell",
",",
"beam",
")",
":",
"dra",
"=",
"beam",
"if",
"dra",
"<",
"beam",
"else",
"dra",
"# assume every source is at least as large as the psf",
"ddec",
"=",
"beam",
"i... | convert a sky region to pixel positions | [
"convert",
"a",
"sky",
"region",
"to",
"pixel",
"positions"
] | 292e80461a0c3498da8e7e987e2891d3ae5981ad | https://github.com/SpheMakh/Stimela/blob/292e80461a0c3498da8e7e987e2891d3ae5981ad/stimela/cargo/cab/specfit/src/addSPI.py#L35-L47 | train | 26,224 |
yuma-m/pychord | pychord/quality.py | Quality.get_components | def get_components(self, root='C', visible=False):
""" Get components of chord quality
:param str root: the root note of the chord
:param bool visible: returns the name of notes if True
:rtype: list[str|int]
:return: components of chord quality
"""
root_val = note_to_val(root)
components = [v + root_val for v in self.components]
if visible:
components = [val_to_note(c, scale=root) for c in components]
return components | python | def get_components(self, root='C', visible=False):
""" Get components of chord quality
:param str root: the root note of the chord
:param bool visible: returns the name of notes if True
:rtype: list[str|int]
:return: components of chord quality
"""
root_val = note_to_val(root)
components = [v + root_val for v in self.components]
if visible:
components = [val_to_note(c, scale=root) for c in components]
return components | [
"def",
"get_components",
"(",
"self",
",",
"root",
"=",
"'C'",
",",
"visible",
"=",
"False",
")",
":",
"root_val",
"=",
"note_to_val",
"(",
"root",
")",
"components",
"=",
"[",
"v",
"+",
"root_val",
"for",
"v",
"in",
"self",
".",
"components",
"]",
"... | Get components of chord quality
:param str root: the root note of the chord
:param bool visible: returns the name of notes if True
:rtype: list[str|int]
:return: components of chord quality | [
"Get",
"components",
"of",
"chord",
"quality"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L40-L54 | train | 26,225 |
yuma-m/pychord | pychord/quality.py | Quality.append_on_chord | def append_on_chord(self, on_chord, root):
""" Append on chord
To create Am7/G
q = Quality('m7')
q.append_on_chord('G', root='A')
:param str on_chord: bass note of the chord
:param str root: root note of the chord
"""
root_val = note_to_val(root)
on_chord_val = note_to_val(on_chord) - root_val
list_ = list(self.components)
for idx, val in enumerate(list_):
if val % 12 == on_chord_val:
self.components.remove(val)
break
if on_chord_val > root_val:
on_chord_val -= 12
if on_chord_val not in self.components:
self.components.insert(0, on_chord_val) | python | def append_on_chord(self, on_chord, root):
""" Append on chord
To create Am7/G
q = Quality('m7')
q.append_on_chord('G', root='A')
:param str on_chord: bass note of the chord
:param str root: root note of the chord
"""
root_val = note_to_val(root)
on_chord_val = note_to_val(on_chord) - root_val
list_ = list(self.components)
for idx, val in enumerate(list_):
if val % 12 == on_chord_val:
self.components.remove(val)
break
if on_chord_val > root_val:
on_chord_val -= 12
if on_chord_val not in self.components:
self.components.insert(0, on_chord_val) | [
"def",
"append_on_chord",
"(",
"self",
",",
"on_chord",
",",
"root",
")",
":",
"root_val",
"=",
"note_to_val",
"(",
"root",
")",
"on_chord_val",
"=",
"note_to_val",
"(",
"on_chord",
")",
"-",
"root_val",
"list_",
"=",
"list",
"(",
"self",
".",
"components"... | Append on chord
To create Am7/G
q = Quality('m7')
q.append_on_chord('G', root='A')
:param str on_chord: bass note of the chord
:param str root: root note of the chord | [
"Append",
"on",
"chord"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L56-L79 | train | 26,226 |
yuma-m/pychord | pychord/quality.py | Quality.append_note | def append_note(self, note, root, scale=0):
""" Append a note to quality
:param str note: note to append on quality
:param str root: root note of chord
:param int scale: key scale
"""
root_val = note_to_val(root)
note_val = note_to_val(note) - root_val + scale * 12
if note_val not in self.components:
self.components.append(note_val)
self.components.sort() | python | def append_note(self, note, root, scale=0):
""" Append a note to quality
:param str note: note to append on quality
:param str root: root note of chord
:param int scale: key scale
"""
root_val = note_to_val(root)
note_val = note_to_val(note) - root_val + scale * 12
if note_val not in self.components:
self.components.append(note_val)
self.components.sort() | [
"def",
"append_note",
"(",
"self",
",",
"note",
",",
"root",
",",
"scale",
"=",
"0",
")",
":",
"root_val",
"=",
"note_to_val",
"(",
"root",
")",
"note_val",
"=",
"note_to_val",
"(",
"note",
")",
"-",
"root_val",
"+",
"scale",
"*",
"12",
"if",
"note_v... | Append a note to quality
:param str note: note to append on quality
:param str root: root note of chord
:param int scale: key scale | [
"Append",
"a",
"note",
"to",
"quality"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L81-L92 | train | 26,227 |
yuma-m/pychord | pychord/quality.py | Quality.append_notes | def append_notes(self, notes, root, scale=0):
""" Append notes to quality
:param list[str] notes: notes to append on quality
:param str root: root note of chord
:param int scale: key scale
"""
for note in notes:
self.append_note(note, root, scale) | python | def append_notes(self, notes, root, scale=0):
""" Append notes to quality
:param list[str] notes: notes to append on quality
:param str root: root note of chord
:param int scale: key scale
"""
for note in notes:
self.append_note(note, root, scale) | [
"def",
"append_notes",
"(",
"self",
",",
"notes",
",",
"root",
",",
"scale",
"=",
"0",
")",
":",
"for",
"note",
"in",
"notes",
":",
"self",
".",
"append_note",
"(",
"note",
",",
"root",
",",
"scale",
")"
] | Append notes to quality
:param list[str] notes: notes to append on quality
:param str root: root note of chord
:param int scale: key scale | [
"Append",
"notes",
"to",
"quality"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/quality.py#L94-L102 | train | 26,228 |
yuma-m/pychord | pychord/progression.py | ChordProgression.insert | def insert(self, index, chord):
""" Insert a chord to chord progressions
:param int index: Index to insert a chord
:type chord: str|pychord.Chord
:param chord: A chord to insert
:return:
"""
self._chords.insert(index, as_chord(chord)) | python | def insert(self, index, chord):
""" Insert a chord to chord progressions
:param int index: Index to insert a chord
:type chord: str|pychord.Chord
:param chord: A chord to insert
:return:
"""
self._chords.insert(index, as_chord(chord)) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"chord",
")",
":",
"self",
".",
"_chords",
".",
"insert",
"(",
"index",
",",
"as_chord",
"(",
"chord",
")",
")"
] | Insert a chord to chord progressions
:param int index: Index to insert a chord
:type chord: str|pychord.Chord
:param chord: A chord to insert
:return: | [
"Insert",
"a",
"chord",
"to",
"chord",
"progressions"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/progression.py#L81-L89 | train | 26,229 |
yuma-m/pychord | pychord/chord.py | as_chord | def as_chord(chord):
""" convert from str to Chord instance if input is str
:type chord: str|pychord.Chord
:param chord: Chord name or Chord instance
:rtype: pychord.Chord
:return: Chord instance
"""
if isinstance(chord, Chord):
return chord
elif isinstance(chord, str):
return Chord(chord)
else:
raise TypeError("input type should be str or Chord instance.") | python | def as_chord(chord):
""" convert from str to Chord instance if input is str
:type chord: str|pychord.Chord
:param chord: Chord name or Chord instance
:rtype: pychord.Chord
:return: Chord instance
"""
if isinstance(chord, Chord):
return chord
elif isinstance(chord, str):
return Chord(chord)
else:
raise TypeError("input type should be str or Chord instance.") | [
"def",
"as_chord",
"(",
"chord",
")",
":",
"if",
"isinstance",
"(",
"chord",
",",
"Chord",
")",
":",
"return",
"chord",
"elif",
"isinstance",
"(",
"chord",
",",
"str",
")",
":",
"return",
"Chord",
"(",
"chord",
")",
"else",
":",
"raise",
"TypeError",
... | convert from str to Chord instance if input is str
:type chord: str|pychord.Chord
:param chord: Chord name or Chord instance
:rtype: pychord.Chord
:return: Chord instance | [
"convert",
"from",
"str",
"to",
"Chord",
"instance",
"if",
"input",
"is",
"str"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L130-L143 | train | 26,230 |
yuma-m/pychord | pychord/chord.py | Chord.transpose | def transpose(self, trans, scale="C"):
""" Transpose the chord
:param int trans: Transpose key
:param str scale: key scale
:return:
"""
if not isinstance(trans, int):
raise TypeError("Expected integers, not {}".format(type(trans)))
self._root = transpose_note(self._root, trans, scale)
if self._on:
self._on = transpose_note(self._on, trans, scale)
self._reconfigure_chord() | python | def transpose(self, trans, scale="C"):
""" Transpose the chord
:param int trans: Transpose key
:param str scale: key scale
:return:
"""
if not isinstance(trans, int):
raise TypeError("Expected integers, not {}".format(type(trans)))
self._root = transpose_note(self._root, trans, scale)
if self._on:
self._on = transpose_note(self._on, trans, scale)
self._reconfigure_chord() | [
"def",
"transpose",
"(",
"self",
",",
"trans",
",",
"scale",
"=",
"\"C\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"trans",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected integers, not {}\"",
".",
"format",
"(",
"type",
"(",
"trans",
")",... | Transpose the chord
:param int trans: Transpose key
:param str scale: key scale
:return: | [
"Transpose",
"the",
"chord"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L85-L97 | train | 26,231 |
yuma-m/pychord | pychord/chord.py | Chord.components | def components(self, visible=True):
""" Return the component notes of chord
:param bool visible: returns the name of notes if True else list of int
:rtype: list[(str or int)]
:return: component notes of chord
"""
if self._on:
self._quality.append_on_chord(self.on, self.root)
return self._quality.get_components(root=self._root, visible=visible) | python | def components(self, visible=True):
""" Return the component notes of chord
:param bool visible: returns the name of notes if True else list of int
:rtype: list[(str or int)]
:return: component notes of chord
"""
if self._on:
self._quality.append_on_chord(self.on, self.root)
return self._quality.get_components(root=self._root, visible=visible) | [
"def",
"components",
"(",
"self",
",",
"visible",
"=",
"True",
")",
":",
"if",
"self",
".",
"_on",
":",
"self",
".",
"_quality",
".",
"append_on_chord",
"(",
"self",
".",
"on",
",",
"self",
".",
"root",
")",
"return",
"self",
".",
"_quality",
".",
... | Return the component notes of chord
:param bool visible: returns the name of notes if True else list of int
:rtype: list[(str or int)]
:return: component notes of chord | [
"Return",
"the",
"component",
"notes",
"of",
"chord"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L99-L109 | train | 26,232 |
yuma-m/pychord | pychord/chord.py | Chord._parse | def _parse(self, chord):
""" parse a chord
:param str chord: Name of chord.
"""
root, quality, appended, on = parse(chord)
self._root = root
self._quality = quality
self._appended = appended
self._on = on | python | def _parse(self, chord):
""" parse a chord
:param str chord: Name of chord.
"""
root, quality, appended, on = parse(chord)
self._root = root
self._quality = quality
self._appended = appended
self._on = on | [
"def",
"_parse",
"(",
"self",
",",
"chord",
")",
":",
"root",
",",
"quality",
",",
"appended",
",",
"on",
"=",
"parse",
"(",
"chord",
")",
"self",
".",
"_root",
"=",
"root",
"self",
".",
"_quality",
"=",
"quality",
"self",
".",
"_appended",
"=",
"a... | parse a chord
:param str chord: Name of chord. | [
"parse",
"a",
"chord"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L111-L120 | train | 26,233 |
yuma-m/pychord | pychord/utils.py | transpose_note | def transpose_note(note, transpose, scale="C"):
""" Transpose a note
:param str note: note to transpose
:type transpose: int
:param str scale: key scale
:rtype: str
:return: transposed note
"""
val = note_to_val(note)
val += transpose
return val_to_note(val, scale) | python | def transpose_note(note, transpose, scale="C"):
""" Transpose a note
:param str note: note to transpose
:type transpose: int
:param str scale: key scale
:rtype: str
:return: transposed note
"""
val = note_to_val(note)
val += transpose
return val_to_note(val, scale) | [
"def",
"transpose_note",
"(",
"note",
",",
"transpose",
",",
"scale",
"=",
"\"C\"",
")",
":",
"val",
"=",
"note_to_val",
"(",
"note",
")",
"val",
"+=",
"transpose",
"return",
"val_to_note",
"(",
"val",
",",
"scale",
")"
] | Transpose a note
:param str note: note to transpose
:type transpose: int
:param str scale: key scale
:rtype: str
:return: transposed note | [
"Transpose",
"a",
"note"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/utils.py#L38-L49 | train | 26,234 |
yuma-m/pychord | pychord/parser.py | parse | def parse(chord):
""" Parse a string to get chord component
:param str chord: str expression of a chord
:rtype: (str, pychord.Quality, str, str)
:return: (root, quality, appended, on)
"""
if len(chord) > 1 and chord[1] in ("b", "#"):
root = chord[:2]
rest = chord[2:]
else:
root = chord[:1]
rest = chord[1:]
check_note(root, chord)
on_chord_idx = rest.find("/")
if on_chord_idx >= 0:
on = rest[on_chord_idx + 1:]
rest = rest[:on_chord_idx]
check_note(on, chord)
else:
on = None
if rest in QUALITY_DICT:
quality = Quality(rest)
else:
raise ValueError("Invalid chord {}: Unknown quality {}".format(chord, rest))
# TODO: Implement parser for appended notes
appended = []
return root, quality, appended, on | python | def parse(chord):
""" Parse a string to get chord component
:param str chord: str expression of a chord
:rtype: (str, pychord.Quality, str, str)
:return: (root, quality, appended, on)
"""
if len(chord) > 1 and chord[1] in ("b", "#"):
root = chord[:2]
rest = chord[2:]
else:
root = chord[:1]
rest = chord[1:]
check_note(root, chord)
on_chord_idx = rest.find("/")
if on_chord_idx >= 0:
on = rest[on_chord_idx + 1:]
rest = rest[:on_chord_idx]
check_note(on, chord)
else:
on = None
if rest in QUALITY_DICT:
quality = Quality(rest)
else:
raise ValueError("Invalid chord {}: Unknown quality {}".format(chord, rest))
# TODO: Implement parser for appended notes
appended = []
return root, quality, appended, on | [
"def",
"parse",
"(",
"chord",
")",
":",
"if",
"len",
"(",
"chord",
")",
">",
"1",
"and",
"chord",
"[",
"1",
"]",
"in",
"(",
"\"b\"",
",",
"\"#\"",
")",
":",
"root",
"=",
"chord",
"[",
":",
"2",
"]",
"rest",
"=",
"chord",
"[",
"2",
":",
"]",... | Parse a string to get chord component
:param str chord: str expression of a chord
:rtype: (str, pychord.Quality, str, str)
:return: (root, quality, appended, on) | [
"Parse",
"a",
"string",
"to",
"get",
"chord",
"component"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/parser.py#L8-L35 | train | 26,235 |
yuma-m/pychord | pychord/parser.py | check_note | def check_note(note, chord):
""" Return True if the note is valid.
:param str note: note to check its validity
:param str chord: the chord which includes the note
:rtype: bool
"""
if note not in NOTE_VAL_DICT:
raise ValueError("Invalid chord {}: Unknown note {}".format(chord, note))
return True | python | def check_note(note, chord):
""" Return True if the note is valid.
:param str note: note to check its validity
:param str chord: the chord which includes the note
:rtype: bool
"""
if note not in NOTE_VAL_DICT:
raise ValueError("Invalid chord {}: Unknown note {}".format(chord, note))
return True | [
"def",
"check_note",
"(",
"note",
",",
"chord",
")",
":",
"if",
"note",
"not",
"in",
"NOTE_VAL_DICT",
":",
"raise",
"ValueError",
"(",
"\"Invalid chord {}: Unknown note {}\"",
".",
"format",
"(",
"chord",
",",
"note",
")",
")",
"return",
"True"
] | Return True if the note is valid.
:param str note: note to check its validity
:param str chord: the chord which includes the note
:rtype: bool | [
"Return",
"True",
"if",
"the",
"note",
"is",
"valid",
"."
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/parser.py#L38-L47 | train | 26,236 |
yuma-m/pychord | pychord/analyzer.py | note_to_chord | def note_to_chord(notes):
""" Convert note list to chord list
:param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"]
:rtype: list[pychord.Chord]
:return: list of chord
"""
if not notes:
raise ValueError("Please specify notes which consist a chord.")
root = notes[0]
root_and_positions = []
for rotated_notes in get_all_rotated_notes(notes):
rotated_root = rotated_notes[0]
root_and_positions.append([rotated_root, notes_to_positions(rotated_notes, rotated_notes[0])])
chords = []
for temp_root, positions in root_and_positions:
quality = find_quality(positions)
if quality is None:
continue
if temp_root == root:
chord = "{}{}".format(root, quality)
else:
chord = "{}{}/{}".format(temp_root, quality, root)
chords.append(Chord(chord))
return chords | python | def note_to_chord(notes):
""" Convert note list to chord list
:param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"]
:rtype: list[pychord.Chord]
:return: list of chord
"""
if not notes:
raise ValueError("Please specify notes which consist a chord.")
root = notes[0]
root_and_positions = []
for rotated_notes in get_all_rotated_notes(notes):
rotated_root = rotated_notes[0]
root_and_positions.append([rotated_root, notes_to_positions(rotated_notes, rotated_notes[0])])
chords = []
for temp_root, positions in root_and_positions:
quality = find_quality(positions)
if quality is None:
continue
if temp_root == root:
chord = "{}{}".format(root, quality)
else:
chord = "{}{}/{}".format(temp_root, quality, root)
chords.append(Chord(chord))
return chords | [
"def",
"note_to_chord",
"(",
"notes",
")",
":",
"if",
"not",
"notes",
":",
"raise",
"ValueError",
"(",
"\"Please specify notes which consist a chord.\"",
")",
"root",
"=",
"notes",
"[",
"0",
"]",
"root_and_positions",
"=",
"[",
"]",
"for",
"rotated_notes",
"in",... | Convert note list to chord list
:param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"]
:rtype: list[pychord.Chord]
:return: list of chord | [
"Convert",
"note",
"list",
"to",
"chord",
"list"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L8-L32 | train | 26,237 |
yuma-m/pychord | pychord/analyzer.py | notes_to_positions | def notes_to_positions(notes, root):
""" Get notes positions.
ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7]
:param list[str] notes: list of notes
:param str root: the root note
:rtype: list[int]
:return: list of note positions
"""
root_pos = note_to_val(root)
current_pos = root_pos
positions = []
for note in notes:
note_pos = note_to_val(note)
if note_pos < current_pos:
note_pos += 12 * ((current_pos - note_pos) // 12 + 1)
positions.append(note_pos - root_pos)
current_pos = note_pos
return positions | python | def notes_to_positions(notes, root):
""" Get notes positions.
ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7]
:param list[str] notes: list of notes
:param str root: the root note
:rtype: list[int]
:return: list of note positions
"""
root_pos = note_to_val(root)
current_pos = root_pos
positions = []
for note in notes:
note_pos = note_to_val(note)
if note_pos < current_pos:
note_pos += 12 * ((current_pos - note_pos) // 12 + 1)
positions.append(note_pos - root_pos)
current_pos = note_pos
return positions | [
"def",
"notes_to_positions",
"(",
"notes",
",",
"root",
")",
":",
"root_pos",
"=",
"note_to_val",
"(",
"root",
")",
"current_pos",
"=",
"root_pos",
"positions",
"=",
"[",
"]",
"for",
"note",
"in",
"notes",
":",
"note_pos",
"=",
"note_to_val",
"(",
"note",
... | Get notes positions.
ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7]
:param list[str] notes: list of notes
:param str root: the root note
:rtype: list[int]
:return: list of note positions | [
"Get",
"notes",
"positions",
"."
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L35-L54 | train | 26,238 |
yuma-m/pychord | pychord/analyzer.py | get_all_rotated_notes | def get_all_rotated_notes(notes):
""" Get all rotated notes
get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]
:type notes: list[str]
:rtype: list[list[str]]
"""
notes_list = []
for x in range(len(notes)):
notes_list.append(notes[x:] + notes[:x])
return notes_list | python | def get_all_rotated_notes(notes):
""" Get all rotated notes
get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]
:type notes: list[str]
:rtype: list[list[str]]
"""
notes_list = []
for x in range(len(notes)):
notes_list.append(notes[x:] + notes[:x])
return notes_list | [
"def",
"get_all_rotated_notes",
"(",
"notes",
")",
":",
"notes_list",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"notes",
")",
")",
":",
"notes_list",
".",
"append",
"(",
"notes",
"[",
"x",
":",
"]",
"+",
"notes",
"[",
":",
"x",
"... | Get all rotated notes
get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]
:type notes: list[str]
:rtype: list[list[str]] | [
"Get",
"all",
"rotated",
"notes"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L57-L68 | train | 26,239 |
yuma-m/pychord | pychord/analyzer.py | find_quality | def find_quality(positions):
""" Find a quality consists of positions
:param list[int] positions: note positions
:rtype: str|None
"""
for q, p in QUALITY_DICT.items():
if positions == list(p):
return q
return None | python | def find_quality(positions):
""" Find a quality consists of positions
:param list[int] positions: note positions
:rtype: str|None
"""
for q, p in QUALITY_DICT.items():
if positions == list(p):
return q
return None | [
"def",
"find_quality",
"(",
"positions",
")",
":",
"for",
"q",
",",
"p",
"in",
"QUALITY_DICT",
".",
"items",
"(",
")",
":",
"if",
"positions",
"==",
"list",
"(",
"p",
")",
":",
"return",
"q",
"return",
"None"
] | Find a quality consists of positions
:param list[int] positions: note positions
:rtype: str|None | [
"Find",
"a",
"quality",
"consists",
"of",
"positions"
] | 4aa39189082daae76e36a2701890f91776d86b47 | https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/analyzer.py#L71-L80 | train | 26,240 |
globality-corp/microcosm-flask | microcosm_flask/conventions/base.py | Convention.configure | def configure(self, ns, mappings=None, **kwargs):
"""
Apply mappings to a namespace.
"""
if mappings is None:
mappings = dict()
mappings.update(kwargs)
for operation, definition in mappings.items():
try:
configure_func = self._find_func(operation)
except AttributeError:
pass
else:
configure_func(ns, self._make_definition(definition)) | python | def configure(self, ns, mappings=None, **kwargs):
"""
Apply mappings to a namespace.
"""
if mappings is None:
mappings = dict()
mappings.update(kwargs)
for operation, definition in mappings.items():
try:
configure_func = self._find_func(operation)
except AttributeError:
pass
else:
configure_func(ns, self._make_definition(definition)) | [
"def",
"configure",
"(",
"self",
",",
"ns",
",",
"mappings",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mappings",
"is",
"None",
":",
"mappings",
"=",
"dict",
"(",
")",
"mappings",
".",
"update",
"(",
"kwargs",
")",
"for",
"operation",
... | Apply mappings to a namespace. | [
"Apply",
"mappings",
"to",
"a",
"namespace",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/base.py#L80-L95 | train | 26,241 |
globality-corp/microcosm-flask | microcosm_flask/conventions/base.py | Convention._find_func | def _find_func(self, operation):
"""
Find the function to use to configure the given operation.
The input might be an `Operation` enum or a string.
"""
if isinstance(operation, Operation):
operation_name = operation.name.lower()
else:
operation_name = operation.lower()
return getattr(self, "configure_{}".format(operation_name)) | python | def _find_func(self, operation):
"""
Find the function to use to configure the given operation.
The input might be an `Operation` enum or a string.
"""
if isinstance(operation, Operation):
operation_name = operation.name.lower()
else:
operation_name = operation.lower()
return getattr(self, "configure_{}".format(operation_name)) | [
"def",
"_find_func",
"(",
"self",
",",
"operation",
")",
":",
"if",
"isinstance",
"(",
"operation",
",",
"Operation",
")",
":",
"operation_name",
"=",
"operation",
".",
"name",
".",
"lower",
"(",
")",
"else",
":",
"operation_name",
"=",
"operation",
".",
... | Find the function to use to configure the given operation.
The input might be an `Operation` enum or a string. | [
"Find",
"the",
"function",
"to",
"use",
"to",
"configure",
"the",
"given",
"operation",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/base.py#L107-L119 | train | 26,242 |
globality-corp/microcosm-flask | microcosm_flask/conventions/base.py | Convention._make_definition | def _make_definition(self, definition):
"""
Generate a definition.
The input might already be a `EndpointDefinition` or it might be a tuple.
"""
if not definition:
return EndpointDefinition()
if isinstance(definition, EndpointDefinition):
return definition
elif len(definition) == 1:
return EndpointDefinition(
func=definition[0],
)
elif len(definition) == 2:
return EndpointDefinition(
func=definition[0],
response_schema=definition[1],
)
elif len(definition) == 3:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
)
elif len(definition) == 4:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
header_func=definition[3],
) | python | def _make_definition(self, definition):
"""
Generate a definition.
The input might already be a `EndpointDefinition` or it might be a tuple.
"""
if not definition:
return EndpointDefinition()
if isinstance(definition, EndpointDefinition):
return definition
elif len(definition) == 1:
return EndpointDefinition(
func=definition[0],
)
elif len(definition) == 2:
return EndpointDefinition(
func=definition[0],
response_schema=definition[1],
)
elif len(definition) == 3:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
)
elif len(definition) == 4:
return EndpointDefinition(
func=definition[0],
request_schema=definition[1],
response_schema=definition[2],
header_func=definition[3],
) | [
"def",
"_make_definition",
"(",
"self",
",",
"definition",
")",
":",
"if",
"not",
"definition",
":",
"return",
"EndpointDefinition",
"(",
")",
"if",
"isinstance",
"(",
"definition",
",",
"EndpointDefinition",
")",
":",
"return",
"definition",
"elif",
"len",
"(... | Generate a definition.
The input might already be a `EndpointDefinition` or it might be a tuple. | [
"Generate",
"a",
"definition",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/base.py#L127-L159 | train | 26,243 |
globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | iter_links | def iter_links(operations, page):
"""
Generate links for an iterable of operations on a starting page.
"""
for operation, ns, rule, func in operations:
yield Link.for_(
operation=operation,
ns=ns,
type=ns.subject_name,
qs=page.to_items(),
) | python | def iter_links(operations, page):
"""
Generate links for an iterable of operations on a starting page.
"""
for operation, ns, rule, func in operations:
yield Link.for_(
operation=operation,
ns=ns,
type=ns.subject_name,
qs=page.to_items(),
) | [
"def",
"iter_links",
"(",
"operations",
",",
"page",
")",
":",
"for",
"operation",
",",
"ns",
",",
"rule",
",",
"func",
"in",
"operations",
":",
"yield",
"Link",
".",
"for_",
"(",
"operation",
"=",
"operation",
",",
"ns",
"=",
"ns",
",",
"type",
"=",... | Generate links for an iterable of operations on a starting page. | [
"Generate",
"links",
"for",
"an",
"iterable",
"of",
"operations",
"on",
"a",
"starting",
"page",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L16-L27 | train | 26,244 |
globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | configure_discovery | def configure_discovery(graph):
"""
Build a singleton endpoint that provides a link to all search endpoints.
"""
ns = Namespace(
subject=graph.config.discovery_convention.name,
)
convention = DiscoveryConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | python | def configure_discovery(graph):
"""
Build a singleton endpoint that provides a link to all search endpoints.
"""
ns = Namespace(
subject=graph.config.discovery_convention.name,
)
convention = DiscoveryConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | [
"def",
"configure_discovery",
"(",
"graph",
")",
":",
"ns",
"=",
"Namespace",
"(",
"subject",
"=",
"graph",
".",
"config",
".",
"discovery_convention",
".",
"name",
",",
")",
"convention",
"=",
"DiscoveryConvention",
"(",
"graph",
")",
"convention",
".",
"co... | Build a singleton endpoint that provides a link to all search endpoints. | [
"Build",
"a",
"singleton",
"endpoint",
"that",
"provides",
"a",
"link",
"to",
"all",
"search",
"endpoints",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L81-L91 | train | 26,245 |
globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | DiscoveryConvention.configure_discover | def configure_discover(self, ns, definition):
"""
Register a discovery endpoint for a set of operations.
"""
page_schema = OffsetLimitPageSchema()
@self.add_route("/", Operation.Discover, ns)
def discover():
# accept pagination limit from request
page = OffsetLimitPage.from_query_string(page_schema)
page.offset = 0
response_data = dict(
_links=Links({
"self": Link.for_(Operation.Discover, ns, qs=page.to_items()),
"search": [
link for link in iter_links(self.find_matching_endpoints(ns), page)
],
}).to_dict()
)
return make_response(response_data) | python | def configure_discover(self, ns, definition):
"""
Register a discovery endpoint for a set of operations.
"""
page_schema = OffsetLimitPageSchema()
@self.add_route("/", Operation.Discover, ns)
def discover():
# accept pagination limit from request
page = OffsetLimitPage.from_query_string(page_schema)
page.offset = 0
response_data = dict(
_links=Links({
"self": Link.for_(Operation.Discover, ns, qs=page.to_items()),
"search": [
link for link in iter_links(self.find_matching_endpoints(ns), page)
],
}).to_dict()
)
return make_response(response_data) | [
"def",
"configure_discover",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"page_schema",
"=",
"OffsetLimitPageSchema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"\"/\"",
",",
"Operation",
".",
"Discover",
",",
"ns",
")",
"def",
"discover",
"(",... | Register a discovery endpoint for a set of operations. | [
"Register",
"a",
"discovery",
"endpoint",
"for",
"a",
"set",
"of",
"operations",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L51-L72 | train | 26,246 |
globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | nested | def nested(*contexts):
"""
Reimplementation of nested in python 3.
"""
with ExitStack() as stack:
results = [
stack.enter_context(context)
for context in contexts
]
yield results | python | def nested(*contexts):
"""
Reimplementation of nested in python 3.
"""
with ExitStack() as stack:
results = [
stack.enter_context(context)
for context in contexts
]
yield results | [
"def",
"nested",
"(",
"*",
"contexts",
")",
":",
"with",
"ExitStack",
"(",
")",
"as",
"stack",
":",
"results",
"=",
"[",
"stack",
".",
"enter_context",
"(",
"context",
")",
"for",
"context",
"in",
"contexts",
"]",
"yield",
"results"
] | Reimplementation of nested in python 3. | [
"Reimplementation",
"of",
"nested",
"in",
"python",
"3",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L27-L36 | train | 26,247 |
globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | temporary_upload | def temporary_upload(name, fileobj):
"""
Upload a file to a temporary location.
Flask will not load sufficiently large files into memory, so it
makes sense to always load files into a temporary directory.
"""
tempdir = mkdtemp()
filename = secure_filename(fileobj.filename)
filepath = join(tempdir, filename)
fileobj.save(filepath)
try:
yield name, filepath, fileobj.filename
finally:
rmtree(tempdir) | python | def temporary_upload(name, fileobj):
"""
Upload a file to a temporary location.
Flask will not load sufficiently large files into memory, so it
makes sense to always load files into a temporary directory.
"""
tempdir = mkdtemp()
filename = secure_filename(fileobj.filename)
filepath = join(tempdir, filename)
fileobj.save(filepath)
try:
yield name, filepath, fileobj.filename
finally:
rmtree(tempdir) | [
"def",
"temporary_upload",
"(",
"name",
",",
"fileobj",
")",
":",
"tempdir",
"=",
"mkdtemp",
"(",
")",
"filename",
"=",
"secure_filename",
"(",
"fileobj",
".",
"filename",
")",
"filepath",
"=",
"join",
"(",
"tempdir",
",",
"filename",
")",
"fileobj",
".",
... | Upload a file to a temporary location.
Flask will not load sufficiently large files into memory, so it
makes sense to always load files into a temporary directory. | [
"Upload",
"a",
"file",
"to",
"a",
"temporary",
"location",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L40-L55 | train | 26,248 |
globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | configure_upload | def configure_upload(graph, ns, mappings, exclude_func=None):
"""
Register Upload endpoints for a resource object.
"""
convention = UploadConvention(graph, exclude_func)
convention.configure(ns, mappings) | python | def configure_upload(graph, ns, mappings, exclude_func=None):
"""
Register Upload endpoints for a resource object.
"""
convention = UploadConvention(graph, exclude_func)
convention.configure(ns, mappings) | [
"def",
"configure_upload",
"(",
"graph",
",",
"ns",
",",
"mappings",
",",
"exclude_func",
"=",
"None",
")",
":",
"convention",
"=",
"UploadConvention",
"(",
"graph",
",",
"exclude_func",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"mappings",
")"
] | Register Upload endpoints for a resource object. | [
"Register",
"Upload",
"endpoints",
"for",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L130-L136 | train | 26,249 |
globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | UploadConvention.configure_upload | def configure_upload(self, ns, definition):
"""
Register an upload endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionally return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
upload = self.create_upload_func(ns, definition, ns.collection_path, Operation.Upload)
upload.__doc__ = "Upload a {}".format(ns.subject_name) | python | def configure_upload(self, ns, definition):
"""
Register an upload endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionally return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
upload = self.create_upload_func(ns, definition, ns.collection_path, Operation.Upload)
upload.__doc__ = "Upload a {}".format(ns.subject_name) | [
"def",
"configure_upload",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"upload",
"=",
"self",
".",
"create_upload_func",
"(",
"ns",
",",
"definition",
",",
"ns",
".",
"collection_path",
",",
"Operation",
".",
"Upload",
")",
"upload",
".",
"__doc__... | Register an upload endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionally return a resource
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"upload",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L97-L111 | train | 26,250 |
globality-corp/microcosm-flask | microcosm_flask/conventions/upload.py | UploadConvention.configure_uploadfor | def configure_uploadfor(self, ns, definition):
"""
Register an upload-for relation endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionall return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
upload_for = self.create_upload_func(ns, definition, ns.relation_path, Operation.UploadFor)
upload_for.__doc__ = "Upload a {} for a {}".format(ns.subject_name, ns.object_name) | python | def configure_uploadfor(self, ns, definition):
"""
Register an upload-for relation endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionall return a resource
:param ns: the namespace
:param definition: the endpoint definition
"""
upload_for = self.create_upload_func(ns, definition, ns.relation_path, Operation.UploadFor)
upload_for.__doc__ = "Upload a {} for a {}".format(ns.subject_name, ns.object_name) | [
"def",
"configure_uploadfor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"upload_for",
"=",
"self",
".",
"create_upload_func",
"(",
"ns",
",",
"definition",
",",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"UploadFor",
")",
"upload_for",
"."... | Register an upload-for relation endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionall return a resource
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"upload",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L113-L127 | train | 26,251 |
globality-corp/microcosm-flask | microcosm_flask/formatting/base.py | BaseFormatter.build_etag | def build_etag(self, response, include_etag=True, **kwargs):
"""
Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html
"""
if not include_etag:
return
if not spooky:
# use built-in md5
response.add_etag()
return
# use spooky
response.headers["ETag"] = quote_etag(
hexlify(
spooky.hash128(
response.get_data(),
).to_bytes(16, "little"),
).decode("utf-8"),
) | python | def build_etag(self, response, include_etag=True, **kwargs):
"""
Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html
"""
if not include_etag:
return
if not spooky:
# use built-in md5
response.add_etag()
return
# use spooky
response.headers["ETag"] = quote_etag(
hexlify(
spooky.hash128(
response.get_data(),
).to_bytes(16, "little"),
).decode("utf-8"),
) | [
"def",
"build_etag",
"(",
"self",
",",
"response",
",",
"include_etag",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"include_etag",
":",
"return",
"if",
"not",
"spooky",
":",
"# use built-in md5",
"response",
".",
"add_etag",
"(",
")",
"... | Add an etag to the response body.
Uses spooky where possible because it is empirically fast and well-regarded.
See: http://blog.reverberate.org/2012/01/state-of-hash-functions-2012.html | [
"Add",
"an",
"etag",
"to",
"the",
"response",
"body",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/formatting/base.py#L50-L74 | train | 26,252 |
globality-corp/microcosm-flask | microcosm_flask/encryption/conventions/crud_adapter.py | EncryptableCRUDStoreAdapter.update_and_reencrypt | def update_and_reencrypt(self, **kwargs):
"""
Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field.
"""
encrypted_field_name = self.store.model_class.__plaintext__
id_ = kwargs[self.identifier_key]
current_model = self.store.retrieve(id_)
current_value = current_model.plaintext
null_update = (
# Check if the update is for the encrypted field, and if it's explicitly set to null
encrypted_field_name in kwargs
and kwargs.get(encrypted_field_name) is None
)
new_value = kwargs.pop(self.store.model_class.__plaintext__, None)
use_new_value = new_value is not None or null_update
updated_value = new_value if use_new_value else current_value
model_kwargs = {
self.identifier_key: id_,
encrypted_field_name: updated_value,
**kwargs,
}
return super().update(
**model_kwargs,
) | python | def update_and_reencrypt(self, **kwargs):
"""
Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field.
"""
encrypted_field_name = self.store.model_class.__plaintext__
id_ = kwargs[self.identifier_key]
current_model = self.store.retrieve(id_)
current_value = current_model.plaintext
null_update = (
# Check if the update is for the encrypted field, and if it's explicitly set to null
encrypted_field_name in kwargs
and kwargs.get(encrypted_field_name) is None
)
new_value = kwargs.pop(self.store.model_class.__plaintext__, None)
use_new_value = new_value is not None or null_update
updated_value = new_value if use_new_value else current_value
model_kwargs = {
self.identifier_key: id_,
encrypted_field_name: updated_value,
**kwargs,
}
return super().update(
**model_kwargs,
) | [
"def",
"update_and_reencrypt",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"encrypted_field_name",
"=",
"self",
".",
"store",
".",
"model_class",
".",
"__plaintext__",
"id_",
"=",
"kwargs",
"[",
"self",
".",
"identifier_key",
"]",
"current_model",
"=",
"... | Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field. | [
"Support",
"re",
"-",
"encryption",
"by",
"enforcing",
"that",
"every",
"update",
"triggers",
"a",
"new",
"encryption",
"call",
"even",
"if",
"the",
"the",
"original",
"call",
"does",
"not",
"update",
"the",
"encrypted",
"field",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/encryption/conventions/crud_adapter.py#L10-L41 | train | 26,253 |
globality-corp/microcosm-flask | microcosm_flask/cloning.py | DAGSchema.unflatten | def unflatten(self, obj):
"""
Translate substitutions dictionary into objects.
"""
obj.substitutions = [
dict(from_id=key, to_id=value)
for key, value in getattr(obj, "substitutions", {}).items()
] | python | def unflatten(self, obj):
"""
Translate substitutions dictionary into objects.
"""
obj.substitutions = [
dict(from_id=key, to_id=value)
for key, value in getattr(obj, "substitutions", {}).items()
] | [
"def",
"unflatten",
"(",
"self",
",",
"obj",
")",
":",
"obj",
".",
"substitutions",
"=",
"[",
"dict",
"(",
"from_id",
"=",
"key",
",",
"to_id",
"=",
"value",
")",
"for",
"key",
",",
"value",
"in",
"getattr",
"(",
"obj",
",",
"\"substitutions\"",
",",... | Translate substitutions dictionary into objects. | [
"Translate",
"substitutions",
"dictionary",
"into",
"objects",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/cloning.py#L69-L77 | train | 26,254 |
globality-corp/microcosm-flask | microcosm_flask/cloning.py | DAGCloningController.clone | def clone(self, substitutions, commit=True, **kwargs):
"""
Clone a DAG, optionally skipping the commit.
"""
return self.store.clone(substitutions, **kwargs) | python | def clone(self, substitutions, commit=True, **kwargs):
"""
Clone a DAG, optionally skipping the commit.
"""
return self.store.clone(substitutions, **kwargs) | [
"def",
"clone",
"(",
"self",
",",
"substitutions",
",",
"commit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"store",
".",
"clone",
"(",
"substitutions",
",",
"*",
"*",
"kwargs",
")"
] | Clone a DAG, optionally skipping the commit. | [
"Clone",
"a",
"DAG",
"optionally",
"skipping",
"the",
"commit",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/cloning.py#L115-L120 | train | 26,255 |
globality-corp/microcosm-flask | microcosm_flask/conventions/relation.py | RelationConvention.configure_createfor | def configure_createfor(self, ns, definition):
"""
Register a create-for relation endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the new instance creation parameters
- return the created instance
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.CreateFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
Operation.CreateFor.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | python | def configure_createfor(self, ns, definition):
"""
Register a create-for relation endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the new instance creation parameters
- return the created instance
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.CreateFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
Operation.CreateFor.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | [
"def",
"configure_createfor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"CreateFor",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",... | Register a create-for relation endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the new instance creation parameters
- return the created instance
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"create",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/relation.py#L36-L66 | train | 26,256 |
globality-corp/microcosm-flask | microcosm_flask/conventions/relation.py | RelationConvention.configure_deletefor | def configure_deletefor(self, ns, definition):
"""
Register a delete-for relation endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.DeleteFor, ns)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
response_data = dict()
require_response_data(definition.func(**path_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.DeleteFor.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | python | def configure_deletefor(self, ns, definition):
"""
Register a delete-for relation endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.DeleteFor, ns)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
response_data = dict()
require_response_data(definition.func(**path_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.DeleteFor.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | [
"def",
"configure_deletefor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"DeleteFor",
",",
"ns",
")",
"@",
"wraps",
"(",
"definition",
".",
"func",
")",
"d... | Register a delete-for relation endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"delete",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/relation.py#L68-L96 | train | 26,257 |
globality-corp/microcosm-flask | microcosm_flask/conventions/relation.py | RelationConvention.configure_replacefor | def configure_replacefor(self, ns, definition):
"""
Register a replace-for relation endpoint.
For typical usage, this relation is not strictly required; once an object exists and has its own ID,
it is better to operate on it directly via dedicated CRUD routes.
However, in some cases, the composite key of (subject_id, object_id) is required to look up the object.
This happens, for example, when using DynamoDB where an object which maintains both a hash key and a range key
requires specifying them both for access.
The definition's func should be a replace function, which must:
- accept kwargs for the new instance replacement parameters
- return the instance
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.ReplaceFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.ReplaceFor.value.default_code,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Replace a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | python | def configure_replacefor(self, ns, definition):
"""
Register a replace-for relation endpoint.
For typical usage, this relation is not strictly required; once an object exists and has its own ID,
it is better to operate on it directly via dedicated CRUD routes.
However, in some cases, the composite key of (subject_id, object_id) is required to look up the object.
This happens, for example, when using DynamoDB where an object which maintains both a hash key and a range key
requires specifying them both for access.
The definition's func should be a replace function, which must:
- accept kwargs for the new instance replacement parameters
- return the instance
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.relation_path, Operation.ReplaceFor, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.ReplaceFor.value.default_code,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Replace a {} relative to a {}".format(pluralize(ns.object_name), ns.subject_name) | [
"def",
"configure_replacefor",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"relation_path",
",",
"Operation",
".",
"ReplaceFor",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema... | Register a replace-for relation endpoint.
For typical usage, this relation is not strictly required; once an object exists and has its own ID,
it is better to operate on it directly via dedicated CRUD routes.
However, in some cases, the composite key of (subject_id, object_id) is required to look up the object.
This happens, for example, when using DynamoDB where an object which maintains both a hash key and a range key
requires specifying them both for access.
The definition's func should be a replace function, which must:
- accept kwargs for the new instance replacement parameters
- return the instance
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"replace",
"-",
"for",
"relation",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/relation.py#L98-L135 | train | 26,258 |
globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/__init__.py | Parameters.build | def build(self, field: Field) -> Mapping[str, Any]:
"""
Build a swagger parameter from a marshmallow field.
"""
builder_types = self.builder_types() + [
# put default last
self.default_builder_type()
]
builders: List[ParameterBuilder] = [
builder_type(
build_parameter=self.build,
)
for builder_type in builder_types
]
builder = next(
builder
for builder in builders
if builder.supports_field(field)
)
return builder.build(field) | python | def build(self, field: Field) -> Mapping[str, Any]:
"""
Build a swagger parameter from a marshmallow field.
"""
builder_types = self.builder_types() + [
# put default last
self.default_builder_type()
]
builders: List[ParameterBuilder] = [
builder_type(
build_parameter=self.build,
)
for builder_type in builder_types
]
builder = next(
builder
for builder in builders
if builder.supports_field(field)
)
return builder.build(field) | [
"def",
"build",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"builder_types",
"=",
"self",
".",
"builder_types",
"(",
")",
"+",
"[",
"# put default last",
"self",
".",
"default_builder_type",
"(",
")",
... | Build a swagger parameter from a marshmallow field. | [
"Build",
"a",
"swagger",
"parameter",
"from",
"a",
"marshmallow",
"field",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/__init__.py#L27-L50 | train | 26,259 |
globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/__init__.py | Parameters.builder_types | def builder_types(cls) -> List[Type[ParameterBuilder]]:
"""
Define the available builder types.
"""
return [
entry_point.load()
for entry_point in iter_entry_points(ENTRY_POINT)
] | python | def builder_types(cls) -> List[Type[ParameterBuilder]]:
"""
Define the available builder types.
"""
return [
entry_point.load()
for entry_point in iter_entry_points(ENTRY_POINT)
] | [
"def",
"builder_types",
"(",
"cls",
")",
"->",
"List",
"[",
"Type",
"[",
"ParameterBuilder",
"]",
"]",
":",
"return",
"[",
"entry_point",
".",
"load",
"(",
")",
"for",
"entry_point",
"in",
"iter_entry_points",
"(",
"ENTRY_POINT",
")",
"]"
] | Define the available builder types. | [
"Define",
"the",
"available",
"builder",
"types",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/__init__.py#L55-L63 | train | 26,260 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | configure_crud | def configure_crud(graph, ns, mappings):
"""
Register CRUD endpoints for a resource object.
:param mappings: a dictionary from operations to tuple, where each tuple contains
the target function and zero or more marshmallow schemas according
to the signature of the "register_<foo>_endpoint" functions
Example mapping:
{
Operation.Create: (create_foo, NewFooSchema(), FooSchema()),
Operation.Delete: (delete_foo,),
Operation.Retrieve: (retrieve_foo, FooSchema()),
Operation.Search: (search_foo, SearchFooSchema(), FooSchema(), [ResponseFormats.CSV]),
}
"""
convention = CRUDConvention(graph)
convention.configure(ns, mappings) | python | def configure_crud(graph, ns, mappings):
"""
Register CRUD endpoints for a resource object.
:param mappings: a dictionary from operations to tuple, where each tuple contains
the target function and zero or more marshmallow schemas according
to the signature of the "register_<foo>_endpoint" functions
Example mapping:
{
Operation.Create: (create_foo, NewFooSchema(), FooSchema()),
Operation.Delete: (delete_foo,),
Operation.Retrieve: (retrieve_foo, FooSchema()),
Operation.Search: (search_foo, SearchFooSchema(), FooSchema(), [ResponseFormats.CSV]),
}
"""
convention = CRUDConvention(graph)
convention.configure(ns, mappings) | [
"def",
"configure_crud",
"(",
"graph",
",",
"ns",
",",
"mappings",
")",
":",
"convention",
"=",
"CRUDConvention",
"(",
"graph",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"mappings",
")"
] | Register CRUD endpoints for a resource object.
:param mappings: a dictionary from operations to tuple, where each tuple contains
the target function and zero or more marshmallow schemas according
to the signature of the "register_<foo>_endpoint" functions
Example mapping:
{
Operation.Create: (create_foo, NewFooSchema(), FooSchema()),
Operation.Delete: (delete_foo,),
Operation.Retrieve: (retrieve_foo, FooSchema()),
Operation.Search: (search_foo, SearchFooSchema(), FooSchema(), [ResponseFormats.CSV]),
} | [
"Register",
"CRUD",
"endpoints",
"for",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L348-L367 | train | 26,261 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_count | def configure_count(self, ns, definition):
"""
Register a count endpoint.
The definition's func should be a count function, which must:
- accept kwargs for the query string
- return a count is the total number of items available
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.collection_path, Operation.Count, ns)
@qs(definition.request_schema)
@wraps(definition.func)
def count(**path_data):
request_data = load_query_string_data(definition.request_schema)
response_data = dict()
count = definition.func(**merge_data(path_data, request_data))
headers = encode_count_header(count)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
None,
None,
headers=headers,
response_format=response_format,
)
count.__doc__ = "Count the size of the collection of all {}".format(pluralize(ns.subject_name)) | python | def configure_count(self, ns, definition):
"""
Register a count endpoint.
The definition's func should be a count function, which must:
- accept kwargs for the query string
- return a count is the total number of items available
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.collection_path, Operation.Count, ns)
@qs(definition.request_schema)
@wraps(definition.func)
def count(**path_data):
request_data = load_query_string_data(definition.request_schema)
response_data = dict()
count = definition.func(**merge_data(path_data, request_data))
headers = encode_count_header(count)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
None,
None,
headers=headers,
response_format=response_format,
)
count.__doc__ = "Count the size of the collection of all {}".format(pluralize(ns.subject_name)) | [
"def",
"configure_count",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"collection_path",
",",
"Operation",
".",
"Count",
",",
"ns",
")",
"@",
"qs",
"(",
"definition",
".",
"request_schema",
")",
"... | Register a count endpoint.
The definition's func should be a count function, which must:
- accept kwargs for the query string
- return a count is the total number of items available
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"count",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L74-L105 | train | 26,262 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_create | def configure_create(self, ns, definition):
"""
Register a create endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.collection_path, Operation.Create, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.Create.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {}".format(ns.subject_name) | python | def configure_create(self, ns, definition):
"""
Register a create endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.collection_path, Operation.Create, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def create(**path_data):
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
headers = encode_id_header(response_data)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=Operation.Create.value.default_code,
headers=headers,
response_format=response_format,
)
create.__doc__ = "Create a new {}".format(ns.subject_name) | [
"def",
"configure_create",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"collection_path",
",",
"Operation",
".",
"Create",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",
"... | Register a create endpoint.
The definition's func should be a create function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"create",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L107-L137 | train | 26,263 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_updatebatch | def configure_updatebatch(self, ns, definition):
"""
Register an update batch endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition
"""
operation = Operation.UpdateBatch
@self.add_route(ns.collection_path, operation, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update_batch(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=operation.value.default_code,
headers=headers,
response_format=response_format,
)
update_batch.__doc__ = "Update a batch of {}".format(ns.subject_name) | python | def configure_updatebatch(self, ns, definition):
"""
Register an update batch endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition
"""
operation = Operation.UpdateBatch
@self.add_route(ns.collection_path, operation, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update_batch(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
response_data = definition.func(**merge_data(path_data, request_data))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
status_code=operation.value.default_code,
headers=headers,
response_format=response_format,
)
update_batch.__doc__ = "Update a batch of {}".format(ns.subject_name) | [
"def",
"configure_updatebatch",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"operation",
"=",
"Operation",
".",
"UpdateBatch",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"collection_path",
",",
"operation",
",",
"ns",
")",
"@",
"request",
"(",... | Register an update batch endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return a new item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"update",
"batch",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L139-L171 | train | 26,264 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_retrieve | def configure_retrieve(self, ns, definition):
"""
Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Retrieve, ns)
@qs(request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def retrieve(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
retrieve.__doc__ = "Retrieve a {} by id".format(ns.subject_name) | python | def configure_retrieve(self, ns, definition):
"""
Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Retrieve, ns)
@qs(request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def retrieve(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
retrieve.__doc__ = "Retrieve a {} by id".format(ns.subject_name) | [
"def",
"configure_retrieve",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"request_schema",
"=",
"definition",
".",
"request_schema",
"or",
"Schema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"... | Register a retrieve endpoint.
The definition's func should be a retrieve function, which must:
- accept kwargs for path data
- return an item or falsey
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"retrieve",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L173-L204 | train | 26,265 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_delete | def configure_delete(self, ns, definition):
"""
Register a delete endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Delete, ns)
@qs(request_schema)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.Delete.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} by id".format(ns.subject_name) | python | def configure_delete(self, ns, definition):
"""
Register a delete endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition
"""
request_schema = definition.request_schema or Schema()
@self.add_route(ns.instance_path, Operation.Delete, ns)
@qs(request_schema)
@wraps(definition.func)
def delete(**path_data):
headers = dict()
request_data = load_query_string_data(request_schema)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
"",
None,
status_code=Operation.Delete.value.default_code,
headers=headers,
response_format=response_format,
)
delete.__doc__ = "Delete a {} by id".format(ns.subject_name) | [
"def",
"configure_delete",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"request_schema",
"=",
"definition",
".",
"request_schema",
"or",
"Schema",
"(",
")",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"De... | Register a delete endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"delete",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L206-L237 | train | 26,266 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_replace | def configure_replace(self, ns, definition):
"""
Register a replace endpoint.
The definition's func should be a replace function, which must:
- accept kwargs for the request and path data
- return the replaced item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.instance_path, Operation.Replace, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
# Replace/put should create a resource if not already present, but we do not
# enforce these semantics at the HTTP layer. If `func` returns falsey, we
# will raise a 404.
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Create or update a {} by id".format(ns.subject_name) | python | def configure_replace(self, ns, definition):
"""
Register a replace endpoint.
The definition's func should be a replace function, which must:
- accept kwargs for the request and path data
- return the replaced item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.instance_path, Operation.Replace, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def replace(**path_data):
headers = dict()
request_data = load_request_data(definition.request_schema)
# Replace/put should create a resource if not already present, but we do not
# enforce these semantics at the HTTP layer. If `func` returns falsey, we
# will raise a 404.
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
replace.__doc__ = "Create or update a {} by id".format(ns.subject_name) | [
"def",
"configure_replace",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"Replace",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",
"... | Register a replace endpoint.
The definition's func should be a replace function, which must:
- accept kwargs for the request and path data
- return the replaced item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"replace",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L239-L271 | train | 26,267 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_update | def configure_update(self, ns, definition):
"""
Register an update endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return an updated item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.instance_path, Operation.Update, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update(**path_data):
headers = dict()
# NB: using partial here means that marshmallow will not validate required fields
request_data = load_request_data(definition.request_schema, partial=True)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
update.__doc__ = "Update some or all of a {} by id".format(ns.subject_name) | python | def configure_update(self, ns, definition):
"""
Register an update endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return an updated item
:param ns: the namespace
:param definition: the endpoint definition
"""
@self.add_route(ns.instance_path, Operation.Update, ns)
@request(definition.request_schema)
@response(definition.response_schema)
@wraps(definition.func)
def update(**path_data):
headers = dict()
# NB: using partial here means that marshmallow will not validate required fields
request_data = load_request_data(definition.request_schema, partial=True)
response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
definition.response_schema,
response_data,
headers=headers,
response_format=response_format,
)
update.__doc__ = "Update some or all of a {} by id".format(ns.subject_name) | [
"def",
"configure_update",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"instance_path",
",",
"Operation",
".",
"Update",
",",
"ns",
")",
"@",
"request",
"(",
"definition",
".",
"request_schema",
")"... | Register an update endpoint.
The definition's func should be an update function, which must:
- accept kwargs for the request and path data
- return an updated item
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"an",
"update",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L273-L303 | train | 26,268 |
globality-corp/microcosm-flask | microcosm_flask/conventions/crud.py | CRUDConvention.configure_createcollection | def configure_createcollection(self, ns, definition):
"""
Register create collection endpoint.
:param ns: the namespace
:param definition: the endpoint definition
"""
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.CreateCollection, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def create_collection(**path_data):
request_data = load_request_data(definition.request_schema)
# NB: if we don't filter the request body through an explicit page schema,
# we will leak other request arguments into the pagination query strings
page = self.page_cls.from_query_string(self.page_schema(), request_data)
result = definition.func(**merge_data(
path_data,
merge_data(
request_data,
page.to_dict(func=identity),
),
))
response_data, headers = page.to_paginated_list(result, ns, Operation.CreateCollection)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
create_collection.__doc__ = "Create the collection of {}".format(pluralize(ns.subject_name)) | python | def configure_createcollection(self, ns, definition):
"""
Register create collection endpoint.
:param ns: the namespace
:param definition: the endpoint definition
"""
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.CreateCollection, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def create_collection(**path_data):
request_data = load_request_data(definition.request_schema)
# NB: if we don't filter the request body through an explicit page schema,
# we will leak other request arguments into the pagination query strings
page = self.page_cls.from_query_string(self.page_schema(), request_data)
result = definition.func(**merge_data(
path_data,
merge_data(
request_data,
page.to_dict(func=identity),
),
))
response_data, headers = page.to_paginated_list(result, ns, Operation.CreateCollection)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
create_collection.__doc__ = "Create the collection of {}".format(pluralize(ns.subject_name)) | [
"def",
"configure_createcollection",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"paginated_list_schema",
"=",
"self",
".",
"page_cls",
".",
"make_paginated_list_schema_class",
"(",
"ns",
",",
"definition",
".",
"response_schema",
",",
")",
"(",
")",
"@... | Register create collection endpoint.
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"create",
"collection",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/crud.py#L305-L345 | train | 26,269 |
globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/nested.py | NestedParameterBuilder.parse_ref | def parse_ref(self, field: Field) -> str:
"""
Parse the reference type for nested fields, if any.
"""
ref_name = type_name(name_for(field.schema))
return f"#/definitions/{ref_name}" | python | def parse_ref(self, field: Field) -> str:
"""
Parse the reference type for nested fields, if any.
"""
ref_name = type_name(name_for(field.schema))
return f"#/definitions/{ref_name}" | [
"def",
"parse_ref",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"str",
":",
"ref_name",
"=",
"type_name",
"(",
"name_for",
"(",
"field",
".",
"schema",
")",
")",
"return",
"f\"#/definitions/{ref_name}\""
] | Parse the reference type for nested fields, if any. | [
"Parse",
"the",
"reference",
"type",
"for",
"nested",
"fields",
"if",
"any",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/nested.py#L16-L22 | train | 26,270 |
globality-corp/microcosm-flask | microcosm_flask/conventions/build_info.py | configure_build_info | def configure_build_info(graph):
"""
Configure the build info endpoint.
"""
ns = Namespace(
subject=BuildInfo,
)
convention = BuildInfoConvention(graph)
convention.configure(ns, retrieve=tuple())
return convention.build_info | python | def configure_build_info(graph):
"""
Configure the build info endpoint.
"""
ns = Namespace(
subject=BuildInfo,
)
convention = BuildInfoConvention(graph)
convention.configure(ns, retrieve=tuple())
return convention.build_info | [
"def",
"configure_build_info",
"(",
"graph",
")",
":",
"ns",
"=",
"Namespace",
"(",
"subject",
"=",
"BuildInfo",
",",
")",
"convention",
"=",
"BuildInfoConvention",
"(",
"graph",
")",
"convention",
".",
"configure",
"(",
"ns",
",",
"retrieve",
"=",
"tuple",
... | Configure the build info endpoint. | [
"Configure",
"the",
"build",
"info",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/build_info.py#L63-L74 | train | 26,271 |
globality-corp/microcosm-flask | microcosm_flask/conventions/logging_level.py | build_logger_tree | def build_logger_tree():
"""
Build a DFS tree representing the logger layout.
Adapted with much appreciation from: https://github.com/brandon-rhodes/logging_tree
"""
cache = {}
tree = make_logger_node("", root)
for name, logger in sorted(root.manager.loggerDict.items()):
if "." in name:
parent_name = ".".join(name.split(".")[:-1])
parent = cache[parent_name]
else:
parent = tree
cache[name] = make_logger_node(name, logger, parent)
return tree | python | def build_logger_tree():
"""
Build a DFS tree representing the logger layout.
Adapted with much appreciation from: https://github.com/brandon-rhodes/logging_tree
"""
cache = {}
tree = make_logger_node("", root)
for name, logger in sorted(root.manager.loggerDict.items()):
if "." in name:
parent_name = ".".join(name.split(".")[:-1])
parent = cache[parent_name]
else:
parent = tree
cache[name] = make_logger_node(name, logger, parent)
return tree | [
"def",
"build_logger_tree",
"(",
")",
":",
"cache",
"=",
"{",
"}",
"tree",
"=",
"make_logger_node",
"(",
"\"\"",
",",
"root",
")",
"for",
"name",
",",
"logger",
"in",
"sorted",
"(",
"root",
".",
"manager",
".",
"loggerDict",
".",
"items",
"(",
")",
"... | Build a DFS tree representing the logger layout.
Adapted with much appreciation from: https://github.com/brandon-rhodes/logging_tree | [
"Build",
"a",
"DFS",
"tree",
"representing",
"the",
"logger",
"layout",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/logging_level.py#L58-L75 | train | 26,272 |
globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/base.py | ParameterBuilder.build | def build(self, field: Field) -> Mapping[str, Any]:
"""
Build a parameter.
"""
return dict(self.iter_parsed_values(field)) | python | def build(self, field: Field) -> Mapping[str, Any]:
"""
Build a parameter.
"""
return dict(self.iter_parsed_values(field)) | [
"def",
"build",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"dict",
"(",
"self",
".",
"iter_parsed_values",
"(",
"field",
")",
")"
] | Build a parameter. | [
"Build",
"a",
"parameter",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/base.py#L39-L44 | train | 26,273 |
globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/base.py | ParameterBuilder.iter_parsed_values | def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]:
"""
Walk the dictionary of parsers and emit all non-null values.
"""
for key, func in self.parsers.items():
value = func(field)
if not value:
continue
yield key, value | python | def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]:
"""
Walk the dictionary of parsers and emit all non-null values.
"""
for key, func in self.parsers.items():
value = func(field)
if not value:
continue
yield key, value | [
"def",
"iter_parsed_values",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"for",
"key",
",",
"func",
"in",
"self",
".",
"parsers",
".",
"items",
"(",
")",
":",
"value",
"=",
... | Walk the dictionary of parsers and emit all non-null values. | [
"Walk",
"the",
"dictionary",
"of",
"parsers",
"and",
"emit",
"all",
"non",
"-",
"null",
"values",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/base.py#L53-L62 | train | 26,274 |
globality-corp/microcosm-flask | microcosm_flask/namespaces.py | Namespace.object_ns | def object_ns(self):
"""
Create a new namespace for the current namespace's object value.
"""
return Namespace(
subject=self.object_,
object_=None,
prefix=self.prefix,
qualifier=self.qualifier,
version=self.version,
) | python | def object_ns(self):
"""
Create a new namespace for the current namespace's object value.
"""
return Namespace(
subject=self.object_,
object_=None,
prefix=self.prefix,
qualifier=self.qualifier,
version=self.version,
) | [
"def",
"object_ns",
"(",
"self",
")",
":",
"return",
"Namespace",
"(",
"subject",
"=",
"self",
".",
"object_",
",",
"object_",
"=",
"None",
",",
"prefix",
"=",
"self",
".",
"prefix",
",",
"qualifier",
"=",
"self",
".",
"qualifier",
",",
"version",
"=",... | Create a new namespace for the current namespace's object value. | [
"Create",
"a",
"new",
"namespace",
"for",
"the",
"current",
"namespace",
"s",
"object",
"value",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/namespaces.py#L81-L92 | train | 26,275 |
globality-corp/microcosm-flask | microcosm_flask/namespaces.py | Namespace.url_for | def url_for(self, operation, _external=True, **kwargs):
"""
Construct a URL for an operation against a resource.
:param kwargs: additional arguments for URL path expansion,
which are passed to flask.url_for.
In particular, _external=True produces absolute url.
"""
return url_for(self.endpoint_for(operation), _external=_external, **kwargs) | python | def url_for(self, operation, _external=True, **kwargs):
"""
Construct a URL for an operation against a resource.
:param kwargs: additional arguments for URL path expansion,
which are passed to flask.url_for.
In particular, _external=True produces absolute url.
"""
return url_for(self.endpoint_for(operation), _external=_external, **kwargs) | [
"def",
"url_for",
"(",
"self",
",",
"operation",
",",
"_external",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"url_for",
"(",
"self",
".",
"endpoint_for",
"(",
"operation",
")",
",",
"_external",
"=",
"_external",
",",
"*",
"*",
"kwargs"... | Construct a URL for an operation against a resource.
:param kwargs: additional arguments for URL path expansion,
which are passed to flask.url_for.
In particular, _external=True produces absolute url. | [
"Construct",
"a",
"URL",
"for",
"an",
"operation",
"against",
"a",
"resource",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/namespaces.py#L159-L168 | train | 26,276 |
globality-corp/microcosm-flask | microcosm_flask/namespaces.py | Namespace.href_for | def href_for(self, operation, qs=None, **kwargs):
"""
Construct an full href for an operation against a resource.
:parm qs: the query string dictionary, if any
:param kwargs: additional arguments for path expansion
"""
url = urljoin(request.url_root, self.url_for(operation, **kwargs))
qs_character = "?" if url.find("?") == -1 else "&"
return "{}{}".format(
url,
"{}{}".format(qs_character, urlencode(qs)) if qs else "",
) | python | def href_for(self, operation, qs=None, **kwargs):
"""
Construct an full href for an operation against a resource.
:parm qs: the query string dictionary, if any
:param kwargs: additional arguments for path expansion
"""
url = urljoin(request.url_root, self.url_for(operation, **kwargs))
qs_character = "?" if url.find("?") == -1 else "&"
return "{}{}".format(
url,
"{}{}".format(qs_character, urlencode(qs)) if qs else "",
) | [
"def",
"href_for",
"(",
"self",
",",
"operation",
",",
"qs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"urljoin",
"(",
"request",
".",
"url_root",
",",
"self",
".",
"url_for",
"(",
"operation",
",",
"*",
"*",
"kwargs",
")",
")",
... | Construct an full href for an operation against a resource.
:parm qs: the query string dictionary, if any
:param kwargs: additional arguments for path expansion | [
"Construct",
"an",
"full",
"href",
"for",
"an",
"operation",
"against",
"a",
"resource",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/namespaces.py#L170-L184 | train | 26,277 |
globality-corp/microcosm-flask | microcosm_flask/conventions/swagger.py | configure_swagger | def configure_swagger(graph):
"""
Build a singleton endpoint that provides swagger definitions for all operations.
"""
ns = Namespace(
subject=graph.config.swagger_convention.name,
version=graph.config.swagger_convention.version,
)
convention = SwaggerConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | python | def configure_swagger(graph):
"""
Build a singleton endpoint that provides swagger definitions for all operations.
"""
ns = Namespace(
subject=graph.config.swagger_convention.name,
version=graph.config.swagger_convention.version,
)
convention = SwaggerConvention(graph)
convention.configure(ns, discover=tuple())
return ns.subject | [
"def",
"configure_swagger",
"(",
"graph",
")",
":",
"ns",
"=",
"Namespace",
"(",
"subject",
"=",
"graph",
".",
"config",
".",
"swagger_convention",
".",
"name",
",",
"version",
"=",
"graph",
".",
"config",
".",
"swagger_convention",
".",
"version",
",",
")... | Build a singleton endpoint that provides swagger definitions for all operations. | [
"Build",
"a",
"singleton",
"endpoint",
"that",
"provides",
"swagger",
"definitions",
"for",
"all",
"operations",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/swagger.py#L76-L87 | train | 26,278 |
globality-corp/microcosm-flask | microcosm_flask/conventions/swagger.py | SwaggerConvention.configure_discover | def configure_discover(self, ns, definition):
"""
Register a swagger endpoint for a set of operations.
"""
@self.add_route(ns.singleton_path, Operation.Discover, ns)
def discover():
swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns))
g.hide_body = True
return make_response(swagger) | python | def configure_discover(self, ns, definition):
"""
Register a swagger endpoint for a set of operations.
"""
@self.add_route(ns.singleton_path, Operation.Discover, ns)
def discover():
swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns))
g.hide_body = True
return make_response(swagger) | [
"def",
"configure_discover",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"@",
"self",
".",
"add_route",
"(",
"ns",
".",
"singleton_path",
",",
"Operation",
".",
"Discover",
",",
"ns",
")",
"def",
"discover",
"(",
")",
":",
"swagger",
"=",
"bui... | Register a swagger endpoint for a set of operations. | [
"Register",
"a",
"swagger",
"endpoint",
"for",
"a",
"set",
"of",
"operations",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/swagger.py#L43-L52 | train | 26,279 |
globality-corp/microcosm-flask | microcosm_flask/swagger/parameters/list.py | ListParameterBuilder.parse_items | def parse_items(self, field: Field) -> Mapping[str, Any]:
"""
Parse the child item type for list fields, if any.
"""
return self.build_parameter(field.container) | python | def parse_items(self, field: Field) -> Mapping[str, Any]:
"""
Parse the child item type for list fields, if any.
"""
return self.build_parameter(field.container) | [
"def",
"parse_items",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"self",
".",
"build_parameter",
"(",
"field",
".",
"container",
")"
] | Parse the child item type for list fields, if any. | [
"Parse",
"the",
"child",
"item",
"type",
"for",
"list",
"fields",
"if",
"any",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/list.py#L16-L21 | train | 26,280 |
globality-corp/microcosm-flask | microcosm_flask/linking.py | Link.for_ | def for_(cls, operation, ns, qs=None, type=None, allow_templates=False, **kwargs):
"""
Create a link to an operation on a resource object.
Supports link templating if enabled by making a best guess as to the URI
template construction.
See also [RFC 6570]( https://tools.ietf.org/html/rfc6570).
:param operation: the operation
:param ns: the namespace
:param qs: an optional query string (e.g. for paging)
:param type: an optional link type
:param allow_templates: whether generated links are allowed to contain templates
:param kwargs: optional endpoint expansion arguments (e.g. for URI parameters)
:raises BuildError: if link templating is needed and disallowed
"""
assert isinstance(ns, Namespace)
try:
href, templated = ns.href_for(operation, qs=qs, **kwargs), False
except BuildError as error:
if not allow_templates:
raise
uri_templates = {
argument: "{{{}}}".format(argument)
for argument in error.suggested.arguments
}
kwargs.update(uri_templates)
href, templated = ns.href_for(operation, qs=qs, **kwargs), True
return cls(
href=href,
type=type,
templated=templated,
) | python | def for_(cls, operation, ns, qs=None, type=None, allow_templates=False, **kwargs):
"""
Create a link to an operation on a resource object.
Supports link templating if enabled by making a best guess as to the URI
template construction.
See also [RFC 6570]( https://tools.ietf.org/html/rfc6570).
:param operation: the operation
:param ns: the namespace
:param qs: an optional query string (e.g. for paging)
:param type: an optional link type
:param allow_templates: whether generated links are allowed to contain templates
:param kwargs: optional endpoint expansion arguments (e.g. for URI parameters)
:raises BuildError: if link templating is needed and disallowed
"""
assert isinstance(ns, Namespace)
try:
href, templated = ns.href_for(operation, qs=qs, **kwargs), False
except BuildError as error:
if not allow_templates:
raise
uri_templates = {
argument: "{{{}}}".format(argument)
for argument in error.suggested.arguments
}
kwargs.update(uri_templates)
href, templated = ns.href_for(operation, qs=qs, **kwargs), True
return cls(
href=href,
type=type,
templated=templated,
) | [
"def",
"for_",
"(",
"cls",
",",
"operation",
",",
"ns",
",",
"qs",
"=",
"None",
",",
"type",
"=",
"None",
",",
"allow_templates",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"ns",
",",
"Namespace",
")",
"try",
":",... | Create a link to an operation on a resource object.
Supports link templating if enabled by making a best guess as to the URI
template construction.
See also [RFC 6570]( https://tools.ietf.org/html/rfc6570).
:param operation: the operation
:param ns: the namespace
:param qs: an optional query string (e.g. for paging)
:param type: an optional link type
:param allow_templates: whether generated links are allowed to contain templates
:param kwargs: optional endpoint expansion arguments (e.g. for URI parameters)
:raises BuildError: if link templating is needed and disallowed | [
"Create",
"a",
"link",
"to",
"an",
"operation",
"on",
"a",
"resource",
"object",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/linking.py#L74-L108 | train | 26,281 |
globality-corp/microcosm-flask | microcosm_flask/swagger/api.py | build_parameter | def build_parameter(field: Field) -> Mapping[str, Any]:
"""
Build JSON parameter from a marshmallow field.
"""
builder = Parameters()
return builder.build(field) | python | def build_parameter(field: Field) -> Mapping[str, Any]:
"""
Build JSON parameter from a marshmallow field.
"""
builder = Parameters()
return builder.build(field) | [
"def",
"build_parameter",
"(",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"builder",
"=",
"Parameters",
"(",
")",
"return",
"builder",
".",
"build",
"(",
"field",
")"
] | Build JSON parameter from a marshmallow field. | [
"Build",
"JSON",
"parameter",
"from",
"a",
"marshmallow",
"field",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/api.py#L39-L45 | train | 26,282 |
globality-corp/microcosm-flask | microcosm_flask/conventions/saved_search.py | SavedSearchConvention.configure_savedsearch | def configure_savedsearch(self, ns, definition):
"""
Register a saved search endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the request data
- return a tuple of (items, count) where count is the total number of items
available (in the case of pagination)
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition
"""
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.SavedSearch, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def saved_search(**path_data):
request_data = load_request_data(definition.request_schema)
page = self.page_cls.from_dict(request_data)
request_data.update(page.to_dict(func=identity))
result = definition.func(**merge_data(path_data, request_data))
response_data, headers = page.to_paginated_list(result, ns, Operation.SavedSearch)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
saved_search.__doc__ = "Persist and return the search results of {}".format(pluralize(ns.subject_name)) | python | def configure_savedsearch(self, ns, definition):
"""
Register a saved search endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the request data
- return a tuple of (items, count) where count is the total number of items
available (in the case of pagination)
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition
"""
paginated_list_schema = self.page_cls.make_paginated_list_schema_class(
ns,
definition.response_schema,
)()
@self.add_route(ns.collection_path, Operation.SavedSearch, ns)
@request(definition.request_schema)
@response(paginated_list_schema)
@wraps(definition.func)
def saved_search(**path_data):
request_data = load_request_data(definition.request_schema)
page = self.page_cls.from_dict(request_data)
request_data.update(page.to_dict(func=identity))
result = definition.func(**merge_data(path_data, request_data))
response_data, headers = page.to_paginated_list(result, ns, Operation.SavedSearch)
definition.header_func(headers, response_data)
response_format = self.negotiate_response_content(definition.response_formats)
return dump_response_data(
paginated_list_schema,
response_data,
headers=headers,
response_format=response_format,
)
saved_search.__doc__ = "Persist and return the search results of {}".format(pluralize(ns.subject_name)) | [
"def",
"configure_savedsearch",
"(",
"self",
",",
"ns",
",",
"definition",
")",
":",
"paginated_list_schema",
"=",
"self",
".",
"page_cls",
".",
"make_paginated_list_schema_class",
"(",
"ns",
",",
"definition",
".",
"response_schema",
",",
")",
"(",
")",
"@",
... | Register a saved search endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the request data
- return a tuple of (items, count) where count is the total number of items
available (in the case of pagination)
The definition's request_schema will be used to process query string arguments.
:param ns: the namespace
:param definition: the endpoint definition | [
"Register",
"a",
"saved",
"search",
"endpoint",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/saved_search.py#L22-L61 | train | 26,283 |
globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | encode_basic_auth | def encode_basic_auth(username, password):
"""
Encode basic auth credentials.
"""
return "Basic {}".format(
b64encode(
"{}:{}".format(
username,
password,
).encode("utf-8")
).decode("utf-8")
) | python | def encode_basic_auth(username, password):
"""
Encode basic auth credentials.
"""
return "Basic {}".format(
b64encode(
"{}:{}".format(
username,
password,
).encode("utf-8")
).decode("utf-8")
) | [
"def",
"encode_basic_auth",
"(",
"username",
",",
"password",
")",
":",
"return",
"\"Basic {}\"",
".",
"format",
"(",
"b64encode",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"username",
",",
"password",
",",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
... | Encode basic auth credentials. | [
"Encode",
"basic",
"auth",
"credentials",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L22-L34 | train | 26,284 |
globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | configure_basic_auth_decorator | def configure_basic_auth_decorator(graph):
"""
Configure a basic auth decorator.
"""
# use the metadata name if no realm is defined
graph.config.setdefault("BASIC_AUTH_REALM", graph.metadata.name)
return ConfigBasicAuth(
app=graph.flask,
# wrap in dict to allow lists of items as well as dictionaries
credentials=dict(graph.config.basic_auth.credentials),
) | python | def configure_basic_auth_decorator(graph):
"""
Configure a basic auth decorator.
"""
# use the metadata name if no realm is defined
graph.config.setdefault("BASIC_AUTH_REALM", graph.metadata.name)
return ConfigBasicAuth(
app=graph.flask,
# wrap in dict to allow lists of items as well as dictionaries
credentials=dict(graph.config.basic_auth.credentials),
) | [
"def",
"configure_basic_auth_decorator",
"(",
"graph",
")",
":",
"# use the metadata name if no realm is defined",
"graph",
".",
"config",
".",
"setdefault",
"(",
"\"BASIC_AUTH_REALM\"",
",",
"graph",
".",
"metadata",
".",
"name",
")",
"return",
"ConfigBasicAuth",
"(",
... | Configure a basic auth decorator. | [
"Configure",
"a",
"basic",
"auth",
"decorator",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L73-L84 | train | 26,285 |
globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | ConfigBasicAuth.check_credentials | def check_credentials(self, username, password):
"""
Override credential checking to use configured credentials.
"""
return password is not None and self.credentials.get(username, None) == password | python | def check_credentials(self, username, password):
"""
Override credential checking to use configured credentials.
"""
return password is not None and self.credentials.get(username, None) == password | [
"def",
"check_credentials",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"return",
"password",
"is",
"not",
"None",
"and",
"self",
".",
"credentials",
".",
"get",
"(",
"username",
",",
"None",
")",
"==",
"password"
] | Override credential checking to use configured credentials. | [
"Override",
"credential",
"checking",
"to",
"use",
"configured",
"credentials",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L50-L55 | train | 26,286 |
globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | ConfigBasicAuth.challenge | def challenge(self):
"""
Override challenge to raise an exception that will trigger regular error handling.
"""
response = super(ConfigBasicAuth, self).challenge()
raise with_headers(Unauthorized(), response.headers) | python | def challenge(self):
"""
Override challenge to raise an exception that will trigger regular error handling.
"""
response = super(ConfigBasicAuth, self).challenge()
raise with_headers(Unauthorized(), response.headers) | [
"def",
"challenge",
"(",
"self",
")",
":",
"response",
"=",
"super",
"(",
"ConfigBasicAuth",
",",
"self",
")",
".",
"challenge",
"(",
")",
"raise",
"with_headers",
"(",
"Unauthorized",
"(",
")",
",",
"response",
".",
"headers",
")"
] | Override challenge to raise an exception that will trigger regular error handling. | [
"Override",
"challenge",
"to",
"raise",
"an",
"exception",
"that",
"will",
"trigger",
"regular",
"error",
"handling",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L57-L63 | train | 26,287 |
globality-corp/microcosm-flask | microcosm_flask/swagger/schemas.py | Schemas.iter_fields | def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: name, field pairs
"""
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | python | def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: name, field pairs
"""
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | [
"def",
"iter_fields",
"(",
"self",
",",
"schema",
":",
"Schema",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Field",
"]",
"]",
":",
"for",
"name",
"in",
"sorted",
"(",
"schema",
".",
"fields",
".",
"keys",
"(",
")",
")",
":",
"field",
... | Iterate through marshmallow schema fields.
Generates: name, field pairs | [
"Iterate",
"through",
"marshmallow",
"schema",
"fields",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/schemas.py#L56-L65 | train | 26,288 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | PaginatedList.links | def links(self):
"""
Include a self link.
"""
links = Links()
links["self"] = Link.for_(
self._operation,
self._ns,
qs=self._page.to_items(),
**self._context
)
return links | python | def links(self):
"""
Include a self link.
"""
links = Links()
links["self"] = Link.for_(
self._operation,
self._ns,
qs=self._page.to_items(),
**self._context
)
return links | [
"def",
"links",
"(",
"self",
")",
":",
"links",
"=",
"Links",
"(",
")",
"links",
"[",
"\"self\"",
"]",
"=",
"Link",
".",
"for_",
"(",
"self",
".",
"_operation",
",",
"self",
".",
"_ns",
",",
"qs",
"=",
"self",
".",
"_page",
".",
"to_items",
"(",
... | Include a self link. | [
"Include",
"a",
"self",
"link",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L85-L97 | train | 26,289 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | OffsetLimitPaginatedList.links | def links(self):
"""
Include previous and next links.
"""
links = super(OffsetLimitPaginatedList, self).links
if self._page.offset + self._page.limit < self.count:
links["next"] = Link.for_(
self._operation,
self._ns,
qs=self._page.next_page.to_items(),
**self._context
)
if self.offset > 0:
links["prev"] = Link.for_(
self._operation,
self._ns,
qs=self._page.prev_page.to_items(),
**self._context
)
return links | python | def links(self):
"""
Include previous and next links.
"""
links = super(OffsetLimitPaginatedList, self).links
if self._page.offset + self._page.limit < self.count:
links["next"] = Link.for_(
self._operation,
self._ns,
qs=self._page.next_page.to_items(),
**self._context
)
if self.offset > 0:
links["prev"] = Link.for_(
self._operation,
self._ns,
qs=self._page.prev_page.to_items(),
**self._context
)
return links | [
"def",
"links",
"(",
"self",
")",
":",
"links",
"=",
"super",
"(",
"OffsetLimitPaginatedList",
",",
"self",
")",
".",
"links",
"if",
"self",
".",
"_page",
".",
"offset",
"+",
"self",
".",
"_page",
".",
"limit",
"<",
"self",
".",
"count",
":",
"links"... | Include previous and next links. | [
"Include",
"previous",
"and",
"next",
"links",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L124-L144 | train | 26,290 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.to_items | def to_items(self, func=str):
"""
Contruct a list of dictionary items.
The items are normalized using:
- A sort function by key (for consistent results)
- A transformation function for values
The transformation function will default to `str`, which is a good choice when encoding values
as part of a response; this requires that complex types (UUID, Enum, etc.) have a valid string
encoding.
The transformation function should be set to `identity` in cases where raw values are desired;
this is normally necessary when passing page data to controller functions as kwargs.
"""
return [
(key, func(self.kwargs[key]))
for key in sorted(self.kwargs.keys())
] | python | def to_items(self, func=str):
"""
Contruct a list of dictionary items.
The items are normalized using:
- A sort function by key (for consistent results)
- A transformation function for values
The transformation function will default to `str`, which is a good choice when encoding values
as part of a response; this requires that complex types (UUID, Enum, etc.) have a valid string
encoding.
The transformation function should be set to `identity` in cases where raw values are desired;
this is normally necessary when passing page data to controller functions as kwargs.
"""
return [
(key, func(self.kwargs[key]))
for key in sorted(self.kwargs.keys())
] | [
"def",
"to_items",
"(",
"self",
",",
"func",
"=",
"str",
")",
":",
"return",
"[",
"(",
"key",
",",
"func",
"(",
"self",
".",
"kwargs",
"[",
"key",
"]",
")",
")",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"kwargs",
".",
"keys",
"(",
")",
... | Contruct a list of dictionary items.
The items are normalized using:
- A sort function by key (for consistent results)
- A transformation function for values
The transformation function will default to `str`, which is a good choice when encoding values
as part of a response; this requires that complex types (UUID, Enum, etc.) have a valid string
encoding.
The transformation function should be set to `identity` in cases where raw values are desired;
this is normally necessary when passing page data to controller functions as kwargs. | [
"Contruct",
"a",
"list",
"of",
"dictionary",
"items",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L155-L174 | train | 26,291 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.to_paginated_list | def to_paginated_list(self, result, _ns, _operation, **kwargs):
"""
Convert a controller result to a paginated list.
The result format is assumed to meet the contract of this page class's `parse_result` function.
"""
items, context = self.parse_result(result)
headers = dict()
paginated_list = PaginatedList(
items=items,
_page=self,
_ns=_ns,
_operation=_operation,
_context=context,
)
return paginated_list, headers | python | def to_paginated_list(self, result, _ns, _operation, **kwargs):
"""
Convert a controller result to a paginated list.
The result format is assumed to meet the contract of this page class's `parse_result` function.
"""
items, context = self.parse_result(result)
headers = dict()
paginated_list = PaginatedList(
items=items,
_page=self,
_ns=_ns,
_operation=_operation,
_context=context,
)
return paginated_list, headers | [
"def",
"to_paginated_list",
"(",
"self",
",",
"result",
",",
"_ns",
",",
"_operation",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
",",
"context",
"=",
"self",
".",
"parse_result",
"(",
"result",
")",
"headers",
"=",
"dict",
"(",
")",
"paginated_list",
... | Convert a controller result to a paginated list.
The result format is assumed to meet the contract of this page class's `parse_result` function. | [
"Convert",
"a",
"controller",
"result",
"to",
"a",
"paginated",
"list",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L179-L195 | train | 26,292 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.parse_result | def parse_result(cls, result):
"""
Parse a simple items result.
May either be two item tuple containing items and a context dictionary (see: relation convention)
or a list of items.
"""
if isinstance(result, tuple) == 2:
items, context = result
else:
context = {}
items = result
return items, context | python | def parse_result(cls, result):
"""
Parse a simple items result.
May either be two item tuple containing items and a context dictionary (see: relation convention)
or a list of items.
"""
if isinstance(result, tuple) == 2:
items, context = result
else:
context = {}
items = result
return items, context | [
"def",
"parse_result",
"(",
"cls",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"tuple",
")",
"==",
"2",
":",
"items",
",",
"context",
"=",
"result",
"else",
":",
"context",
"=",
"{",
"}",
"items",
"=",
"result",
"return",
"items"... | Parse a simple items result.
May either be two item tuple containing items and a context dictionary (see: relation convention)
or a list of items. | [
"Parse",
"a",
"simple",
"items",
"result",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L198-L211 | train | 26,293 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.from_query_string | def from_query_string(cls, schema, qs=None):
"""
Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted)
"""
dct = load_query_string_data(schema, qs)
return cls.from_dict(dct) | python | def from_query_string(cls, schema, qs=None):
"""
Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted)
"""
dct = load_query_string_data(schema, qs)
return cls.from_dict(dct) | [
"def",
"from_query_string",
"(",
"cls",
",",
"schema",
",",
"qs",
"=",
"None",
")",
":",
"dct",
"=",
"load_query_string_data",
"(",
"schema",
",",
"qs",
")",
"return",
"cls",
".",
"from_dict",
"(",
"dct",
")"
] | Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted) | [
"Extract",
"a",
"page",
"from",
"the",
"current",
"query",
"string",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L214-L222 | train | 26,294 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | Page.make_paginated_list_schema_class | def make_paginated_list_schema_class(cls, ns, item_schema):
"""
Generate a schema class that represents a paginted list of items.
"""
class PaginatedListSchema(Schema):
__alias__ = "{}_list".format(ns.subject_name)
items = fields.List(fields.Nested(item_schema), required=True)
_links = fields.Raw()
return PaginatedListSchema | python | def make_paginated_list_schema_class(cls, ns, item_schema):
"""
Generate a schema class that represents a paginted list of items.
"""
class PaginatedListSchema(Schema):
__alias__ = "{}_list".format(ns.subject_name)
items = fields.List(fields.Nested(item_schema), required=True)
_links = fields.Raw()
return PaginatedListSchema | [
"def",
"make_paginated_list_schema_class",
"(",
"cls",
",",
"ns",
",",
"item_schema",
")",
":",
"class",
"PaginatedListSchema",
"(",
"Schema",
")",
":",
"__alias__",
"=",
"\"{}_list\"",
".",
"format",
"(",
"ns",
".",
"subject_name",
")",
"items",
"=",
"fields"... | Generate a schema class that represents a paginted list of items. | [
"Generate",
"a",
"schema",
"class",
"that",
"represents",
"a",
"paginted",
"list",
"of",
"items",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L229-L239 | train | 26,295 |
globality-corp/microcosm-flask | microcosm_flask/paging.py | OffsetLimitPage.parse_result | def parse_result(cls, result):
"""
Parse an items + count tuple result.
May either be three item tuple containing items, count, and a context dictionary (see: relation convention)
or a two item tuple containing only items and count.
"""
if len(result) == 3:
items, count, context = result
else:
context = {}
items, count = result
return items, count, context | python | def parse_result(cls, result):
"""
Parse an items + count tuple result.
May either be three item tuple containing items, count, and a context dictionary (see: relation convention)
or a two item tuple containing only items and count.
"""
if len(result) == 3:
items, count, context = result
else:
context = {}
items, count = result
return items, count, context | [
"def",
"parse_result",
"(",
"cls",
",",
"result",
")",
":",
"if",
"len",
"(",
"result",
")",
"==",
"3",
":",
"items",
",",
"count",
",",
"context",
"=",
"result",
"else",
":",
"context",
"=",
"{",
"}",
"items",
",",
"count",
"=",
"result",
"return"... | Parse an items + count tuple result.
May either be three item tuple containing items, count, and a context dictionary (see: relation convention)
or a two item tuple containing only items and count. | [
"Parse",
"an",
"items",
"+",
"count",
"tuple",
"result",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/paging.py#L299-L312 | train | 26,296 |
globality-corp/microcosm-flask | microcosm_flask/naming.py | name_for | def name_for(obj):
"""
Get a name for something.
Allows overriding of default names using the `__alias__` attribute.
"""
if isinstance(obj, str):
return obj
cls = obj if isclass(obj) else obj.__class__
if hasattr(cls, "__alias__"):
return underscore(cls.__alias__)
else:
return underscore(cls.__name__) | python | def name_for(obj):
"""
Get a name for something.
Allows overriding of default names using the `__alias__` attribute.
"""
if isinstance(obj, str):
return obj
cls = obj if isclass(obj) else obj.__class__
if hasattr(cls, "__alias__"):
return underscore(cls.__alias__)
else:
return underscore(cls.__name__) | [
"def",
"name_for",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
"cls",
"=",
"obj",
"if",
"isclass",
"(",
"obj",
")",
"else",
"obj",
".",
"__class__",
"if",
"hasattr",
"(",
"cls",
",",
"\"__alias__\"",
... | Get a name for something.
Allows overriding of default names using the `__alias__` attribute. | [
"Get",
"a",
"name",
"for",
"something",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/naming.py#L10-L25 | train | 26,297 |
globality-corp/microcosm-flask | microcosm_flask/naming.py | instance_path_for | def instance_path_for(name, identifier_type, identifier_key=None):
"""
Get a path for thing.
"""
return "/{}/<{}:{}>".format(
name_for(name),
identifier_type,
identifier_key or "{}_id".format(name_for(name)),
) | python | def instance_path_for(name, identifier_type, identifier_key=None):
"""
Get a path for thing.
"""
return "/{}/<{}:{}>".format(
name_for(name),
identifier_type,
identifier_key or "{}_id".format(name_for(name)),
) | [
"def",
"instance_path_for",
"(",
"name",
",",
"identifier_type",
",",
"identifier_key",
"=",
"None",
")",
":",
"return",
"\"/{}/<{}:{}>\"",
".",
"format",
"(",
"name_for",
"(",
"name",
")",
",",
"identifier_type",
",",
"identifier_key",
"or",
"\"{}_id\"",
".",
... | Get a path for thing. | [
"Get",
"a",
"path",
"for",
"thing",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/naming.py#L48-L57 | train | 26,298 |
globality-corp/microcosm-flask | microcosm_flask/naming.py | relation_path_for | def relation_path_for(from_name, to_name, identifier_type, identifier_key=None):
"""
Get a path relating a thing to another.
"""
return "/{}/<{}:{}>/{}".format(
name_for(from_name),
identifier_type,
identifier_key or "{}_id".format(name_for(from_name)),
name_for(to_name),
) | python | def relation_path_for(from_name, to_name, identifier_type, identifier_key=None):
"""
Get a path relating a thing to another.
"""
return "/{}/<{}:{}>/{}".format(
name_for(from_name),
identifier_type,
identifier_key or "{}_id".format(name_for(from_name)),
name_for(to_name),
) | [
"def",
"relation_path_for",
"(",
"from_name",
",",
"to_name",
",",
"identifier_type",
",",
"identifier_key",
"=",
"None",
")",
":",
"return",
"\"/{}/<{}:{}>/{}\"",
".",
"format",
"(",
"name_for",
"(",
"from_name",
")",
",",
"identifier_type",
",",
"identifier_key"... | Get a path relating a thing to another. | [
"Get",
"a",
"path",
"relating",
"a",
"thing",
"to",
"another",
"."
] | c2eaf57f03e7d041eea343751a4a90fcc80df418 | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/naming.py#L71-L81 | train | 26,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.