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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
KE-works/pykechain | pykechain/utils.py | parse_datetime | def parse_datetime(value):
"""
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
the input contains one, the output uses a timezone with a fixed offset from UTC.
Inspired on the Django project. From `django.utils.dateparse.parse_datetime`. The code is copyrighted and
licences with an MIT license in the following fashion::
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
..versionadded 2.5:
:param value: datetime string
:type value: str or None
:return: datetime of the value is well formatted. Otherwise (including if value is None) returns None
:rtype: datetime or None
:raises ValueError: if the value is well formatted but not a valid datetime
"""
if value is None:
# do not process the value
return None
def _get_fixed_timezone(offset):
"""Return a tzinfo instance with a fixed offset from UTC."""
if isinstance(offset, timedelta):
offset = offset.seconds // 60
sign = '-' if offset < 0 else '+'
hhmm = '%02d%02d' % divmod(abs(offset), 60)
name = sign + hhmm
return pytz.FixedOffset(offset, name)
DATETIME_RE = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
)
match = DATETIME_RE.match(value)
if match:
kw = match.groupdict()
if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
tzinfo = kw.pop('tzinfo')
if tzinfo == 'Z':
tzinfo = pytz.UTC
elif tzinfo is not None:
offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
offset = 60 * int(tzinfo[1:3]) + offset_mins
if tzinfo[0] == '-':
offset = -offset
tzinfo = _get_fixed_timezone(offset)
kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
kw['tzinfo'] = tzinfo
return datetime(**kw) | python | def parse_datetime(value):
"""
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
the input contains one, the output uses a timezone with a fixed offset from UTC.
Inspired on the Django project. From `django.utils.dateparse.parse_datetime`. The code is copyrighted and
licences with an MIT license in the following fashion::
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
..versionadded 2.5:
:param value: datetime string
:type value: str or None
:return: datetime of the value is well formatted. Otherwise (including if value is None) returns None
:rtype: datetime or None
:raises ValueError: if the value is well formatted but not a valid datetime
"""
if value is None:
# do not process the value
return None
def _get_fixed_timezone(offset):
"""Return a tzinfo instance with a fixed offset from UTC."""
if isinstance(offset, timedelta):
offset = offset.seconds // 60
sign = '-' if offset < 0 else '+'
hhmm = '%02d%02d' % divmod(abs(offset), 60)
name = sign + hhmm
return pytz.FixedOffset(offset, name)
DATETIME_RE = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
)
match = DATETIME_RE.match(value)
if match:
kw = match.groupdict()
if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
tzinfo = kw.pop('tzinfo')
if tzinfo == 'Z':
tzinfo = pytz.UTC
elif tzinfo is not None:
offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
offset = 60 * int(tzinfo[1:3]) + offset_mins
if tzinfo[0] == '-':
offset = -offset
tzinfo = _get_fixed_timezone(offset)
kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
kw['tzinfo'] = tzinfo
return datetime(**kw) | [
"def",
"parse_datetime",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"# do not process the value",
"return",
"None",
"def",
"_get_fixed_timezone",
"(",
"offset",
")",
":",
"\"\"\"Return a tzinfo instance with a fixed offset from UTC.\"\"\"",
"if",
"isinstance",
"(",
"offset",
",",
"timedelta",
")",
":",
"offset",
"=",
"offset",
".",
"seconds",
"//",
"60",
"sign",
"=",
"'-'",
"if",
"offset",
"<",
"0",
"else",
"'+'",
"hhmm",
"=",
"'%02d%02d'",
"%",
"divmod",
"(",
"abs",
"(",
"offset",
")",
",",
"60",
")",
"name",
"=",
"sign",
"+",
"hhmm",
"return",
"pytz",
".",
"FixedOffset",
"(",
"offset",
",",
"name",
")",
"DATETIME_RE",
"=",
"re",
".",
"compile",
"(",
"r'(?P<year>\\d{4})-(?P<month>\\d{1,2})-(?P<day>\\d{1,2})'",
"r'[T ](?P<hour>\\d{1,2}):(?P<minute>\\d{1,2})'",
"r'(?::(?P<second>\\d{1,2})(?:\\.(?P<microsecond>\\d{1,6})\\d{0,6})?)?'",
"r'(?P<tzinfo>Z|[+-]\\d{2}(?::?\\d{2})?)?$'",
")",
"match",
"=",
"DATETIME_RE",
".",
"match",
"(",
"value",
")",
"if",
"match",
":",
"kw",
"=",
"match",
".",
"groupdict",
"(",
")",
"if",
"kw",
"[",
"'microsecond'",
"]",
":",
"kw",
"[",
"'microsecond'",
"]",
"=",
"kw",
"[",
"'microsecond'",
"]",
".",
"ljust",
"(",
"6",
",",
"'0'",
")",
"tzinfo",
"=",
"kw",
".",
"pop",
"(",
"'tzinfo'",
")",
"if",
"tzinfo",
"==",
"'Z'",
":",
"tzinfo",
"=",
"pytz",
".",
"UTC",
"elif",
"tzinfo",
"is",
"not",
"None",
":",
"offset_mins",
"=",
"int",
"(",
"tzinfo",
"[",
"-",
"2",
":",
"]",
")",
"if",
"len",
"(",
"tzinfo",
")",
">",
"3",
"else",
"0",
"offset",
"=",
"60",
"*",
"int",
"(",
"tzinfo",
"[",
"1",
":",
"3",
"]",
")",
"+",
"offset_mins",
"if",
"tzinfo",
"[",
"0",
"]",
"==",
"'-'",
":",
"offset",
"=",
"-",
"offset",
"tzinfo",
"=",
"_get_fixed_timezone",
"(",
"offset",
")",
"kw",
"=",
"{",
"k",
":",
"int",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"kw",
")",
"if",
"v",
"is",
"not",
"None",
"}",
"kw",
"[",
"'tzinfo'",
"]",
"=",
"tzinfo",
"return",
"datetime",
"(",
"*",
"*",
"kw",
")"
] | Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
the input contains one, the output uses a timezone with a fixed offset from UTC.
Inspired on the Django project. From `django.utils.dateparse.parse_datetime`. The code is copyrighted and
licences with an MIT license in the following fashion::
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
..versionadded 2.5:
:param value: datetime string
:type value: str or None
:return: datetime of the value is well formatted. Otherwise (including if value is None) returns None
:rtype: datetime or None
:raises ValueError: if the value is well formatted but not a valid datetime | [
"Convert",
"datetime",
"string",
"to",
"datetime",
"object",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/utils.py#L86-L144 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization._save_customization | def _save_customization(self, widgets):
"""
Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized
"""
if len(widgets) > 0:
# Get the current customization and only replace the 'ext' part of it
customization = self.activity._json_data.get('customization', dict())
if customization:
customization['ext'] = dict(widgets=widgets)
else:
customization = dict(ext=dict(widgets=widgets))
# Empty the customization if if the widgets list is empty
else:
customization = None
# perform validation
if customization:
validate(customization, widgetconfig_json_schema)
# Save to the activity and store the saved activity to self
response = self._client._request("PUT",
self._client._build_url("activity", activity_id=str(self.activity.id)),
json=dict(customization=customization))
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not save customization ({})".format(response))
else:
# refresh the activity json
self.activity = self._client.activity(pk=self.activity.id) | python | def _save_customization(self, widgets):
"""
Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized
"""
if len(widgets) > 0:
# Get the current customization and only replace the 'ext' part of it
customization = self.activity._json_data.get('customization', dict())
if customization:
customization['ext'] = dict(widgets=widgets)
else:
customization = dict(ext=dict(widgets=widgets))
# Empty the customization if if the widgets list is empty
else:
customization = None
# perform validation
if customization:
validate(customization, widgetconfig_json_schema)
# Save to the activity and store the saved activity to self
response = self._client._request("PUT",
self._client._build_url("activity", activity_id=str(self.activity.id)),
json=dict(customization=customization))
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not save customization ({})".format(response))
else:
# refresh the activity json
self.activity = self._client.activity(pk=self.activity.id) | [
"def",
"_save_customization",
"(",
"self",
",",
"widgets",
")",
":",
"if",
"len",
"(",
"widgets",
")",
">",
"0",
":",
"# Get the current customization and only replace the 'ext' part of it",
"customization",
"=",
"self",
".",
"activity",
".",
"_json_data",
".",
"get",
"(",
"'customization'",
",",
"dict",
"(",
")",
")",
"if",
"customization",
":",
"customization",
"[",
"'ext'",
"]",
"=",
"dict",
"(",
"widgets",
"=",
"widgets",
")",
"else",
":",
"customization",
"=",
"dict",
"(",
"ext",
"=",
"dict",
"(",
"widgets",
"=",
"widgets",
")",
")",
"# Empty the customization if if the widgets list is empty",
"else",
":",
"customization",
"=",
"None",
"# perform validation",
"if",
"customization",
":",
"validate",
"(",
"customization",
",",
"widgetconfig_json_schema",
")",
"# Save to the activity and store the saved activity to self",
"response",
"=",
"self",
".",
"_client",
".",
"_request",
"(",
"\"PUT\"",
",",
"self",
".",
"_client",
".",
"_build_url",
"(",
"\"activity\"",
",",
"activity_id",
"=",
"str",
"(",
"self",
".",
"activity",
".",
"id",
")",
")",
",",
"json",
"=",
"dict",
"(",
"customization",
"=",
"customization",
")",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"APIError",
"(",
"\"Could not save customization ({})\"",
".",
"format",
"(",
"response",
")",
")",
"else",
":",
"# refresh the activity json",
"self",
".",
"activity",
"=",
"self",
".",
"_client",
".",
"activity",
"(",
"pk",
"=",
"self",
".",
"activity",
".",
"id",
")"
] | Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized | [
"Save",
"the",
"complete",
"customization",
"to",
"the",
"activity",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L96-L126 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization._add_widget | def _add_widget(self, widget):
"""
Add a widget to the customization.
Will save the widget to KE-chain.
:param widget: The widget (specific json dict) to be added
:type widget: dict
"""
widgets = self.widgets()
widgets += [widget]
self._save_customization(widgets) | python | def _add_widget(self, widget):
"""
Add a widget to the customization.
Will save the widget to KE-chain.
:param widget: The widget (specific json dict) to be added
:type widget: dict
"""
widgets = self.widgets()
widgets += [widget]
self._save_customization(widgets) | [
"def",
"_add_widget",
"(",
"self",
",",
"widget",
")",
":",
"widgets",
"=",
"self",
".",
"widgets",
"(",
")",
"widgets",
"+=",
"[",
"widget",
"]",
"self",
".",
"_save_customization",
"(",
"widgets",
")"
] | Add a widget to the customization.
Will save the widget to KE-chain.
:param widget: The widget (specific json dict) to be added
:type widget: dict | [
"Add",
"a",
"widget",
"to",
"the",
"customization",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L128-L139 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization.widgets | def widgets(self):
"""
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form
"""
customization = self.activity._json_data.get('customization')
if customization and "ext" in customization.keys():
return customization['ext']['widgets']
else:
return [] | python | def widgets(self):
"""
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form
"""
customization = self.activity._json_data.get('customization')
if customization and "ext" in customization.keys():
return customization['ext']['widgets']
else:
return [] | [
"def",
"widgets",
"(",
"self",
")",
":",
"customization",
"=",
"self",
".",
"activity",
".",
"_json_data",
".",
"get",
"(",
"'customization'",
")",
"if",
"customization",
"and",
"\"ext\"",
"in",
"customization",
".",
"keys",
"(",
")",
":",
"return",
"customization",
"[",
"'ext'",
"]",
"[",
"'widgets'",
"]",
"else",
":",
"return",
"[",
"]"
] | Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form | [
"Get",
"the",
"Ext",
"JS",
"specific",
"customization",
"from",
"the",
"activity",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L141-L152 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization.delete_widget | def delete_widget(self, index):
"""
Delete widgets by index.
The widgets are saved to KE-chain.
:param index: The index of the widget to be deleted in the self.widgets
:type index: int
:raises ValueError: if the customization has no widgets
"""
widgets = self.widgets()
if len(widgets) == 0:
raise ValueError("This customization has no widgets")
widgets.pop(index)
self._save_customization(widgets) | python | def delete_widget(self, index):
"""
Delete widgets by index.
The widgets are saved to KE-chain.
:param index: The index of the widget to be deleted in the self.widgets
:type index: int
:raises ValueError: if the customization has no widgets
"""
widgets = self.widgets()
if len(widgets) == 0:
raise ValueError("This customization has no widgets")
widgets.pop(index)
self._save_customization(widgets) | [
"def",
"delete_widget",
"(",
"self",
",",
"index",
")",
":",
"widgets",
"=",
"self",
".",
"widgets",
"(",
")",
"if",
"len",
"(",
"widgets",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"This customization has no widgets\"",
")",
"widgets",
".",
"pop",
"(",
"index",
")",
"self",
".",
"_save_customization",
"(",
"widgets",
")"
] | Delete widgets by index.
The widgets are saved to KE-chain.
:param index: The index of the widget to be deleted in the self.widgets
:type index: int
:raises ValueError: if the customization has no widgets | [
"Delete",
"widgets",
"by",
"index",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L154-L168 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization.add_json_widget | def add_json_widget(self, config):
"""
Add an Ext Json Widget to the customization.
The configuration json provided must be interpretable by KE-chain. The json will be validated
against the widget json schema.
The widget will be saved to KE-chain.
:param config: The json configuration of the widget
:type config: dict
"""
validate(config, component_jsonwidget_schema)
self._add_widget(dict(config=config, name=WidgetNames.JSONWIDGET)) | python | def add_json_widget(self, config):
"""
Add an Ext Json Widget to the customization.
The configuration json provided must be interpretable by KE-chain. The json will be validated
against the widget json schema.
The widget will be saved to KE-chain.
:param config: The json configuration of the widget
:type config: dict
"""
validate(config, component_jsonwidget_schema)
self._add_widget(dict(config=config, name=WidgetNames.JSONWIDGET)) | [
"def",
"add_json_widget",
"(",
"self",
",",
"config",
")",
":",
"validate",
"(",
"config",
",",
"component_jsonwidget_schema",
")",
"self",
".",
"_add_widget",
"(",
"dict",
"(",
"config",
"=",
"config",
",",
"name",
"=",
"WidgetNames",
".",
"JSONWIDGET",
")",
")"
] | Add an Ext Json Widget to the customization.
The configuration json provided must be interpretable by KE-chain. The json will be validated
against the widget json schema.
The widget will be saved to KE-chain.
:param config: The json configuration of the widget
:type config: dict | [
"Add",
"an",
"Ext",
"Json",
"Widget",
"to",
"the",
"customization",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L177-L190 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization.add_property_grid_widget | def add_property_grid_widget(self, part_instance, max_height=None, custom_title=False, show_headers=True,
show_columns=None):
"""
Add a KE-chain Property Grid widget to the customization.
The widget will be saved to KE-chain.
:param part_instance: The part instance on which the property grid will be based
:type part_instance: :class:`Part` or UUID
:param max_height: The max height of the property grid in pixels
:type max_height: int or None
:param custom_title: A custom title for the property grid::
* False (default): Part instance name
* String value: Custom title
* None: No title
:type custom_title: bool or basestring or None
:param show_headers: Show or hide the headers in the grid (default True)
:type show_headers: bool
:param show_columns: Columns to be hidden or shown (default to 'unit' and 'description')
:type show_columns: list
:raises IllegalArgumentError: When unknown or illegal arguments are passed.
"""
height = max_height
# Check whether the parent_part_instance is uuid type or class `Part`
if isinstance(part_instance, Part):
part_instance_id = part_instance.id
elif isinstance(part_instance, text_type) and is_uuid(part_instance):
part_instance_id = part_instance
part_instance = self._client.part(id=part_instance_id)
else:
raise IllegalArgumentError("When using the add_property_grid_widget, part_instance must be a "
"Part or Part id. Type is: {}".format(type(part_instance)))
if not show_columns:
show_columns = list()
# Set the display_columns for the config
possible_columns = [ShowColumnTypes.DESCRIPTION, ShowColumnTypes.UNIT]
display_columns = dict()
for possible_column in possible_columns:
if possible_column in show_columns:
display_columns[possible_column] = True
else:
display_columns[possible_column] = False
# Declare property grid config
config = {
"xtype": ComponentXType.PROPERTYGRID,
"category": Category.INSTANCE,
"filter": {
"activity_id": str(self.activity.id),
"part": part_instance_id
},
"hideHeaders": not show_headers,
"viewModel": {
"data": {
"displayColumns": display_columns
}
},
}
# Add max height and custom title
if height:
config['height'] = height
if custom_title is False:
show_title_value = "Default"
title = part_instance.name
elif custom_title is None:
show_title_value = "No title"
title = str()
else:
show_title_value = "Custom title"
title = str(custom_title)
config["title"] = title
config["showTitleValue"] = show_title_value
# Declare the meta info for the property grid
meta = {
"activityId": str(self.activity.id),
"customHeight": height if height else None,
"customTitle": title,
"partInstanceId": part_instance_id,
"showColumns": show_columns,
"showHeaders": show_headers,
"showHeightValue": "Set height" if height else "Automatic height",
"showTitleValue": show_title_value
}
self._add_widget(dict(config=config, meta=meta, name=WidgetNames.PROPERTYGRIDWIDGET)) | python | def add_property_grid_widget(self, part_instance, max_height=None, custom_title=False, show_headers=True,
show_columns=None):
"""
Add a KE-chain Property Grid widget to the customization.
The widget will be saved to KE-chain.
:param part_instance: The part instance on which the property grid will be based
:type part_instance: :class:`Part` or UUID
:param max_height: The max height of the property grid in pixels
:type max_height: int or None
:param custom_title: A custom title for the property grid::
* False (default): Part instance name
* String value: Custom title
* None: No title
:type custom_title: bool or basestring or None
:param show_headers: Show or hide the headers in the grid (default True)
:type show_headers: bool
:param show_columns: Columns to be hidden or shown (default to 'unit' and 'description')
:type show_columns: list
:raises IllegalArgumentError: When unknown or illegal arguments are passed.
"""
height = max_height
# Check whether the parent_part_instance is uuid type or class `Part`
if isinstance(part_instance, Part):
part_instance_id = part_instance.id
elif isinstance(part_instance, text_type) and is_uuid(part_instance):
part_instance_id = part_instance
part_instance = self._client.part(id=part_instance_id)
else:
raise IllegalArgumentError("When using the add_property_grid_widget, part_instance must be a "
"Part or Part id. Type is: {}".format(type(part_instance)))
if not show_columns:
show_columns = list()
# Set the display_columns for the config
possible_columns = [ShowColumnTypes.DESCRIPTION, ShowColumnTypes.UNIT]
display_columns = dict()
for possible_column in possible_columns:
if possible_column in show_columns:
display_columns[possible_column] = True
else:
display_columns[possible_column] = False
# Declare property grid config
config = {
"xtype": ComponentXType.PROPERTYGRID,
"category": Category.INSTANCE,
"filter": {
"activity_id": str(self.activity.id),
"part": part_instance_id
},
"hideHeaders": not show_headers,
"viewModel": {
"data": {
"displayColumns": display_columns
}
},
}
# Add max height and custom title
if height:
config['height'] = height
if custom_title is False:
show_title_value = "Default"
title = part_instance.name
elif custom_title is None:
show_title_value = "No title"
title = str()
else:
show_title_value = "Custom title"
title = str(custom_title)
config["title"] = title
config["showTitleValue"] = show_title_value
# Declare the meta info for the property grid
meta = {
"activityId": str(self.activity.id),
"customHeight": height if height else None,
"customTitle": title,
"partInstanceId": part_instance_id,
"showColumns": show_columns,
"showHeaders": show_headers,
"showHeightValue": "Set height" if height else "Automatic height",
"showTitleValue": show_title_value
}
self._add_widget(dict(config=config, meta=meta, name=WidgetNames.PROPERTYGRIDWIDGET)) | [
"def",
"add_property_grid_widget",
"(",
"self",
",",
"part_instance",
",",
"max_height",
"=",
"None",
",",
"custom_title",
"=",
"False",
",",
"show_headers",
"=",
"True",
",",
"show_columns",
"=",
"None",
")",
":",
"height",
"=",
"max_height",
"# Check whether the parent_part_instance is uuid type or class `Part`",
"if",
"isinstance",
"(",
"part_instance",
",",
"Part",
")",
":",
"part_instance_id",
"=",
"part_instance",
".",
"id",
"elif",
"isinstance",
"(",
"part_instance",
",",
"text_type",
")",
"and",
"is_uuid",
"(",
"part_instance",
")",
":",
"part_instance_id",
"=",
"part_instance",
"part_instance",
"=",
"self",
".",
"_client",
".",
"part",
"(",
"id",
"=",
"part_instance_id",
")",
"else",
":",
"raise",
"IllegalArgumentError",
"(",
"\"When using the add_property_grid_widget, part_instance must be a \"",
"\"Part or Part id. Type is: {}\"",
".",
"format",
"(",
"type",
"(",
"part_instance",
")",
")",
")",
"if",
"not",
"show_columns",
":",
"show_columns",
"=",
"list",
"(",
")",
"# Set the display_columns for the config",
"possible_columns",
"=",
"[",
"ShowColumnTypes",
".",
"DESCRIPTION",
",",
"ShowColumnTypes",
".",
"UNIT",
"]",
"display_columns",
"=",
"dict",
"(",
")",
"for",
"possible_column",
"in",
"possible_columns",
":",
"if",
"possible_column",
"in",
"show_columns",
":",
"display_columns",
"[",
"possible_column",
"]",
"=",
"True",
"else",
":",
"display_columns",
"[",
"possible_column",
"]",
"=",
"False",
"# Declare property grid config",
"config",
"=",
"{",
"\"xtype\"",
":",
"ComponentXType",
".",
"PROPERTYGRID",
",",
"\"category\"",
":",
"Category",
".",
"INSTANCE",
",",
"\"filter\"",
":",
"{",
"\"activity_id\"",
":",
"str",
"(",
"self",
".",
"activity",
".",
"id",
")",
",",
"\"part\"",
":",
"part_instance_id",
"}",
",",
"\"hideHeaders\"",
":",
"not",
"show_headers",
",",
"\"viewModel\"",
":",
"{",
"\"data\"",
":",
"{",
"\"displayColumns\"",
":",
"display_columns",
"}",
"}",
",",
"}",
"# Add max height and custom title",
"if",
"height",
":",
"config",
"[",
"'height'",
"]",
"=",
"height",
"if",
"custom_title",
"is",
"False",
":",
"show_title_value",
"=",
"\"Default\"",
"title",
"=",
"part_instance",
".",
"name",
"elif",
"custom_title",
"is",
"None",
":",
"show_title_value",
"=",
"\"No title\"",
"title",
"=",
"str",
"(",
")",
"else",
":",
"show_title_value",
"=",
"\"Custom title\"",
"title",
"=",
"str",
"(",
"custom_title",
")",
"config",
"[",
"\"title\"",
"]",
"=",
"title",
"config",
"[",
"\"showTitleValue\"",
"]",
"=",
"show_title_value",
"# Declare the meta info for the property grid",
"meta",
"=",
"{",
"\"activityId\"",
":",
"str",
"(",
"self",
".",
"activity",
".",
"id",
")",
",",
"\"customHeight\"",
":",
"height",
"if",
"height",
"else",
"None",
",",
"\"customTitle\"",
":",
"title",
",",
"\"partInstanceId\"",
":",
"part_instance_id",
",",
"\"showColumns\"",
":",
"show_columns",
",",
"\"showHeaders\"",
":",
"show_headers",
",",
"\"showHeightValue\"",
":",
"\"Set height\"",
"if",
"height",
"else",
"\"Automatic height\"",
",",
"\"showTitleValue\"",
":",
"show_title_value",
"}",
"self",
".",
"_add_widget",
"(",
"dict",
"(",
"config",
"=",
"config",
",",
"meta",
"=",
"meta",
",",
"name",
"=",
"WidgetNames",
".",
"PROPERTYGRIDWIDGET",
")",
")"
] | Add a KE-chain Property Grid widget to the customization.
The widget will be saved to KE-chain.
:param part_instance: The part instance on which the property grid will be based
:type part_instance: :class:`Part` or UUID
:param max_height: The max height of the property grid in pixels
:type max_height: int or None
:param custom_title: A custom title for the property grid::
* False (default): Part instance name
* String value: Custom title
* None: No title
:type custom_title: bool or basestring or None
:param show_headers: Show or hide the headers in the grid (default True)
:type show_headers: bool
:param show_columns: Columns to be hidden or shown (default to 'unit' and 'description')
:type show_columns: list
:raises IllegalArgumentError: When unknown or illegal arguments are passed. | [
"Add",
"a",
"KE",
"-",
"chain",
"Property",
"Grid",
"widget",
"to",
"the",
"customization",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L360-L450 | train |
KE-works/pykechain | pykechain/models/customization.py | ExtCustomization.add_text_widget | def add_text_widget(self, text=None, custom_title=None, collapsible=True, collapsed=False):
"""
Add a KE-chain Text widget to the customization.
The widget will be saved to KE-chain.
:param text: The text that will be shown by the widget.
:type text: basestring or None
:param custom_title: A custom title for the text panel::
* None (default): No title
* String value: Custom title
:type custom_title: basestring or None
:param collapsible: A boolean to decide whether the panel is collapsible or not (default True)
:type collapsible: bool
:param collapsed: A boolean to decide whether the panel is collapsed or not (default False)
:type collapsible: bool
:raises IllegalArgumentError: When unknown or illegal arguments are passed.
"""
# Declare text widget config
config = {
"xtype": ComponentXType.HTMLPANEL,
"filter": {
"activity_id": str(self.activity.id),
}
}
# Add text and custom title
if text:
config['html'] = text
if custom_title:
show_title_value = "Custom title"
title = custom_title
else:
show_title_value = "No title"
title = None
config['collapsible'] = collapsible
# A widget can only be collapsed if it is collapsible in the first place
if collapsible:
config['collapsed'] = collapsed
else:
config['collapsed'] = False
config['title'] = title
# Declare the meta info for the property grid
meta = {
"activityId": str(self.activity.id),
"customTitle": title,
"collapsible": collapsible,
"collapsed": collapsed,
"html": text,
"showTitleValue": show_title_value
}
self._add_widget(dict(config=config, meta=meta, name=WidgetNames.HTMLWIDGET)) | python | def add_text_widget(self, text=None, custom_title=None, collapsible=True, collapsed=False):
"""
Add a KE-chain Text widget to the customization.
The widget will be saved to KE-chain.
:param text: The text that will be shown by the widget.
:type text: basestring or None
:param custom_title: A custom title for the text panel::
* None (default): No title
* String value: Custom title
:type custom_title: basestring or None
:param collapsible: A boolean to decide whether the panel is collapsible or not (default True)
:type collapsible: bool
:param collapsed: A boolean to decide whether the panel is collapsed or not (default False)
:type collapsible: bool
:raises IllegalArgumentError: When unknown or illegal arguments are passed.
"""
# Declare text widget config
config = {
"xtype": ComponentXType.HTMLPANEL,
"filter": {
"activity_id": str(self.activity.id),
}
}
# Add text and custom title
if text:
config['html'] = text
if custom_title:
show_title_value = "Custom title"
title = custom_title
else:
show_title_value = "No title"
title = None
config['collapsible'] = collapsible
# A widget can only be collapsed if it is collapsible in the first place
if collapsible:
config['collapsed'] = collapsed
else:
config['collapsed'] = False
config['title'] = title
# Declare the meta info for the property grid
meta = {
"activityId": str(self.activity.id),
"customTitle": title,
"collapsible": collapsible,
"collapsed": collapsed,
"html": text,
"showTitleValue": show_title_value
}
self._add_widget(dict(config=config, meta=meta, name=WidgetNames.HTMLWIDGET)) | [
"def",
"add_text_widget",
"(",
"self",
",",
"text",
"=",
"None",
",",
"custom_title",
"=",
"None",
",",
"collapsible",
"=",
"True",
",",
"collapsed",
"=",
"False",
")",
":",
"# Declare text widget config",
"config",
"=",
"{",
"\"xtype\"",
":",
"ComponentXType",
".",
"HTMLPANEL",
",",
"\"filter\"",
":",
"{",
"\"activity_id\"",
":",
"str",
"(",
"self",
".",
"activity",
".",
"id",
")",
",",
"}",
"}",
"# Add text and custom title",
"if",
"text",
":",
"config",
"[",
"'html'",
"]",
"=",
"text",
"if",
"custom_title",
":",
"show_title_value",
"=",
"\"Custom title\"",
"title",
"=",
"custom_title",
"else",
":",
"show_title_value",
"=",
"\"No title\"",
"title",
"=",
"None",
"config",
"[",
"'collapsible'",
"]",
"=",
"collapsible",
"# A widget can only be collapsed if it is collapsible in the first place",
"if",
"collapsible",
":",
"config",
"[",
"'collapsed'",
"]",
"=",
"collapsed",
"else",
":",
"config",
"[",
"'collapsed'",
"]",
"=",
"False",
"config",
"[",
"'title'",
"]",
"=",
"title",
"# Declare the meta info for the property grid",
"meta",
"=",
"{",
"\"activityId\"",
":",
"str",
"(",
"self",
".",
"activity",
".",
"id",
")",
",",
"\"customTitle\"",
":",
"title",
",",
"\"collapsible\"",
":",
"collapsible",
",",
"\"collapsed\"",
":",
"collapsed",
",",
"\"html\"",
":",
"text",
",",
"\"showTitleValue\"",
":",
"show_title_value",
"}",
"self",
".",
"_add_widget",
"(",
"dict",
"(",
"config",
"=",
"config",
",",
"meta",
"=",
"meta",
",",
"name",
"=",
"WidgetNames",
".",
"HTMLWIDGET",
")",
")"
] | Add a KE-chain Text widget to the customization.
The widget will be saved to KE-chain.
:param text: The text that will be shown by the widget.
:type text: basestring or None
:param custom_title: A custom title for the text panel::
* None (default): No title
* String value: Custom title
:type custom_title: basestring or None
:param collapsible: A boolean to decide whether the panel is collapsible or not (default True)
:type collapsible: bool
:param collapsed: A boolean to decide whether the panel is collapsed or not (default False)
:type collapsible: bool
:raises IllegalArgumentError: When unknown or illegal arguments are passed. | [
"Add",
"a",
"KE",
"-",
"chain",
"Text",
"widget",
"to",
"the",
"customization",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L452-L504 | train |
lobocv/crashreporter | crashreporter/process.py | enable_mp_crash_reporting | def enable_mp_crash_reporting():
"""
Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess.
Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead.
This function must be called before any imports to mulitprocessing in order for the monkey-patching to work.
"""
global mp_crash_reporting_enabled
multiprocessing.Process = multiprocessing.process.Process = CrashReportingProcess
mp_crash_reporting_enabled = True | python | def enable_mp_crash_reporting():
"""
Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess.
Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead.
This function must be called before any imports to mulitprocessing in order for the monkey-patching to work.
"""
global mp_crash_reporting_enabled
multiprocessing.Process = multiprocessing.process.Process = CrashReportingProcess
mp_crash_reporting_enabled = True | [
"def",
"enable_mp_crash_reporting",
"(",
")",
":",
"global",
"mp_crash_reporting_enabled",
"multiprocessing",
".",
"Process",
"=",
"multiprocessing",
".",
"process",
".",
"Process",
"=",
"CrashReportingProcess",
"mp_crash_reporting_enabled",
"=",
"True"
] | Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess.
Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead.
This function must be called before any imports to mulitprocessing in order for the monkey-patching to work. | [
"Monkey",
"-",
"patch",
"the",
"multiprocessing",
".",
"Process",
"class",
"with",
"our",
"own",
"CrashReportingProcess",
".",
"Any",
"subsequent",
"imports",
"of",
"multiprocessing",
".",
"Process",
"will",
"reference",
"CrashReportingProcess",
"instead",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/process.py#L11-L20 | train |
thomasdelaet/python-velbus | velbus/parser.py | VelbusParser.feed | def feed(self, data):
"""
Add new incoming data to buffer and try to process
"""
self.buffer += data
while len(self.buffer) >= 6:
self.next_packet() | python | def feed(self, data):
"""
Add new incoming data to buffer and try to process
"""
self.buffer += data
while len(self.buffer) >= 6:
self.next_packet() | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"buffer",
"+=",
"data",
"while",
"len",
"(",
"self",
".",
"buffer",
")",
">=",
"6",
":",
"self",
".",
"next_packet",
"(",
")"
] | Add new incoming data to buffer and try to process | [
"Add",
"new",
"incoming",
"data",
"to",
"buffer",
"and",
"try",
"to",
"process"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L26-L32 | train |
thomasdelaet/python-velbus | velbus/parser.py | VelbusParser.valid_header_waiting | def valid_header_waiting(self):
"""
Check if a valid header is waiting in buffer
"""
if len(self.buffer) < 4:
self.logger.debug("Buffer does not yet contain full header")
result = False
else:
result = True
result = result and self.buffer[0] == velbus.START_BYTE
if not result:
self.logger.warning("Start byte not recognized")
result = result and (self.buffer[1] in velbus.PRIORITY)
if not result:
self.logger.warning("Priority not recognized")
result = result and (self.buffer[3] & 0x0F <= 8)
if not result:
self.logger.warning("Message size not recognized")
self.logger.debug("Valid Header Waiting: %s(%s)", result, str(self.buffer))
return result | python | def valid_header_waiting(self):
"""
Check if a valid header is waiting in buffer
"""
if len(self.buffer) < 4:
self.logger.debug("Buffer does not yet contain full header")
result = False
else:
result = True
result = result and self.buffer[0] == velbus.START_BYTE
if not result:
self.logger.warning("Start byte not recognized")
result = result and (self.buffer[1] in velbus.PRIORITY)
if not result:
self.logger.warning("Priority not recognized")
result = result and (self.buffer[3] & 0x0F <= 8)
if not result:
self.logger.warning("Message size not recognized")
self.logger.debug("Valid Header Waiting: %s(%s)", result, str(self.buffer))
return result | [
"def",
"valid_header_waiting",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"buffer",
")",
"<",
"4",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Buffer does not yet contain full header\"",
")",
"result",
"=",
"False",
"else",
":",
"result",
"=",
"True",
"result",
"=",
"result",
"and",
"self",
".",
"buffer",
"[",
"0",
"]",
"==",
"velbus",
".",
"START_BYTE",
"if",
"not",
"result",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Start byte not recognized\"",
")",
"result",
"=",
"result",
"and",
"(",
"self",
".",
"buffer",
"[",
"1",
"]",
"in",
"velbus",
".",
"PRIORITY",
")",
"if",
"not",
"result",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Priority not recognized\"",
")",
"result",
"=",
"result",
"and",
"(",
"self",
".",
"buffer",
"[",
"3",
"]",
"&",
"0x0F",
"<=",
"8",
")",
"if",
"not",
"result",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Message size not recognized\"",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Valid Header Waiting: %s(%s)\"",
",",
"result",
",",
"str",
"(",
"self",
".",
"buffer",
")",
")",
"return",
"result"
] | Check if a valid header is waiting in buffer | [
"Check",
"if",
"a",
"valid",
"header",
"is",
"waiting",
"in",
"buffer"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L34-L53 | train |
thomasdelaet/python-velbus | velbus/parser.py | VelbusParser.valid_body_waiting | def valid_body_waiting(self):
"""
Check if a valid body is waiting in buffer
"""
# 0f f8 be 04 00 08 00 00 2f 04
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
if len(self.buffer) < packet_size:
self.logger.debug("Buffer does not yet contain full message")
result = False
else:
result = True
result = result and self.buffer[packet_size - 1] == velbus.END_BYTE
if not result:
self.logger.warning("End byte not recognized")
result = result and velbus.checksum(
self.buffer[0:packet_size - 2])[0] == self.buffer[packet_size - 2]
if not result:
self.logger.warning("Checksum not recognized")
self.logger.debug("Valid Body Waiting: %s (%s)", result, str(self.buffer))
return result | python | def valid_body_waiting(self):
"""
Check if a valid body is waiting in buffer
"""
# 0f f8 be 04 00 08 00 00 2f 04
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
if len(self.buffer) < packet_size:
self.logger.debug("Buffer does not yet contain full message")
result = False
else:
result = True
result = result and self.buffer[packet_size - 1] == velbus.END_BYTE
if not result:
self.logger.warning("End byte not recognized")
result = result and velbus.checksum(
self.buffer[0:packet_size - 2])[0] == self.buffer[packet_size - 2]
if not result:
self.logger.warning("Checksum not recognized")
self.logger.debug("Valid Body Waiting: %s (%s)", result, str(self.buffer))
return result | [
"def",
"valid_body_waiting",
"(",
"self",
")",
":",
"# 0f f8 be 04 00 08 00 00 2f 04",
"packet_size",
"=",
"velbus",
".",
"MINIMUM_MESSAGE_SIZE",
"+",
"(",
"self",
".",
"buffer",
"[",
"3",
"]",
"&",
"0x0F",
")",
"if",
"len",
"(",
"self",
".",
"buffer",
")",
"<",
"packet_size",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Buffer does not yet contain full message\"",
")",
"result",
"=",
"False",
"else",
":",
"result",
"=",
"True",
"result",
"=",
"result",
"and",
"self",
".",
"buffer",
"[",
"packet_size",
"-",
"1",
"]",
"==",
"velbus",
".",
"END_BYTE",
"if",
"not",
"result",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"End byte not recognized\"",
")",
"result",
"=",
"result",
"and",
"velbus",
".",
"checksum",
"(",
"self",
".",
"buffer",
"[",
"0",
":",
"packet_size",
"-",
"2",
"]",
")",
"[",
"0",
"]",
"==",
"self",
".",
"buffer",
"[",
"packet_size",
"-",
"2",
"]",
"if",
"not",
"result",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Checksum not recognized\"",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Valid Body Waiting: %s (%s)\"",
",",
"result",
",",
"str",
"(",
"self",
".",
"buffer",
")",
")",
"return",
"result"
] | Check if a valid body is waiting in buffer | [
"Check",
"if",
"a",
"valid",
"body",
"is",
"waiting",
"in",
"buffer"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L55-L75 | train |
thomasdelaet/python-velbus | velbus/parser.py | VelbusParser.next_packet | def next_packet(self):
"""
Process next packet if present
"""
try:
start_byte_index = self.buffer.index(velbus.START_BYTE)
except ValueError:
self.buffer = bytes([])
return
if start_byte_index >= 0:
self.buffer = self.buffer[start_byte_index:]
if self.valid_header_waiting() and self.valid_body_waiting():
next_packet = self.extract_packet()
self.buffer = self.buffer[len(next_packet):]
message = self.parse(next_packet)
if isinstance(message, velbus.Message):
self.controller.new_message(message) | python | def next_packet(self):
"""
Process next packet if present
"""
try:
start_byte_index = self.buffer.index(velbus.START_BYTE)
except ValueError:
self.buffer = bytes([])
return
if start_byte_index >= 0:
self.buffer = self.buffer[start_byte_index:]
if self.valid_header_waiting() and self.valid_body_waiting():
next_packet = self.extract_packet()
self.buffer = self.buffer[len(next_packet):]
message = self.parse(next_packet)
if isinstance(message, velbus.Message):
self.controller.new_message(message) | [
"def",
"next_packet",
"(",
"self",
")",
":",
"try",
":",
"start_byte_index",
"=",
"self",
".",
"buffer",
".",
"index",
"(",
"velbus",
".",
"START_BYTE",
")",
"except",
"ValueError",
":",
"self",
".",
"buffer",
"=",
"bytes",
"(",
"[",
"]",
")",
"return",
"if",
"start_byte_index",
">=",
"0",
":",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"start_byte_index",
":",
"]",
"if",
"self",
".",
"valid_header_waiting",
"(",
")",
"and",
"self",
".",
"valid_body_waiting",
"(",
")",
":",
"next_packet",
"=",
"self",
".",
"extract_packet",
"(",
")",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"len",
"(",
"next_packet",
")",
":",
"]",
"message",
"=",
"self",
".",
"parse",
"(",
"next_packet",
")",
"if",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"Message",
")",
":",
"self",
".",
"controller",
".",
"new_message",
"(",
"message",
")"
] | Process next packet if present | [
"Process",
"next",
"packet",
"if",
"present"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L77-L93 | train |
thomasdelaet/python-velbus | velbus/parser.py | VelbusParser.extract_packet | def extract_packet(self):
"""
Extract packet from buffer
"""
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
packet = self.buffer[0:packet_size]
return packet | python | def extract_packet(self):
"""
Extract packet from buffer
"""
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
packet = self.buffer[0:packet_size]
return packet | [
"def",
"extract_packet",
"(",
"self",
")",
":",
"packet_size",
"=",
"velbus",
".",
"MINIMUM_MESSAGE_SIZE",
"+",
"(",
"self",
".",
"buffer",
"[",
"3",
"]",
"&",
"0x0F",
")",
"packet",
"=",
"self",
".",
"buffer",
"[",
"0",
":",
"packet_size",
"]",
"return",
"packet"
] | Extract packet from buffer | [
"Extract",
"packet",
"from",
"buffer"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L95-L102 | train |
pytroll/trollsift | trollsift/parser.py | _get_number_from_fmt | def _get_number_from_fmt(fmt):
"""
Helper function for extract_values,
figures out string length from format string.
"""
if '%' in fmt:
# its datetime
return len(("{0:" + fmt + "}").format(dt.datetime.now()))
else:
# its something else
fmt = fmt.lstrip('0')
return int(re.search('[0-9]+', fmt).group(0)) | python | def _get_number_from_fmt(fmt):
"""
Helper function for extract_values,
figures out string length from format string.
"""
if '%' in fmt:
# its datetime
return len(("{0:" + fmt + "}").format(dt.datetime.now()))
else:
# its something else
fmt = fmt.lstrip('0')
return int(re.search('[0-9]+', fmt).group(0)) | [
"def",
"_get_number_from_fmt",
"(",
"fmt",
")",
":",
"if",
"'%'",
"in",
"fmt",
":",
"# its datetime",
"return",
"len",
"(",
"(",
"\"{0:\"",
"+",
"fmt",
"+",
"\"}\"",
")",
".",
"format",
"(",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"else",
":",
"# its something else",
"fmt",
"=",
"fmt",
".",
"lstrip",
"(",
"'0'",
")",
"return",
"int",
"(",
"re",
".",
"search",
"(",
"'[0-9]+'",
",",
"fmt",
")",
".",
"group",
"(",
"0",
")",
")"
] | Helper function for extract_values,
figures out string length from format string. | [
"Helper",
"function",
"for",
"extract_values",
"figures",
"out",
"string",
"length",
"from",
"format",
"string",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L309-L320 | train |
pytroll/trollsift | trollsift/parser.py | get_convert_dict | def get_convert_dict(fmt):
"""Retrieve parse definition from the format string `fmt`."""
convdef = {}
for literal_text, field_name, format_spec, conversion in formatter.parse(fmt):
if field_name is None:
continue
# XXX: Do I need to include 'conversion'?
convdef[field_name] = format_spec
return convdef | python | def get_convert_dict(fmt):
"""Retrieve parse definition from the format string `fmt`."""
convdef = {}
for literal_text, field_name, format_spec, conversion in formatter.parse(fmt):
if field_name is None:
continue
# XXX: Do I need to include 'conversion'?
convdef[field_name] = format_spec
return convdef | [
"def",
"get_convert_dict",
"(",
"fmt",
")",
":",
"convdef",
"=",
"{",
"}",
"for",
"literal_text",
",",
"field_name",
",",
"format_spec",
",",
"conversion",
"in",
"formatter",
".",
"parse",
"(",
"fmt",
")",
":",
"if",
"field_name",
"is",
"None",
":",
"continue",
"# XXX: Do I need to include 'conversion'?",
"convdef",
"[",
"field_name",
"]",
"=",
"format_spec",
"return",
"convdef"
] | Retrieve parse definition from the format string `fmt`. | [
"Retrieve",
"parse",
"definition",
"from",
"the",
"format",
"string",
"fmt",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L354-L362 | train |
pytroll/trollsift | trollsift/parser.py | _generate_data_for_format | def _generate_data_for_format(fmt):
"""Generate a fake data dictionary to fill in the provided format string."""
# finally try some data, create some random data for the fmt.
data = {}
# keep track of how many "free_size" (wildcard) parameters we have
# if we get two in a row then we know the pattern is invalid, meaning
# we'll never be able to match the second wildcard field
free_size_start = False
for literal_text, field_name, format_spec, conversion in formatter.parse(fmt):
if literal_text:
free_size_start = False
if not field_name:
free_size_start = False
continue
# encapsulating free size keys,
# e.g. {:s}{:s} or {:s}{:4s}{:d}
if not format_spec or format_spec == "s" or format_spec == "d":
if free_size_start:
return None
else:
free_size_start = True
# make some data for this key and format
if format_spec and '%' in format_spec:
# some datetime
t = dt.datetime.now()
# run once through format to limit precision
t = parse(
"{t:" + format_spec + "}", compose("{t:" + format_spec + "}", {'t': t}))['t']
data[field_name] = t
elif format_spec and 'd' in format_spec:
# random number (with n sign. figures)
if not format_spec.isalpha():
n = _get_number_from_fmt(format_spec)
else:
# clearly bad
return None
data[field_name] = random.randint(0, 99999999999999999) % (10 ** n)
else:
# string type
if format_spec is None:
n = 4
elif format_spec.isalnum():
n = _get_number_from_fmt(format_spec)
else:
n = 4
randstri = ''
for x in range(n):
randstri += random.choice(string.ascii_letters)
data[field_name] = randstri
return data | python | def _generate_data_for_format(fmt):
"""Generate a fake data dictionary to fill in the provided format string."""
# finally try some data, create some random data for the fmt.
data = {}
# keep track of how many "free_size" (wildcard) parameters we have
# if we get two in a row then we know the pattern is invalid, meaning
# we'll never be able to match the second wildcard field
free_size_start = False
for literal_text, field_name, format_spec, conversion in formatter.parse(fmt):
if literal_text:
free_size_start = False
if not field_name:
free_size_start = False
continue
# encapsulating free size keys,
# e.g. {:s}{:s} or {:s}{:4s}{:d}
if not format_spec or format_spec == "s" or format_spec == "d":
if free_size_start:
return None
else:
free_size_start = True
# make some data for this key and format
if format_spec and '%' in format_spec:
# some datetime
t = dt.datetime.now()
# run once through format to limit precision
t = parse(
"{t:" + format_spec + "}", compose("{t:" + format_spec + "}", {'t': t}))['t']
data[field_name] = t
elif format_spec and 'd' in format_spec:
# random number (with n sign. figures)
if not format_spec.isalpha():
n = _get_number_from_fmt(format_spec)
else:
# clearly bad
return None
data[field_name] = random.randint(0, 99999999999999999) % (10 ** n)
else:
# string type
if format_spec is None:
n = 4
elif format_spec.isalnum():
n = _get_number_from_fmt(format_spec)
else:
n = 4
randstri = ''
for x in range(n):
randstri += random.choice(string.ascii_letters)
data[field_name] = randstri
return data | [
"def",
"_generate_data_for_format",
"(",
"fmt",
")",
":",
"# finally try some data, create some random data for the fmt.",
"data",
"=",
"{",
"}",
"# keep track of how many \"free_size\" (wildcard) parameters we have",
"# if we get two in a row then we know the pattern is invalid, meaning",
"# we'll never be able to match the second wildcard field",
"free_size_start",
"=",
"False",
"for",
"literal_text",
",",
"field_name",
",",
"format_spec",
",",
"conversion",
"in",
"formatter",
".",
"parse",
"(",
"fmt",
")",
":",
"if",
"literal_text",
":",
"free_size_start",
"=",
"False",
"if",
"not",
"field_name",
":",
"free_size_start",
"=",
"False",
"continue",
"# encapsulating free size keys,",
"# e.g. {:s}{:s} or {:s}{:4s}{:d}",
"if",
"not",
"format_spec",
"or",
"format_spec",
"==",
"\"s\"",
"or",
"format_spec",
"==",
"\"d\"",
":",
"if",
"free_size_start",
":",
"return",
"None",
"else",
":",
"free_size_start",
"=",
"True",
"# make some data for this key and format",
"if",
"format_spec",
"and",
"'%'",
"in",
"format_spec",
":",
"# some datetime",
"t",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"# run once through format to limit precision",
"t",
"=",
"parse",
"(",
"\"{t:\"",
"+",
"format_spec",
"+",
"\"}\"",
",",
"compose",
"(",
"\"{t:\"",
"+",
"format_spec",
"+",
"\"}\"",
",",
"{",
"'t'",
":",
"t",
"}",
")",
")",
"[",
"'t'",
"]",
"data",
"[",
"field_name",
"]",
"=",
"t",
"elif",
"format_spec",
"and",
"'d'",
"in",
"format_spec",
":",
"# random number (with n sign. figures)",
"if",
"not",
"format_spec",
".",
"isalpha",
"(",
")",
":",
"n",
"=",
"_get_number_from_fmt",
"(",
"format_spec",
")",
"else",
":",
"# clearly bad",
"return",
"None",
"data",
"[",
"field_name",
"]",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"99999999999999999",
")",
"%",
"(",
"10",
"**",
"n",
")",
"else",
":",
"# string type",
"if",
"format_spec",
"is",
"None",
":",
"n",
"=",
"4",
"elif",
"format_spec",
".",
"isalnum",
"(",
")",
":",
"n",
"=",
"_get_number_from_fmt",
"(",
"format_spec",
")",
"else",
":",
"n",
"=",
"4",
"randstri",
"=",
"''",
"for",
"x",
"in",
"range",
"(",
"n",
")",
":",
"randstri",
"+=",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
")",
"data",
"[",
"field_name",
"]",
"=",
"randstri",
"return",
"data"
] | Generate a fake data dictionary to fill in the provided format string. | [
"Generate",
"a",
"fake",
"data",
"dictionary",
"to",
"fill",
"in",
"the",
"provided",
"format",
"string",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L472-L524 | train |
pytroll/trollsift | trollsift/parser.py | is_one2one | def is_one2one(fmt):
"""
Runs a check to evaluate if the format string has a
one to one correspondence. I.e. that successive composing and
parsing opperations will result in the original data.
In other words, that input data maps to a string,
which then maps back to the original data without any change
or loss in information.
Note: This test only applies to sensible usage of the format string.
If string or numeric data is causes overflow, e.g.
if composing "abcd" into {3s}, one to one correspondence will always
be broken in such cases. This of course also applies to precision
losses when using datetime data.
"""
data = _generate_data_for_format(fmt)
if data is None:
return False
# run data forward once and back to data
stri = compose(fmt, data)
data2 = parse(fmt, stri)
# check if data2 equal to original data
if len(data) != len(data2):
return False
for key in data:
if key not in data2:
return False
if data2[key] != data[key]:
return False
# all checks passed, so just return True
return True | python | def is_one2one(fmt):
"""
Runs a check to evaluate if the format string has a
one to one correspondence. I.e. that successive composing and
parsing opperations will result in the original data.
In other words, that input data maps to a string,
which then maps back to the original data without any change
or loss in information.
Note: This test only applies to sensible usage of the format string.
If string or numeric data is causes overflow, e.g.
if composing "abcd" into {3s}, one to one correspondence will always
be broken in such cases. This of course also applies to precision
losses when using datetime data.
"""
data = _generate_data_for_format(fmt)
if data is None:
return False
# run data forward once and back to data
stri = compose(fmt, data)
data2 = parse(fmt, stri)
# check if data2 equal to original data
if len(data) != len(data2):
return False
for key in data:
if key not in data2:
return False
if data2[key] != data[key]:
return False
# all checks passed, so just return True
return True | [
"def",
"is_one2one",
"(",
"fmt",
")",
":",
"data",
"=",
"_generate_data_for_format",
"(",
"fmt",
")",
"if",
"data",
"is",
"None",
":",
"return",
"False",
"# run data forward once and back to data",
"stri",
"=",
"compose",
"(",
"fmt",
",",
"data",
")",
"data2",
"=",
"parse",
"(",
"fmt",
",",
"stri",
")",
"# check if data2 equal to original data",
"if",
"len",
"(",
"data",
")",
"!=",
"len",
"(",
"data2",
")",
":",
"return",
"False",
"for",
"key",
"in",
"data",
":",
"if",
"key",
"not",
"in",
"data2",
":",
"return",
"False",
"if",
"data2",
"[",
"key",
"]",
"!=",
"data",
"[",
"key",
"]",
":",
"return",
"False",
"# all checks passed, so just return True",
"return",
"True"
] | Runs a check to evaluate if the format string has a
one to one correspondence. I.e. that successive composing and
parsing opperations will result in the original data.
In other words, that input data maps to a string,
which then maps back to the original data without any change
or loss in information.
Note: This test only applies to sensible usage of the format string.
If string or numeric data is causes overflow, e.g.
if composing "abcd" into {3s}, one to one correspondence will always
be broken in such cases. This of course also applies to precision
losses when using datetime data. | [
"Runs",
"a",
"check",
"to",
"evaluate",
"if",
"the",
"format",
"string",
"has",
"a",
"one",
"to",
"one",
"correspondence",
".",
"I",
".",
"e",
".",
"that",
"successive",
"composing",
"and",
"parsing",
"opperations",
"will",
"result",
"in",
"the",
"original",
"data",
".",
"In",
"other",
"words",
"that",
"input",
"data",
"maps",
"to",
"a",
"string",
"which",
"then",
"maps",
"back",
"to",
"the",
"original",
"data",
"without",
"any",
"change",
"or",
"loss",
"in",
"information",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L527-L558 | train |
pytroll/trollsift | trollsift/parser.py | StringFormatter.convert_field | def convert_field(self, value, conversion):
"""Apply conversions mentioned above."""
func = self.CONV_FUNCS.get(conversion)
if func is not None:
value = getattr(value, func)()
elif conversion not in ['R']:
# default conversion ('r', 's')
return super(StringFormatter, self).convert_field(value, conversion)
if conversion in ['h', 'H', 'R']:
value = value.replace('-', '').replace('_', '').replace(':', '').replace(' ', '')
return value | python | def convert_field(self, value, conversion):
"""Apply conversions mentioned above."""
func = self.CONV_FUNCS.get(conversion)
if func is not None:
value = getattr(value, func)()
elif conversion not in ['R']:
# default conversion ('r', 's')
return super(StringFormatter, self).convert_field(value, conversion)
if conversion in ['h', 'H', 'R']:
value = value.replace('-', '').replace('_', '').replace(':', '').replace(' ', '')
return value | [
"def",
"convert_field",
"(",
"self",
",",
"value",
",",
"conversion",
")",
":",
"func",
"=",
"self",
".",
"CONV_FUNCS",
".",
"get",
"(",
"conversion",
")",
"if",
"func",
"is",
"not",
"None",
":",
"value",
"=",
"getattr",
"(",
"value",
",",
"func",
")",
"(",
")",
"elif",
"conversion",
"not",
"in",
"[",
"'R'",
"]",
":",
"# default conversion ('r', 's')",
"return",
"super",
"(",
"StringFormatter",
",",
"self",
")",
".",
"convert_field",
"(",
"value",
",",
"conversion",
")",
"if",
"conversion",
"in",
"[",
"'h'",
",",
"'H'",
",",
"'R'",
"]",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
".",
"replace",
"(",
"':'",
",",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"value"
] | Apply conversions mentioned above. | [
"Apply",
"conversions",
"mentioned",
"above",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L123-L134 | train |
pytroll/trollsift | trollsift/parser.py | RegexFormatter._escape | def _escape(self, s):
"""Escape bad characters for regular expressions.
Similar to `re.escape` but allows '%' to pass through.
"""
for ch, r_ch in self.ESCAPE_SETS:
s = s.replace(ch, r_ch)
return s | python | def _escape(self, s):
"""Escape bad characters for regular expressions.
Similar to `re.escape` but allows '%' to pass through.
"""
for ch, r_ch in self.ESCAPE_SETS:
s = s.replace(ch, r_ch)
return s | [
"def",
"_escape",
"(",
"self",
",",
"s",
")",
":",
"for",
"ch",
",",
"r_ch",
"in",
"self",
".",
"ESCAPE_SETS",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"ch",
",",
"r_ch",
")",
"return",
"s"
] | Escape bad characters for regular expressions.
Similar to `re.escape` but allows '%' to pass through. | [
"Escape",
"bad",
"characters",
"for",
"regular",
"expressions",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L196-L204 | train |
pytroll/trollsift | trollsift/parser.py | RegexFormatter.format_spec_to_regex | def format_spec_to_regex(field_name, format_spec):
"""Make an attempt at converting a format spec to a regular expression."""
# NOTE: remove escaped backslashes so regex matches
regex_match = fmt_spec_regex.match(format_spec.replace('\\', ''))
if regex_match is None:
raise ValueError("Invalid format specification: '{}'".format(format_spec))
regex_dict = regex_match.groupdict()
fill = regex_dict['fill']
ftype = regex_dict['type']
width = regex_dict['width']
align = regex_dict['align']
# NOTE: does not properly handle `=` alignment
if fill is None:
if width is not None and width[0] == '0':
fill = '0'
elif ftype in ['s', 'd']:
fill = ' '
char_type = spec_regexes[ftype]
if ftype == 's' and align and align.endswith('='):
raise ValueError("Invalid format specification: '{}'".format(format_spec))
final_regex = char_type
if ftype in allow_multiple and (not width or width == '0'):
final_regex += r'*'
elif width and width != '0':
if not fill:
# we know we have exactly this many characters
final_regex += r'{{{}}}'.format(int(width))
elif fill:
# we don't know how many fill characters we have compared to
# field characters so just match all characters and sort it out
# later during type conversion.
final_regex = r'.{{{}}}'.format(int(width))
elif ftype in allow_multiple:
final_regex += r'*'
return r'(?P<{}>{})'.format(field_name, final_regex) | python | def format_spec_to_regex(field_name, format_spec):
"""Make an attempt at converting a format spec to a regular expression."""
# NOTE: remove escaped backslashes so regex matches
regex_match = fmt_spec_regex.match(format_spec.replace('\\', ''))
if regex_match is None:
raise ValueError("Invalid format specification: '{}'".format(format_spec))
regex_dict = regex_match.groupdict()
fill = regex_dict['fill']
ftype = regex_dict['type']
width = regex_dict['width']
align = regex_dict['align']
# NOTE: does not properly handle `=` alignment
if fill is None:
if width is not None and width[0] == '0':
fill = '0'
elif ftype in ['s', 'd']:
fill = ' '
char_type = spec_regexes[ftype]
if ftype == 's' and align and align.endswith('='):
raise ValueError("Invalid format specification: '{}'".format(format_spec))
final_regex = char_type
if ftype in allow_multiple and (not width or width == '0'):
final_regex += r'*'
elif width and width != '0':
if not fill:
# we know we have exactly this many characters
final_regex += r'{{{}}}'.format(int(width))
elif fill:
# we don't know how many fill characters we have compared to
# field characters so just match all characters and sort it out
# later during type conversion.
final_regex = r'.{{{}}}'.format(int(width))
elif ftype in allow_multiple:
final_regex += r'*'
return r'(?P<{}>{})'.format(field_name, final_regex) | [
"def",
"format_spec_to_regex",
"(",
"field_name",
",",
"format_spec",
")",
":",
"# NOTE: remove escaped backslashes so regex matches",
"regex_match",
"=",
"fmt_spec_regex",
".",
"match",
"(",
"format_spec",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
")",
"if",
"regex_match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid format specification: '{}'\"",
".",
"format",
"(",
"format_spec",
")",
")",
"regex_dict",
"=",
"regex_match",
".",
"groupdict",
"(",
")",
"fill",
"=",
"regex_dict",
"[",
"'fill'",
"]",
"ftype",
"=",
"regex_dict",
"[",
"'type'",
"]",
"width",
"=",
"regex_dict",
"[",
"'width'",
"]",
"align",
"=",
"regex_dict",
"[",
"'align'",
"]",
"# NOTE: does not properly handle `=` alignment",
"if",
"fill",
"is",
"None",
":",
"if",
"width",
"is",
"not",
"None",
"and",
"width",
"[",
"0",
"]",
"==",
"'0'",
":",
"fill",
"=",
"'0'",
"elif",
"ftype",
"in",
"[",
"'s'",
",",
"'d'",
"]",
":",
"fill",
"=",
"' '",
"char_type",
"=",
"spec_regexes",
"[",
"ftype",
"]",
"if",
"ftype",
"==",
"'s'",
"and",
"align",
"and",
"align",
".",
"endswith",
"(",
"'='",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid format specification: '{}'\"",
".",
"format",
"(",
"format_spec",
")",
")",
"final_regex",
"=",
"char_type",
"if",
"ftype",
"in",
"allow_multiple",
"and",
"(",
"not",
"width",
"or",
"width",
"==",
"'0'",
")",
":",
"final_regex",
"+=",
"r'*'",
"elif",
"width",
"and",
"width",
"!=",
"'0'",
":",
"if",
"not",
"fill",
":",
"# we know we have exactly this many characters",
"final_regex",
"+=",
"r'{{{}}}'",
".",
"format",
"(",
"int",
"(",
"width",
")",
")",
"elif",
"fill",
":",
"# we don't know how many fill characters we have compared to",
"# field characters so just match all characters and sort it out",
"# later during type conversion.",
"final_regex",
"=",
"r'.{{{}}}'",
".",
"format",
"(",
"int",
"(",
"width",
")",
")",
"elif",
"ftype",
"in",
"allow_multiple",
":",
"final_regex",
"+=",
"r'*'",
"return",
"r'(?P<{}>{})'",
".",
"format",
"(",
"field_name",
",",
"final_regex",
")"
] | Make an attempt at converting a format spec to a regular expression. | [
"Make",
"an",
"attempt",
"at",
"converting",
"a",
"format",
"spec",
"to",
"a",
"regular",
"expression",
"."
] | d0e5b6006e248974d806d0dd8e20cc6641d778fb | https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L235-L271 | train |
thomasdelaet/python-velbus | velbus/controller.py | Controller.feed_parser | def feed_parser(self, data):
"""
Feed parser with new data
:return: None
"""
assert isinstance(data, bytes)
self.parser.feed(data) | python | def feed_parser(self, data):
"""
Feed parser with new data
:return: None
"""
assert isinstance(data, bytes)
self.parser.feed(data) | [
"def",
"feed_parser",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"parser",
".",
"feed",
"(",
"data",
")"
] | Feed parser with new data
:return: None | [
"Feed",
"parser",
"with",
"new",
"data"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L49-L56 | train |
thomasdelaet/python-velbus | velbus/controller.py | Controller.scan | def scan(self, callback=None):
"""
Scan the bus and call the callback when a new module is discovered
:return: None
"""
def scan_finished():
"""
Callback when scan is finished
"""
time.sleep(3)
logging.info('Scan finished')
self._nb_of_modules_loaded = 0
def module_loaded():
self._nb_of_modules_loaded += 1
if self._nb_of_modules_loaded >= len(self._modules):
callback()
for module in self._modules:
self._modules[module].load(module_loaded)
for address in range(0, 256):
message = velbus.ModuleTypeRequestMessage(address)
if address == 255:
self.send(message, scan_finished)
else:
self.send(message) | python | def scan(self, callback=None):
"""
Scan the bus and call the callback when a new module is discovered
:return: None
"""
def scan_finished():
"""
Callback when scan is finished
"""
time.sleep(3)
logging.info('Scan finished')
self._nb_of_modules_loaded = 0
def module_loaded():
self._nb_of_modules_loaded += 1
if self._nb_of_modules_loaded >= len(self._modules):
callback()
for module in self._modules:
self._modules[module].load(module_loaded)
for address in range(0, 256):
message = velbus.ModuleTypeRequestMessage(address)
if address == 255:
self.send(message, scan_finished)
else:
self.send(message) | [
"def",
"scan",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"def",
"scan_finished",
"(",
")",
":",
"\"\"\"\n Callback when scan is finished\n \"\"\"",
"time",
".",
"sleep",
"(",
"3",
")",
"logging",
".",
"info",
"(",
"'Scan finished'",
")",
"self",
".",
"_nb_of_modules_loaded",
"=",
"0",
"def",
"module_loaded",
"(",
")",
":",
"self",
".",
"_nb_of_modules_loaded",
"+=",
"1",
"if",
"self",
".",
"_nb_of_modules_loaded",
">=",
"len",
"(",
"self",
".",
"_modules",
")",
":",
"callback",
"(",
")",
"for",
"module",
"in",
"self",
".",
"_modules",
":",
"self",
".",
"_modules",
"[",
"module",
"]",
".",
"load",
"(",
"module_loaded",
")",
"for",
"address",
"in",
"range",
"(",
"0",
",",
"256",
")",
":",
"message",
"=",
"velbus",
".",
"ModuleTypeRequestMessage",
"(",
"address",
")",
"if",
"address",
"==",
"255",
":",
"self",
".",
"send",
"(",
"message",
",",
"scan_finished",
")",
"else",
":",
"self",
".",
"send",
"(",
"message",
")"
] | Scan the bus and call the callback when a new module is discovered
:return: None | [
"Scan",
"the",
"bus",
"and",
"call",
"the",
"callback",
"when",
"a",
"new",
"module",
"is",
"discovered"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L96-L121 | train |
thomasdelaet/python-velbus | velbus/controller.py | Controller.sync_clock | def sync_clock(self):
"""
This will send all the needed messages to sync the cloc
"""
self.send(velbus.SetRealtimeClock())
self.send(velbus.SetDate())
self.send(velbus.SetDaylightSaving()) | python | def sync_clock(self):
"""
This will send all the needed messages to sync the cloc
"""
self.send(velbus.SetRealtimeClock())
self.send(velbus.SetDate())
self.send(velbus.SetDaylightSaving()) | [
"def",
"sync_clock",
"(",
"self",
")",
":",
"self",
".",
"send",
"(",
"velbus",
".",
"SetRealtimeClock",
"(",
")",
")",
"self",
".",
"send",
"(",
"velbus",
".",
"SetDate",
"(",
")",
")",
"self",
".",
"send",
"(",
"velbus",
".",
"SetDaylightSaving",
"(",
")",
")"
] | This will send all the needed messages to sync the cloc | [
"This",
"will",
"send",
"all",
"the",
"needed",
"messages",
"to",
"sync",
"the",
"cloc"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L167-L173 | train |
lobocv/crashreporter | crashreporter/tools.py | string_variable_lookup | def string_variable_lookup(tb, s):
"""
Look up the value of an object in a traceback by a dot-lookup string.
ie. "self.crashreporter.application_name"
Returns ValueError if value was not found in the scope of the traceback.
:param tb: traceback
:param s: lookup string
:return: value of the
"""
refs = []
dot_refs = s.split('.')
DOT_LOOKUP = 0
DICT_LOOKUP = 1
for ii, ref in enumerate(dot_refs):
dict_refs = dict_lookup_regex.findall(ref)
if dict_refs:
bracket = ref.index('[')
refs.append((DOT_LOOKUP, ref[:bracket]))
refs.extend([(DICT_LOOKUP, t) for t in dict_refs])
else:
refs.append((DOT_LOOKUP, ref))
scope = tb.tb_frame.f_locals.get(refs[0][1], ValueError)
if scope is ValueError:
return scope
for lookup, ref in refs[1:]:
try:
if lookup == DOT_LOOKUP:
scope = getattr(scope, ref, ValueError)
else:
scope = scope.get(ref, ValueError)
except Exception as e:
logging.error(e)
scope = ValueError
if scope is ValueError:
return scope
elif isinstance(scope, (FunctionType, MethodType, ModuleType, BuiltinMethodType, BuiltinFunctionType)):
return ValueError
return scope | python | def string_variable_lookup(tb, s):
"""
Look up the value of an object in a traceback by a dot-lookup string.
ie. "self.crashreporter.application_name"
Returns ValueError if value was not found in the scope of the traceback.
:param tb: traceback
:param s: lookup string
:return: value of the
"""
refs = []
dot_refs = s.split('.')
DOT_LOOKUP = 0
DICT_LOOKUP = 1
for ii, ref in enumerate(dot_refs):
dict_refs = dict_lookup_regex.findall(ref)
if dict_refs:
bracket = ref.index('[')
refs.append((DOT_LOOKUP, ref[:bracket]))
refs.extend([(DICT_LOOKUP, t) for t in dict_refs])
else:
refs.append((DOT_LOOKUP, ref))
scope = tb.tb_frame.f_locals.get(refs[0][1], ValueError)
if scope is ValueError:
return scope
for lookup, ref in refs[1:]:
try:
if lookup == DOT_LOOKUP:
scope = getattr(scope, ref, ValueError)
else:
scope = scope.get(ref, ValueError)
except Exception as e:
logging.error(e)
scope = ValueError
if scope is ValueError:
return scope
elif isinstance(scope, (FunctionType, MethodType, ModuleType, BuiltinMethodType, BuiltinFunctionType)):
return ValueError
return scope | [
"def",
"string_variable_lookup",
"(",
"tb",
",",
"s",
")",
":",
"refs",
"=",
"[",
"]",
"dot_refs",
"=",
"s",
".",
"split",
"(",
"'.'",
")",
"DOT_LOOKUP",
"=",
"0",
"DICT_LOOKUP",
"=",
"1",
"for",
"ii",
",",
"ref",
"in",
"enumerate",
"(",
"dot_refs",
")",
":",
"dict_refs",
"=",
"dict_lookup_regex",
".",
"findall",
"(",
"ref",
")",
"if",
"dict_refs",
":",
"bracket",
"=",
"ref",
".",
"index",
"(",
"'['",
")",
"refs",
".",
"append",
"(",
"(",
"DOT_LOOKUP",
",",
"ref",
"[",
":",
"bracket",
"]",
")",
")",
"refs",
".",
"extend",
"(",
"[",
"(",
"DICT_LOOKUP",
",",
"t",
")",
"for",
"t",
"in",
"dict_refs",
"]",
")",
"else",
":",
"refs",
".",
"append",
"(",
"(",
"DOT_LOOKUP",
",",
"ref",
")",
")",
"scope",
"=",
"tb",
".",
"tb_frame",
".",
"f_locals",
".",
"get",
"(",
"refs",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"ValueError",
")",
"if",
"scope",
"is",
"ValueError",
":",
"return",
"scope",
"for",
"lookup",
",",
"ref",
"in",
"refs",
"[",
"1",
":",
"]",
":",
"try",
":",
"if",
"lookup",
"==",
"DOT_LOOKUP",
":",
"scope",
"=",
"getattr",
"(",
"scope",
",",
"ref",
",",
"ValueError",
")",
"else",
":",
"scope",
"=",
"scope",
".",
"get",
"(",
"ref",
",",
"ValueError",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"e",
")",
"scope",
"=",
"ValueError",
"if",
"scope",
"is",
"ValueError",
":",
"return",
"scope",
"elif",
"isinstance",
"(",
"scope",
",",
"(",
"FunctionType",
",",
"MethodType",
",",
"ModuleType",
",",
"BuiltinMethodType",
",",
"BuiltinFunctionType",
")",
")",
":",
"return",
"ValueError",
"return",
"scope"
] | Look up the value of an object in a traceback by a dot-lookup string.
ie. "self.crashreporter.application_name"
Returns ValueError if value was not found in the scope of the traceback.
:param tb: traceback
:param s: lookup string
:return: value of the | [
"Look",
"up",
"the",
"value",
"of",
"an",
"object",
"in",
"a",
"traceback",
"by",
"a",
"dot",
"-",
"lookup",
"string",
".",
"ie",
".",
"self",
".",
"crashreporter",
".",
"application_name"
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L28-L70 | train |
lobocv/crashreporter | crashreporter/tools.py | get_object_references | def get_object_references(tb, source, max_string_length=1000):
"""
Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
global obj_ref_regex
referenced_attr = set()
for line in source.split('\n'):
referenced_attr.update(set(re.findall(obj_ref_regex, line)))
referenced_attr = sorted(referenced_attr)
info = []
for attr in referenced_attr:
v = string_variable_lookup(tb, attr)
if v is not ValueError:
ref_string = format_reference(v, max_string_length=max_string_length)
info.append((attr, ref_string))
return info | python | def get_object_references(tb, source, max_string_length=1000):
"""
Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
global obj_ref_regex
referenced_attr = set()
for line in source.split('\n'):
referenced_attr.update(set(re.findall(obj_ref_regex, line)))
referenced_attr = sorted(referenced_attr)
info = []
for attr in referenced_attr:
v = string_variable_lookup(tb, attr)
if v is not ValueError:
ref_string = format_reference(v, max_string_length=max_string_length)
info.append((attr, ref_string))
return info | [
"def",
"get_object_references",
"(",
"tb",
",",
"source",
",",
"max_string_length",
"=",
"1000",
")",
":",
"global",
"obj_ref_regex",
"referenced_attr",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"source",
".",
"split",
"(",
"'\\n'",
")",
":",
"referenced_attr",
".",
"update",
"(",
"set",
"(",
"re",
".",
"findall",
"(",
"obj_ref_regex",
",",
"line",
")",
")",
")",
"referenced_attr",
"=",
"sorted",
"(",
"referenced_attr",
")",
"info",
"=",
"[",
"]",
"for",
"attr",
"in",
"referenced_attr",
":",
"v",
"=",
"string_variable_lookup",
"(",
"tb",
",",
"attr",
")",
"if",
"v",
"is",
"not",
"ValueError",
":",
"ref_string",
"=",
"format_reference",
"(",
"v",
",",
"max_string_length",
"=",
"max_string_length",
")",
"info",
".",
"append",
"(",
"(",
"attr",
",",
"ref_string",
")",
")",
"return",
"info"
] | Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value) | [
"Find",
"the",
"values",
"of",
"referenced",
"attributes",
"of",
"objects",
"within",
"the",
"traceback",
"scope",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L73-L91 | train |
lobocv/crashreporter | crashreporter/tools.py | get_local_references | def get_local_references(tb, max_string_length=1000):
"""
Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
if 'self' in tb.tb_frame.f_locals:
_locals = [('self', repr(tb.tb_frame.f_locals['self']))]
else:
_locals = []
for k, v in tb.tb_frame.f_locals.iteritems():
if k == 'self':
continue
try:
vstr = format_reference(v, max_string_length=max_string_length)
_locals.append((k, vstr))
except TypeError:
pass
return _locals | python | def get_local_references(tb, max_string_length=1000):
"""
Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
if 'self' in tb.tb_frame.f_locals:
_locals = [('self', repr(tb.tb_frame.f_locals['self']))]
else:
_locals = []
for k, v in tb.tb_frame.f_locals.iteritems():
if k == 'self':
continue
try:
vstr = format_reference(v, max_string_length=max_string_length)
_locals.append((k, vstr))
except TypeError:
pass
return _locals | [
"def",
"get_local_references",
"(",
"tb",
",",
"max_string_length",
"=",
"1000",
")",
":",
"if",
"'self'",
"in",
"tb",
".",
"tb_frame",
".",
"f_locals",
":",
"_locals",
"=",
"[",
"(",
"'self'",
",",
"repr",
"(",
"tb",
".",
"tb_frame",
".",
"f_locals",
"[",
"'self'",
"]",
")",
")",
"]",
"else",
":",
"_locals",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"tb",
".",
"tb_frame",
".",
"f_locals",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"==",
"'self'",
":",
"continue",
"try",
":",
"vstr",
"=",
"format_reference",
"(",
"v",
",",
"max_string_length",
"=",
"max_string_length",
")",
"_locals",
".",
"append",
"(",
"(",
"k",
",",
"vstr",
")",
")",
"except",
"TypeError",
":",
"pass",
"return",
"_locals"
] | Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value) | [
"Find",
"the",
"values",
"of",
"the",
"local",
"variables",
"within",
"the",
"traceback",
"scope",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L94-L113 | train |
lobocv/crashreporter | crashreporter/tools.py | analyze_traceback | def analyze_traceback(tb, inspection_level=None, limit=None):
"""
Extract trace back information into a list of dictionaries.
:param tb: traceback
:return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks
"""
info = []
tb_level = tb
extracted_tb = traceback.extract_tb(tb, limit=limit)
for ii, (filepath, line, module, code) in enumerate(extracted_tb):
func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)
d = {"File": filepath,
"Error Line Number": line,
"Module": module,
"Error Line": code,
"Module Line Number": func_lineno,
"Custom Inspection": {},
"Source Code": ''}
if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
# Perform advanced inspection on the last `inspection_level` tracebacks.
d['Source Code'] = ''.join(func_source)
d['Local Variables'] = get_local_references(tb_level)
d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
tb_level = getattr(tb_level, 'tb_next', None)
info.append(d)
return info | python | def analyze_traceback(tb, inspection_level=None, limit=None):
"""
Extract trace back information into a list of dictionaries.
:param tb: traceback
:return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks
"""
info = []
tb_level = tb
extracted_tb = traceback.extract_tb(tb, limit=limit)
for ii, (filepath, line, module, code) in enumerate(extracted_tb):
func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)
d = {"File": filepath,
"Error Line Number": line,
"Module": module,
"Error Line": code,
"Module Line Number": func_lineno,
"Custom Inspection": {},
"Source Code": ''}
if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
# Perform advanced inspection on the last `inspection_level` tracebacks.
d['Source Code'] = ''.join(func_source)
d['Local Variables'] = get_local_references(tb_level)
d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
tb_level = getattr(tb_level, 'tb_next', None)
info.append(d)
return info | [
"def",
"analyze_traceback",
"(",
"tb",
",",
"inspection_level",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"info",
"=",
"[",
"]",
"tb_level",
"=",
"tb",
"extracted_tb",
"=",
"traceback",
".",
"extract_tb",
"(",
"tb",
",",
"limit",
"=",
"limit",
")",
"for",
"ii",
",",
"(",
"filepath",
",",
"line",
",",
"module",
",",
"code",
")",
"in",
"enumerate",
"(",
"extracted_tb",
")",
":",
"func_source",
",",
"func_lineno",
"=",
"inspect",
".",
"getsourcelines",
"(",
"tb_level",
".",
"tb_frame",
")",
"d",
"=",
"{",
"\"File\"",
":",
"filepath",
",",
"\"Error Line Number\"",
":",
"line",
",",
"\"Module\"",
":",
"module",
",",
"\"Error Line\"",
":",
"code",
",",
"\"Module Line Number\"",
":",
"func_lineno",
",",
"\"Custom Inspection\"",
":",
"{",
"}",
",",
"\"Source Code\"",
":",
"''",
"}",
"if",
"inspection_level",
"is",
"None",
"or",
"len",
"(",
"extracted_tb",
")",
"-",
"ii",
"<=",
"inspection_level",
":",
"# Perform advanced inspection on the last `inspection_level` tracebacks.",
"d",
"[",
"'Source Code'",
"]",
"=",
"''",
".",
"join",
"(",
"func_source",
")",
"d",
"[",
"'Local Variables'",
"]",
"=",
"get_local_references",
"(",
"tb_level",
")",
"d",
"[",
"'Object Variables'",
"]",
"=",
"get_object_references",
"(",
"tb_level",
",",
"d",
"[",
"'Source Code'",
"]",
")",
"tb_level",
"=",
"getattr",
"(",
"tb_level",
",",
"'tb_next'",
",",
"None",
")",
"info",
".",
"append",
"(",
"d",
")",
"return",
"info"
] | Extract trace back information into a list of dictionaries.
:param tb: traceback
:return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks | [
"Extract",
"trace",
"back",
"information",
"into",
"a",
"list",
"of",
"dictionaries",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L155-L183 | train |
kytos/kytos-utils | kytos/utils/config.py | KytosConfig.log_configs | def log_configs(self):
"""Log the read configs if debug is enabled."""
for sec in self.config.sections():
LOG.debug(' %s: %s', sec, self.config.options(sec)) | python | def log_configs(self):
"""Log the read configs if debug is enabled."""
for sec in self.config.sections():
LOG.debug(' %s: %s', sec, self.config.options(sec)) | [
"def",
"log_configs",
"(",
"self",
")",
":",
"for",
"sec",
"in",
"self",
".",
"config",
".",
"sections",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"' %s: %s'",
",",
"sec",
",",
"self",
".",
"config",
".",
"options",
"(",
"sec",
")",
")"
] | Log the read configs if debug is enabled. | [
"Log",
"the",
"read",
"configs",
"if",
"debug",
"is",
"enabled",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L51-L54 | train |
kytos/kytos-utils | kytos/utils/config.py | KytosConfig.set_env_or_defaults | def set_env_or_defaults(self):
"""Read some environment variables and set them on the config.
If no environment variable is found and the config section/key is
empty, then set some default values.
"""
option = namedtuple('Option', ['section', 'name', 'env_var',
'default_value'])
options = [option('auth', 'user', 'NAPPS_USER', None),
option('auth', 'token', 'NAPPS_TOKEN', None),
option('napps', 'api', 'NAPPS_API_URI',
'https://napps.kytos.io/api/'),
option('napps', 'repo', 'NAPPS_REPO_URI',
'https://napps.kytos.io/repo'),
option('kytos', 'api', 'KYTOS_API',
'http://localhost:8181/')]
for option in options:
if not self.config.has_option(option.section, option.name):
env_value = os.environ.get(option.env_var,
option.default_value)
if env_value:
self.config.set(option.section, option.name, env_value)
self.config.set('global', 'debug', str(self.debug)) | python | def set_env_or_defaults(self):
"""Read some environment variables and set them on the config.
If no environment variable is found and the config section/key is
empty, then set some default values.
"""
option = namedtuple('Option', ['section', 'name', 'env_var',
'default_value'])
options = [option('auth', 'user', 'NAPPS_USER', None),
option('auth', 'token', 'NAPPS_TOKEN', None),
option('napps', 'api', 'NAPPS_API_URI',
'https://napps.kytos.io/api/'),
option('napps', 'repo', 'NAPPS_REPO_URI',
'https://napps.kytos.io/repo'),
option('kytos', 'api', 'KYTOS_API',
'http://localhost:8181/')]
for option in options:
if not self.config.has_option(option.section, option.name):
env_value = os.environ.get(option.env_var,
option.default_value)
if env_value:
self.config.set(option.section, option.name, env_value)
self.config.set('global', 'debug', str(self.debug)) | [
"def",
"set_env_or_defaults",
"(",
"self",
")",
":",
"option",
"=",
"namedtuple",
"(",
"'Option'",
",",
"[",
"'section'",
",",
"'name'",
",",
"'env_var'",
",",
"'default_value'",
"]",
")",
"options",
"=",
"[",
"option",
"(",
"'auth'",
",",
"'user'",
",",
"'NAPPS_USER'",
",",
"None",
")",
",",
"option",
"(",
"'auth'",
",",
"'token'",
",",
"'NAPPS_TOKEN'",
",",
"None",
")",
",",
"option",
"(",
"'napps'",
",",
"'api'",
",",
"'NAPPS_API_URI'",
",",
"'https://napps.kytos.io/api/'",
")",
",",
"option",
"(",
"'napps'",
",",
"'repo'",
",",
"'NAPPS_REPO_URI'",
",",
"'https://napps.kytos.io/repo'",
")",
",",
"option",
"(",
"'kytos'",
",",
"'api'",
",",
"'KYTOS_API'",
",",
"'http://localhost:8181/'",
")",
"]",
"for",
"option",
"in",
"options",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_option",
"(",
"option",
".",
"section",
",",
"option",
".",
"name",
")",
":",
"env_value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"option",
".",
"env_var",
",",
"option",
".",
"default_value",
")",
"if",
"env_value",
":",
"self",
".",
"config",
".",
"set",
"(",
"option",
".",
"section",
",",
"option",
".",
"name",
",",
"env_value",
")",
"self",
".",
"config",
".",
"set",
"(",
"'global'",
",",
"'debug'",
",",
"str",
"(",
"self",
".",
"debug",
")",
")"
] | Read some environment variables and set them on the config.
If no environment variable is found and the config section/key is
empty, then set some default values. | [
"Read",
"some",
"environment",
"variables",
"and",
"set",
"them",
"on",
"the",
"config",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L56-L81 | train |
kytos/kytos-utils | kytos/utils/config.py | KytosConfig.check_sections | def check_sections(config):
"""Create a empty config file."""
default_sections = ['global', 'auth', 'napps', 'kytos']
for section in default_sections:
if not config.has_section(section):
config.add_section(section) | python | def check_sections(config):
"""Create a empty config file."""
default_sections = ['global', 'auth', 'napps', 'kytos']
for section in default_sections:
if not config.has_section(section):
config.add_section(section) | [
"def",
"check_sections",
"(",
"config",
")",
":",
"default_sections",
"=",
"[",
"'global'",
",",
"'auth'",
",",
"'napps'",
",",
"'kytos'",
"]",
"for",
"section",
"in",
"default_sections",
":",
"if",
"not",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"config",
".",
"add_section",
"(",
"section",
")"
] | Create a empty config file. | [
"Create",
"a",
"empty",
"config",
"file",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L84-L89 | train |
kytos/kytos-utils | kytos/utils/config.py | KytosConfig.save_token | def save_token(self, user, token):
"""Save the token on the config file."""
self.config.set('auth', 'user', user)
self.config.set('auth', 'token', token)
# allow_no_value=True is used to keep the comments on the config file.
new_config = ConfigParser(allow_no_value=True)
# Parse the config file. If no config file was found, then create some
# default sections on the config variable.
new_config.read(self.config_file)
self.check_sections(new_config)
new_config.set('auth', 'user', user)
new_config.set('auth', 'token', token)
filename = os.path.expanduser(self.config_file)
with open(filename, 'w') as out_file:
os.chmod(filename, 0o0600)
new_config.write(out_file) | python | def save_token(self, user, token):
"""Save the token on the config file."""
self.config.set('auth', 'user', user)
self.config.set('auth', 'token', token)
# allow_no_value=True is used to keep the comments on the config file.
new_config = ConfigParser(allow_no_value=True)
# Parse the config file. If no config file was found, then create some
# default sections on the config variable.
new_config.read(self.config_file)
self.check_sections(new_config)
new_config.set('auth', 'user', user)
new_config.set('auth', 'token', token)
filename = os.path.expanduser(self.config_file)
with open(filename, 'w') as out_file:
os.chmod(filename, 0o0600)
new_config.write(out_file) | [
"def",
"save_token",
"(",
"self",
",",
"user",
",",
"token",
")",
":",
"self",
".",
"config",
".",
"set",
"(",
"'auth'",
",",
"'user'",
",",
"user",
")",
"self",
".",
"config",
".",
"set",
"(",
"'auth'",
",",
"'token'",
",",
"token",
")",
"# allow_no_value=True is used to keep the comments on the config file.",
"new_config",
"=",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"# Parse the config file. If no config file was found, then create some",
"# default sections on the config variable.",
"new_config",
".",
"read",
"(",
"self",
".",
"config_file",
")",
"self",
".",
"check_sections",
"(",
"new_config",
")",
"new_config",
".",
"set",
"(",
"'auth'",
",",
"'user'",
",",
"user",
")",
"new_config",
".",
"set",
"(",
"'auth'",
",",
"'token'",
",",
"token",
")",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"config_file",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"out_file",
":",
"os",
".",
"chmod",
"(",
"filename",
",",
"0o0600",
")",
"new_config",
".",
"write",
"(",
"out_file",
")"
] | Save the token on the config file. | [
"Save",
"the",
"token",
"on",
"the",
"config",
"file",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L91-L108 | train |
kytos/kytos-utils | kytos/utils/config.py | KytosConfig.clear_token | def clear_token(self):
"""Clear Token information on config file."""
# allow_no_value=True is used to keep the comments on the config file.
new_config = ConfigParser(allow_no_value=True)
# Parse the config file. If no config file was found, then create some
# default sections on the config variable.
new_config.read(self.config_file)
self.check_sections(new_config)
new_config.remove_option('auth', 'user')
new_config.remove_option('auth', 'token')
filename = os.path.expanduser(self.config_file)
with open(filename, 'w') as out_file:
os.chmod(filename, 0o0600)
new_config.write(out_file) | python | def clear_token(self):
"""Clear Token information on config file."""
# allow_no_value=True is used to keep the comments on the config file.
new_config = ConfigParser(allow_no_value=True)
# Parse the config file. If no config file was found, then create some
# default sections on the config variable.
new_config.read(self.config_file)
self.check_sections(new_config)
new_config.remove_option('auth', 'user')
new_config.remove_option('auth', 'token')
filename = os.path.expanduser(self.config_file)
with open(filename, 'w') as out_file:
os.chmod(filename, 0o0600)
new_config.write(out_file) | [
"def",
"clear_token",
"(",
"self",
")",
":",
"# allow_no_value=True is used to keep the comments on the config file.",
"new_config",
"=",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"# Parse the config file. If no config file was found, then create some",
"# default sections on the config variable.",
"new_config",
".",
"read",
"(",
"self",
".",
"config_file",
")",
"self",
".",
"check_sections",
"(",
"new_config",
")",
"new_config",
".",
"remove_option",
"(",
"'auth'",
",",
"'user'",
")",
"new_config",
".",
"remove_option",
"(",
"'auth'",
",",
"'token'",
")",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"config_file",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"out_file",
":",
"os",
".",
"chmod",
"(",
"filename",
",",
"0o0600",
")",
"new_config",
".",
"write",
"(",
"out_file",
")"
] | Clear Token information on config file. | [
"Clear",
"Token",
"information",
"on",
"config",
"file",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L110-L125 | train |
KE-works/pykechain | pykechain/extra_utils.py | relocate_model | def relocate_model(part, target_parent, name=None, include_children=True):
"""
Move the `Part` model to target parent.
.. versionadded:: 2.3
:param part: `Part` object to be moved
:type part: :class:`Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: Part model.
:raises IllegalArgumentError: if target_parent is descendant of part
"""
if target_parent.id in get_illegal_targets(part, include={part.id}):
raise IllegalArgumentError('cannot relocate part "{}" under target parent "{}", because the target is part of '
'its descendants'.format(part.name, target_parent.name))
# First, if the user doesn't provide the name, then just use the default "Clone - ..." name
if not name:
name = "CLONE - {}".format(part.name)
# The description cannot be added when creating a model, so edit the model after creation.
part_desc = part._json_data['description']
moved_part_model = target_parent.add_model(name=name, multiplicity=part.multiplicity)
if part_desc:
moved_part_model.edit(description=str(part_desc))
# Map the current part model id with newly created part model Object
get_mapping_dictionary().update({part.id: moved_part_model})
# Loop through properties and retrieve their type, description and unit
list_of_properties_sorted_by_order = part.properties
list_of_properties_sorted_by_order.sort(key=lambda x: x._json_data['order'])
for prop in list_of_properties_sorted_by_order:
prop_type = prop._json_data.get('property_type')
desc = prop._json_data.get('description')
unit = prop._json_data.get('unit')
options = prop._json_data.get('options')
# On "Part references" properties, the models referenced also need to be added
if prop_type == PropertyType.REFERENCES_VALUE:
referenced_part_ids = [referenced_part.id for referenced_part in prop.value]
moved_prop = moved_part_model.add_property(name=prop.name, description=desc, property_type=prop_type,
default_value=referenced_part_ids)
# On "Attachment" properties, attachments needs to be downloaded and re-uploaded to the new property.
elif prop_type == PropertyType.ATTACHMENT_VALUE:
moved_prop = moved_part_model.add_property(name=prop.name, description=desc, property_type=prop_type)
if prop.value:
attachment_name = prop._json_data['value'].split('/')[-1]
with temp_chdir() as target_dir:
full_path = os.path.join(target_dir or os.getcwd(), attachment_name)
prop.save_as(filename=full_path)
moved_prop.upload(full_path)
# Other properties are quite straightforward
else:
moved_prop = moved_part_model.add_property(name=prop.name, description=desc, property_type=prop_type,
default_value=prop.value, unit=unit, options=options)
# Map the current property model id with newly created property model Object
get_mapping_dictionary()[prop.id] = moved_prop
# Now copy the sub-tree of the part
if include_children:
# Populate the part so multiple children retrieval is not needed
part.populate_descendants()
# For each part, recursively run this function
for sub_part in part._cached_children:
relocate_model(part=sub_part, target_parent=moved_part_model, name=sub_part.name,
include_children=include_children)
return moved_part_model | python | def relocate_model(part, target_parent, name=None, include_children=True):
"""
Move the `Part` model to target parent.
.. versionadded:: 2.3
:param part: `Part` object to be moved
:type part: :class:`Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: Part model.
:raises IllegalArgumentError: if target_parent is descendant of part
"""
if target_parent.id in get_illegal_targets(part, include={part.id}):
raise IllegalArgumentError('cannot relocate part "{}" under target parent "{}", because the target is part of '
'its descendants'.format(part.name, target_parent.name))
# First, if the user doesn't provide the name, then just use the default "Clone - ..." name
if not name:
name = "CLONE - {}".format(part.name)
# The description cannot be added when creating a model, so edit the model after creation.
part_desc = part._json_data['description']
moved_part_model = target_parent.add_model(name=name, multiplicity=part.multiplicity)
if part_desc:
moved_part_model.edit(description=str(part_desc))
# Map the current part model id with newly created part model Object
get_mapping_dictionary().update({part.id: moved_part_model})
# Loop through properties and retrieve their type, description and unit
list_of_properties_sorted_by_order = part.properties
list_of_properties_sorted_by_order.sort(key=lambda x: x._json_data['order'])
for prop in list_of_properties_sorted_by_order:
prop_type = prop._json_data.get('property_type')
desc = prop._json_data.get('description')
unit = prop._json_data.get('unit')
options = prop._json_data.get('options')
# On "Part references" properties, the models referenced also need to be added
if prop_type == PropertyType.REFERENCES_VALUE:
referenced_part_ids = [referenced_part.id for referenced_part in prop.value]
moved_prop = moved_part_model.add_property(name=prop.name, description=desc, property_type=prop_type,
default_value=referenced_part_ids)
# On "Attachment" properties, attachments needs to be downloaded and re-uploaded to the new property.
elif prop_type == PropertyType.ATTACHMENT_VALUE:
moved_prop = moved_part_model.add_property(name=prop.name, description=desc, property_type=prop_type)
if prop.value:
attachment_name = prop._json_data['value'].split('/')[-1]
with temp_chdir() as target_dir:
full_path = os.path.join(target_dir or os.getcwd(), attachment_name)
prop.save_as(filename=full_path)
moved_prop.upload(full_path)
# Other properties are quite straightforward
else:
moved_prop = moved_part_model.add_property(name=prop.name, description=desc, property_type=prop_type,
default_value=prop.value, unit=unit, options=options)
# Map the current property model id with newly created property model Object
get_mapping_dictionary()[prop.id] = moved_prop
# Now copy the sub-tree of the part
if include_children:
# Populate the part so multiple children retrieval is not needed
part.populate_descendants()
# For each part, recursively run this function
for sub_part in part._cached_children:
relocate_model(part=sub_part, target_parent=moved_part_model, name=sub_part.name,
include_children=include_children)
return moved_part_model | [
"def",
"relocate_model",
"(",
"part",
",",
"target_parent",
",",
"name",
"=",
"None",
",",
"include_children",
"=",
"True",
")",
":",
"if",
"target_parent",
".",
"id",
"in",
"get_illegal_targets",
"(",
"part",
",",
"include",
"=",
"{",
"part",
".",
"id",
"}",
")",
":",
"raise",
"IllegalArgumentError",
"(",
"'cannot relocate part \"{}\" under target parent \"{}\", because the target is part of '",
"'its descendants'",
".",
"format",
"(",
"part",
".",
"name",
",",
"target_parent",
".",
"name",
")",
")",
"# First, if the user doesn't provide the name, then just use the default \"Clone - ...\" name",
"if",
"not",
"name",
":",
"name",
"=",
"\"CLONE - {}\"",
".",
"format",
"(",
"part",
".",
"name",
")",
"# The description cannot be added when creating a model, so edit the model after creation.",
"part_desc",
"=",
"part",
".",
"_json_data",
"[",
"'description'",
"]",
"moved_part_model",
"=",
"target_parent",
".",
"add_model",
"(",
"name",
"=",
"name",
",",
"multiplicity",
"=",
"part",
".",
"multiplicity",
")",
"if",
"part_desc",
":",
"moved_part_model",
".",
"edit",
"(",
"description",
"=",
"str",
"(",
"part_desc",
")",
")",
"# Map the current part model id with newly created part model Object",
"get_mapping_dictionary",
"(",
")",
".",
"update",
"(",
"{",
"part",
".",
"id",
":",
"moved_part_model",
"}",
")",
"# Loop through properties and retrieve their type, description and unit",
"list_of_properties_sorted_by_order",
"=",
"part",
".",
"properties",
"list_of_properties_sorted_by_order",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"_json_data",
"[",
"'order'",
"]",
")",
"for",
"prop",
"in",
"list_of_properties_sorted_by_order",
":",
"prop_type",
"=",
"prop",
".",
"_json_data",
".",
"get",
"(",
"'property_type'",
")",
"desc",
"=",
"prop",
".",
"_json_data",
".",
"get",
"(",
"'description'",
")",
"unit",
"=",
"prop",
".",
"_json_data",
".",
"get",
"(",
"'unit'",
")",
"options",
"=",
"prop",
".",
"_json_data",
".",
"get",
"(",
"'options'",
")",
"# On \"Part references\" properties, the models referenced also need to be added",
"if",
"prop_type",
"==",
"PropertyType",
".",
"REFERENCES_VALUE",
":",
"referenced_part_ids",
"=",
"[",
"referenced_part",
".",
"id",
"for",
"referenced_part",
"in",
"prop",
".",
"value",
"]",
"moved_prop",
"=",
"moved_part_model",
".",
"add_property",
"(",
"name",
"=",
"prop",
".",
"name",
",",
"description",
"=",
"desc",
",",
"property_type",
"=",
"prop_type",
",",
"default_value",
"=",
"referenced_part_ids",
")",
"# On \"Attachment\" properties, attachments needs to be downloaded and re-uploaded to the new property.",
"elif",
"prop_type",
"==",
"PropertyType",
".",
"ATTACHMENT_VALUE",
":",
"moved_prop",
"=",
"moved_part_model",
".",
"add_property",
"(",
"name",
"=",
"prop",
".",
"name",
",",
"description",
"=",
"desc",
",",
"property_type",
"=",
"prop_type",
")",
"if",
"prop",
".",
"value",
":",
"attachment_name",
"=",
"prop",
".",
"_json_data",
"[",
"'value'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"with",
"temp_chdir",
"(",
")",
"as",
"target_dir",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
"or",
"os",
".",
"getcwd",
"(",
")",
",",
"attachment_name",
")",
"prop",
".",
"save_as",
"(",
"filename",
"=",
"full_path",
")",
"moved_prop",
".",
"upload",
"(",
"full_path",
")",
"# Other properties are quite straightforward",
"else",
":",
"moved_prop",
"=",
"moved_part_model",
".",
"add_property",
"(",
"name",
"=",
"prop",
".",
"name",
",",
"description",
"=",
"desc",
",",
"property_type",
"=",
"prop_type",
",",
"default_value",
"=",
"prop",
".",
"value",
",",
"unit",
"=",
"unit",
",",
"options",
"=",
"options",
")",
"# Map the current property model id with newly created property model Object",
"get_mapping_dictionary",
"(",
")",
"[",
"prop",
".",
"id",
"]",
"=",
"moved_prop",
"# Now copy the sub-tree of the part",
"if",
"include_children",
":",
"# Populate the part so multiple children retrieval is not needed",
"part",
".",
"populate_descendants",
"(",
")",
"# For each part, recursively run this function",
"for",
"sub_part",
"in",
"part",
".",
"_cached_children",
":",
"relocate_model",
"(",
"part",
"=",
"sub_part",
",",
"target_parent",
"=",
"moved_part_model",
",",
"name",
"=",
"sub_part",
".",
"name",
",",
"include_children",
"=",
"include_children",
")",
"return",
"moved_part_model"
] | Move the `Part` model to target parent.
.. versionadded:: 2.3
:param part: `Part` object to be moved
:type part: :class:`Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: Part model.
:raises IllegalArgumentError: if target_parent is descendant of part | [
"Move",
"the",
"Part",
"model",
"to",
"target",
"parent",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L42-L117 | train |
KE-works/pykechain | pykechain/extra_utils.py | relocate_instance | def relocate_instance(part, target_parent, name=None, include_children=True):
"""
Move the `Part` instance to target parent.
.. versionadded:: 2.3
:param part: `Part` object to be moved
:type part: :class:`Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: `Part` instance
"""
# First, if the user doesn't provide the name, then just use the default "Clone - ..." name
if not name:
name = "CLONE - {}".format(part.name)
# Initially the model of the part needs to be recreated under the model of the target_parent. Retrieve them.
part_model = part.model()
target_parent_model = target_parent.model()
# Call the move_part() function for those models.
relocate_model(part=part_model, target_parent=target_parent_model, name=part_model.name,
include_children=include_children)
# Populate the descendants of the Part (category=Instance), in order to avoid to retrieve children for every
# level and save time. Only need it the children should be included.
if include_children:
part.populate_descendants()
# This function will move the part instance under the target_parent instance, and its children if required.
moved_instance = move_part_instance(part_instance=part, target_parent=target_parent, part_model=part_model,
name=name, include_children=include_children)
return moved_instance | python | def relocate_instance(part, target_parent, name=None, include_children=True):
"""
Move the `Part` instance to target parent.
.. versionadded:: 2.3
:param part: `Part` object to be moved
:type part: :class:`Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: `Part` instance
"""
# First, if the user doesn't provide the name, then just use the default "Clone - ..." name
if not name:
name = "CLONE - {}".format(part.name)
# Initially the model of the part needs to be recreated under the model of the target_parent. Retrieve them.
part_model = part.model()
target_parent_model = target_parent.model()
# Call the move_part() function for those models.
relocate_model(part=part_model, target_parent=target_parent_model, name=part_model.name,
include_children=include_children)
# Populate the descendants of the Part (category=Instance), in order to avoid to retrieve children for every
# level and save time. Only need it the children should be included.
if include_children:
part.populate_descendants()
# This function will move the part instance under the target_parent instance, and its children if required.
moved_instance = move_part_instance(part_instance=part, target_parent=target_parent, part_model=part_model,
name=name, include_children=include_children)
return moved_instance | [
"def",
"relocate_instance",
"(",
"part",
",",
"target_parent",
",",
"name",
"=",
"None",
",",
"include_children",
"=",
"True",
")",
":",
"# First, if the user doesn't provide the name, then just use the default \"Clone - ...\" name",
"if",
"not",
"name",
":",
"name",
"=",
"\"CLONE - {}\"",
".",
"format",
"(",
"part",
".",
"name",
")",
"# Initially the model of the part needs to be recreated under the model of the target_parent. Retrieve them.",
"part_model",
"=",
"part",
".",
"model",
"(",
")",
"target_parent_model",
"=",
"target_parent",
".",
"model",
"(",
")",
"# Call the move_part() function for those models.",
"relocate_model",
"(",
"part",
"=",
"part_model",
",",
"target_parent",
"=",
"target_parent_model",
",",
"name",
"=",
"part_model",
".",
"name",
",",
"include_children",
"=",
"include_children",
")",
"# Populate the descendants of the Part (category=Instance), in order to avoid to retrieve children for every",
"# level and save time. Only need it the children should be included.",
"if",
"include_children",
":",
"part",
".",
"populate_descendants",
"(",
")",
"# This function will move the part instance under the target_parent instance, and its children if required.",
"moved_instance",
"=",
"move_part_instance",
"(",
"part_instance",
"=",
"part",
",",
"target_parent",
"=",
"target_parent",
",",
"part_model",
"=",
"part_model",
",",
"name",
"=",
"name",
",",
"include_children",
"=",
"include_children",
")",
"return",
"moved_instance"
] | Move the `Part` instance to target parent.
.. versionadded:: 2.3
:param part: `Part` object to be moved
:type part: :class:`Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: `Part` instance | [
"Move",
"the",
"Part",
"instance",
"to",
"target",
"parent",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L137-L172 | train |
KE-works/pykechain | pykechain/extra_utils.py | move_part_instance | def move_part_instance(part_instance, target_parent, part_model, name=None, include_children=True):
"""
Move the `Part` instance to target parent and updates the properties based on the original part instance.
.. versionadded:: 2.3
:param part_instance: `Part` object to be moved
:type part_instance: :class:`Part`
:param part_model: `Part` object representing the model of part_instance
:type part_model: :class: `Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: `Part` instance
"""
# If no specific name has been required, then call in as Clone of the part_instance.
if not name:
name = part_instance.name
# Retrieve the model of the future part to be created
moved_model = get_mapping_dictionary()[part_model.id]
# Now act based on multiplicity
if moved_model.multiplicity == Multiplicity.ONE:
# If multiplicity is 'Exactly 1', that means the instance was automatically created with the model, so just
# retrieve it, map the original instance with the moved one and update the name and property values.
moved_instance = moved_model.instances(parent_id=target_parent.id)[0]
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
elif moved_model.multiplicity == Multiplicity.ONE_MANY:
# If multiplicity is '1 or more', that means one instance has automatically been created with the model, so
# retrieve it, map the original instance with the moved one and update the name and property values. Store
# the model in a list, in case there are multiple instance those need to be recreated.
if target_parent.id not in get_edited_one_many():
moved_instance = moved_model.instances(parent_id=target_parent.id)[0]
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
get_edited_one_many().append(target_parent.id)
else:
moved_instance = target_parent.add(name=part_instance.name, model=moved_model, suppress_kevents=True)
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
else:
# If multiplicity is '0 or more' or '0 or 1', it means no instance has been created automatically with the
# model, so then everything must be created and then updated.
moved_instance = target_parent.add(name=name, model=moved_model, suppress_kevents=True)
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
# If include_children is True, then recursively call this function for every descendant. Keep the name of the
# original sub-instance.
if include_children:
for sub_instance in part_instance._cached_children:
move_part_instance(part_instance=sub_instance, target_parent=moved_instance,
part_model=sub_instance.model(),
name=sub_instance.name, include_children=True)
return moved_instance | python | def move_part_instance(part_instance, target_parent, part_model, name=None, include_children=True):
"""
Move the `Part` instance to target parent and updates the properties based on the original part instance.
.. versionadded:: 2.3
:param part_instance: `Part` object to be moved
:type part_instance: :class:`Part`
:param part_model: `Part` object representing the model of part_instance
:type part_model: :class: `Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: `Part` instance
"""
# If no specific name has been required, then call in as Clone of the part_instance.
if not name:
name = part_instance.name
# Retrieve the model of the future part to be created
moved_model = get_mapping_dictionary()[part_model.id]
# Now act based on multiplicity
if moved_model.multiplicity == Multiplicity.ONE:
# If multiplicity is 'Exactly 1', that means the instance was automatically created with the model, so just
# retrieve it, map the original instance with the moved one and update the name and property values.
moved_instance = moved_model.instances(parent_id=target_parent.id)[0]
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
elif moved_model.multiplicity == Multiplicity.ONE_MANY:
# If multiplicity is '1 or more', that means one instance has automatically been created with the model, so
# retrieve it, map the original instance with the moved one and update the name and property values. Store
# the model in a list, in case there are multiple instance those need to be recreated.
if target_parent.id not in get_edited_one_many():
moved_instance = moved_model.instances(parent_id=target_parent.id)[0]
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
get_edited_one_many().append(target_parent.id)
else:
moved_instance = target_parent.add(name=part_instance.name, model=moved_model, suppress_kevents=True)
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
else:
# If multiplicity is '0 or more' or '0 or 1', it means no instance has been created automatically with the
# model, so then everything must be created and then updated.
moved_instance = target_parent.add(name=name, model=moved_model, suppress_kevents=True)
map_property_instances(part_instance, moved_instance)
moved_instance = update_part_with_properties(part_instance, moved_instance, name=str(name))
# If include_children is True, then recursively call this function for every descendant. Keep the name of the
# original sub-instance.
if include_children:
for sub_instance in part_instance._cached_children:
move_part_instance(part_instance=sub_instance, target_parent=moved_instance,
part_model=sub_instance.model(),
name=sub_instance.name, include_children=True)
return moved_instance | [
"def",
"move_part_instance",
"(",
"part_instance",
",",
"target_parent",
",",
"part_model",
",",
"name",
"=",
"None",
",",
"include_children",
"=",
"True",
")",
":",
"# If no specific name has been required, then call in as Clone of the part_instance.",
"if",
"not",
"name",
":",
"name",
"=",
"part_instance",
".",
"name",
"# Retrieve the model of the future part to be created",
"moved_model",
"=",
"get_mapping_dictionary",
"(",
")",
"[",
"part_model",
".",
"id",
"]",
"# Now act based on multiplicity",
"if",
"moved_model",
".",
"multiplicity",
"==",
"Multiplicity",
".",
"ONE",
":",
"# If multiplicity is 'Exactly 1', that means the instance was automatically created with the model, so just",
"# retrieve it, map the original instance with the moved one and update the name and property values.",
"moved_instance",
"=",
"moved_model",
".",
"instances",
"(",
"parent_id",
"=",
"target_parent",
".",
"id",
")",
"[",
"0",
"]",
"map_property_instances",
"(",
"part_instance",
",",
"moved_instance",
")",
"moved_instance",
"=",
"update_part_with_properties",
"(",
"part_instance",
",",
"moved_instance",
",",
"name",
"=",
"str",
"(",
"name",
")",
")",
"elif",
"moved_model",
".",
"multiplicity",
"==",
"Multiplicity",
".",
"ONE_MANY",
":",
"# If multiplicity is '1 or more', that means one instance has automatically been created with the model, so",
"# retrieve it, map the original instance with the moved one and update the name and property values. Store",
"# the model in a list, in case there are multiple instance those need to be recreated.",
"if",
"target_parent",
".",
"id",
"not",
"in",
"get_edited_one_many",
"(",
")",
":",
"moved_instance",
"=",
"moved_model",
".",
"instances",
"(",
"parent_id",
"=",
"target_parent",
".",
"id",
")",
"[",
"0",
"]",
"map_property_instances",
"(",
"part_instance",
",",
"moved_instance",
")",
"moved_instance",
"=",
"update_part_with_properties",
"(",
"part_instance",
",",
"moved_instance",
",",
"name",
"=",
"str",
"(",
"name",
")",
")",
"get_edited_one_many",
"(",
")",
".",
"append",
"(",
"target_parent",
".",
"id",
")",
"else",
":",
"moved_instance",
"=",
"target_parent",
".",
"add",
"(",
"name",
"=",
"part_instance",
".",
"name",
",",
"model",
"=",
"moved_model",
",",
"suppress_kevents",
"=",
"True",
")",
"map_property_instances",
"(",
"part_instance",
",",
"moved_instance",
")",
"moved_instance",
"=",
"update_part_with_properties",
"(",
"part_instance",
",",
"moved_instance",
",",
"name",
"=",
"str",
"(",
"name",
")",
")",
"else",
":",
"# If multiplicity is '0 or more' or '0 or 1', it means no instance has been created automatically with the",
"# model, so then everything must be created and then updated.",
"moved_instance",
"=",
"target_parent",
".",
"add",
"(",
"name",
"=",
"name",
",",
"model",
"=",
"moved_model",
",",
"suppress_kevents",
"=",
"True",
")",
"map_property_instances",
"(",
"part_instance",
",",
"moved_instance",
")",
"moved_instance",
"=",
"update_part_with_properties",
"(",
"part_instance",
",",
"moved_instance",
",",
"name",
"=",
"str",
"(",
"name",
")",
")",
"# If include_children is True, then recursively call this function for every descendant. Keep the name of the",
"# original sub-instance.",
"if",
"include_children",
":",
"for",
"sub_instance",
"in",
"part_instance",
".",
"_cached_children",
":",
"move_part_instance",
"(",
"part_instance",
"=",
"sub_instance",
",",
"target_parent",
"=",
"moved_instance",
",",
"part_model",
"=",
"sub_instance",
".",
"model",
"(",
")",
",",
"name",
"=",
"sub_instance",
".",
"name",
",",
"include_children",
"=",
"True",
")",
"return",
"moved_instance"
] | Move the `Part` instance to target parent and updates the properties based on the original part instance.
.. versionadded:: 2.3
:param part_instance: `Part` object to be moved
:type part_instance: :class:`Part`
:param part_model: `Part` object representing the model of part_instance
:type part_model: :class: `Part`
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:return: moved :class: `Part` instance | [
"Move",
"the",
"Part",
"instance",
"to",
"target",
"parent",
"and",
"updates",
"the",
"properties",
"based",
"on",
"the",
"original",
"part",
"instance",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L175-L235 | train |
KE-works/pykechain | pykechain/extra_utils.py | update_part_with_properties | def update_part_with_properties(part_instance, moved_instance, name=None):
"""
Update the newly created part and its properties based on the original one.
:param part_instance: `Part` object to be copied
:type part_instance: :class:`Part`
:param moved_instance: `Part` object copied
:type moved_instance: :class:`Part`
:param name: Name of the updated part
:type name: basestring
:return: moved :class: `Part` instance
"""
# Instantiate and empty dictionary later used to map {property.id: property.value} in order to update the part
# in one go
properties_id_dict = dict()
for prop_instance in part_instance.properties:
# Do different magic if there is an attachment property and it has a value
if prop_instance._json_data['property_type'] == PropertyType.ATTACHMENT_VALUE:
moved_prop = get_mapping_dictionary()[prop_instance.id]
if prop_instance.value:
attachment_name = prop_instance._json_data['value'].split('/')[-1]
with temp_chdir() as target_dir:
full_path = os.path.join(target_dir or os.getcwd(), attachment_name)
prop_instance.save_as(filename=full_path)
moved_prop.upload(full_path)
else:
moved_prop.clear()
# For a reference value property, add the id's of the part referenced {property.id: [part1.id, part2.id, ...]},
# if there is part referenced at all.
elif prop_instance._json_data['property_type'] == PropertyType.REFERENCES_VALUE:
if prop_instance.value:
moved_prop_instance = get_mapping_dictionary()[prop_instance.id]
properties_id_dict[moved_prop_instance.id] = [ref_part.id for ref_part in prop_instance.value]
else:
moved_prop_instance = get_mapping_dictionary()[prop_instance.id]
properties_id_dict[moved_prop_instance.id] = prop_instance.value
# Update the name and property values in one go.
moved_instance.update(name=str(name), update_dict=properties_id_dict, bulk=True, suppress_kevents=True)
return moved_instance | python | def update_part_with_properties(part_instance, moved_instance, name=None):
"""
Update the newly created part and its properties based on the original one.
:param part_instance: `Part` object to be copied
:type part_instance: :class:`Part`
:param moved_instance: `Part` object copied
:type moved_instance: :class:`Part`
:param name: Name of the updated part
:type name: basestring
:return: moved :class: `Part` instance
"""
# Instantiate and empty dictionary later used to map {property.id: property.value} in order to update the part
# in one go
properties_id_dict = dict()
for prop_instance in part_instance.properties:
# Do different magic if there is an attachment property and it has a value
if prop_instance._json_data['property_type'] == PropertyType.ATTACHMENT_VALUE:
moved_prop = get_mapping_dictionary()[prop_instance.id]
if prop_instance.value:
attachment_name = prop_instance._json_data['value'].split('/')[-1]
with temp_chdir() as target_dir:
full_path = os.path.join(target_dir or os.getcwd(), attachment_name)
prop_instance.save_as(filename=full_path)
moved_prop.upload(full_path)
else:
moved_prop.clear()
# For a reference value property, add the id's of the part referenced {property.id: [part1.id, part2.id, ...]},
# if there is part referenced at all.
elif prop_instance._json_data['property_type'] == PropertyType.REFERENCES_VALUE:
if prop_instance.value:
moved_prop_instance = get_mapping_dictionary()[prop_instance.id]
properties_id_dict[moved_prop_instance.id] = [ref_part.id for ref_part in prop_instance.value]
else:
moved_prop_instance = get_mapping_dictionary()[prop_instance.id]
properties_id_dict[moved_prop_instance.id] = prop_instance.value
# Update the name and property values in one go.
moved_instance.update(name=str(name), update_dict=properties_id_dict, bulk=True, suppress_kevents=True)
return moved_instance | [
"def",
"update_part_with_properties",
"(",
"part_instance",
",",
"moved_instance",
",",
"name",
"=",
"None",
")",
":",
"# Instantiate and empty dictionary later used to map {property.id: property.value} in order to update the part",
"# in one go",
"properties_id_dict",
"=",
"dict",
"(",
")",
"for",
"prop_instance",
"in",
"part_instance",
".",
"properties",
":",
"# Do different magic if there is an attachment property and it has a value",
"if",
"prop_instance",
".",
"_json_data",
"[",
"'property_type'",
"]",
"==",
"PropertyType",
".",
"ATTACHMENT_VALUE",
":",
"moved_prop",
"=",
"get_mapping_dictionary",
"(",
")",
"[",
"prop_instance",
".",
"id",
"]",
"if",
"prop_instance",
".",
"value",
":",
"attachment_name",
"=",
"prop_instance",
".",
"_json_data",
"[",
"'value'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"with",
"temp_chdir",
"(",
")",
"as",
"target_dir",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
"or",
"os",
".",
"getcwd",
"(",
")",
",",
"attachment_name",
")",
"prop_instance",
".",
"save_as",
"(",
"filename",
"=",
"full_path",
")",
"moved_prop",
".",
"upload",
"(",
"full_path",
")",
"else",
":",
"moved_prop",
".",
"clear",
"(",
")",
"# For a reference value property, add the id's of the part referenced {property.id: [part1.id, part2.id, ...]},",
"# if there is part referenced at all.",
"elif",
"prop_instance",
".",
"_json_data",
"[",
"'property_type'",
"]",
"==",
"PropertyType",
".",
"REFERENCES_VALUE",
":",
"if",
"prop_instance",
".",
"value",
":",
"moved_prop_instance",
"=",
"get_mapping_dictionary",
"(",
")",
"[",
"prop_instance",
".",
"id",
"]",
"properties_id_dict",
"[",
"moved_prop_instance",
".",
"id",
"]",
"=",
"[",
"ref_part",
".",
"id",
"for",
"ref_part",
"in",
"prop_instance",
".",
"value",
"]",
"else",
":",
"moved_prop_instance",
"=",
"get_mapping_dictionary",
"(",
")",
"[",
"prop_instance",
".",
"id",
"]",
"properties_id_dict",
"[",
"moved_prop_instance",
".",
"id",
"]",
"=",
"prop_instance",
".",
"value",
"# Update the name and property values in one go.",
"moved_instance",
".",
"update",
"(",
"name",
"=",
"str",
"(",
"name",
")",
",",
"update_dict",
"=",
"properties_id_dict",
",",
"bulk",
"=",
"True",
",",
"suppress_kevents",
"=",
"True",
")",
"return",
"moved_instance"
] | Update the newly created part and its properties based on the original one.
:param part_instance: `Part` object to be copied
:type part_instance: :class:`Part`
:param moved_instance: `Part` object copied
:type moved_instance: :class:`Part`
:param name: Name of the updated part
:type name: basestring
:return: moved :class: `Part` instance | [
"Update",
"the",
"newly",
"created",
"part",
"and",
"its",
"properties",
"based",
"on",
"the",
"original",
"one",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L238-L276 | train |
KE-works/pykechain | pykechain/extra_utils.py | map_property_instances | def map_property_instances(original_part, new_part):
"""
Map the id of the original part with the `Part` object of the newly created one.
Updated the singleton `mapping dictionary` with the new mapping table values.
:param original_part: `Part` object to be copied/moved
:type original_part: :class:`Part`
:param new_part: `Part` object copied/moved
:type new_part: :class:`Part`
:return: None
"""
# Map the original part with the new one
get_mapping_dictionary()[original_part.id] = new_part
# Do the same for each Property of original part instance, using the 'model' id and the get_mapping_dictionary
for prop_original in original_part.properties:
get_mapping_dictionary()[prop_original.id] = [prop_new for prop_new in new_part.properties if
get_mapping_dictionary()[prop_original._json_data['model']].id ==
prop_new._json_data['model']][0] | python | def map_property_instances(original_part, new_part):
"""
Map the id of the original part with the `Part` object of the newly created one.
Updated the singleton `mapping dictionary` with the new mapping table values.
:param original_part: `Part` object to be copied/moved
:type original_part: :class:`Part`
:param new_part: `Part` object copied/moved
:type new_part: :class:`Part`
:return: None
"""
# Map the original part with the new one
get_mapping_dictionary()[original_part.id] = new_part
# Do the same for each Property of original part instance, using the 'model' id and the get_mapping_dictionary
for prop_original in original_part.properties:
get_mapping_dictionary()[prop_original.id] = [prop_new for prop_new in new_part.properties if
get_mapping_dictionary()[prop_original._json_data['model']].id ==
prop_new._json_data['model']][0] | [
"def",
"map_property_instances",
"(",
"original_part",
",",
"new_part",
")",
":",
"# Map the original part with the new one",
"get_mapping_dictionary",
"(",
")",
"[",
"original_part",
".",
"id",
"]",
"=",
"new_part",
"# Do the same for each Property of original part instance, using the 'model' id and the get_mapping_dictionary",
"for",
"prop_original",
"in",
"original_part",
".",
"properties",
":",
"get_mapping_dictionary",
"(",
")",
"[",
"prop_original",
".",
"id",
"]",
"=",
"[",
"prop_new",
"for",
"prop_new",
"in",
"new_part",
".",
"properties",
"if",
"get_mapping_dictionary",
"(",
")",
"[",
"prop_original",
".",
"_json_data",
"[",
"'model'",
"]",
"]",
".",
"id",
"==",
"prop_new",
".",
"_json_data",
"[",
"'model'",
"]",
"]",
"[",
"0",
"]"
] | Map the id of the original part with the `Part` object of the newly created one.
Updated the singleton `mapping dictionary` with the new mapping table values.
:param original_part: `Part` object to be copied/moved
:type original_part: :class:`Part`
:param new_part: `Part` object copied/moved
:type new_part: :class:`Part`
:return: None | [
"Map",
"the",
"id",
"of",
"the",
"original",
"part",
"with",
"the",
"Part",
"object",
"of",
"the",
"newly",
"created",
"one",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L279-L298 | train |
kytos/kytos-utils | kytos/utils/users.py | UsersManager.ask_question | def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False,
password=False):
"""Ask a question and get the input values.
This method will validade the input values.
Args:
field_name(string): Field name used to ask for input value.
pattern(tuple): Pattern to validate the input value.
is_required(bool): Boolean value if the input value is required.
password(bool): Boolean value to get input password with mask.
Returns:
input_value(string): Input value validated.
"""
input_value = ""
question = ("Insert the field using the pattern below:"
"\n{}\n{}: ".format(pattern[0], field_name))
while not input_value:
input_value = getpass(question) if password else input(question)
if not (input_value or is_required):
break
if password:
confirm_password = getpass('Confirm your password: ')
if confirm_password != input_value:
print("Password does not match")
input_value = ""
if not self.valid_attribute(input_value, pattern[1]):
error_message = "The content must fit the pattern: {}\n"
print(error_message.format(pattern[0]))
input_value = ""
return input_value | python | def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False,
password=False):
"""Ask a question and get the input values.
This method will validade the input values.
Args:
field_name(string): Field name used to ask for input value.
pattern(tuple): Pattern to validate the input value.
is_required(bool): Boolean value if the input value is required.
password(bool): Boolean value to get input password with mask.
Returns:
input_value(string): Input value validated.
"""
input_value = ""
question = ("Insert the field using the pattern below:"
"\n{}\n{}: ".format(pattern[0], field_name))
while not input_value:
input_value = getpass(question) if password else input(question)
if not (input_value or is_required):
break
if password:
confirm_password = getpass('Confirm your password: ')
if confirm_password != input_value:
print("Password does not match")
input_value = ""
if not self.valid_attribute(input_value, pattern[1]):
error_message = "The content must fit the pattern: {}\n"
print(error_message.format(pattern[0]))
input_value = ""
return input_value | [
"def",
"ask_question",
"(",
"self",
",",
"field_name",
",",
"pattern",
"=",
"NAME_PATTERN",
",",
"is_required",
"=",
"False",
",",
"password",
"=",
"False",
")",
":",
"input_value",
"=",
"\"\"",
"question",
"=",
"(",
"\"Insert the field using the pattern below:\"",
"\"\\n{}\\n{}: \"",
".",
"format",
"(",
"pattern",
"[",
"0",
"]",
",",
"field_name",
")",
")",
"while",
"not",
"input_value",
":",
"input_value",
"=",
"getpass",
"(",
"question",
")",
"if",
"password",
"else",
"input",
"(",
"question",
")",
"if",
"not",
"(",
"input_value",
"or",
"is_required",
")",
":",
"break",
"if",
"password",
":",
"confirm_password",
"=",
"getpass",
"(",
"'Confirm your password: '",
")",
"if",
"confirm_password",
"!=",
"input_value",
":",
"print",
"(",
"\"Password does not match\"",
")",
"input_value",
"=",
"\"\"",
"if",
"not",
"self",
".",
"valid_attribute",
"(",
"input_value",
",",
"pattern",
"[",
"1",
"]",
")",
":",
"error_message",
"=",
"\"The content must fit the pattern: {}\\n\"",
"print",
"(",
"error_message",
".",
"format",
"(",
"pattern",
"[",
"0",
"]",
")",
")",
"input_value",
"=",
"\"\"",
"return",
"input_value"
] | Ask a question and get the input values.
This method will validade the input values.
Args:
field_name(string): Field name used to ask for input value.
pattern(tuple): Pattern to validate the input value.
is_required(bool): Boolean value if the input value is required.
password(bool): Boolean value to get input password with mask.
Returns:
input_value(string): Input value validated. | [
"Ask",
"a",
"question",
"and",
"get",
"the",
"input",
"values",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/users.py#L81-L116 | train |
samuelcolvin/grablib | grablib/cli.py | cli | def cli(action, config_file, debug, verbose):
"""
Static asset management in python.
Called with no arguments grablib will download, then build. You can also choose to only download or build.
See `grablib -h` and https://github.com/samuelcolvin/grablib for more help.
"""
if verbose is True:
log_level = 'DEBUG'
elif verbose is False:
log_level = 'WARNING'
else:
assert verbose is None
log_level = 'INFO'
setup_logging(log_level)
try:
grab = Grab(config_file, debug=debug)
if action in {'download', None}:
grab.download()
if action in {'build', None}:
grab.build()
except GrablibError as e:
click.secho('Error: %s' % e, fg='red')
sys.exit(2) | python | def cli(action, config_file, debug, verbose):
"""
Static asset management in python.
Called with no arguments grablib will download, then build. You can also choose to only download or build.
See `grablib -h` and https://github.com/samuelcolvin/grablib for more help.
"""
if verbose is True:
log_level = 'DEBUG'
elif verbose is False:
log_level = 'WARNING'
else:
assert verbose is None
log_level = 'INFO'
setup_logging(log_level)
try:
grab = Grab(config_file, debug=debug)
if action in {'download', None}:
grab.download()
if action in {'build', None}:
grab.build()
except GrablibError as e:
click.secho('Error: %s' % e, fg='red')
sys.exit(2) | [
"def",
"cli",
"(",
"action",
",",
"config_file",
",",
"debug",
",",
"verbose",
")",
":",
"if",
"verbose",
"is",
"True",
":",
"log_level",
"=",
"'DEBUG'",
"elif",
"verbose",
"is",
"False",
":",
"log_level",
"=",
"'WARNING'",
"else",
":",
"assert",
"verbose",
"is",
"None",
"log_level",
"=",
"'INFO'",
"setup_logging",
"(",
"log_level",
")",
"try",
":",
"grab",
"=",
"Grab",
"(",
"config_file",
",",
"debug",
"=",
"debug",
")",
"if",
"action",
"in",
"{",
"'download'",
",",
"None",
"}",
":",
"grab",
".",
"download",
"(",
")",
"if",
"action",
"in",
"{",
"'build'",
",",
"None",
"}",
":",
"grab",
".",
"build",
"(",
")",
"except",
"GrablibError",
"as",
"e",
":",
"click",
".",
"secho",
"(",
"'Error: %s'",
"%",
"e",
",",
"fg",
"=",
"'red'",
")",
"sys",
".",
"exit",
"(",
"2",
")"
] | Static asset management in python.
Called with no arguments grablib will download, then build. You can also choose to only download or build.
See `grablib -h` and https://github.com/samuelcolvin/grablib for more help. | [
"Static",
"asset",
"management",
"in",
"python",
"."
] | 2fca8a3950f29fb2a97a7bd75c0839060a91cedf | https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/cli.py#L18-L43 | train |
KE-works/pykechain | pykechain/models/property.py | Property.part | def part(self):
"""Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found
"""
part_id = self._json_data['part']
return self._client.part(pk=part_id, category=self._json_data['category']) | python | def part(self):
"""Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found
"""
part_id = self._json_data['part']
return self._client.part(pk=part_id, category=self._json_data['category']) | [
"def",
"part",
"(",
"self",
")",
":",
"part_id",
"=",
"self",
".",
"_json_data",
"[",
"'part'",
"]",
"return",
"self",
".",
"_client",
".",
"part",
"(",
"pk",
"=",
"part_id",
",",
"category",
"=",
"self",
".",
"_json_data",
"[",
"'category'",
"]",
")"
] | Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found | [
"Retrieve",
"the",
"part",
"that",
"holds",
"this",
"Property",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L110-L118 | train |
KE-works/pykechain | pykechain/models/property.py | Property.delete | def delete(self):
# type () -> ()
"""Delete this property.
:return: None
:raises APIError: if delete was not successful
"""
r = self._client._request('DELETE', self._client._build_url('property', property_id=self.id))
if r.status_code != requests.codes.no_content: # pragma: no cover
raise APIError("Could not delete property: {} with id {}".format(self.name, self.id)) | python | def delete(self):
# type () -> ()
"""Delete this property.
:return: None
:raises APIError: if delete was not successful
"""
r = self._client._request('DELETE', self._client._build_url('property', property_id=self.id))
if r.status_code != requests.codes.no_content: # pragma: no cover
raise APIError("Could not delete property: {} with id {}".format(self.name, self.id)) | [
"def",
"delete",
"(",
"self",
")",
":",
"# type () -> ()",
"r",
"=",
"self",
".",
"_client",
".",
"_request",
"(",
"'DELETE'",
",",
"self",
".",
"_client",
".",
"_build_url",
"(",
"'property'",
",",
"property_id",
"=",
"self",
".",
"id",
")",
")",
"if",
"r",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"no_content",
":",
"# pragma: no cover",
"raise",
"APIError",
"(",
"\"Could not delete property: {} with id {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"id",
")",
")"
] | Delete this property.
:return: None
:raises APIError: if delete was not successful | [
"Delete",
"this",
"property",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L120-L130 | train |
KE-works/pykechain | pykechain/models/property.py | Property.create | def create(cls, json, **kwargs):
# type: (dict, **Any) -> Property
"""Create a property based on the json data.
This method will attach the right class to a property, enabling the use of type-specific methods.
It does not create a property object in KE-chain. But a pseudo :class:`Property` object.
:param json: the json from which the :class:`Property` object to create
:type json: dict
:return: a :class:`Property` object
"""
property_type = json.get('property_type')
if property_type == PropertyType.ATTACHMENT_VALUE:
from .property_attachment import AttachmentProperty
return AttachmentProperty(json, **kwargs)
elif property_type == PropertyType.SINGLE_SELECT_VALUE:
from .property_selectlist import SelectListProperty
return SelectListProperty(json, **kwargs)
elif property_type == PropertyType.REFERENCE_VALUE:
from .property_reference import ReferenceProperty
return ReferenceProperty(json, **kwargs)
elif property_type == PropertyType.REFERENCES_VALUE:
from .property_multi_reference import MultiReferenceProperty
return MultiReferenceProperty(json, **kwargs)
else:
return Property(json, **kwargs) | python | def create(cls, json, **kwargs):
# type: (dict, **Any) -> Property
"""Create a property based on the json data.
This method will attach the right class to a property, enabling the use of type-specific methods.
It does not create a property object in KE-chain. But a pseudo :class:`Property` object.
:param json: the json from which the :class:`Property` object to create
:type json: dict
:return: a :class:`Property` object
"""
property_type = json.get('property_type')
if property_type == PropertyType.ATTACHMENT_VALUE:
from .property_attachment import AttachmentProperty
return AttachmentProperty(json, **kwargs)
elif property_type == PropertyType.SINGLE_SELECT_VALUE:
from .property_selectlist import SelectListProperty
return SelectListProperty(json, **kwargs)
elif property_type == PropertyType.REFERENCE_VALUE:
from .property_reference import ReferenceProperty
return ReferenceProperty(json, **kwargs)
elif property_type == PropertyType.REFERENCES_VALUE:
from .property_multi_reference import MultiReferenceProperty
return MultiReferenceProperty(json, **kwargs)
else:
return Property(json, **kwargs) | [
"def",
"create",
"(",
"cls",
",",
"json",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (dict, **Any) -> Property",
"property_type",
"=",
"json",
".",
"get",
"(",
"'property_type'",
")",
"if",
"property_type",
"==",
"PropertyType",
".",
"ATTACHMENT_VALUE",
":",
"from",
".",
"property_attachment",
"import",
"AttachmentProperty",
"return",
"AttachmentProperty",
"(",
"json",
",",
"*",
"*",
"kwargs",
")",
"elif",
"property_type",
"==",
"PropertyType",
".",
"SINGLE_SELECT_VALUE",
":",
"from",
".",
"property_selectlist",
"import",
"SelectListProperty",
"return",
"SelectListProperty",
"(",
"json",
",",
"*",
"*",
"kwargs",
")",
"elif",
"property_type",
"==",
"PropertyType",
".",
"REFERENCE_VALUE",
":",
"from",
".",
"property_reference",
"import",
"ReferenceProperty",
"return",
"ReferenceProperty",
"(",
"json",
",",
"*",
"*",
"kwargs",
")",
"elif",
"property_type",
"==",
"PropertyType",
".",
"REFERENCES_VALUE",
":",
"from",
".",
"property_multi_reference",
"import",
"MultiReferenceProperty",
"return",
"MultiReferenceProperty",
"(",
"json",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"Property",
"(",
"json",
",",
"*",
"*",
"kwargs",
")"
] | Create a property based on the json data.
This method will attach the right class to a property, enabling the use of type-specific methods.
It does not create a property object in KE-chain. But a pseudo :class:`Property` object.
:param json: the json from which the :class:`Property` object to create
:type json: dict
:return: a :class:`Property` object | [
"Create",
"a",
"property",
"based",
"on",
"the",
"json",
"data",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L143-L170 | train |
KE-works/pykechain | pykechain/models/property.py | Property.__parse_validators | def __parse_validators(self):
"""Parse the validator in the options to validators."""
self._validators = []
validators_json = self._options.get('validators')
for validator_json in validators_json:
self._validators.append(PropertyValidator.parse(json=validator_json)) | python | def __parse_validators(self):
"""Parse the validator in the options to validators."""
self._validators = []
validators_json = self._options.get('validators')
for validator_json in validators_json:
self._validators.append(PropertyValidator.parse(json=validator_json)) | [
"def",
"__parse_validators",
"(",
"self",
")",
":",
"self",
".",
"_validators",
"=",
"[",
"]",
"validators_json",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'validators'",
")",
"for",
"validator_json",
"in",
"validators_json",
":",
"self",
".",
"_validators",
".",
"append",
"(",
"PropertyValidator",
".",
"parse",
"(",
"json",
"=",
"validator_json",
")",
")"
] | Parse the validator in the options to validators. | [
"Parse",
"the",
"validator",
"in",
"the",
"options",
"to",
"validators",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L242-L247 | train |
KE-works/pykechain | pykechain/models/property.py | Property.__dump_validators | def __dump_validators(self):
"""Dump the validators as json inside the _options dictionary with the key `validators`."""
if hasattr(self, '_validators'):
validators_json = []
for validator in self._validators:
if isinstance(validator, PropertyValidator):
validators_json.append(validator.as_json())
else:
raise APIError("validator is not a PropertyValidator: '{}'".format(validator))
if self._options.get('validators', list()) == validators_json:
# no change
pass
else:
new_options = self._options.copy() # make a copy
new_options.update({'validators': validators_json})
validate(new_options, options_json_schema)
self._options = new_options | python | def __dump_validators(self):
"""Dump the validators as json inside the _options dictionary with the key `validators`."""
if hasattr(self, '_validators'):
validators_json = []
for validator in self._validators:
if isinstance(validator, PropertyValidator):
validators_json.append(validator.as_json())
else:
raise APIError("validator is not a PropertyValidator: '{}'".format(validator))
if self._options.get('validators', list()) == validators_json:
# no change
pass
else:
new_options = self._options.copy() # make a copy
new_options.update({'validators': validators_json})
validate(new_options, options_json_schema)
self._options = new_options | [
"def",
"__dump_validators",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_validators'",
")",
":",
"validators_json",
"=",
"[",
"]",
"for",
"validator",
"in",
"self",
".",
"_validators",
":",
"if",
"isinstance",
"(",
"validator",
",",
"PropertyValidator",
")",
":",
"validators_json",
".",
"append",
"(",
"validator",
".",
"as_json",
"(",
")",
")",
"else",
":",
"raise",
"APIError",
"(",
"\"validator is not a PropertyValidator: '{}'\"",
".",
"format",
"(",
"validator",
")",
")",
"if",
"self",
".",
"_options",
".",
"get",
"(",
"'validators'",
",",
"list",
"(",
")",
")",
"==",
"validators_json",
":",
"# no change",
"pass",
"else",
":",
"new_options",
"=",
"self",
".",
"_options",
".",
"copy",
"(",
")",
"# make a copy",
"new_options",
".",
"update",
"(",
"{",
"'validators'",
":",
"validators_json",
"}",
")",
"validate",
"(",
"new_options",
",",
"options_json_schema",
")",
"self",
".",
"_options",
"=",
"new_options"
] | Dump the validators as json inside the _options dictionary with the key `validators`. | [
"Dump",
"the",
"validators",
"as",
"json",
"inside",
"the",
"_options",
"dictionary",
"with",
"the",
"key",
"validators",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L249-L265 | train |
KE-works/pykechain | pykechain/models/property.py | Property.is_valid | def is_valid(self):
# type: () -> Union[bool, None]
"""Determine if the value in the property is valid.
If the value of the property is validated as 'valid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the :ivar:`value` is valid
:rtype: bool or None
"""
if not hasattr(self, '_validators'):
return None
else:
self.validate(reason=False)
if all([vr is None for vr in self._validation_results]):
return None
else:
return all(self._validation_results) | python | def is_valid(self):
# type: () -> Union[bool, None]
"""Determine if the value in the property is valid.
If the value of the property is validated as 'valid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the :ivar:`value` is valid
:rtype: bool or None
"""
if not hasattr(self, '_validators'):
return None
else:
self.validate(reason=False)
if all([vr is None for vr in self._validation_results]):
return None
else:
return all(self._validation_results) | [
"def",
"is_valid",
"(",
"self",
")",
":",
"# type: () -> Union[bool, None]",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_validators'",
")",
":",
"return",
"None",
"else",
":",
"self",
".",
"validate",
"(",
"reason",
"=",
"False",
")",
"if",
"all",
"(",
"[",
"vr",
"is",
"None",
"for",
"vr",
"in",
"self",
".",
"_validation_results",
"]",
")",
":",
"return",
"None",
"else",
":",
"return",
"all",
"(",
"self",
".",
"_validation_results",
")"
] | Determine if the value in the property is valid.
If the value of the property is validated as 'valid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the :ivar:`value` is valid
:rtype: bool or None | [
"Determine",
"if",
"the",
"value",
"in",
"the",
"property",
"is",
"valid",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L268-L286 | train |
fprimex/zdeskcfg | zdeskcfg.py | get_ini_config | def get_ini_config(config=os.path.join(os.path.expanduser('~'), '.zdeskcfg'),
default_section=None, section=None):
"""This is a convenience function for getting the zdesk configuration
from an ini file without the need to decorate and call your own function.
Handy when using zdesk and zdeskcfg from the interactive prompt."""
plac_ini.call(__placeholder__, config=config, default_section=default_section)
return __placeholder__.getconfig(section) | python | def get_ini_config(config=os.path.join(os.path.expanduser('~'), '.zdeskcfg'),
default_section=None, section=None):
"""This is a convenience function for getting the zdesk configuration
from an ini file without the need to decorate and call your own function.
Handy when using zdesk and zdeskcfg from the interactive prompt."""
plac_ini.call(__placeholder__, config=config, default_section=default_section)
return __placeholder__.getconfig(section) | [
"def",
"get_ini_config",
"(",
"config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.zdeskcfg'",
")",
",",
"default_section",
"=",
"None",
",",
"section",
"=",
"None",
")",
":",
"plac_ini",
".",
"call",
"(",
"__placeholder__",
",",
"config",
"=",
"config",
",",
"default_section",
"=",
"default_section",
")",
"return",
"__placeholder__",
".",
"getconfig",
"(",
"section",
")"
] | This is a convenience function for getting the zdesk configuration
from an ini file without the need to decorate and call your own function.
Handy when using zdesk and zdeskcfg from the interactive prompt. | [
"This",
"is",
"a",
"convenience",
"function",
"for",
"getting",
"the",
"zdesk",
"configuration",
"from",
"an",
"ini",
"file",
"without",
"the",
"need",
"to",
"decorate",
"and",
"call",
"your",
"own",
"function",
".",
"Handy",
"when",
"using",
"zdesk",
"and",
"zdeskcfg",
"from",
"the",
"interactive",
"prompt",
"."
] | 4283733123a62c0ab7679ca8aba0d4b02e6bb8d7 | https://github.com/fprimex/zdeskcfg/blob/4283733123a62c0ab7679ca8aba0d4b02e6bb8d7/zdeskcfg.py#L165-L171 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | _ecg_band_pass_filter | def _ecg_band_pass_filter(data, sample_rate):
"""
Bandpass filter with a bandpass setting of 5 to 15 Hz
----------
Parameters
----------
data : list
List with the ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
out : list
Filtered signal.
"""
nyquist_sample_rate = sample_rate / 2.
normalized_cut_offs = [5/nyquist_sample_rate, 15/nyquist_sample_rate]
b_coeff, a_coeff = butter(2, normalized_cut_offs, btype='bandpass')[:2]
return filtfilt(b_coeff, a_coeff, data, padlen=150) | python | def _ecg_band_pass_filter(data, sample_rate):
"""
Bandpass filter with a bandpass setting of 5 to 15 Hz
----------
Parameters
----------
data : list
List with the ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
out : list
Filtered signal.
"""
nyquist_sample_rate = sample_rate / 2.
normalized_cut_offs = [5/nyquist_sample_rate, 15/nyquist_sample_rate]
b_coeff, a_coeff = butter(2, normalized_cut_offs, btype='bandpass')[:2]
return filtfilt(b_coeff, a_coeff, data, padlen=150) | [
"def",
"_ecg_band_pass_filter",
"(",
"data",
",",
"sample_rate",
")",
":",
"nyquist_sample_rate",
"=",
"sample_rate",
"/",
"2.",
"normalized_cut_offs",
"=",
"[",
"5",
"/",
"nyquist_sample_rate",
",",
"15",
"/",
"nyquist_sample_rate",
"]",
"b_coeff",
",",
"a_coeff",
"=",
"butter",
"(",
"2",
",",
"normalized_cut_offs",
",",
"btype",
"=",
"'bandpass'",
")",
"[",
":",
"2",
"]",
"return",
"filtfilt",
"(",
"b_coeff",
",",
"a_coeff",
",",
"data",
",",
"padlen",
"=",
"150",
")"
] | Bandpass filter with a bandpass setting of 5 to 15 Hz
----------
Parameters
----------
data : list
List with the ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
out : list
Filtered signal. | [
"Bandpass",
"filter",
"with",
"a",
"bandpass",
"setting",
"of",
"5",
"to",
"15",
"Hz"
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L365-L385 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | _integration | def _integration(data, sample_rate):
"""
Moving window integration. N is the number of samples in the width of the integration
window
----------
Parameters
----------
data : ndarray
Samples of the signal where a moving window integration will be applied.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
out : ndarray
Integrated signal samples.
"""
wind_size = int(0.080 * sample_rate)
int_ecg = numpy.zeros_like(data)
cum_sum = data.cumsum()
int_ecg[wind_size:] = (cum_sum[wind_size:] - cum_sum[:-wind_size]) / wind_size
int_ecg[:wind_size] = cum_sum[:wind_size] / numpy.arange(1, wind_size + 1)
return int_ecg | python | def _integration(data, sample_rate):
"""
Moving window integration. N is the number of samples in the width of the integration
window
----------
Parameters
----------
data : ndarray
Samples of the signal where a moving window integration will be applied.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
out : ndarray
Integrated signal samples.
"""
wind_size = int(0.080 * sample_rate)
int_ecg = numpy.zeros_like(data)
cum_sum = data.cumsum()
int_ecg[wind_size:] = (cum_sum[wind_size:] - cum_sum[:-wind_size]) / wind_size
int_ecg[:wind_size] = cum_sum[:wind_size] / numpy.arange(1, wind_size + 1)
return int_ecg | [
"def",
"_integration",
"(",
"data",
",",
"sample_rate",
")",
":",
"wind_size",
"=",
"int",
"(",
"0.080",
"*",
"sample_rate",
")",
"int_ecg",
"=",
"numpy",
".",
"zeros_like",
"(",
"data",
")",
"cum_sum",
"=",
"data",
".",
"cumsum",
"(",
")",
"int_ecg",
"[",
"wind_size",
":",
"]",
"=",
"(",
"cum_sum",
"[",
"wind_size",
":",
"]",
"-",
"cum_sum",
"[",
":",
"-",
"wind_size",
"]",
")",
"/",
"wind_size",
"int_ecg",
"[",
":",
"wind_size",
"]",
"=",
"cum_sum",
"[",
":",
"wind_size",
"]",
"/",
"numpy",
".",
"arange",
"(",
"1",
",",
"wind_size",
"+",
"1",
")",
"return",
"int_ecg"
] | Moving window integration. N is the number of samples in the width of the integration
window
----------
Parameters
----------
data : ndarray
Samples of the signal where a moving window integration will be applied.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
out : ndarray
Integrated signal samples. | [
"Moving",
"window",
"integration",
".",
"N",
"is",
"the",
"number",
"of",
"samples",
"in",
"the",
"width",
"of",
"the",
"integration",
"window"
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L428-L452 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | _buffer_ini | def _buffer_ini(data, sample_rate):
"""
Initializes the buffer with eight 1s intervals
----------
Parameters
----------
data : ndarray
Pre-processed ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
rr_buffer : list
Data structure that stores eight samples (in the future this buffer will store the duration
of eight RR intervals instead of the 1 second values defined in initialisation).
spk1 : float
Initial value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
npk1 : int
Initial value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named noise peak).
threshold : float
Initial value of the adaptive threshold level (relevant parameter for the application of
specific criteria during the identification of R peaks).
Sources
-------
https://www.robots.ox.ac.uk/~gari/teaching/cdt/A3/readings/ECG/Pan+Tompkins.pdf
"""
rr_buffer = [1] * 8
spk1 = max(data[sample_rate:2*sample_rate])
npk1 = 0
threshold = _buffer_update(npk1, spk1)
return rr_buffer, spk1, npk1, threshold | python | def _buffer_ini(data, sample_rate):
"""
Initializes the buffer with eight 1s intervals
----------
Parameters
----------
data : ndarray
Pre-processed ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
rr_buffer : list
Data structure that stores eight samples (in the future this buffer will store the duration
of eight RR intervals instead of the 1 second values defined in initialisation).
spk1 : float
Initial value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
npk1 : int
Initial value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named noise peak).
threshold : float
Initial value of the adaptive threshold level (relevant parameter for the application of
specific criteria during the identification of R peaks).
Sources
-------
https://www.robots.ox.ac.uk/~gari/teaching/cdt/A3/readings/ECG/Pan+Tompkins.pdf
"""
rr_buffer = [1] * 8
spk1 = max(data[sample_rate:2*sample_rate])
npk1 = 0
threshold = _buffer_update(npk1, spk1)
return rr_buffer, spk1, npk1, threshold | [
"def",
"_buffer_ini",
"(",
"data",
",",
"sample_rate",
")",
":",
"rr_buffer",
"=",
"[",
"1",
"]",
"*",
"8",
"spk1",
"=",
"max",
"(",
"data",
"[",
"sample_rate",
":",
"2",
"*",
"sample_rate",
"]",
")",
"npk1",
"=",
"0",
"threshold",
"=",
"_buffer_update",
"(",
"npk1",
",",
"spk1",
")",
"return",
"rr_buffer",
",",
"spk1",
",",
"npk1",
",",
"threshold"
] | Initializes the buffer with eight 1s intervals
----------
Parameters
----------
data : ndarray
Pre-processed ECG signal samples.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
rr_buffer : list
Data structure that stores eight samples (in the future this buffer will store the duration
of eight RR intervals instead of the 1 second values defined in initialisation).
spk1 : float
Initial value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
npk1 : int
Initial value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named noise peak).
threshold : float
Initial value of the adaptive threshold level (relevant parameter for the application of
specific criteria during the identification of R peaks).
Sources
-------
https://www.robots.ox.ac.uk/~gari/teaching/cdt/A3/readings/ECG/Pan+Tompkins.pdf | [
"Initializes",
"the",
"buffer",
"with",
"eight",
"1s",
"intervals"
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L455-L493 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | _detects_peaks | def _detects_peaks(ecg_integrated, sample_rate):
"""
Detects peaks from local maximum
----------
Parameters
----------
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
choosen_peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
a R peak.
possible_peaks : list
List with all the local maximums in the signal.
"""
# Minimum RR interval = 200 ms
min_rr = (sample_rate / 1000) * 200
# Computes all possible peaks and their amplitudes
possible_peaks = [i for i in range(0, len(ecg_integrated)-1)
if ecg_integrated[i-1] < ecg_integrated[i] and
ecg_integrated[i] > ecg_integrated[i+1]]
possible_amplitudes = [ecg_integrated[k] for k in possible_peaks]
chosen_peaks = []
# Starts with first peak
if not possible_peaks:
raise Exception("No Peaks Detected.")
peak_candidate_i = possible_peaks[0]
peak_candidate_amp = possible_amplitudes[0]
for peak_i, peak_amp in zip(possible_peaks, possible_amplitudes):
if peak_i - peak_candidate_i <= min_rr and peak_amp > peak_candidate_amp:
peak_candidate_i = peak_i
peak_candidate_amp = peak_amp
elif peak_i - peak_candidate_i > min_rr:
chosen_peaks += [peak_candidate_i - 6] # Delay of 6 samples
peak_candidate_i = peak_i
peak_candidate_amp = peak_amp
else:
pass
return chosen_peaks, possible_peaks | python | def _detects_peaks(ecg_integrated, sample_rate):
"""
Detects peaks from local maximum
----------
Parameters
----------
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
choosen_peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
a R peak.
possible_peaks : list
List with all the local maximums in the signal.
"""
# Minimum RR interval = 200 ms
min_rr = (sample_rate / 1000) * 200
# Computes all possible peaks and their amplitudes
possible_peaks = [i for i in range(0, len(ecg_integrated)-1)
if ecg_integrated[i-1] < ecg_integrated[i] and
ecg_integrated[i] > ecg_integrated[i+1]]
possible_amplitudes = [ecg_integrated[k] for k in possible_peaks]
chosen_peaks = []
# Starts with first peak
if not possible_peaks:
raise Exception("No Peaks Detected.")
peak_candidate_i = possible_peaks[0]
peak_candidate_amp = possible_amplitudes[0]
for peak_i, peak_amp in zip(possible_peaks, possible_amplitudes):
if peak_i - peak_candidate_i <= min_rr and peak_amp > peak_candidate_amp:
peak_candidate_i = peak_i
peak_candidate_amp = peak_amp
elif peak_i - peak_candidate_i > min_rr:
chosen_peaks += [peak_candidate_i - 6] # Delay of 6 samples
peak_candidate_i = peak_i
peak_candidate_amp = peak_amp
else:
pass
return chosen_peaks, possible_peaks | [
"def",
"_detects_peaks",
"(",
"ecg_integrated",
",",
"sample_rate",
")",
":",
"# Minimum RR interval = 200 ms",
"min_rr",
"=",
"(",
"sample_rate",
"/",
"1000",
")",
"*",
"200",
"# Computes all possible peaks and their amplitudes",
"possible_peaks",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"ecg_integrated",
")",
"-",
"1",
")",
"if",
"ecg_integrated",
"[",
"i",
"-",
"1",
"]",
"<",
"ecg_integrated",
"[",
"i",
"]",
"and",
"ecg_integrated",
"[",
"i",
"]",
">",
"ecg_integrated",
"[",
"i",
"+",
"1",
"]",
"]",
"possible_amplitudes",
"=",
"[",
"ecg_integrated",
"[",
"k",
"]",
"for",
"k",
"in",
"possible_peaks",
"]",
"chosen_peaks",
"=",
"[",
"]",
"# Starts with first peak",
"if",
"not",
"possible_peaks",
":",
"raise",
"Exception",
"(",
"\"No Peaks Detected.\"",
")",
"peak_candidate_i",
"=",
"possible_peaks",
"[",
"0",
"]",
"peak_candidate_amp",
"=",
"possible_amplitudes",
"[",
"0",
"]",
"for",
"peak_i",
",",
"peak_amp",
"in",
"zip",
"(",
"possible_peaks",
",",
"possible_amplitudes",
")",
":",
"if",
"peak_i",
"-",
"peak_candidate_i",
"<=",
"min_rr",
"and",
"peak_amp",
">",
"peak_candidate_amp",
":",
"peak_candidate_i",
"=",
"peak_i",
"peak_candidate_amp",
"=",
"peak_amp",
"elif",
"peak_i",
"-",
"peak_candidate_i",
">",
"min_rr",
":",
"chosen_peaks",
"+=",
"[",
"peak_candidate_i",
"-",
"6",
"]",
"# Delay of 6 samples",
"peak_candidate_i",
"=",
"peak_i",
"peak_candidate_amp",
"=",
"peak_amp",
"else",
":",
"pass",
"return",
"chosen_peaks",
",",
"possible_peaks"
] | Detects peaks from local maximum
----------
Parameters
----------
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
Returns
-------
choosen_peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
a R peak.
possible_peaks : list
List with all the local maximums in the signal. | [
"Detects",
"peaks",
"from",
"local",
"maximum"
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L521-L570 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | _checkup | def _checkup(peaks, ecg_integrated, sample_rate, rr_buffer, spk1, npk1, threshold):
"""
Check each peak according to thresholds
----------
Parameters
----------
peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
an R peak.
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
rr_buffer : list
Data structure that stores the duration of the last eight RR intervals.
spk1 : float
Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
npk1 : int
Actual value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named noise peak).
threshold : float
Initial value of the adaptive threshold level (relevant parameter for the application of
specific criteria during the identification of R peaks).
Returns
-------
out : list
List with the position of the peaks considered as R peak by the algorithm.
"""
peaks_amp = [ecg_integrated[peak] for peak in peaks]
definitive_peaks = []
for i, peak in enumerate(peaks):
amp = peaks_amp[i]
# accept if larger than threshold and slope in raw signal
# is +-30% of previous slopes
if amp > threshold:
definitive_peaks, spk1, rr_buffer = _acceptpeak(peak, amp, definitive_peaks, spk1,
rr_buffer)
# accept as qrs if higher than half threshold,
# but is 360 ms after last qrs and next peak
# is more than 1.5 rr intervals away
# just abandon it if there is no peak before
# or after
elif amp > threshold / 2 and list(definitive_peaks) and len(peaks) > i + 1:
mean_rr = numpy.mean(rr_buffer)
last_qrs_ms = (peak - definitive_peaks[-1]) * (1000 / sample_rate)
last_qrs_to_next_peak = peaks[i+1] - definitive_peaks[-1]
if last_qrs_ms > 360 and last_qrs_to_next_peak > 1.5 * mean_rr:
definitive_peaks, spk1, rr_buffer = _acceptpeak(peak, amp, definitive_peaks, spk1,
rr_buffer)
else:
npk1 = _noisepeak(amp, npk1)
# if not either of these it is noise
else:
npk1 = _noisepeak(amp, npk1)
threshold = _buffer_update(npk1, spk1)
definitive_peaks = numpy.array(definitive_peaks)
return definitive_peaks | python | def _checkup(peaks, ecg_integrated, sample_rate, rr_buffer, spk1, npk1, threshold):
"""
Check each peak according to thresholds
----------
Parameters
----------
peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
an R peak.
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
rr_buffer : list
Data structure that stores the duration of the last eight RR intervals.
spk1 : float
Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
npk1 : int
Actual value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named noise peak).
threshold : float
Initial value of the adaptive threshold level (relevant parameter for the application of
specific criteria during the identification of R peaks).
Returns
-------
out : list
List with the position of the peaks considered as R peak by the algorithm.
"""
peaks_amp = [ecg_integrated[peak] for peak in peaks]
definitive_peaks = []
for i, peak in enumerate(peaks):
amp = peaks_amp[i]
# accept if larger than threshold and slope in raw signal
# is +-30% of previous slopes
if amp > threshold:
definitive_peaks, spk1, rr_buffer = _acceptpeak(peak, amp, definitive_peaks, spk1,
rr_buffer)
# accept as qrs if higher than half threshold,
# but is 360 ms after last qrs and next peak
# is more than 1.5 rr intervals away
# just abandon it if there is no peak before
# or after
elif amp > threshold / 2 and list(definitive_peaks) and len(peaks) > i + 1:
mean_rr = numpy.mean(rr_buffer)
last_qrs_ms = (peak - definitive_peaks[-1]) * (1000 / sample_rate)
last_qrs_to_next_peak = peaks[i+1] - definitive_peaks[-1]
if last_qrs_ms > 360 and last_qrs_to_next_peak > 1.5 * mean_rr:
definitive_peaks, spk1, rr_buffer = _acceptpeak(peak, amp, definitive_peaks, spk1,
rr_buffer)
else:
npk1 = _noisepeak(amp, npk1)
# if not either of these it is noise
else:
npk1 = _noisepeak(amp, npk1)
threshold = _buffer_update(npk1, spk1)
definitive_peaks = numpy.array(definitive_peaks)
return definitive_peaks | [
"def",
"_checkup",
"(",
"peaks",
",",
"ecg_integrated",
",",
"sample_rate",
",",
"rr_buffer",
",",
"spk1",
",",
"npk1",
",",
"threshold",
")",
":",
"peaks_amp",
"=",
"[",
"ecg_integrated",
"[",
"peak",
"]",
"for",
"peak",
"in",
"peaks",
"]",
"definitive_peaks",
"=",
"[",
"]",
"for",
"i",
",",
"peak",
"in",
"enumerate",
"(",
"peaks",
")",
":",
"amp",
"=",
"peaks_amp",
"[",
"i",
"]",
"# accept if larger than threshold and slope in raw signal",
"# is +-30% of previous slopes",
"if",
"amp",
">",
"threshold",
":",
"definitive_peaks",
",",
"spk1",
",",
"rr_buffer",
"=",
"_acceptpeak",
"(",
"peak",
",",
"amp",
",",
"definitive_peaks",
",",
"spk1",
",",
"rr_buffer",
")",
"# accept as qrs if higher than half threshold,",
"# but is 360 ms after last qrs and next peak",
"# is more than 1.5 rr intervals away",
"# just abandon it if there is no peak before",
"# or after",
"elif",
"amp",
">",
"threshold",
"/",
"2",
"and",
"list",
"(",
"definitive_peaks",
")",
"and",
"len",
"(",
"peaks",
")",
">",
"i",
"+",
"1",
":",
"mean_rr",
"=",
"numpy",
".",
"mean",
"(",
"rr_buffer",
")",
"last_qrs_ms",
"=",
"(",
"peak",
"-",
"definitive_peaks",
"[",
"-",
"1",
"]",
")",
"*",
"(",
"1000",
"/",
"sample_rate",
")",
"last_qrs_to_next_peak",
"=",
"peaks",
"[",
"i",
"+",
"1",
"]",
"-",
"definitive_peaks",
"[",
"-",
"1",
"]",
"if",
"last_qrs_ms",
">",
"360",
"and",
"last_qrs_to_next_peak",
">",
"1.5",
"*",
"mean_rr",
":",
"definitive_peaks",
",",
"spk1",
",",
"rr_buffer",
"=",
"_acceptpeak",
"(",
"peak",
",",
"amp",
",",
"definitive_peaks",
",",
"spk1",
",",
"rr_buffer",
")",
"else",
":",
"npk1",
"=",
"_noisepeak",
"(",
"amp",
",",
"npk1",
")",
"# if not either of these it is noise",
"else",
":",
"npk1",
"=",
"_noisepeak",
"(",
"amp",
",",
"npk1",
")",
"threshold",
"=",
"_buffer_update",
"(",
"npk1",
",",
"spk1",
")",
"definitive_peaks",
"=",
"numpy",
".",
"array",
"(",
"definitive_peaks",
")",
"return",
"definitive_peaks"
] | Check each peak according to thresholds
----------
Parameters
----------
peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
an R peak.
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
sample_rate : int
Sampling rate at which the acquisition took place.
rr_buffer : list
Data structure that stores the duration of the last eight RR intervals.
spk1 : float
Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
npk1 : int
Actual value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named noise peak).
threshold : float
Initial value of the adaptive threshold level (relevant parameter for the application of
specific criteria during the identification of R peaks).
Returns
-------
out : list
List with the position of the peaks considered as R peak by the algorithm. | [
"Check",
"each",
"peak",
"according",
"to",
"thresholds"
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L573-L638 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | _acceptpeak | def _acceptpeak(peak, amp, definitive_peaks, spk1, rr_buffer):
"""
Private function intended to insert a new RR interval in the buffer.
----------
Parameters
----------
peak : int
Sample where the peak under analysis is located.
amp : int
Amplitude of the peak under analysis.
definitive_peaks : list
List with the definitive_peaks stored until the present instant.
spk1 : float
Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
rr_buffer : list
Data structure that stores the duration of the last eight RR intervals.
Returns
-------
definitive_peaks_out : list
Definitive peaks list.
spk1 : float
Updated value of SPK1 parameter.
rr_buffer : list
Buffer after appending a new RR interval and excluding the oldest one.
"""
definitive_peaks_out = definitive_peaks
definitive_peaks_out = numpy.append(definitive_peaks_out, peak)
spk1 = 0.125 * amp + 0.875 * spk1 # spk1 is the running estimate of the signal peak
if len(definitive_peaks_out) > 1:
rr_buffer.pop(0)
rr_buffer += [definitive_peaks_out[-1] - definitive_peaks_out[-2]]
return numpy.array(definitive_peaks_out), spk1, rr_buffer | python | def _acceptpeak(peak, amp, definitive_peaks, spk1, rr_buffer):
"""
Private function intended to insert a new RR interval in the buffer.
----------
Parameters
----------
peak : int
Sample where the peak under analysis is located.
amp : int
Amplitude of the peak under analysis.
definitive_peaks : list
List with the definitive_peaks stored until the present instant.
spk1 : float
Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
rr_buffer : list
Data structure that stores the duration of the last eight RR intervals.
Returns
-------
definitive_peaks_out : list
Definitive peaks list.
spk1 : float
Updated value of SPK1 parameter.
rr_buffer : list
Buffer after appending a new RR interval and excluding the oldest one.
"""
definitive_peaks_out = definitive_peaks
definitive_peaks_out = numpy.append(definitive_peaks_out, peak)
spk1 = 0.125 * amp + 0.875 * spk1 # spk1 is the running estimate of the signal peak
if len(definitive_peaks_out) > 1:
rr_buffer.pop(0)
rr_buffer += [definitive_peaks_out[-1] - definitive_peaks_out[-2]]
return numpy.array(definitive_peaks_out), spk1, rr_buffer | [
"def",
"_acceptpeak",
"(",
"peak",
",",
"amp",
",",
"definitive_peaks",
",",
"spk1",
",",
"rr_buffer",
")",
":",
"definitive_peaks_out",
"=",
"definitive_peaks",
"definitive_peaks_out",
"=",
"numpy",
".",
"append",
"(",
"definitive_peaks_out",
",",
"peak",
")",
"spk1",
"=",
"0.125",
"*",
"amp",
"+",
"0.875",
"*",
"spk1",
"# spk1 is the running estimate of the signal peak",
"if",
"len",
"(",
"definitive_peaks_out",
")",
">",
"1",
":",
"rr_buffer",
".",
"pop",
"(",
"0",
")",
"rr_buffer",
"+=",
"[",
"definitive_peaks_out",
"[",
"-",
"1",
"]",
"-",
"definitive_peaks_out",
"[",
"-",
"2",
"]",
"]",
"return",
"numpy",
".",
"array",
"(",
"definitive_peaks_out",
")",
",",
"spk1",
",",
"rr_buffer"
] | Private function intended to insert a new RR interval in the buffer.
----------
Parameters
----------
peak : int
Sample where the peak under analysis is located.
amp : int
Amplitude of the peak under analysis.
definitive_peaks : list
List with the definitive_peaks stored until the present instant.
spk1 : float
Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm
(named signal peak).
rr_buffer : list
Data structure that stores the duration of the last eight RR intervals.
Returns
-------
definitive_peaks_out : list
Definitive peaks list.
spk1 : float
Updated value of SPK1 parameter.
rr_buffer : list
Buffer after appending a new RR interval and excluding the oldest one. | [
"Private",
"function",
"intended",
"to",
"insert",
"a",
"new",
"RR",
"interval",
"in",
"the",
"buffer",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L641-L678 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py | tachogram | def tachogram(data, sample_rate, signal=False, in_seconds=False, out_seconds=False):
"""
Function for generation of ECG Tachogram.
----------
Parameters
----------
data : list
ECG signal or R peak list. When the input is a raw signal the input flag signal should be
True.
sample_rate : int
Sampling frequency.
signal : boolean
If True, then the data argument contains the set of the ECG acquired samples.
in_seconds : boolean
If the R peaks list defined as the input argument "data" contains the sample numbers where
the R peaks occur, then in_seconds needs to be False.
out_seconds : boolean
If True then each sample of the returned time axis is expressed in seconds.
Returns
-------
out : list, list
List of tachogram samples. List of instants where each cardiac cycle ends.
"""
if signal is False: # data is a list of R peaks position.
data_copy = data
time_axis = numpy.array(data)#.cumsum()
if out_seconds is True and in_seconds is False:
time_axis = time_axis / sample_rate
else: # data is a ECG signal.
# Detection of R peaks.
data_copy = detect_r_peaks(data, sample_rate, time_units=out_seconds, volts=False,
resolution=None, plot_result=False)[0]
time_axis = data_copy
# Generation of Tachogram.
tachogram_data = numpy.diff(time_axis)
tachogram_time = time_axis[1:]
return tachogram_data, tachogram_time | python | def tachogram(data, sample_rate, signal=False, in_seconds=False, out_seconds=False):
"""
Function for generation of ECG Tachogram.
----------
Parameters
----------
data : list
ECG signal or R peak list. When the input is a raw signal the input flag signal should be
True.
sample_rate : int
Sampling frequency.
signal : boolean
If True, then the data argument contains the set of the ECG acquired samples.
in_seconds : boolean
If the R peaks list defined as the input argument "data" contains the sample numbers where
the R peaks occur, then in_seconds needs to be False.
out_seconds : boolean
If True then each sample of the returned time axis is expressed in seconds.
Returns
-------
out : list, list
List of tachogram samples. List of instants where each cardiac cycle ends.
"""
if signal is False: # data is a list of R peaks position.
data_copy = data
time_axis = numpy.array(data)#.cumsum()
if out_seconds is True and in_seconds is False:
time_axis = time_axis / sample_rate
else: # data is a ECG signal.
# Detection of R peaks.
data_copy = detect_r_peaks(data, sample_rate, time_units=out_seconds, volts=False,
resolution=None, plot_result=False)[0]
time_axis = data_copy
# Generation of Tachogram.
tachogram_data = numpy.diff(time_axis)
tachogram_time = time_axis[1:]
return tachogram_data, tachogram_time | [
"def",
"tachogram",
"(",
"data",
",",
"sample_rate",
",",
"signal",
"=",
"False",
",",
"in_seconds",
"=",
"False",
",",
"out_seconds",
"=",
"False",
")",
":",
"if",
"signal",
"is",
"False",
":",
"# data is a list of R peaks position.",
"data_copy",
"=",
"data",
"time_axis",
"=",
"numpy",
".",
"array",
"(",
"data",
")",
"#.cumsum()",
"if",
"out_seconds",
"is",
"True",
"and",
"in_seconds",
"is",
"False",
":",
"time_axis",
"=",
"time_axis",
"/",
"sample_rate",
"else",
":",
"# data is a ECG signal.",
"# Detection of R peaks.",
"data_copy",
"=",
"detect_r_peaks",
"(",
"data",
",",
"sample_rate",
",",
"time_units",
"=",
"out_seconds",
",",
"volts",
"=",
"False",
",",
"resolution",
"=",
"None",
",",
"plot_result",
"=",
"False",
")",
"[",
"0",
"]",
"time_axis",
"=",
"data_copy",
"# Generation of Tachogram.",
"tachogram_data",
"=",
"numpy",
".",
"diff",
"(",
"time_axis",
")",
"tachogram_time",
"=",
"time_axis",
"[",
"1",
":",
"]",
"return",
"tachogram_data",
",",
"tachogram_time"
] | Function for generation of ECG Tachogram.
----------
Parameters
----------
data : list
ECG signal or R peak list. When the input is a raw signal the input flag signal should be
True.
sample_rate : int
Sampling frequency.
signal : boolean
If True, then the data argument contains the set of the ECG acquired samples.
in_seconds : boolean
If the R peaks list defined as the input argument "data" contains the sample numbers where
the R peaks occur, then in_seconds needs to be False.
out_seconds : boolean
If True then each sample of the returned time axis is expressed in seconds.
Returns
-------
out : list, list
List of tachogram samples. List of instants where each cardiac cycle ends. | [
"Function",
"for",
"generation",
"of",
"ECG",
"Tachogram",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L704-L750 | train |
thomasdelaet/python-velbus | velbus/connections/serial.py | VelbusUSBConnection.stop | def stop(self):
"""Close serial port."""
self.logger.warning("Stop executed")
try:
self._reader.close()
except serial.serialutil.SerialException:
self.logger.error("Error while closing device")
raise VelbusException("Error while closing device")
time.sleep(1) | python | def stop(self):
"""Close serial port."""
self.logger.warning("Stop executed")
try:
self._reader.close()
except serial.serialutil.SerialException:
self.logger.error("Error while closing device")
raise VelbusException("Error while closing device")
time.sleep(1) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Stop executed\"",
")",
"try",
":",
"self",
".",
"_reader",
".",
"close",
"(",
")",
"except",
"serial",
".",
"serialutil",
".",
"SerialException",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error while closing device\"",
")",
"raise",
"VelbusException",
"(",
"\"Error while closing device\"",
")",
"time",
".",
"sleep",
"(",
"1",
")"
] | Close serial port. | [
"Close",
"serial",
"port",
"."
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L77-L85 | train |
thomasdelaet/python-velbus | velbus/connections/serial.py | VelbusUSBConnection.feed_parser | def feed_parser(self, data):
"""Parse received message."""
assert isinstance(data, bytes)
self.controller.feed_parser(data) | python | def feed_parser(self, data):
"""Parse received message."""
assert isinstance(data, bytes)
self.controller.feed_parser(data) | [
"def",
"feed_parser",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"controller",
".",
"feed_parser",
"(",
"data",
")"
] | Parse received message. | [
"Parse",
"received",
"message",
"."
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L87-L90 | train |
thomasdelaet/python-velbus | velbus/connections/serial.py | VelbusUSBConnection.send | def send(self, message, callback=None):
"""Add message to write queue."""
assert isinstance(message, velbus.Message)
self._write_queue.put_nowait((message, callback)) | python | def send(self, message, callback=None):
"""Add message to write queue."""
assert isinstance(message, velbus.Message)
self._write_queue.put_nowait((message, callback)) | [
"def",
"send",
"(",
"self",
",",
"message",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"Message",
")",
"self",
".",
"_write_queue",
".",
"put_nowait",
"(",
"(",
"message",
",",
"callback",
")",
")"
] | Add message to write queue. | [
"Add",
"message",
"to",
"write",
"queue",
"."
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L92-L95 | train |
thomasdelaet/python-velbus | velbus/connections/serial.py | VelbusUSBConnection.write_daemon | def write_daemon(self):
"""Write thread."""
while True:
(message, callback) = self._write_queue.get(block=True)
self.logger.info("Sending message on USB bus: %s", str(message))
self.logger.debug("Sending binary message: %s", str(message.to_binary()))
self._reader.write(message.to_binary())
time.sleep(self.SLEEP_TIME)
if callback:
callback() | python | def write_daemon(self):
"""Write thread."""
while True:
(message, callback) = self._write_queue.get(block=True)
self.logger.info("Sending message on USB bus: %s", str(message))
self.logger.debug("Sending binary message: %s", str(message.to_binary()))
self._reader.write(message.to_binary())
time.sleep(self.SLEEP_TIME)
if callback:
callback() | [
"def",
"write_daemon",
"(",
"self",
")",
":",
"while",
"True",
":",
"(",
"message",
",",
"callback",
")",
"=",
"self",
".",
"_write_queue",
".",
"get",
"(",
"block",
"=",
"True",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Sending message on USB bus: %s\"",
",",
"str",
"(",
"message",
")",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Sending binary message: %s\"",
",",
"str",
"(",
"message",
".",
"to_binary",
"(",
")",
")",
")",
"self",
".",
"_reader",
".",
"write",
"(",
"message",
".",
"to_binary",
"(",
")",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"SLEEP_TIME",
")",
"if",
"callback",
":",
"callback",
"(",
")"
] | Write thread. | [
"Write",
"thread",
"."
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L97-L106 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.__require_kytos_config | def __require_kytos_config(self):
"""Set path locations from kytosd API.
It should not be called directly, but from properties that require a
running kytosd instance.
"""
if self.__enabled is None:
uri = self._kytos_api + 'api/kytos/core/config/'
try:
options = json.loads(urllib.request.urlopen(uri).read())
except urllib.error.URLError:
print('Kytos is not running.')
sys.exit()
self.__enabled = Path(options.get('napps'))
self.__installed = Path(options.get('installed_napps')) | python | def __require_kytos_config(self):
"""Set path locations from kytosd API.
It should not be called directly, but from properties that require a
running kytosd instance.
"""
if self.__enabled is None:
uri = self._kytos_api + 'api/kytos/core/config/'
try:
options = json.loads(urllib.request.urlopen(uri).read())
except urllib.error.URLError:
print('Kytos is not running.')
sys.exit()
self.__enabled = Path(options.get('napps'))
self.__installed = Path(options.get('installed_napps')) | [
"def",
"__require_kytos_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"__enabled",
"is",
"None",
":",
"uri",
"=",
"self",
".",
"_kytos_api",
"+",
"'api/kytos/core/config/'",
"try",
":",
"options",
"=",
"json",
".",
"loads",
"(",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"uri",
")",
".",
"read",
"(",
")",
")",
"except",
"urllib",
".",
"error",
".",
"URLError",
":",
"print",
"(",
"'Kytos is not running.'",
")",
"sys",
".",
"exit",
"(",
")",
"self",
".",
"__enabled",
"=",
"Path",
"(",
"options",
".",
"get",
"(",
"'napps'",
")",
")",
"self",
".",
"__installed",
"=",
"Path",
"(",
"options",
".",
"get",
"(",
"'installed_napps'",
")",
")"
] | Set path locations from kytosd API.
It should not be called directly, but from properties that require a
running kytosd instance. | [
"Set",
"path",
"locations",
"from",
"kytosd",
"API",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L69-L83 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.set_napp | def set_napp(self, user, napp, version=None):
"""Set info about NApp.
Args:
user (str): NApps Server username.
napp (str): NApp name.
version (str): NApp version.
"""
self.user = user
self.napp = napp
self.version = version or 'latest' | python | def set_napp(self, user, napp, version=None):
"""Set info about NApp.
Args:
user (str): NApps Server username.
napp (str): NApp name.
version (str): NApp version.
"""
self.user = user
self.napp = napp
self.version = version or 'latest' | [
"def",
"set_napp",
"(",
"self",
",",
"user",
",",
"napp",
",",
"version",
"=",
"None",
")",
":",
"self",
".",
"user",
"=",
"user",
"self",
".",
"napp",
"=",
"napp",
"self",
".",
"version",
"=",
"version",
"or",
"'latest'"
] | Set info about NApp.
Args:
user (str): NApps Server username.
napp (str): NApp name.
version (str): NApp version. | [
"Set",
"info",
"about",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L85-L95 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.dependencies | def dependencies(self, user=None, napp=None):
"""Get napp_dependencies from install NApp.
Args:
user(string) A Username.
napp(string): A NApp name.
Returns:
napps(list): List with tuples with Username and NApp name.
e.g. [('kytos'/'of_core'), ('kytos/of_l2ls')]
"""
napps = self._get_napp_key('napp_dependencies', user, napp)
return [tuple(napp.split('/')) for napp in napps] | python | def dependencies(self, user=None, napp=None):
"""Get napp_dependencies from install NApp.
Args:
user(string) A Username.
napp(string): A NApp name.
Returns:
napps(list): List with tuples with Username and NApp name.
e.g. [('kytos'/'of_core'), ('kytos/of_l2ls')]
"""
napps = self._get_napp_key('napp_dependencies', user, napp)
return [tuple(napp.split('/')) for napp in napps] | [
"def",
"dependencies",
"(",
"self",
",",
"user",
"=",
"None",
",",
"napp",
"=",
"None",
")",
":",
"napps",
"=",
"self",
".",
"_get_napp_key",
"(",
"'napp_dependencies'",
",",
"user",
",",
"napp",
")",
"return",
"[",
"tuple",
"(",
"napp",
".",
"split",
"(",
"'/'",
")",
")",
"for",
"napp",
"in",
"napps",
"]"
] | Get napp_dependencies from install NApp.
Args:
user(string) A Username.
napp(string): A NApp name.
Returns:
napps(list): List with tuples with Username and NApp name.
e.g. [('kytos'/'of_core'), ('kytos/of_l2ls')] | [
"Get",
"napp_dependencies",
"from",
"install",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L129-L141 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager._get_napp_key | def _get_napp_key(self, key, user=None, napp=None):
"""Return a value from kytos.json.
Args:
user (string): A Username.
napp (string): A NApp name
key (string): Key used to get the value within kytos.json.
Returns:
meta (object): Value stored in kytos.json.
"""
if user is None:
user = self.user
if napp is None:
napp = self.napp
kytos_json = self._installed / user / napp / 'kytos.json'
try:
with kytos_json.open() as file_descriptor:
meta = json.load(file_descriptor)
return meta[key]
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return '' | python | def _get_napp_key(self, key, user=None, napp=None):
"""Return a value from kytos.json.
Args:
user (string): A Username.
napp (string): A NApp name
key (string): Key used to get the value within kytos.json.
Returns:
meta (object): Value stored in kytos.json.
"""
if user is None:
user = self.user
if napp is None:
napp = self.napp
kytos_json = self._installed / user / napp / 'kytos.json'
try:
with kytos_json.open() as file_descriptor:
meta = json.load(file_descriptor)
return meta[key]
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return '' | [
"def",
"_get_napp_key",
"(",
"self",
",",
"key",
",",
"user",
"=",
"None",
",",
"napp",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"self",
".",
"user",
"if",
"napp",
"is",
"None",
":",
"napp",
"=",
"self",
".",
"napp",
"kytos_json",
"=",
"self",
".",
"_installed",
"/",
"user",
"/",
"napp",
"/",
"'kytos.json'",
"try",
":",
"with",
"kytos_json",
".",
"open",
"(",
")",
"as",
"file_descriptor",
":",
"meta",
"=",
"json",
".",
"load",
"(",
"file_descriptor",
")",
"return",
"meta",
"[",
"key",
"]",
"except",
"(",
"FileNotFoundError",
",",
"json",
".",
"JSONDecodeError",
",",
"KeyError",
")",
":",
"return",
"''"
] | Return a value from kytos.json.
Args:
user (string): A Username.
napp (string): A NApp name
key (string): Key used to get the value within kytos.json.
Returns:
meta (object): Value stored in kytos.json. | [
"Return",
"a",
"value",
"from",
"kytos",
".",
"json",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L151-L173 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.disable | def disable(self):
"""Disable a NApp if it is enabled."""
core_napps_manager = CoreNAppsManager(base_path=self._enabled)
core_napps_manager.disable(self.user, self.napp) | python | def disable(self):
"""Disable a NApp if it is enabled."""
core_napps_manager = CoreNAppsManager(base_path=self._enabled)
core_napps_manager.disable(self.user, self.napp) | [
"def",
"disable",
"(",
"self",
")",
":",
"core_napps_manager",
"=",
"CoreNAppsManager",
"(",
"base_path",
"=",
"self",
".",
"_enabled",
")",
"core_napps_manager",
".",
"disable",
"(",
"self",
".",
"user",
",",
"self",
".",
"napp",
")"
] | Disable a NApp if it is enabled. | [
"Disable",
"a",
"NApp",
"if",
"it",
"is",
"enabled",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L175-L178 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.enable | def enable(self):
"""Enable a NApp if not already enabled.
Raises:
FileNotFoundError: If NApp is not installed.
PermissionError: No filesystem permission to enable NApp.
"""
core_napps_manager = CoreNAppsManager(base_path=self._enabled)
core_napps_manager.enable(self.user, self.napp) | python | def enable(self):
"""Enable a NApp if not already enabled.
Raises:
FileNotFoundError: If NApp is not installed.
PermissionError: No filesystem permission to enable NApp.
"""
core_napps_manager = CoreNAppsManager(base_path=self._enabled)
core_napps_manager.enable(self.user, self.napp) | [
"def",
"enable",
"(",
"self",
")",
":",
"core_napps_manager",
"=",
"CoreNAppsManager",
"(",
"base_path",
"=",
"self",
".",
"_enabled",
")",
"core_napps_manager",
".",
"enable",
"(",
"self",
".",
"user",
",",
"self",
".",
"napp",
")"
] | Enable a NApp if not already enabled.
Raises:
FileNotFoundError: If NApp is not installed.
PermissionError: No filesystem permission to enable NApp. | [
"Enable",
"a",
"NApp",
"if",
"not",
"already",
"enabled",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L188-L197 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.uninstall | def uninstall(self):
"""Delete code inside NApp directory, if existent."""
if self.is_installed():
installed = self.installed_dir()
if installed.is_symlink():
installed.unlink()
else:
shutil.rmtree(str(installed)) | python | def uninstall(self):
"""Delete code inside NApp directory, if existent."""
if self.is_installed():
installed = self.installed_dir()
if installed.is_symlink():
installed.unlink()
else:
shutil.rmtree(str(installed)) | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_installed",
"(",
")",
":",
"installed",
"=",
"self",
".",
"installed_dir",
"(",
")",
"if",
"installed",
".",
"is_symlink",
"(",
")",
":",
"installed",
".",
"unlink",
"(",
")",
"else",
":",
"shutil",
".",
"rmtree",
"(",
"str",
"(",
"installed",
")",
")"
] | Delete code inside NApp directory, if existent. | [
"Delete",
"code",
"inside",
"NApp",
"directory",
"if",
"existent",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L203-L210 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.render_template | def render_template(templates_path, template_filename, context):
"""Render Jinja2 template for a NApp structure."""
template_env = Environment(
autoescape=False, trim_blocks=False,
loader=FileSystemLoader(str(templates_path)))
return template_env.get_template(str(template_filename)) \
.render(context) | python | def render_template(templates_path, template_filename, context):
"""Render Jinja2 template for a NApp structure."""
template_env = Environment(
autoescape=False, trim_blocks=False,
loader=FileSystemLoader(str(templates_path)))
return template_env.get_template(str(template_filename)) \
.render(context) | [
"def",
"render_template",
"(",
"templates_path",
",",
"template_filename",
",",
"context",
")",
":",
"template_env",
"=",
"Environment",
"(",
"autoescape",
"=",
"False",
",",
"trim_blocks",
"=",
"False",
",",
"loader",
"=",
"FileSystemLoader",
"(",
"str",
"(",
"templates_path",
")",
")",
")",
"return",
"template_env",
".",
"get_template",
"(",
"str",
"(",
"template_filename",
")",
")",
".",
"render",
"(",
"context",
")"
] | Render Jinja2 template for a NApp structure. | [
"Render",
"Jinja2",
"template",
"for",
"a",
"NApp",
"structure",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L223-L229 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.search | def search(pattern):
"""Search all server NApps matching pattern.
Args:
pattern (str): Python regular expression.
"""
def match(napp):
"""Whether a NApp metadata matches the pattern."""
# WARNING: This will change for future versions, when 'author' will
# be removed.
username = napp.get('username', napp.get('author'))
strings = ['{}/{}'.format(username, napp.get('name')),
napp.get('description')] + napp.get('tags')
return any(pattern.match(string) for string in strings)
napps = NAppsClient().get_napps()
return [napp for napp in napps if match(napp)] | python | def search(pattern):
"""Search all server NApps matching pattern.
Args:
pattern (str): Python regular expression.
"""
def match(napp):
"""Whether a NApp metadata matches the pattern."""
# WARNING: This will change for future versions, when 'author' will
# be removed.
username = napp.get('username', napp.get('author'))
strings = ['{}/{}'.format(username, napp.get('name')),
napp.get('description')] + napp.get('tags')
return any(pattern.match(string) for string in strings)
napps = NAppsClient().get_napps()
return [napp for napp in napps if match(napp)] | [
"def",
"search",
"(",
"pattern",
")",
":",
"def",
"match",
"(",
"napp",
")",
":",
"\"\"\"Whether a NApp metadata matches the pattern.\"\"\"",
"# WARNING: This will change for future versions, when 'author' will",
"# be removed.",
"username",
"=",
"napp",
".",
"get",
"(",
"'username'",
",",
"napp",
".",
"get",
"(",
"'author'",
")",
")",
"strings",
"=",
"[",
"'{}/{}'",
".",
"format",
"(",
"username",
",",
"napp",
".",
"get",
"(",
"'name'",
")",
")",
",",
"napp",
".",
"get",
"(",
"'description'",
")",
"]",
"+",
"napp",
".",
"get",
"(",
"'tags'",
")",
"return",
"any",
"(",
"pattern",
".",
"match",
"(",
"string",
")",
"for",
"string",
"in",
"strings",
")",
"napps",
"=",
"NAppsClient",
"(",
")",
".",
"get_napps",
"(",
")",
"return",
"[",
"napp",
"for",
"napp",
"in",
"napps",
"if",
"match",
"(",
"napp",
")",
"]"
] | Search all server NApps matching pattern.
Args:
pattern (str): Python regular expression. | [
"Search",
"all",
"server",
"NApps",
"matching",
"pattern",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L232-L249 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.install_local | def install_local(self):
"""Make a symlink in install folder to a local NApp.
Raises:
FileNotFoundError: If NApp is not found.
"""
folder = self._get_local_folder()
installed = self.installed_dir()
self._check_module(installed.parent)
installed.symlink_to(folder.resolve()) | python | def install_local(self):
"""Make a symlink in install folder to a local NApp.
Raises:
FileNotFoundError: If NApp is not found.
"""
folder = self._get_local_folder()
installed = self.installed_dir()
self._check_module(installed.parent)
installed.symlink_to(folder.resolve()) | [
"def",
"install_local",
"(",
"self",
")",
":",
"folder",
"=",
"self",
".",
"_get_local_folder",
"(",
")",
"installed",
"=",
"self",
".",
"installed_dir",
"(",
")",
"self",
".",
"_check_module",
"(",
"installed",
".",
"parent",
")",
"installed",
".",
"symlink_to",
"(",
"folder",
".",
"resolve",
"(",
")",
")"
] | Make a symlink in install folder to a local NApp.
Raises:
FileNotFoundError: If NApp is not found. | [
"Make",
"a",
"symlink",
"in",
"install",
"folder",
"to",
"a",
"local",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L251-L261 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager._get_local_folder | def _get_local_folder(self, root=None):
"""Return local NApp root folder.
Search for kytos.json in _./_ folder and _./user/napp_.
Args:
root (pathlib.Path): Where to begin searching.
Return:
pathlib.Path: NApp root folder.
Raises:
FileNotFoundError: If there is no such local NApp.
"""
if root is None:
root = Path()
for folders in ['.'], [self.user, self.napp]:
kytos_json = root / Path(*folders) / 'kytos.json'
if kytos_json.exists():
with kytos_json.open() as file_descriptor:
meta = json.load(file_descriptor)
# WARNING: This will change in future versions, when
# 'author' will be removed.
username = meta.get('username', meta.get('author'))
if username == self.user and meta.get('name') == self.napp:
return kytos_json.parent
raise FileNotFoundError('kytos.json not found.') | python | def _get_local_folder(self, root=None):
"""Return local NApp root folder.
Search for kytos.json in _./_ folder and _./user/napp_.
Args:
root (pathlib.Path): Where to begin searching.
Return:
pathlib.Path: NApp root folder.
Raises:
FileNotFoundError: If there is no such local NApp.
"""
if root is None:
root = Path()
for folders in ['.'], [self.user, self.napp]:
kytos_json = root / Path(*folders) / 'kytos.json'
if kytos_json.exists():
with kytos_json.open() as file_descriptor:
meta = json.load(file_descriptor)
# WARNING: This will change in future versions, when
# 'author' will be removed.
username = meta.get('username', meta.get('author'))
if username == self.user and meta.get('name') == self.napp:
return kytos_json.parent
raise FileNotFoundError('kytos.json not found.') | [
"def",
"_get_local_folder",
"(",
"self",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"Path",
"(",
")",
"for",
"folders",
"in",
"[",
"'.'",
"]",
",",
"[",
"self",
".",
"user",
",",
"self",
".",
"napp",
"]",
":",
"kytos_json",
"=",
"root",
"/",
"Path",
"(",
"*",
"folders",
")",
"/",
"'kytos.json'",
"if",
"kytos_json",
".",
"exists",
"(",
")",
":",
"with",
"kytos_json",
".",
"open",
"(",
")",
"as",
"file_descriptor",
":",
"meta",
"=",
"json",
".",
"load",
"(",
"file_descriptor",
")",
"# WARNING: This will change in future versions, when",
"# 'author' will be removed.",
"username",
"=",
"meta",
".",
"get",
"(",
"'username'",
",",
"meta",
".",
"get",
"(",
"'author'",
")",
")",
"if",
"username",
"==",
"self",
".",
"user",
"and",
"meta",
".",
"get",
"(",
"'name'",
")",
"==",
"self",
".",
"napp",
":",
"return",
"kytos_json",
".",
"parent",
"raise",
"FileNotFoundError",
"(",
"'kytos.json not found.'",
")"
] | Return local NApp root folder.
Search for kytos.json in _./_ folder and _./user/napp_.
Args:
root (pathlib.Path): Where to begin searching.
Return:
pathlib.Path: NApp root folder.
Raises:
FileNotFoundError: If there is no such local NApp. | [
"Return",
"local",
"NApp",
"root",
"folder",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L263-L290 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.install_remote | def install_remote(self):
"""Download, extract and install NApp."""
package, pkg_folder = None, None
try:
package = self._download()
pkg_folder = self._extract(package)
napp_folder = self._get_local_folder(pkg_folder)
dst = self._installed / self.user / self.napp
self._check_module(dst.parent)
shutil.move(str(napp_folder), str(dst))
finally:
# Delete temporary files
if package:
Path(package).unlink()
if pkg_folder and pkg_folder.exists():
shutil.rmtree(str(pkg_folder)) | python | def install_remote(self):
"""Download, extract and install NApp."""
package, pkg_folder = None, None
try:
package = self._download()
pkg_folder = self._extract(package)
napp_folder = self._get_local_folder(pkg_folder)
dst = self._installed / self.user / self.napp
self._check_module(dst.parent)
shutil.move(str(napp_folder), str(dst))
finally:
# Delete temporary files
if package:
Path(package).unlink()
if pkg_folder and pkg_folder.exists():
shutil.rmtree(str(pkg_folder)) | [
"def",
"install_remote",
"(",
"self",
")",
":",
"package",
",",
"pkg_folder",
"=",
"None",
",",
"None",
"try",
":",
"package",
"=",
"self",
".",
"_download",
"(",
")",
"pkg_folder",
"=",
"self",
".",
"_extract",
"(",
"package",
")",
"napp_folder",
"=",
"self",
".",
"_get_local_folder",
"(",
"pkg_folder",
")",
"dst",
"=",
"self",
".",
"_installed",
"/",
"self",
".",
"user",
"/",
"self",
".",
"napp",
"self",
".",
"_check_module",
"(",
"dst",
".",
"parent",
")",
"shutil",
".",
"move",
"(",
"str",
"(",
"napp_folder",
")",
",",
"str",
"(",
"dst",
")",
")",
"finally",
":",
"# Delete temporary files",
"if",
"package",
":",
"Path",
"(",
"package",
")",
".",
"unlink",
"(",
")",
"if",
"pkg_folder",
"and",
"pkg_folder",
".",
"exists",
"(",
")",
":",
"shutil",
".",
"rmtree",
"(",
"str",
"(",
"pkg_folder",
")",
")"
] | Download, extract and install NApp. | [
"Download",
"extract",
"and",
"install",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L292-L307 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager._download | def _download(self):
"""Download NApp package from server.
Return:
str: Downloaded temp filename.
Raises:
urllib.error.HTTPError: If download is not successful.
"""
repo = self._config.get('napps', 'repo')
napp_id = '{}/{}-{}.napp'.format(self.user, self.napp, self.version)
uri = os.path.join(repo, napp_id)
return urllib.request.urlretrieve(uri)[0] | python | def _download(self):
"""Download NApp package from server.
Return:
str: Downloaded temp filename.
Raises:
urllib.error.HTTPError: If download is not successful.
"""
repo = self._config.get('napps', 'repo')
napp_id = '{}/{}-{}.napp'.format(self.user, self.napp, self.version)
uri = os.path.join(repo, napp_id)
return urllib.request.urlretrieve(uri)[0] | [
"def",
"_download",
"(",
"self",
")",
":",
"repo",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'napps'",
",",
"'repo'",
")",
"napp_id",
"=",
"'{}/{}-{}.napp'",
".",
"format",
"(",
"self",
".",
"user",
",",
"self",
".",
"napp",
",",
"self",
".",
"version",
")",
"uri",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repo",
",",
"napp_id",
")",
"return",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"uri",
")",
"[",
"0",
"]"
] | Download NApp package from server.
Return:
str: Downloaded temp filename.
Raises:
urllib.error.HTTPError: If download is not successful. | [
"Download",
"NApp",
"package",
"from",
"server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L309-L322 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager._extract | def _extract(filename):
"""Extract package to a temporary folder.
Return:
pathlib.Path: Temp dir with package contents.
"""
random_string = '{:0d}'.format(randint(0, 10**6))
tmp = '/tmp/kytos-napp-' + Path(filename).stem + '-' + random_string
os.mkdir(tmp)
with tarfile.open(filename, 'r:xz') as tar:
tar.extractall(tmp)
return Path(tmp) | python | def _extract(filename):
"""Extract package to a temporary folder.
Return:
pathlib.Path: Temp dir with package contents.
"""
random_string = '{:0d}'.format(randint(0, 10**6))
tmp = '/tmp/kytos-napp-' + Path(filename).stem + '-' + random_string
os.mkdir(tmp)
with tarfile.open(filename, 'r:xz') as tar:
tar.extractall(tmp)
return Path(tmp) | [
"def",
"_extract",
"(",
"filename",
")",
":",
"random_string",
"=",
"'{:0d}'",
".",
"format",
"(",
"randint",
"(",
"0",
",",
"10",
"**",
"6",
")",
")",
"tmp",
"=",
"'/tmp/kytos-napp-'",
"+",
"Path",
"(",
"filename",
")",
".",
"stem",
"+",
"'-'",
"+",
"random_string",
"os",
".",
"mkdir",
"(",
"tmp",
")",
"with",
"tarfile",
".",
"open",
"(",
"filename",
",",
"'r:xz'",
")",
"as",
"tar",
":",
"tar",
".",
"extractall",
"(",
"tmp",
")",
"return",
"Path",
"(",
"tmp",
")"
] | Extract package to a temporary folder.
Return:
pathlib.Path: Temp dir with package contents. | [
"Extract",
"package",
"to",
"a",
"temporary",
"folder",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L325-L337 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.create_napp | def create_napp(cls, meta_package=False):
"""Bootstrap a basic NApp structure for you to develop your NApp.
This will create, on the current folder, a clean structure of a NAPP,
filling some contents on this structure.
"""
templates_path = SKEL_PATH / 'napp-structure/username/napp'
ui_templates_path = os.path.join(templates_path, 'ui')
username = None
napp_name = None
print('--------------------------------------------------------------')
print('Welcome to the bootstrap process of your NApp.')
print('--------------------------------------------------------------')
print('In order to answer both the username and the napp name,')
print('You must follow this naming rules:')
print(' - name starts with a letter')
print(' - name contains only letters, numbers or underscores')
print(' - at least three characters')
print('--------------------------------------------------------------')
print('')
while not cls.valid_name(username):
username = input('Please, insert your NApps Server username: ')
while not cls.valid_name(napp_name):
napp_name = input('Please, insert your NApp name: ')
description = input('Please, insert a brief description for your'
'NApp [optional]: ')
if not description:
# pylint: disable=fixme
description = '# TODO: <<<< Insert your NApp description here >>>>'
# pylint: enable=fixme
context = {'username': username, 'napp': napp_name,
'description': description}
#: Creating the directory structure (username/napp_name)
os.makedirs(username, exist_ok=True)
#: Creating ``__init__.py`` files
with open(os.path.join(username, '__init__.py'), 'w') as init_file:
init_file.write(f'"""Napps for the user {username}.""""')
os.makedirs(os.path.join(username, napp_name))
#: Creating the other files based on the templates
templates = os.listdir(templates_path)
templates.remove('ui')
templates.remove('openapi.yml.template')
if meta_package:
templates.remove('main.py.template')
templates.remove('settings.py.template')
for tmp in templates:
fname = os.path.join(username, napp_name,
tmp.rsplit('.template')[0])
with open(fname, 'w') as file:
content = cls.render_template(templates_path, tmp, context)
file.write(content)
if not meta_package:
NAppsManager.create_ui_structure(username, napp_name,
ui_templates_path, context)
print()
print(f'Congratulations! Your NApp has been bootstrapped!\nNow you '
'can go to the directory {username}/{napp_name} and begin to '
'code your NApp.')
print('Have fun!') | python | def create_napp(cls, meta_package=False):
"""Bootstrap a basic NApp structure for you to develop your NApp.
This will create, on the current folder, a clean structure of a NAPP,
filling some contents on this structure.
"""
templates_path = SKEL_PATH / 'napp-structure/username/napp'
ui_templates_path = os.path.join(templates_path, 'ui')
username = None
napp_name = None
print('--------------------------------------------------------------')
print('Welcome to the bootstrap process of your NApp.')
print('--------------------------------------------------------------')
print('In order to answer both the username and the napp name,')
print('You must follow this naming rules:')
print(' - name starts with a letter')
print(' - name contains only letters, numbers or underscores')
print(' - at least three characters')
print('--------------------------------------------------------------')
print('')
while not cls.valid_name(username):
username = input('Please, insert your NApps Server username: ')
while not cls.valid_name(napp_name):
napp_name = input('Please, insert your NApp name: ')
description = input('Please, insert a brief description for your'
'NApp [optional]: ')
if not description:
# pylint: disable=fixme
description = '# TODO: <<<< Insert your NApp description here >>>>'
# pylint: enable=fixme
context = {'username': username, 'napp': napp_name,
'description': description}
#: Creating the directory structure (username/napp_name)
os.makedirs(username, exist_ok=True)
#: Creating ``__init__.py`` files
with open(os.path.join(username, '__init__.py'), 'w') as init_file:
init_file.write(f'"""Napps for the user {username}.""""')
os.makedirs(os.path.join(username, napp_name))
#: Creating the other files based on the templates
templates = os.listdir(templates_path)
templates.remove('ui')
templates.remove('openapi.yml.template')
if meta_package:
templates.remove('main.py.template')
templates.remove('settings.py.template')
for tmp in templates:
fname = os.path.join(username, napp_name,
tmp.rsplit('.template')[0])
with open(fname, 'w') as file:
content = cls.render_template(templates_path, tmp, context)
file.write(content)
if not meta_package:
NAppsManager.create_ui_structure(username, napp_name,
ui_templates_path, context)
print()
print(f'Congratulations! Your NApp has been bootstrapped!\nNow you '
'can go to the directory {username}/{napp_name} and begin to '
'code your NApp.')
print('Have fun!') | [
"def",
"create_napp",
"(",
"cls",
",",
"meta_package",
"=",
"False",
")",
":",
"templates_path",
"=",
"SKEL_PATH",
"/",
"'napp-structure/username/napp'",
"ui_templates_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"templates_path",
",",
"'ui'",
")",
"username",
"=",
"None",
"napp_name",
"=",
"None",
"print",
"(",
"'--------------------------------------------------------------'",
")",
"print",
"(",
"'Welcome to the bootstrap process of your NApp.'",
")",
"print",
"(",
"'--------------------------------------------------------------'",
")",
"print",
"(",
"'In order to answer both the username and the napp name,'",
")",
"print",
"(",
"'You must follow this naming rules:'",
")",
"print",
"(",
"' - name starts with a letter'",
")",
"print",
"(",
"' - name contains only letters, numbers or underscores'",
")",
"print",
"(",
"' - at least three characters'",
")",
"print",
"(",
"'--------------------------------------------------------------'",
")",
"print",
"(",
"''",
")",
"while",
"not",
"cls",
".",
"valid_name",
"(",
"username",
")",
":",
"username",
"=",
"input",
"(",
"'Please, insert your NApps Server username: '",
")",
"while",
"not",
"cls",
".",
"valid_name",
"(",
"napp_name",
")",
":",
"napp_name",
"=",
"input",
"(",
"'Please, insert your NApp name: '",
")",
"description",
"=",
"input",
"(",
"'Please, insert a brief description for your'",
"'NApp [optional]: '",
")",
"if",
"not",
"description",
":",
"# pylint: disable=fixme",
"description",
"=",
"'# TODO: <<<< Insert your NApp description here >>>>'",
"# pylint: enable=fixme",
"context",
"=",
"{",
"'username'",
":",
"username",
",",
"'napp'",
":",
"napp_name",
",",
"'description'",
":",
"description",
"}",
"#: Creating the directory structure (username/napp_name)",
"os",
".",
"makedirs",
"(",
"username",
",",
"exist_ok",
"=",
"True",
")",
"#: Creating ``__init__.py`` files",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"username",
",",
"'__init__.py'",
")",
",",
"'w'",
")",
"as",
"init_file",
":",
"init_file",
".",
"write",
"(",
"f'\"\"\"Napps for the user {username}.\"\"\"\"'",
")",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"username",
",",
"napp_name",
")",
")",
"#: Creating the other files based on the templates",
"templates",
"=",
"os",
".",
"listdir",
"(",
"templates_path",
")",
"templates",
".",
"remove",
"(",
"'ui'",
")",
"templates",
".",
"remove",
"(",
"'openapi.yml.template'",
")",
"if",
"meta_package",
":",
"templates",
".",
"remove",
"(",
"'main.py.template'",
")",
"templates",
".",
"remove",
"(",
"'settings.py.template'",
")",
"for",
"tmp",
"in",
"templates",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"username",
",",
"napp_name",
",",
"tmp",
".",
"rsplit",
"(",
"'.template'",
")",
"[",
"0",
"]",
")",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"file",
":",
"content",
"=",
"cls",
".",
"render_template",
"(",
"templates_path",
",",
"tmp",
",",
"context",
")",
"file",
".",
"write",
"(",
"content",
")",
"if",
"not",
"meta_package",
":",
"NAppsManager",
".",
"create_ui_structure",
"(",
"username",
",",
"napp_name",
",",
"ui_templates_path",
",",
"context",
")",
"print",
"(",
")",
"print",
"(",
"f'Congratulations! Your NApp has been bootstrapped!\\nNow you '",
"'can go to the directory {username}/{napp_name} and begin to '",
"'code your NApp.'",
")",
"print",
"(",
"'Have fun!'",
")"
] | Bootstrap a basic NApp structure for you to develop your NApp.
This will create, on the current folder, a clean structure of a NAPP,
filling some contents on this structure. | [
"Bootstrap",
"a",
"basic",
"NApp",
"structure",
"for",
"you",
"to",
"develop",
"your",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L340-L412 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.create_ui_structure | def create_ui_structure(cls, username, napp_name, ui_templates_path,
context):
"""Create the ui directory structure."""
for section in ['k-info-panel', 'k-toolbar', 'k-action-menu']:
os.makedirs(os.path.join(username, napp_name, 'ui', section))
templates = os.listdir(ui_templates_path)
for tmp in templates:
fname = os.path.join(username, napp_name, 'ui',
tmp.rsplit('.template')[0])
with open(fname, 'w') as file:
content = cls.render_template(ui_templates_path, tmp,
context)
file.write(content) | python | def create_ui_structure(cls, username, napp_name, ui_templates_path,
context):
"""Create the ui directory structure."""
for section in ['k-info-panel', 'k-toolbar', 'k-action-menu']:
os.makedirs(os.path.join(username, napp_name, 'ui', section))
templates = os.listdir(ui_templates_path)
for tmp in templates:
fname = os.path.join(username, napp_name, 'ui',
tmp.rsplit('.template')[0])
with open(fname, 'w') as file:
content = cls.render_template(ui_templates_path, tmp,
context)
file.write(content) | [
"def",
"create_ui_structure",
"(",
"cls",
",",
"username",
",",
"napp_name",
",",
"ui_templates_path",
",",
"context",
")",
":",
"for",
"section",
"in",
"[",
"'k-info-panel'",
",",
"'k-toolbar'",
",",
"'k-action-menu'",
"]",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"username",
",",
"napp_name",
",",
"'ui'",
",",
"section",
")",
")",
"templates",
"=",
"os",
".",
"listdir",
"(",
"ui_templates_path",
")",
"for",
"tmp",
"in",
"templates",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"username",
",",
"napp_name",
",",
"'ui'",
",",
"tmp",
".",
"rsplit",
"(",
"'.template'",
")",
"[",
"0",
"]",
")",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"file",
":",
"content",
"=",
"cls",
".",
"render_template",
"(",
"ui_templates_path",
",",
"tmp",
",",
"context",
")",
"file",
".",
"write",
"(",
"content",
")"
] | Create the ui directory structure. | [
"Create",
"the",
"ui",
"directory",
"structure",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L415-L430 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.build_napp_package | def build_napp_package(napp_name):
"""Build the .napp file to be sent to the napps server.
Args:
napp_identifier (str): Identifier formatted as
<username>/<napp_name>
Return:
file_payload (binary): The binary representation of the napp
package that will be POSTed to the napp server.
"""
ignored_extensions = ['.swp', '.pyc', '.napp']
ignored_dirs = ['__pycache__', '.git', '.tox']
files = os.listdir()
for filename in files:
if os.path.isfile(filename) and '.' in filename and \
filename.rsplit('.', 1)[1] in ignored_extensions:
files.remove(filename)
elif os.path.isdir(filename) and filename in ignored_dirs:
files.remove(filename)
# Create the '.napp' package
napp_file = tarfile.open(napp_name + '.napp', 'x:xz')
for local_f in files:
napp_file.add(local_f)
napp_file.close()
# Get the binary payload of the package
file_payload = open(napp_name + '.napp', 'rb')
# remove the created package from the filesystem
os.remove(napp_name + '.napp')
return file_payload | python | def build_napp_package(napp_name):
"""Build the .napp file to be sent to the napps server.
Args:
napp_identifier (str): Identifier formatted as
<username>/<napp_name>
Return:
file_payload (binary): The binary representation of the napp
package that will be POSTed to the napp server.
"""
ignored_extensions = ['.swp', '.pyc', '.napp']
ignored_dirs = ['__pycache__', '.git', '.tox']
files = os.listdir()
for filename in files:
if os.path.isfile(filename) and '.' in filename and \
filename.rsplit('.', 1)[1] in ignored_extensions:
files.remove(filename)
elif os.path.isdir(filename) and filename in ignored_dirs:
files.remove(filename)
# Create the '.napp' package
napp_file = tarfile.open(napp_name + '.napp', 'x:xz')
for local_f in files:
napp_file.add(local_f)
napp_file.close()
# Get the binary payload of the package
file_payload = open(napp_name + '.napp', 'rb')
# remove the created package from the filesystem
os.remove(napp_name + '.napp')
return file_payload | [
"def",
"build_napp_package",
"(",
"napp_name",
")",
":",
"ignored_extensions",
"=",
"[",
"'.swp'",
",",
"'.pyc'",
",",
"'.napp'",
"]",
"ignored_dirs",
"=",
"[",
"'__pycache__'",
",",
"'.git'",
",",
"'.tox'",
"]",
"files",
"=",
"os",
".",
"listdir",
"(",
")",
"for",
"filename",
"in",
"files",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
"and",
"'.'",
"in",
"filename",
"and",
"filename",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"1",
"]",
"in",
"ignored_extensions",
":",
"files",
".",
"remove",
"(",
"filename",
")",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"filename",
")",
"and",
"filename",
"in",
"ignored_dirs",
":",
"files",
".",
"remove",
"(",
"filename",
")",
"# Create the '.napp' package",
"napp_file",
"=",
"tarfile",
".",
"open",
"(",
"napp_name",
"+",
"'.napp'",
",",
"'x:xz'",
")",
"for",
"local_f",
"in",
"files",
":",
"napp_file",
".",
"add",
"(",
"local_f",
")",
"napp_file",
".",
"close",
"(",
")",
"# Get the binary payload of the package",
"file_payload",
"=",
"open",
"(",
"napp_name",
"+",
"'.napp'",
",",
"'rb'",
")",
"# remove the created package from the filesystem",
"os",
".",
"remove",
"(",
"napp_name",
"+",
"'.napp'",
")",
"return",
"file_payload"
] | Build the .napp file to be sent to the napps server.
Args:
napp_identifier (str): Identifier formatted as
<username>/<napp_name>
Return:
file_payload (binary): The binary representation of the napp
package that will be POSTed to the napp server. | [
"Build",
"the",
".",
"napp",
"file",
"to",
"be",
"sent",
"to",
"the",
"napps",
"server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L444-L478 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.create_metadata | def create_metadata(*args, **kwargs): # pylint: disable=unused-argument
"""Generate the metadata to send the napp package."""
json_filename = kwargs.get('json_filename', 'kytos.json')
readme_filename = kwargs.get('readme_filename', 'README.rst')
ignore_json = kwargs.get('ignore_json', False)
metadata = {}
if not ignore_json:
try:
with open(json_filename) as json_file:
metadata = json.load(json_file)
except FileNotFoundError:
print("ERROR: Could not access kytos.json file.")
sys.exit(1)
try:
with open(readme_filename) as readme_file:
metadata['readme'] = readme_file.read()
except FileNotFoundError:
metadata['readme'] = ''
try:
yaml = YAML(typ='safe')
openapi_dict = yaml.load(Path('openapi.yml').open())
openapi = json.dumps(openapi_dict)
except FileNotFoundError:
openapi = ''
metadata['OpenAPI_Spec'] = openapi
return metadata | python | def create_metadata(*args, **kwargs): # pylint: disable=unused-argument
"""Generate the metadata to send the napp package."""
json_filename = kwargs.get('json_filename', 'kytos.json')
readme_filename = kwargs.get('readme_filename', 'README.rst')
ignore_json = kwargs.get('ignore_json', False)
metadata = {}
if not ignore_json:
try:
with open(json_filename) as json_file:
metadata = json.load(json_file)
except FileNotFoundError:
print("ERROR: Could not access kytos.json file.")
sys.exit(1)
try:
with open(readme_filename) as readme_file:
metadata['readme'] = readme_file.read()
except FileNotFoundError:
metadata['readme'] = ''
try:
yaml = YAML(typ='safe')
openapi_dict = yaml.load(Path('openapi.yml').open())
openapi = json.dumps(openapi_dict)
except FileNotFoundError:
openapi = ''
metadata['OpenAPI_Spec'] = openapi
return metadata | [
"def",
"create_metadata",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"json_filename",
"=",
"kwargs",
".",
"get",
"(",
"'json_filename'",
",",
"'kytos.json'",
")",
"readme_filename",
"=",
"kwargs",
".",
"get",
"(",
"'readme_filename'",
",",
"'README.rst'",
")",
"ignore_json",
"=",
"kwargs",
".",
"get",
"(",
"'ignore_json'",
",",
"False",
")",
"metadata",
"=",
"{",
"}",
"if",
"not",
"ignore_json",
":",
"try",
":",
"with",
"open",
"(",
"json_filename",
")",
"as",
"json_file",
":",
"metadata",
"=",
"json",
".",
"load",
"(",
"json_file",
")",
"except",
"FileNotFoundError",
":",
"print",
"(",
"\"ERROR: Could not access kytos.json file.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"try",
":",
"with",
"open",
"(",
"readme_filename",
")",
"as",
"readme_file",
":",
"metadata",
"[",
"'readme'",
"]",
"=",
"readme_file",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"metadata",
"[",
"'readme'",
"]",
"=",
"''",
"try",
":",
"yaml",
"=",
"YAML",
"(",
"typ",
"=",
"'safe'",
")",
"openapi_dict",
"=",
"yaml",
".",
"load",
"(",
"Path",
"(",
"'openapi.yml'",
")",
".",
"open",
"(",
")",
")",
"openapi",
"=",
"json",
".",
"dumps",
"(",
"openapi_dict",
")",
"except",
"FileNotFoundError",
":",
"openapi",
"=",
"''",
"metadata",
"[",
"'OpenAPI_Spec'",
"]",
"=",
"openapi",
"return",
"metadata"
] | Generate the metadata to send the napp package. | [
"Generate",
"the",
"metadata",
"to",
"send",
"the",
"napp",
"package",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L481-L510 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.upload | def upload(self, *args, **kwargs):
"""Create package and upload it to NApps Server.
Raises:
FileNotFoundError: If kytos.json is not found.
"""
self.prepare()
metadata = self.create_metadata(*args, **kwargs)
package = self.build_napp_package(metadata.get('name'))
NAppsClient().upload_napp(metadata, package) | python | def upload(self, *args, **kwargs):
"""Create package and upload it to NApps Server.
Raises:
FileNotFoundError: If kytos.json is not found.
"""
self.prepare()
metadata = self.create_metadata(*args, **kwargs)
package = self.build_napp_package(metadata.get('name'))
NAppsClient().upload_napp(metadata, package) | [
"def",
"upload",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"prepare",
"(",
")",
"metadata",
"=",
"self",
".",
"create_metadata",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"package",
"=",
"self",
".",
"build_napp_package",
"(",
"metadata",
".",
"get",
"(",
"'name'",
")",
")",
"NAppsClient",
"(",
")",
".",
"upload_napp",
"(",
"metadata",
",",
"package",
")"
] | Create package and upload it to NApps Server.
Raises:
FileNotFoundError: If kytos.json is not found. | [
"Create",
"package",
"and",
"upload",
"it",
"to",
"NApps",
"Server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L512-L523 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.prepare | def prepare(cls):
"""Prepare NApp to be uploaded by creating openAPI skeleton."""
if cls._ask_openapi():
napp_path = Path()
tpl_path = SKEL_PATH / 'napp-structure/username/napp'
OpenAPI(napp_path, tpl_path).render_template()
print('Please, update your openapi.yml file.')
sys.exit() | python | def prepare(cls):
"""Prepare NApp to be uploaded by creating openAPI skeleton."""
if cls._ask_openapi():
napp_path = Path()
tpl_path = SKEL_PATH / 'napp-structure/username/napp'
OpenAPI(napp_path, tpl_path).render_template()
print('Please, update your openapi.yml file.')
sys.exit() | [
"def",
"prepare",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_ask_openapi",
"(",
")",
":",
"napp_path",
"=",
"Path",
"(",
")",
"tpl_path",
"=",
"SKEL_PATH",
"/",
"'napp-structure/username/napp'",
"OpenAPI",
"(",
"napp_path",
",",
"tpl_path",
")",
".",
"render_template",
"(",
")",
"print",
"(",
"'Please, update your openapi.yml file.'",
")",
"sys",
".",
"exit",
"(",
")"
] | Prepare NApp to be uploaded by creating openAPI skeleton. | [
"Prepare",
"NApp",
"to",
"be",
"uploaded",
"by",
"creating",
"openAPI",
"skeleton",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L536-L543 | train |
kytos/kytos-utils | kytos/utils/napps.py | NAppsManager.reload | def reload(self, napps=None):
"""Reload a NApp or all NApps.
Args:
napps (list): NApp list to be reloaded.
Raises:
requests.HTTPError: When there's a server error.
"""
client = NAppsClient(self._config)
client.reload_napps(napps) | python | def reload(self, napps=None):
"""Reload a NApp or all NApps.
Args:
napps (list): NApp list to be reloaded.
Raises:
requests.HTTPError: When there's a server error.
"""
client = NAppsClient(self._config)
client.reload_napps(napps) | [
"def",
"reload",
"(",
"self",
",",
"napps",
"=",
"None",
")",
":",
"client",
"=",
"NAppsClient",
"(",
"self",
".",
"_config",
")",
"client",
".",
"reload_napps",
"(",
"napps",
")"
] | Reload a NApp or all NApps.
Args:
napps (list): NApp list to be reloaded.
Raises:
requests.HTTPError: When there's a server error. | [
"Reload",
"a",
"NApp",
"or",
"all",
"NApps",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L565-L575 | train |
manikos/django-progressiveimagefield | progressiveimagefield/templatetags/progressive_tags.py | _get_thumbnail_url | def _get_thumbnail_url(image):
""" Given a large image, return the thumbnail url """
lhs, rhs = splitext(image.url)
lhs += THUMB_EXT
thumb_url = f'{lhs}{rhs}'
return thumb_url | python | def _get_thumbnail_url(image):
""" Given a large image, return the thumbnail url """
lhs, rhs = splitext(image.url)
lhs += THUMB_EXT
thumb_url = f'{lhs}{rhs}'
return thumb_url | [
"def",
"_get_thumbnail_url",
"(",
"image",
")",
":",
"lhs",
",",
"rhs",
"=",
"splitext",
"(",
"image",
".",
"url",
")",
"lhs",
"+=",
"THUMB_EXT",
"thumb_url",
"=",
"f'{lhs}{rhs}'",
"return",
"thumb_url"
] | Given a large image, return the thumbnail url | [
"Given",
"a",
"large",
"image",
"return",
"the",
"thumbnail",
"url"
] | a432c79d23d87ea8944ac252ae7d15df1e4f3072 | https://github.com/manikos/django-progressiveimagefield/blob/a432c79d23d87ea8944ac252ae7d15df1e4f3072/progressiveimagefield/templatetags/progressive_tags.py#L24-L29 | train |
KE-works/pykechain | pykechain/client.py | Client.from_env | def from_env(cls, env_filename=None):
# type: (Optional[str]) -> Client
"""Create a client from environment variable settings.
:param basestring env_filename: filename of the environment file, defaults to '.env' in the local dir
(or parent dir)
:return: :class:`pykechain.Client`
Example
-------
Initiates the pykechain client from the contents of an environment file. Authentication information is optional
but ensure that you provide this later in your code. Offered are both username/password authentication and
user token authentication.
.. code-block:: none
:caption: .env
:name: dot-env
# User token here (required)
KECHAIN_TOKEN=...<secret user token>...
KECHAIN_URL=https://an_url.ke-chain.com
# or use Basic Auth with username/password
KECHAIN_USERNAME=...
KECHAIN_PASSWORD=...
# optional add a scope name or scope id
KECHAIN_SCOPE=...
KECHAIN_SCOPE_ID=...
>>> client = Client().from_env()
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
env.read_envfile(env_filename)
client = cls(url=env(KechainEnv.KECHAIN_URL))
if env(KechainEnv.KECHAIN_TOKEN, None):
client.login(token=env(KechainEnv.KECHAIN_TOKEN))
elif env(KechainEnv.KECHAIN_USERNAME, None) and env(KechainEnv.KECHAIN_PASSWORD, None):
client.login(username=env(KechainEnv.KECHAIN_USERNAME), password=env(KechainEnv.KECHAIN_PASSWORD))
return client | python | def from_env(cls, env_filename=None):
# type: (Optional[str]) -> Client
"""Create a client from environment variable settings.
:param basestring env_filename: filename of the environment file, defaults to '.env' in the local dir
(or parent dir)
:return: :class:`pykechain.Client`
Example
-------
Initiates the pykechain client from the contents of an environment file. Authentication information is optional
but ensure that you provide this later in your code. Offered are both username/password authentication and
user token authentication.
.. code-block:: none
:caption: .env
:name: dot-env
# User token here (required)
KECHAIN_TOKEN=...<secret user token>...
KECHAIN_URL=https://an_url.ke-chain.com
# or use Basic Auth with username/password
KECHAIN_USERNAME=...
KECHAIN_PASSWORD=...
# optional add a scope name or scope id
KECHAIN_SCOPE=...
KECHAIN_SCOPE_ID=...
>>> client = Client().from_env()
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
env.read_envfile(env_filename)
client = cls(url=env(KechainEnv.KECHAIN_URL))
if env(KechainEnv.KECHAIN_TOKEN, None):
client.login(token=env(KechainEnv.KECHAIN_TOKEN))
elif env(KechainEnv.KECHAIN_USERNAME, None) and env(KechainEnv.KECHAIN_PASSWORD, None):
client.login(username=env(KechainEnv.KECHAIN_USERNAME), password=env(KechainEnv.KECHAIN_PASSWORD))
return client | [
"def",
"from_env",
"(",
"cls",
",",
"env_filename",
"=",
"None",
")",
":",
"# type: (Optional[str]) -> Client",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
",",
"UserWarning",
")",
"env",
".",
"read_envfile",
"(",
"env_filename",
")",
"client",
"=",
"cls",
"(",
"url",
"=",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_URL",
")",
")",
"if",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_TOKEN",
",",
"None",
")",
":",
"client",
".",
"login",
"(",
"token",
"=",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_TOKEN",
")",
")",
"elif",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_USERNAME",
",",
"None",
")",
"and",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_PASSWORD",
",",
"None",
")",
":",
"client",
".",
"login",
"(",
"username",
"=",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_USERNAME",
")",
",",
"password",
"=",
"env",
"(",
"KechainEnv",
".",
"KECHAIN_PASSWORD",
")",
")",
"return",
"client"
] | Create a client from environment variable settings.
:param basestring env_filename: filename of the environment file, defaults to '.env' in the local dir
(or parent dir)
:return: :class:`pykechain.Client`
Example
-------
Initiates the pykechain client from the contents of an environment file. Authentication information is optional
but ensure that you provide this later in your code. Offered are both username/password authentication and
user token authentication.
.. code-block:: none
:caption: .env
:name: dot-env
# User token here (required)
KECHAIN_TOKEN=...<secret user token>...
KECHAIN_URL=https://an_url.ke-chain.com
# or use Basic Auth with username/password
KECHAIN_USERNAME=...
KECHAIN_PASSWORD=...
# optional add a scope name or scope id
KECHAIN_SCOPE=...
KECHAIN_SCOPE_ID=...
>>> client = Client().from_env() | [
"Create",
"a",
"client",
"from",
"environment",
"variable",
"settings",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L107-L151 | train |
KE-works/pykechain | pykechain/client.py | Client._build_url | def _build_url(self, resource, **kwargs):
# type: (str, **str) -> str
"""Build the correct API url."""
return urljoin(self.api_root, API_PATH[resource].format(**kwargs)) | python | def _build_url(self, resource, **kwargs):
# type: (str, **str) -> str
"""Build the correct API url."""
return urljoin(self.api_root, API_PATH[resource].format(**kwargs)) | [
"def",
"_build_url",
"(",
"self",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, **str) -> str",
"return",
"urljoin",
"(",
"self",
".",
"api_root",
",",
"API_PATH",
"[",
"resource",
"]",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")"
] | Build the correct API url. | [
"Build",
"the",
"correct",
"API",
"url",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L184-L187 | train |
KE-works/pykechain | pykechain/client.py | Client._retrieve_users | def _retrieve_users(self):
"""
Retrieve user objects of the entire administration.
:return: list of dictionary with users information
:rtype: list(dict)
-------
"""
users_url = self._build_url('users')
response = self._request('GET', users_url)
users = response.json()
return users | python | def _retrieve_users(self):
"""
Retrieve user objects of the entire administration.
:return: list of dictionary with users information
:rtype: list(dict)
-------
"""
users_url = self._build_url('users')
response = self._request('GET', users_url)
users = response.json()
return users | [
"def",
"_retrieve_users",
"(",
"self",
")",
":",
"users_url",
"=",
"self",
".",
"_build_url",
"(",
"'users'",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"users_url",
")",
"users",
"=",
"response",
".",
"json",
"(",
")",
"return",
"users"
] | Retrieve user objects of the entire administration.
:return: list of dictionary with users information
:rtype: list(dict)
------- | [
"Retrieve",
"user",
"objects",
"of",
"the",
"entire",
"administration",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L189-L201 | train |
KE-works/pykechain | pykechain/client.py | Client._request | def _request(self, method, url, **kwargs):
# type: (str, str, **Any) -> requests.Response
"""Perform the request on the API."""
self.last_request = None
self.last_response = self.session.request(method, url, auth=self.auth, headers=self.headers, **kwargs)
self.last_request = self.last_response.request
self.last_url = self.last_response.url
if self.last_response.status_code == requests.codes.forbidden:
raise ForbiddenError(self.last_response.json()['results'][0]['detail'])
return self.last_response | python | def _request(self, method, url, **kwargs):
# type: (str, str, **Any) -> requests.Response
"""Perform the request on the API."""
self.last_request = None
self.last_response = self.session.request(method, url, auth=self.auth, headers=self.headers, **kwargs)
self.last_request = self.last_response.request
self.last_url = self.last_response.url
if self.last_response.status_code == requests.codes.forbidden:
raise ForbiddenError(self.last_response.json()['results'][0]['detail'])
return self.last_response | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, str, **Any) -> requests.Response",
"self",
".",
"last_request",
"=",
"None",
"self",
".",
"last_response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"auth",
"=",
"self",
".",
"auth",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"last_request",
"=",
"self",
".",
"last_response",
".",
"request",
"self",
".",
"last_url",
"=",
"self",
".",
"last_response",
".",
"url",
"if",
"self",
".",
"last_response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"forbidden",
":",
"raise",
"ForbiddenError",
"(",
"self",
".",
"last_response",
".",
"json",
"(",
")",
"[",
"'results'",
"]",
"[",
"0",
"]",
"[",
"'detail'",
"]",
")",
"return",
"self",
".",
"last_response"
] | Perform the request on the API. | [
"Perform",
"the",
"request",
"on",
"the",
"API",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L203-L214 | train |
KE-works/pykechain | pykechain/client.py | Client.app_versions | def app_versions(self):
"""List of the versions of the internal KE-chain 'app' modules."""
if not self._app_versions:
app_versions_url = self._build_url('versions')
response = self._request('GET', app_versions_url)
if response.status_code == requests.codes.not_found:
self._app_versions = []
elif response.status_code == requests.codes.forbidden:
raise ForbiddenError(response.json()['results'][0]['detail'])
elif response.status_code != requests.codes.ok:
raise APIError("Could not retrieve app versions: {}".format(response))
else:
self._app_versions = response.json().get('results')
return self._app_versions | python | def app_versions(self):
"""List of the versions of the internal KE-chain 'app' modules."""
if not self._app_versions:
app_versions_url = self._build_url('versions')
response = self._request('GET', app_versions_url)
if response.status_code == requests.codes.not_found:
self._app_versions = []
elif response.status_code == requests.codes.forbidden:
raise ForbiddenError(response.json()['results'][0]['detail'])
elif response.status_code != requests.codes.ok:
raise APIError("Could not retrieve app versions: {}".format(response))
else:
self._app_versions = response.json().get('results')
return self._app_versions | [
"def",
"app_versions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_app_versions",
":",
"app_versions_url",
"=",
"self",
".",
"_build_url",
"(",
"'versions'",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"app_versions_url",
")",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"not_found",
":",
"self",
".",
"_app_versions",
"=",
"[",
"]",
"elif",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"forbidden",
":",
"raise",
"ForbiddenError",
"(",
"response",
".",
"json",
"(",
")",
"[",
"'results'",
"]",
"[",
"0",
"]",
"[",
"'detail'",
"]",
")",
"elif",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"raise",
"APIError",
"(",
"\"Could not retrieve app versions: {}\"",
".",
"format",
"(",
"response",
")",
")",
"else",
":",
"self",
".",
"_app_versions",
"=",
"response",
".",
"json",
"(",
")",
".",
"get",
"(",
"'results'",
")",
"return",
"self",
".",
"_app_versions"
] | List of the versions of the internal KE-chain 'app' modules. | [
"List",
"of",
"the",
"versions",
"of",
"the",
"internal",
"KE",
"-",
"chain",
"app",
"modules",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L217-L233 | train |
KE-works/pykechain | pykechain/client.py | Client.match_app_version | def match_app_version(self, app=None, label=None, version=None, default=False):
"""Match app version against a semantic version string.
Checks if a KE-chain app matches a version comparison. Uses the `semver` matcher to check.
`match("2.0.0", ">=1.0.0")` => `True`
`match("1.0.0", ">1.0.0")` => `False`
Examples
--------
>>> client.match_app_version(label='wim', version=">=1.99")
>>> True
>>> client.match_app_version(app='kechain2.core.pim', version=">=1.0.0")
>>> True
:param app: (optional) appname eg. 'kechain.core.wim'
:type app: basestring or None
:param label: (optional) app label (last part of the app name) eb 'wim'
:type label: basestring or None
:param version: semantic version string to match appname version against eg '2.0.0' or '>=2.0.0'
:type version: basestring
:param default: (optional) boolean to return if the version of the app is not set but the app found.
Set to None to return a NotFoundError when a version if not found in the app.
:type default: bool or None
:return: True if the version of the app matches against the match_version, otherwise False
:raises IllegalArgumentError: if no app nor a label is provided
:raises NotFoundError: if the app is not found
:raises ValueError: if the version provided is not parseable by semver,
should contain (<operand><major>.<minor>.<patch) where <operand> is '>,<,>=,<=,=='
"""
if not app or not label and not (app and label):
target_app = [a for a in self.app_versions if a.get('app') == app or a.get('label') == label]
if not target_app and not isinstance(default, bool):
raise NotFoundError("Could not find the app or label provided")
elif not target_app and isinstance(default, bool):
return default
else:
raise IllegalArgumentError("Please provide either app or label")
if not version:
raise IllegalArgumentError("Please provide semantic version string including operand eg: `>=1.0.0`")
app_version = target_app[0].get('version')
if target_app and app_version and version:
import semver
return semver.match(app_version, version)
elif not app_version:
if isinstance(default, bool):
return default
else:
raise NotFoundError("No version found on the app '{}'".format(target_app[0].get('app'))) | python | def match_app_version(self, app=None, label=None, version=None, default=False):
"""Match app version against a semantic version string.
Checks if a KE-chain app matches a version comparison. Uses the `semver` matcher to check.
`match("2.0.0", ">=1.0.0")` => `True`
`match("1.0.0", ">1.0.0")` => `False`
Examples
--------
>>> client.match_app_version(label='wim', version=">=1.99")
>>> True
>>> client.match_app_version(app='kechain2.core.pim', version=">=1.0.0")
>>> True
:param app: (optional) appname eg. 'kechain.core.wim'
:type app: basestring or None
:param label: (optional) app label (last part of the app name) eb 'wim'
:type label: basestring or None
:param version: semantic version string to match appname version against eg '2.0.0' or '>=2.0.0'
:type version: basestring
:param default: (optional) boolean to return if the version of the app is not set but the app found.
Set to None to return a NotFoundError when a version if not found in the app.
:type default: bool or None
:return: True if the version of the app matches against the match_version, otherwise False
:raises IllegalArgumentError: if no app nor a label is provided
:raises NotFoundError: if the app is not found
:raises ValueError: if the version provided is not parseable by semver,
should contain (<operand><major>.<minor>.<patch) where <operand> is '>,<,>=,<=,=='
"""
if not app or not label and not (app and label):
target_app = [a for a in self.app_versions if a.get('app') == app or a.get('label') == label]
if not target_app and not isinstance(default, bool):
raise NotFoundError("Could not find the app or label provided")
elif not target_app and isinstance(default, bool):
return default
else:
raise IllegalArgumentError("Please provide either app or label")
if not version:
raise IllegalArgumentError("Please provide semantic version string including operand eg: `>=1.0.0`")
app_version = target_app[0].get('version')
if target_app and app_version and version:
import semver
return semver.match(app_version, version)
elif not app_version:
if isinstance(default, bool):
return default
else:
raise NotFoundError("No version found on the app '{}'".format(target_app[0].get('app'))) | [
"def",
"match_app_version",
"(",
"self",
",",
"app",
"=",
"None",
",",
"label",
"=",
"None",
",",
"version",
"=",
"None",
",",
"default",
"=",
"False",
")",
":",
"if",
"not",
"app",
"or",
"not",
"label",
"and",
"not",
"(",
"app",
"and",
"label",
")",
":",
"target_app",
"=",
"[",
"a",
"for",
"a",
"in",
"self",
".",
"app_versions",
"if",
"a",
".",
"get",
"(",
"'app'",
")",
"==",
"app",
"or",
"a",
".",
"get",
"(",
"'label'",
")",
"==",
"label",
"]",
"if",
"not",
"target_app",
"and",
"not",
"isinstance",
"(",
"default",
",",
"bool",
")",
":",
"raise",
"NotFoundError",
"(",
"\"Could not find the app or label provided\"",
")",
"elif",
"not",
"target_app",
"and",
"isinstance",
"(",
"default",
",",
"bool",
")",
":",
"return",
"default",
"else",
":",
"raise",
"IllegalArgumentError",
"(",
"\"Please provide either app or label\"",
")",
"if",
"not",
"version",
":",
"raise",
"IllegalArgumentError",
"(",
"\"Please provide semantic version string including operand eg: `>=1.0.0`\"",
")",
"app_version",
"=",
"target_app",
"[",
"0",
"]",
".",
"get",
"(",
"'version'",
")",
"if",
"target_app",
"and",
"app_version",
"and",
"version",
":",
"import",
"semver",
"return",
"semver",
".",
"match",
"(",
"app_version",
",",
"version",
")",
"elif",
"not",
"app_version",
":",
"if",
"isinstance",
"(",
"default",
",",
"bool",
")",
":",
"return",
"default",
"else",
":",
"raise",
"NotFoundError",
"(",
"\"No version found on the app '{}'\"",
".",
"format",
"(",
"target_app",
"[",
"0",
"]",
".",
"get",
"(",
"'app'",
")",
")",
")"
] | Match app version against a semantic version string.
Checks if a KE-chain app matches a version comparison. Uses the `semver` matcher to check.
`match("2.0.0", ">=1.0.0")` => `True`
`match("1.0.0", ">1.0.0")` => `False`
Examples
--------
>>> client.match_app_version(label='wim', version=">=1.99")
>>> True
>>> client.match_app_version(app='kechain2.core.pim', version=">=1.0.0")
>>> True
:param app: (optional) appname eg. 'kechain.core.wim'
:type app: basestring or None
:param label: (optional) app label (last part of the app name) eb 'wim'
:type label: basestring or None
:param version: semantic version string to match appname version against eg '2.0.0' or '>=2.0.0'
:type version: basestring
:param default: (optional) boolean to return if the version of the app is not set but the app found.
Set to None to return a NotFoundError when a version if not found in the app.
:type default: bool or None
:return: True if the version of the app matches against the match_version, otherwise False
:raises IllegalArgumentError: if no app nor a label is provided
:raises NotFoundError: if the app is not found
:raises ValueError: if the version provided is not parseable by semver,
should contain (<operand><major>.<minor>.<patch) where <operand> is '>,<,>=,<=,==' | [
"Match",
"app",
"version",
"against",
"a",
"semantic",
"version",
"string",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L235-L288 | train |
KE-works/pykechain | pykechain/client.py | Client.reload | def reload(self, obj, extra_params=None):
"""Reload an object from server. This method is immutable and will return a new object.
:param obj: object to reload
:type obj: :py:obj:`obj`
:param extra_params: additional object specific extra query string params (eg for activity)
:type extra_params: dict
:return: a new object
:raises NotFoundError: if original object is not found or deleted in the mean time
"""
if not obj._json_data.get('url'): # pragma: no cover
raise NotFoundError("Could not reload object, there is no url for object '{}' configured".format(obj))
response = self._request('GET', obj._json_data.get('url'), params=extra_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not reload object ({})".format(response))
data = response.json()
return obj.__class__(data['results'][0], client=self) | python | def reload(self, obj, extra_params=None):
"""Reload an object from server. This method is immutable and will return a new object.
:param obj: object to reload
:type obj: :py:obj:`obj`
:param extra_params: additional object specific extra query string params (eg for activity)
:type extra_params: dict
:return: a new object
:raises NotFoundError: if original object is not found or deleted in the mean time
"""
if not obj._json_data.get('url'): # pragma: no cover
raise NotFoundError("Could not reload object, there is no url for object '{}' configured".format(obj))
response = self._request('GET', obj._json_data.get('url'), params=extra_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not reload object ({})".format(response))
data = response.json()
return obj.__class__(data['results'][0], client=self) | [
"def",
"reload",
"(",
"self",
",",
"obj",
",",
"extra_params",
"=",
"None",
")",
":",
"if",
"not",
"obj",
".",
"_json_data",
".",
"get",
"(",
"'url'",
")",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not reload object, there is no url for object '{}' configured\"",
".",
"format",
"(",
"obj",
")",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"obj",
".",
"_json_data",
".",
"get",
"(",
"'url'",
")",
",",
"params",
"=",
"extra_params",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not reload object ({})\"",
".",
"format",
"(",
"response",
")",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"obj",
".",
"__class__",
"(",
"data",
"[",
"'results'",
"]",
"[",
"0",
"]",
",",
"client",
"=",
"self",
")"
] | Reload an object from server. This method is immutable and will return a new object.
:param obj: object to reload
:type obj: :py:obj:`obj`
:param extra_params: additional object specific extra query string params (eg for activity)
:type extra_params: dict
:return: a new object
:raises NotFoundError: if original object is not found or deleted in the mean time | [
"Reload",
"an",
"object",
"from",
"server",
".",
"This",
"method",
"is",
"immutable",
"and",
"will",
"return",
"a",
"new",
"object",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L290-L310 | train |
KE-works/pykechain | pykechain/client.py | Client.scope | def scope(self, *args, **kwargs):
# type: (*Any, **Any) -> Scope
"""Return a single scope based on the provided name.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Scope`
:raises NotFoundError: When no `Scope` is found
:raises MultipleFoundError: When more than a single `Scope` is found
"""
_scopes = self.scopes(*args, **kwargs)
if len(_scopes) == 0:
raise NotFoundError("No scope fits criteria")
if len(_scopes) != 1:
raise MultipleFoundError("Multiple scopes fit criteria")
return _scopes[0] | python | def scope(self, *args, **kwargs):
# type: (*Any, **Any) -> Scope
"""Return a single scope based on the provided name.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Scope`
:raises NotFoundError: When no `Scope` is found
:raises MultipleFoundError: When more than a single `Scope` is found
"""
_scopes = self.scopes(*args, **kwargs)
if len(_scopes) == 0:
raise NotFoundError("No scope fits criteria")
if len(_scopes) != 1:
raise MultipleFoundError("Multiple scopes fit criteria")
return _scopes[0] | [
"def",
"scope",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Scope",
"_scopes",
"=",
"self",
".",
"scopes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_scopes",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No scope fits criteria\"",
")",
"if",
"len",
"(",
"_scopes",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple scopes fit criteria\"",
")",
"return",
"_scopes",
"[",
"0",
"]"
] | Return a single scope based on the provided name.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Scope`
:raises NotFoundError: When no `Scope` is found
:raises MultipleFoundError: When more than a single `Scope` is found | [
"Return",
"a",
"single",
"scope",
"based",
"on",
"the",
"provided",
"name",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L362-L380 | train |
KE-works/pykechain | pykechain/client.py | Client.activities | def activities(self, name=None, pk=None, scope=None, **kwargs):
# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity]
"""Search for activities with optional name, pk and scope filter.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param pk: id (primary key) of the activity to retrieve
:type pk: basestring or None
:param name: filter the activities by name
:type name: basestring or None
:param scope: filter by scope id
:type scope: basestring or None
:return: list of :class:`models.Activity`
:raises NotFoundError: If no `Activities` are found
"""
request_params = {
'id': pk,
'name': name,
'scope': scope
}
# update the fields query params
# for 'kechain.core.wim >= 2.0.0' add additional API params
if self.match_app_version(label='wim', version='>=2.0.0', default=False):
request_params.update(API_EXTRA_PARAMS['activity'])
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('activities'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve activities. Server responded with {}".format(str(response)))
data = response.json()
# for 'kechain.core.wim >= 2.0.0' we return Activity2, otherwise Activity1
if self.match_app_version(label='wim', version='<2.0.0', default=True):
# WIM1
return [Activity(a, client=self) for a in data['results']]
else:
# WIM2
return [Activity2(a, client=self) for a in data['results']] | python | def activities(self, name=None, pk=None, scope=None, **kwargs):
# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity]
"""Search for activities with optional name, pk and scope filter.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param pk: id (primary key) of the activity to retrieve
:type pk: basestring or None
:param name: filter the activities by name
:type name: basestring or None
:param scope: filter by scope id
:type scope: basestring or None
:return: list of :class:`models.Activity`
:raises NotFoundError: If no `Activities` are found
"""
request_params = {
'id': pk,
'name': name,
'scope': scope
}
# update the fields query params
# for 'kechain.core.wim >= 2.0.0' add additional API params
if self.match_app_version(label='wim', version='>=2.0.0', default=False):
request_params.update(API_EXTRA_PARAMS['activity'])
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('activities'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve activities. Server responded with {}".format(str(response)))
data = response.json()
# for 'kechain.core.wim >= 2.0.0' we return Activity2, otherwise Activity1
if self.match_app_version(label='wim', version='<2.0.0', default=True):
# WIM1
return [Activity(a, client=self) for a in data['results']]
else:
# WIM2
return [Activity2(a, client=self) for a in data['results']] | [
"def",
"activities",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity]",
"request_params",
"=",
"{",
"'id'",
":",
"pk",
",",
"'name'",
":",
"name",
",",
"'scope'",
":",
"scope",
"}",
"# update the fields query params",
"# for 'kechain.core.wim >= 2.0.0' add additional API params",
"if",
"self",
".",
"match_app_version",
"(",
"label",
"=",
"'wim'",
",",
"version",
"=",
"'>=2.0.0'",
",",
"default",
"=",
"False",
")",
":",
"request_params",
".",
"update",
"(",
"API_EXTRA_PARAMS",
"[",
"'activity'",
"]",
")",
"if",
"kwargs",
":",
"request_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"self",
".",
"_build_url",
"(",
"'activities'",
")",
",",
"params",
"=",
"request_params",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not retrieve activities. Server responded with {}\"",
".",
"format",
"(",
"str",
"(",
"response",
")",
")",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"# for 'kechain.core.wim >= 2.0.0' we return Activity2, otherwise Activity1",
"if",
"self",
".",
"match_app_version",
"(",
"label",
"=",
"'wim'",
",",
"version",
"=",
"'<2.0.0'",
",",
"default",
"=",
"True",
")",
":",
"# WIM1",
"return",
"[",
"Activity",
"(",
"a",
",",
"client",
"=",
"self",
")",
"for",
"a",
"in",
"data",
"[",
"'results'",
"]",
"]",
"else",
":",
"# WIM2",
"return",
"[",
"Activity2",
"(",
"a",
",",
"client",
"=",
"self",
")",
"for",
"a",
"in",
"data",
"[",
"'results'",
"]",
"]"
] | Search for activities with optional name, pk and scope filter.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param pk: id (primary key) of the activity to retrieve
:type pk: basestring or None
:param name: filter the activities by name
:type name: basestring or None
:param scope: filter by scope id
:type scope: basestring or None
:return: list of :class:`models.Activity`
:raises NotFoundError: If no `Activities` are found | [
"Search",
"for",
"activities",
"with",
"optional",
"name",
"pk",
"and",
"scope",
"filter",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L382-L425 | train |
KE-works/pykechain | pykechain/client.py | Client.activity | def activity(self, *args, **kwargs):
# type: (*Any, **Any) -> Activity
"""Search for a single activity.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param pk: id (primary key) of the activity to retrieve
:type pk: basestring or None
:param name: filter the activities by name
:type name: basestring or None
:param scope: filter by scope id
:type scope: basestring or None
:return: a single :class:`models.Activity`
:raises NotFoundError: When no `Activity` is found
:raises MultipleFoundError: When more than a single `Activity` is found
"""
_activities = self.activities(*args, **kwargs)
if len(_activities) == 0:
raise NotFoundError("No activity fits criteria")
if len(_activities) != 1:
raise MultipleFoundError("Multiple activities fit criteria")
return _activities[0] | python | def activity(self, *args, **kwargs):
# type: (*Any, **Any) -> Activity
"""Search for a single activity.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param pk: id (primary key) of the activity to retrieve
:type pk: basestring or None
:param name: filter the activities by name
:type name: basestring or None
:param scope: filter by scope id
:type scope: basestring or None
:return: a single :class:`models.Activity`
:raises NotFoundError: When no `Activity` is found
:raises MultipleFoundError: When more than a single `Activity` is found
"""
_activities = self.activities(*args, **kwargs)
if len(_activities) == 0:
raise NotFoundError("No activity fits criteria")
if len(_activities) != 1:
raise MultipleFoundError("Multiple activities fit criteria")
return _activities[0] | [
"def",
"activity",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Activity",
"_activities",
"=",
"self",
".",
"activities",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_activities",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No activity fits criteria\"",
")",
"if",
"len",
"(",
"_activities",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple activities fit criteria\"",
")",
"return",
"_activities",
"[",
"0",
"]"
] | Search for a single activity.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param pk: id (primary key) of the activity to retrieve
:type pk: basestring or None
:param name: filter the activities by name
:type name: basestring or None
:param scope: filter by scope id
:type scope: basestring or None
:return: a single :class:`models.Activity`
:raises NotFoundError: When no `Activity` is found
:raises MultipleFoundError: When more than a single `Activity` is found | [
"Search",
"for",
"a",
"single",
"activity",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L427-L451 | train |
KE-works/pykechain | pykechain/client.py | Client.parts | def parts(self,
name=None, # type: Optional[str]
pk=None, # type: Optional[str]
model=None, # type: Optional[Part]
category=Category.INSTANCE, # type: Optional[str]
bucket=None, # type: Optional[str]
parent=None, # type: Optional[str]
activity=None, # type: Optional[str]
limit=None, # type: Optional[int]
batch=100, # type: int
**kwargs):
# type: (...) -> PartSet
"""Retrieve multiple KE-chain parts.
If no parameters are provided, all parts are retrieved.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: filter on name
:type name: basestring or None
:param pk: filter on primary key
:type pk: basestring or None
:param model: filter on model_id
:type model: basestring or None
:param category: filter on category (INSTANCE, MODEL, None)
:type category: basestring or None
:param bucket: filter on bucket_id
:type bucket: basestring or None
:param parent: filter on the parent_id, returns all childrent of the parent_id
:type parent: basestring or None
:param activity: filter on activity_id
:type activity: basestring or None
:param limit: limit the return to # items (default unlimited, so return all results)
:type limit: int or None
:param batch: limit the batch size to # items (defaults to 100 items per batch)
:type batch: int or None
:param kwargs: additional `keyword=value` arguments for the api
:type kwargs: dict or None
:return: :class:`models.PartSet` which is an iterator of :class:`models.Part`
:raises NotFoundError: If no `Part` is found
Examples
--------
Return all parts (defaults to instances) with exact name 'Gears'.
>>> client = Client(url='https://default.localhost:9443', verify=False)
>>> client.login('admin','pass')
>>> client.parts(name='Gears') # doctest:Ellipsis
...
Return all parts with category is MODEL or category is INSTANCE.
>>> client.parts(name='Gears', category=None) # doctest:Ellipsis
...
Return a maximum of 5 parts
>>> client.parts(limit=5) # doctest:Ellipsis
...
"""
# if limit is provided and the batchsize is bigger than the limit, ensure that the batch size is maximised
if limit and limit < batch:
batch = limit
request_params = {
'id': pk,
'name': name,
'model': model.id if model else None,
'category': category,
'bucket': bucket,
'parent': parent,
'activity_id': activity,
'limit': batch
}
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('parts'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve parts")
data = response.json()
part_results = data['results']
if batch and data.get('next'):
while data['next']:
# respect the limit if set to > 0
if limit and len(part_results) >= limit:
break
response = self._request('GET', data['next'])
data = response.json()
part_results.extend(data['results'])
return PartSet((Part(p, client=self) for p in part_results)) | python | def parts(self,
name=None, # type: Optional[str]
pk=None, # type: Optional[str]
model=None, # type: Optional[Part]
category=Category.INSTANCE, # type: Optional[str]
bucket=None, # type: Optional[str]
parent=None, # type: Optional[str]
activity=None, # type: Optional[str]
limit=None, # type: Optional[int]
batch=100, # type: int
**kwargs):
# type: (...) -> PartSet
"""Retrieve multiple KE-chain parts.
If no parameters are provided, all parts are retrieved.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: filter on name
:type name: basestring or None
:param pk: filter on primary key
:type pk: basestring or None
:param model: filter on model_id
:type model: basestring or None
:param category: filter on category (INSTANCE, MODEL, None)
:type category: basestring or None
:param bucket: filter on bucket_id
:type bucket: basestring or None
:param parent: filter on the parent_id, returns all childrent of the parent_id
:type parent: basestring or None
:param activity: filter on activity_id
:type activity: basestring or None
:param limit: limit the return to # items (default unlimited, so return all results)
:type limit: int or None
:param batch: limit the batch size to # items (defaults to 100 items per batch)
:type batch: int or None
:param kwargs: additional `keyword=value` arguments for the api
:type kwargs: dict or None
:return: :class:`models.PartSet` which is an iterator of :class:`models.Part`
:raises NotFoundError: If no `Part` is found
Examples
--------
Return all parts (defaults to instances) with exact name 'Gears'.
>>> client = Client(url='https://default.localhost:9443', verify=False)
>>> client.login('admin','pass')
>>> client.parts(name='Gears') # doctest:Ellipsis
...
Return all parts with category is MODEL or category is INSTANCE.
>>> client.parts(name='Gears', category=None) # doctest:Ellipsis
...
Return a maximum of 5 parts
>>> client.parts(limit=5) # doctest:Ellipsis
...
"""
# if limit is provided and the batchsize is bigger than the limit, ensure that the batch size is maximised
if limit and limit < batch:
batch = limit
request_params = {
'id': pk,
'name': name,
'model': model.id if model else None,
'category': category,
'bucket': bucket,
'parent': parent,
'activity_id': activity,
'limit': batch
}
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('parts'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve parts")
data = response.json()
part_results = data['results']
if batch and data.get('next'):
while data['next']:
# respect the limit if set to > 0
if limit and len(part_results) >= limit:
break
response = self._request('GET', data['next'])
data = response.json()
part_results.extend(data['results'])
return PartSet((Part(p, client=self) for p in part_results)) | [
"def",
"parts",
"(",
"self",
",",
"name",
"=",
"None",
",",
"# type: Optional[str]",
"pk",
"=",
"None",
",",
"# type: Optional[str]",
"model",
"=",
"None",
",",
"# type: Optional[Part]",
"category",
"=",
"Category",
".",
"INSTANCE",
",",
"# type: Optional[str]",
"bucket",
"=",
"None",
",",
"# type: Optional[str]",
"parent",
"=",
"None",
",",
"# type: Optional[str]",
"activity",
"=",
"None",
",",
"# type: Optional[str]",
"limit",
"=",
"None",
",",
"# type: Optional[int]",
"batch",
"=",
"100",
",",
"# type: int",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> PartSet",
"# if limit is provided and the batchsize is bigger than the limit, ensure that the batch size is maximised",
"if",
"limit",
"and",
"limit",
"<",
"batch",
":",
"batch",
"=",
"limit",
"request_params",
"=",
"{",
"'id'",
":",
"pk",
",",
"'name'",
":",
"name",
",",
"'model'",
":",
"model",
".",
"id",
"if",
"model",
"else",
"None",
",",
"'category'",
":",
"category",
",",
"'bucket'",
":",
"bucket",
",",
"'parent'",
":",
"parent",
",",
"'activity_id'",
":",
"activity",
",",
"'limit'",
":",
"batch",
"}",
"if",
"kwargs",
":",
"request_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"self",
".",
"_build_url",
"(",
"'parts'",
")",
",",
"params",
"=",
"request_params",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not retrieve parts\"",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"part_results",
"=",
"data",
"[",
"'results'",
"]",
"if",
"batch",
"and",
"data",
".",
"get",
"(",
"'next'",
")",
":",
"while",
"data",
"[",
"'next'",
"]",
":",
"# respect the limit if set to > 0",
"if",
"limit",
"and",
"len",
"(",
"part_results",
")",
">=",
"limit",
":",
"break",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"data",
"[",
"'next'",
"]",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"part_results",
".",
"extend",
"(",
"data",
"[",
"'results'",
"]",
")",
"return",
"PartSet",
"(",
"(",
"Part",
"(",
"p",
",",
"client",
"=",
"self",
")",
"for",
"p",
"in",
"part_results",
")",
")"
] | Retrieve multiple KE-chain parts.
If no parameters are provided, all parts are retrieved.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: filter on name
:type name: basestring or None
:param pk: filter on primary key
:type pk: basestring or None
:param model: filter on model_id
:type model: basestring or None
:param category: filter on category (INSTANCE, MODEL, None)
:type category: basestring or None
:param bucket: filter on bucket_id
:type bucket: basestring or None
:param parent: filter on the parent_id, returns all childrent of the parent_id
:type parent: basestring or None
:param activity: filter on activity_id
:type activity: basestring or None
:param limit: limit the return to # items (default unlimited, so return all results)
:type limit: int or None
:param batch: limit the batch size to # items (defaults to 100 items per batch)
:type batch: int or None
:param kwargs: additional `keyword=value` arguments for the api
:type kwargs: dict or None
:return: :class:`models.PartSet` which is an iterator of :class:`models.Part`
:raises NotFoundError: If no `Part` is found
Examples
--------
Return all parts (defaults to instances) with exact name 'Gears'.
>>> client = Client(url='https://default.localhost:9443', verify=False)
>>> client.login('admin','pass')
>>> client.parts(name='Gears') # doctest:Ellipsis
...
Return all parts with category is MODEL or category is INSTANCE.
>>> client.parts(name='Gears', category=None) # doctest:Ellipsis
...
Return a maximum of 5 parts
>>> client.parts(limit=5) # doctest:Ellipsis
... | [
"Retrieve",
"multiple",
"KE",
"-",
"chain",
"parts",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L453-L551 | train |
KE-works/pykechain | pykechain/client.py | Client.part | def part(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
"""Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found
"""
_parts = self.parts(*args, **kwargs)
if len(_parts) == 0:
raise NotFoundError("No part fits criteria")
if len(_parts) != 1:
raise MultipleFoundError("Multiple parts fit criteria")
return _parts[0] | python | def part(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
"""Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found
"""
_parts = self.parts(*args, **kwargs)
if len(_parts) == 0:
raise NotFoundError("No part fits criteria")
if len(_parts) != 1:
raise MultipleFoundError("Multiple parts fit criteria")
return _parts[0] | [
"def",
"part",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Part",
"_parts",
"=",
"self",
".",
"parts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_parts",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No part fits criteria\"",
")",
"if",
"len",
"(",
"_parts",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple parts fit criteria\"",
")",
"return",
"_parts",
"[",
"0",
"]"
] | Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found | [
"Retrieve",
"single",
"KE",
"-",
"chain",
"part",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L553-L574 | train |
KE-works/pykechain | pykechain/client.py | Client.model | def model(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
"""Retrieve single KE-chain part model.
Uses the same interface as the :func:`part` method but returns only a single pykechain
:class:`models.Part` instance of category `MODEL`.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found
"""
kwargs['category'] = Category.MODEL
_parts = self.parts(*args, **kwargs)
if len(_parts) == 0:
raise NotFoundError("No model fits criteria")
if len(_parts) != 1:
raise MultipleFoundError("Multiple models fit criteria")
return _parts[0] | python | def model(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
"""Retrieve single KE-chain part model.
Uses the same interface as the :func:`part` method but returns only a single pykechain
:class:`models.Part` instance of category `MODEL`.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found
"""
kwargs['category'] = Category.MODEL
_parts = self.parts(*args, **kwargs)
if len(_parts) == 0:
raise NotFoundError("No model fits criteria")
if len(_parts) != 1:
raise MultipleFoundError("Multiple models fit criteria")
return _parts[0] | [
"def",
"model",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Part",
"kwargs",
"[",
"'category'",
"]",
"=",
"Category",
".",
"MODEL",
"_parts",
"=",
"self",
".",
"parts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_parts",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No model fits criteria\"",
")",
"if",
"len",
"(",
"_parts",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple models fit criteria\"",
")",
"return",
"_parts",
"[",
"0",
"]"
] | Retrieve single KE-chain part model.
Uses the same interface as the :func:`part` method but returns only a single pykechain
:class:`models.Part` instance of category `MODEL`.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Part`
:raises NotFoundError: When no `Part` is found
:raises MultipleFoundError: When more than a single `Part` is found | [
"Retrieve",
"single",
"KE",
"-",
"chain",
"part",
"model",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L576-L598 | train |
KE-works/pykechain | pykechain/client.py | Client.property | def property(self, *args, **kwargs):
# type: (*Any, **Any) -> Property
"""Retrieve single KE-chain Property.
Uses the same interface as the :func:`properties` method but returns only a single pykechain :class:
`models.Property` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Property`
:raises NotFoundError: When no `Property` is found
:raises MultipleFoundError: When more than a single `Property` is found
"""
_properties = self.properties(*args, **kwargs)
if len(_properties) == 0:
raise NotFoundError("No property fits criteria")
if len(_properties) != 1:
raise MultipleFoundError("Multiple properties fit criteria")
return _properties[0] | python | def property(self, *args, **kwargs):
# type: (*Any, **Any) -> Property
"""Retrieve single KE-chain Property.
Uses the same interface as the :func:`properties` method but returns only a single pykechain :class:
`models.Property` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Property`
:raises NotFoundError: When no `Property` is found
:raises MultipleFoundError: When more than a single `Property` is found
"""
_properties = self.properties(*args, **kwargs)
if len(_properties) == 0:
raise NotFoundError("No property fits criteria")
if len(_properties) != 1:
raise MultipleFoundError("Multiple properties fit criteria")
return _properties[0] | [
"def",
"property",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Property",
"_properties",
"=",
"self",
".",
"properties",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_properties",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No property fits criteria\"",
")",
"if",
"len",
"(",
"_properties",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple properties fit criteria\"",
")",
"return",
"_properties",
"[",
"0",
"]"
] | Retrieve single KE-chain Property.
Uses the same interface as the :func:`properties` method but returns only a single pykechain :class:
`models.Property` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Property`
:raises NotFoundError: When no `Property` is found
:raises MultipleFoundError: When more than a single `Property` is found | [
"Retrieve",
"single",
"KE",
"-",
"chain",
"Property",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L600-L621 | train |
KE-works/pykechain | pykechain/client.py | Client.properties | def properties(self, name=None, pk=None, category=Category.INSTANCE, **kwargs):
# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Property]
"""Retrieve properties.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: name to limit the search for.
:type name: basestring or None
:param pk: primary key or id (UUID) of the property to search for
:type pk: basestring or None
:param category: filter the properties by category. Defaults to INSTANCE. Other options MODEL or None
:type category: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: list of :class:`models.Property`
:raises NotFoundError: When no `Property` is found
"""
request_params = {
'name': name,
'id': pk,
'category': category
}
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('properties'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve properties")
data = response.json()
return [Property.create(p, client=self) for p in data['results']] | python | def properties(self, name=None, pk=None, category=Category.INSTANCE, **kwargs):
# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Property]
"""Retrieve properties.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: name to limit the search for.
:type name: basestring or None
:param pk: primary key or id (UUID) of the property to search for
:type pk: basestring or None
:param category: filter the properties by category. Defaults to INSTANCE. Other options MODEL or None
:type category: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: list of :class:`models.Property`
:raises NotFoundError: When no `Property` is found
"""
request_params = {
'name': name,
'id': pk,
'category': category
}
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('properties'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve properties")
data = response.json()
return [Property.create(p, client=self) for p in data['results']] | [
"def",
"properties",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"category",
"=",
"Category",
".",
"INSTANCE",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Property]",
"request_params",
"=",
"{",
"'name'",
":",
"name",
",",
"'id'",
":",
"pk",
",",
"'category'",
":",
"category",
"}",
"if",
"kwargs",
":",
"request_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"self",
".",
"_build_url",
"(",
"'properties'",
")",
",",
"params",
"=",
"request_params",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not retrieve properties\"",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"[",
"Property",
".",
"create",
"(",
"p",
",",
"client",
"=",
"self",
")",
"for",
"p",
"in",
"data",
"[",
"'results'",
"]",
"]"
] | Retrieve properties.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: name to limit the search for.
:type name: basestring or None
:param pk: primary key or id (UUID) of the property to search for
:type pk: basestring or None
:param category: filter the properties by category. Defaults to INSTANCE. Other options MODEL or None
:type category: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: list of :class:`models.Property`
:raises NotFoundError: When no `Property` is found | [
"Retrieve",
"properties",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L623-L656 | train |
KE-works/pykechain | pykechain/client.py | Client.services | def services(self, name=None, pk=None, scope=None, **kwargs):
"""
Retrieve Services.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: list of :class:`models.Service` objects
:raises NotFoundError: When no `Service` objects are found
"""
request_params = {
'name': name,
'id': pk,
'scope': scope
}
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('services'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve services")
data = response.json()
return [Service(service, client=self) for service in data['results']] | python | def services(self, name=None, pk=None, scope=None, **kwargs):
"""
Retrieve Services.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: list of :class:`models.Service` objects
:raises NotFoundError: When no `Service` objects are found
"""
request_params = {
'name': name,
'id': pk,
'scope': scope
}
if kwargs:
request_params.update(**kwargs)
response = self._request('GET', self._build_url('services'), params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve services")
data = response.json()
return [Service(service, client=self) for service in data['results']] | [
"def",
"services",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"request_params",
"=",
"{",
"'name'",
":",
"name",
",",
"'id'",
":",
"pk",
",",
"'scope'",
":",
"scope",
"}",
"if",
"kwargs",
":",
"request_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"self",
".",
"_build_url",
"(",
"'services'",
")",
",",
"params",
"=",
"request_params",
")",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not retrieve services\"",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"[",
"Service",
"(",
"service",
",",
"client",
"=",
"self",
")",
"for",
"service",
"in",
"data",
"[",
"'results'",
"]",
"]"
] | Retrieve Services.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: list of :class:`models.Service` objects
:raises NotFoundError: When no `Service` objects are found | [
"Retrieve",
"Services",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L658-L690 | train |
KE-works/pykechain | pykechain/client.py | Client.service | def service(self, name=None, pk=None, scope=None, **kwargs):
"""
Retrieve single KE-chain Service.
Uses the same interface as the :func:`services` method but returns only a single pykechain
:class:`models.Service` instance.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.Service` object
:raises NotFoundError: When no `Service` object is found
:raises MultipleFoundError: When more than a single `Service` object is found
"""
_services = self.services(name=name, pk=pk, scope=scope, **kwargs)
if len(_services) == 0:
raise NotFoundError("No service fits criteria")
if len(_services) != 1:
raise MultipleFoundError("Multiple services fit criteria")
return _services[0] | python | def service(self, name=None, pk=None, scope=None, **kwargs):
"""
Retrieve single KE-chain Service.
Uses the same interface as the :func:`services` method but returns only a single pykechain
:class:`models.Service` instance.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.Service` object
:raises NotFoundError: When no `Service` object is found
:raises MultipleFoundError: When more than a single `Service` object is found
"""
_services = self.services(name=name, pk=pk, scope=scope, **kwargs)
if len(_services) == 0:
raise NotFoundError("No service fits criteria")
if len(_services) != 1:
raise MultipleFoundError("Multiple services fit criteria")
return _services[0] | [
"def",
"service",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_services",
"=",
"self",
".",
"services",
"(",
"name",
"=",
"name",
",",
"pk",
"=",
"pk",
",",
"scope",
"=",
"scope",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_services",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No service fits criteria\"",
")",
"if",
"len",
"(",
"_services",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple services fit criteria\"",
")",
"return",
"_services",
"[",
"0",
"]"
] | Retrieve single KE-chain Service.
Uses the same interface as the :func:`services` method but returns only a single pykechain
:class:`models.Service` instance.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.Service` object
:raises NotFoundError: When no `Service` object is found
:raises MultipleFoundError: When more than a single `Service` object is found | [
"Retrieve",
"single",
"KE",
"-",
"chain",
"Service",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L692-L718 | train |
KE-works/pykechain | pykechain/client.py | Client.service_executions | def service_executions(self, name=None, pk=None, scope=None, service=None, **kwargs):
"""
Retrieve Service Executions.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param service: (optional) service UUID to filter on
:type service: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.ServiceExecution` object
:raises NotFoundError: When no `ServiceExecution` object is found
"""
request_params = {
'name': name,
'id': pk,
'service': service,
'scope': scope
}
if kwargs:
request_params.update(**kwargs)
r = self._request('GET', self._build_url('service_executions'), params=request_params)
if r.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve service executions")
data = r.json()
return [ServiceExecution(service_exeuction, client=self) for service_exeuction in data['results']] | python | def service_executions(self, name=None, pk=None, scope=None, service=None, **kwargs):
"""
Retrieve Service Executions.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param service: (optional) service UUID to filter on
:type service: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.ServiceExecution` object
:raises NotFoundError: When no `ServiceExecution` object is found
"""
request_params = {
'name': name,
'id': pk,
'service': service,
'scope': scope
}
if kwargs:
request_params.update(**kwargs)
r = self._request('GET', self._build_url('service_executions'), params=request_params)
if r.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve service executions")
data = r.json()
return [ServiceExecution(service_exeuction, client=self) for service_exeuction in data['results']] | [
"def",
"service_executions",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"service",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"request_params",
"=",
"{",
"'name'",
":",
"name",
",",
"'id'",
":",
"pk",
",",
"'service'",
":",
"service",
",",
"'scope'",
":",
"scope",
"}",
"if",
"kwargs",
":",
"request_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"r",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"self",
".",
"_build_url",
"(",
"'service_executions'",
")",
",",
"params",
"=",
"request_params",
")",
"if",
"r",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not retrieve service executions\"",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"return",
"[",
"ServiceExecution",
"(",
"service_exeuction",
",",
"client",
"=",
"self",
")",
"for",
"service_exeuction",
"in",
"data",
"[",
"'results'",
"]",
"]"
] | Retrieve Service Executions.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param service: (optional) service UUID to filter on
:type service: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.ServiceExecution` object
:raises NotFoundError: When no `ServiceExecution` object is found | [
"Retrieve",
"Service",
"Executions",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L720-L755 | train |
KE-works/pykechain | pykechain/client.py | Client.service_execution | def service_execution(self, name=None, pk=None, scope=None, service=None, **kwargs):
"""
Retrieve single KE-chain ServiceExecution.
Uses the same interface as the :func:`service_executions` method but returns only a single
pykechain :class:`models.ServiceExecution` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.ServiceExecution` object
:raises NotFoundError: When no `ServiceExecution` object is found
:raises MultipleFoundError: When more than a single `ServiceExecution` object is found
"""
_service_executions = self.service_executions(name=name, pk=pk, scope=scope, service=service, **kwargs)
if len(_service_executions) == 0:
raise NotFoundError("No service execution fits criteria")
if len(_service_executions) != 1:
raise MultipleFoundError("Multiple service executions fit criteria")
return _service_executions[0] | python | def service_execution(self, name=None, pk=None, scope=None, service=None, **kwargs):
"""
Retrieve single KE-chain ServiceExecution.
Uses the same interface as the :func:`service_executions` method but returns only a single
pykechain :class:`models.ServiceExecution` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.ServiceExecution` object
:raises NotFoundError: When no `ServiceExecution` object is found
:raises MultipleFoundError: When more than a single `ServiceExecution` object is found
"""
_service_executions = self.service_executions(name=name, pk=pk, scope=scope, service=service, **kwargs)
if len(_service_executions) == 0:
raise NotFoundError("No service execution fits criteria")
if len(_service_executions) != 1:
raise MultipleFoundError("Multiple service executions fit criteria")
return _service_executions[0] | [
"def",
"service_execution",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"service",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_service_executions",
"=",
"self",
".",
"service_executions",
"(",
"name",
"=",
"name",
",",
"pk",
"=",
"pk",
",",
"scope",
"=",
"scope",
",",
"service",
"=",
"service",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_service_executions",
")",
"==",
"0",
":",
"raise",
"NotFoundError",
"(",
"\"No service execution fits criteria\"",
")",
"if",
"len",
"(",
"_service_executions",
")",
"!=",
"1",
":",
"raise",
"MultipleFoundError",
"(",
"\"Multiple service executions fit criteria\"",
")",
"return",
"_service_executions",
"[",
"0",
"]"
] | Retrieve single KE-chain ServiceExecution.
Uses the same interface as the :func:`service_executions` method but returns only a single
pykechain :class:`models.ServiceExecution` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: (optional) name to limit the search for
:type name: basestring or None
:param pk: (optional) primary key or id (UUID) of the service to search for
:type pk: basestring or None
:param scope: (optional) id (UUID) of the scope to search in
:type scope: basestring or None
:param kwargs: (optional) additional search keyword arguments
:type kwargs: dict or None
:return: a single :class:`models.ServiceExecution` object
:raises NotFoundError: When no `ServiceExecution` object is found
:raises MultipleFoundError: When more than a single `ServiceExecution` object is found | [
"Retrieve",
"single",
"KE",
"-",
"chain",
"ServiceExecution",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L757-L786 | train |
KE-works/pykechain | pykechain/client.py | Client.users | def users(self, username=None, pk=None, **kwargs):
"""
Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:param pk: (optional) id of the user to filter
:type pk: basestring or None
:param kwargs: Additional filtering keyword=value arguments
:type kwargs: dict or None
:return: List of :class:`Users`
:raises NotFoundError: when a user could not be found
"""
request_params = {
'username': username,
'pk': pk,
}
if kwargs:
request_params.update(**kwargs)
r = self._request('GET', self._build_url('users'), params=request_params)
if r.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not find users: '{}'".format(r.json()))
data = r.json()
return [User(user, client=self) for user in data['results']] | python | def users(self, username=None, pk=None, **kwargs):
"""
Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:param pk: (optional) id of the user to filter
:type pk: basestring or None
:param kwargs: Additional filtering keyword=value arguments
:type kwargs: dict or None
:return: List of :class:`Users`
:raises NotFoundError: when a user could not be found
"""
request_params = {
'username': username,
'pk': pk,
}
if kwargs:
request_params.update(**kwargs)
r = self._request('GET', self._build_url('users'), params=request_params)
if r.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not find users: '{}'".format(r.json()))
data = r.json()
return [User(user, client=self) for user in data['results']] | [
"def",
"users",
"(",
"self",
",",
"username",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"request_params",
"=",
"{",
"'username'",
":",
"username",
",",
"'pk'",
":",
"pk",
",",
"}",
"if",
"kwargs",
":",
"request_params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"r",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"self",
".",
"_build_url",
"(",
"'users'",
")",
",",
"params",
"=",
"request_params",
")",
"if",
"r",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"# pragma: no cover",
"raise",
"NotFoundError",
"(",
"\"Could not find users: '{}'\"",
".",
"format",
"(",
"r",
".",
"json",
"(",
")",
")",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"return",
"[",
"User",
"(",
"user",
",",
"client",
"=",
"self",
")",
"for",
"user",
"in",
"data",
"[",
"'results'",
"]",
"]"
] | Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:param pk: (optional) id of the user to filter
:type pk: basestring or None
:param kwargs: Additional filtering keyword=value arguments
:type kwargs: dict or None
:return: List of :class:`Users`
:raises NotFoundError: when a user could not be found | [
"Users",
"of",
"KE",
"-",
"chain",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L788-L816 | train |
Subsets and Splits