query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
listlengths 20
553
|
|---|---|---|---|---|
Convert datetime string to datetime object .
|
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 )
| 4,200
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/utils.py#L86-L144
|
[
"def",
"get_line",
"(",
"self",
",",
"line",
"=",
"1",
")",
":",
"verse_size",
"=",
"len",
"(",
"self",
".",
"get_verse",
"(",
")",
")",
"+",
"1",
"if",
"line",
">",
"1",
":",
"verse",
"=",
"math",
".",
"floor",
"(",
"(",
"line",
"-",
"1",
")",
"/",
"verse_size",
")",
"line_in_verse",
"=",
"(",
"line",
"-",
"1",
")",
"%",
"verse_size",
"try",
":",
"return",
"self",
".",
"verses",
"[",
"verse",
"]",
"[",
"line_in_verse",
"]",
"except",
"IndexError",
":",
"return",
"''",
"else",
":",
"return",
"self",
".",
"verses",
"[",
"0",
"]",
"[",
"0",
"]"
] |
Save the complete customization to the activity .
|
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 )
| 4,201
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L96-L126
|
[
"def",
"set_etag",
"(",
"self",
",",
"etag",
",",
"weak",
"=",
"False",
")",
":",
"self",
".",
"headers",
"[",
"\"ETag\"",
"]",
"=",
"quote_etag",
"(",
"etag",
",",
"weak",
")"
] |
Add a widget to the customization .
|
def _add_widget ( self , widget ) : widgets = self . widgets ( ) widgets += [ widget ] self . _save_customization ( widgets )
| 4,202
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L128-L139
|
[
"def",
"read_sheets",
"(",
"archive",
")",
":",
"xml_source",
"=",
"archive",
".",
"read",
"(",
"ARC_WORKBOOK",
")",
"tree",
"=",
"fromstring",
"(",
"xml_source",
")",
"for",
"element",
"in",
"safe_iterator",
"(",
"tree",
",",
"'{%s}sheet'",
"%",
"SHEET_MAIN_NS",
")",
":",
"attrib",
"=",
"element",
".",
"attrib",
"attrib",
"[",
"'id'",
"]",
"=",
"attrib",
"[",
"\"{%s}id\"",
"%",
"REL_NS",
"]",
"del",
"attrib",
"[",
"\"{%s}id\"",
"%",
"REL_NS",
"]",
"if",
"attrib",
"[",
"'id'",
"]",
":",
"yield",
"attrib"
] |
Get the Ext JS specific customization from the activity .
|
def widgets ( self ) : customization = self . activity . _json_data . get ( 'customization' ) if customization and "ext" in customization . keys ( ) : return customization [ 'ext' ] [ 'widgets' ] else : return [ ]
| 4,203
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L141-L152
|
[
"def",
"delete_value",
"(",
"hive",
",",
"key",
",",
"vname",
"=",
"None",
",",
"use_32bit_registry",
"=",
"False",
")",
":",
"local_hive",
"=",
"_to_unicode",
"(",
"hive",
")",
"local_key",
"=",
"_to_unicode",
"(",
"key",
")",
"local_vname",
"=",
"_to_unicode",
"(",
"vname",
")",
"registry",
"=",
"Registry",
"(",
")",
"try",
":",
"hkey",
"=",
"registry",
".",
"hkeys",
"[",
"local_hive",
"]",
"except",
"KeyError",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid Hive: {0}'",
".",
"format",
"(",
"local_hive",
")",
")",
"access_mask",
"=",
"registry",
".",
"registry_32",
"[",
"use_32bit_registry",
"]",
"|",
"win32con",
".",
"KEY_ALL_ACCESS",
"handle",
"=",
"None",
"try",
":",
"handle",
"=",
"win32api",
".",
"RegOpenKeyEx",
"(",
"hkey",
",",
"local_key",
",",
"0",
",",
"access_mask",
")",
"win32api",
".",
"RegDeleteValue",
"(",
"handle",
",",
"local_vname",
")",
"broadcast_change",
"(",
")",
"return",
"True",
"except",
"Exception",
"as",
"exc",
":",
"# pylint: disable=E0602",
"if",
"exc",
".",
"winerror",
"==",
"2",
":",
"return",
"None",
"else",
":",
"log",
".",
"error",
"(",
"exc",
",",
"exc_info",
"=",
"True",
")",
"log",
".",
"error",
"(",
"'Hive: %s'",
",",
"local_hive",
")",
"log",
".",
"error",
"(",
"'Key: %s'",
",",
"local_key",
")",
"log",
".",
"error",
"(",
"'ValueName: %s'",
",",
"local_vname",
")",
"log",
".",
"error",
"(",
"'32bit Reg: %s'",
",",
"use_32bit_registry",
")",
"return",
"False",
"finally",
":",
"if",
"handle",
":",
"win32api",
".",
"RegCloseKey",
"(",
"handle",
")"
] |
Delete widgets by index .
|
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 )
| 4,204
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L154-L168
|
[
"def",
"resolve_pkix_certificate",
"(",
"url",
")",
":",
"http",
"=",
"urllib3",
".",
"PoolManager",
"(",
")",
"rsp",
"=",
"http",
".",
"request",
"(",
"'GET'",
",",
"url",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/pkix-cert'",
"}",
")",
"if",
"rsp",
".",
"status",
"==",
"200",
":",
"# if strict_compliance and 'application/x-x509-ca-cert' not in rsp.headers:",
"# # This web server's response isn't following the RFC, but might contain",
"# # data representing a DER encoded certificate.",
"# return",
"try",
":",
"return",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_ASN1",
",",
"rsp",
".",
"data",
")",
"except",
"crypto",
".",
"Error",
":",
"log",
".",
"error",
"(",
"'Failed to load DER encoded certificate from %s'",
",",
"url",
")",
"try",
":",
"return",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"rsp",
".",
"data",
")",
"except",
"crypto",
".",
"Error",
":",
"log",
".",
"error",
"(",
"'Failed to load PEM encoded certificate from %s'",
",",
"url",
")",
"raise",
"RuntimeError",
"(",
"'Failed to load any certificate from %s'",
",",
"url",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Failed to fetch intermediate certificate at {0}!'",
".",
"format",
"(",
"url",
")",
")"
] |
Add an Ext Json Widget to the customization .
|
def add_json_widget ( self , config ) : validate ( config , component_jsonwidget_schema ) self . _add_widget ( dict ( config = config , name = WidgetNames . JSONWIDGET ) )
| 4,205
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L177-L190
|
[
"def",
"delete_value",
"(",
"hive",
",",
"key",
",",
"vname",
"=",
"None",
",",
"use_32bit_registry",
"=",
"False",
")",
":",
"return",
"__utils__",
"[",
"'reg.delete_value'",
"]",
"(",
"hive",
"=",
"hive",
",",
"key",
"=",
"key",
",",
"vname",
"=",
"vname",
",",
"use_32bit_registry",
"=",
"use_32bit_registry",
")"
] |
Add a KE - chain Property Grid widget to the customization .
|
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 ) )
| 4,206
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L360-L450
|
[
"def",
"_openResources",
"(",
"self",
")",
":",
"try",
":",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"ex",
")",
"logger",
".",
"warning",
"(",
"\"Unable to read wav with memmory mapping. Trying without now.\"",
")",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"False",
")",
"self",
".",
"_array",
"=",
"data",
"self",
".",
"attributes",
"[",
"'rate'",
"]",
"=",
"rate"
] |
Add a KE - chain Text widget to the customization .
|
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 ) )
| 4,207
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/customization.py#L452-L504
|
[
"def",
"save_voxel_grid",
"(",
"voxel_grid",
",",
"file_name",
")",
":",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"'wb'",
")",
"as",
"fp",
":",
"for",
"voxel",
"in",
"voxel_grid",
":",
"fp",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"<I\"",
",",
"voxel",
")",
")",
"except",
"IOError",
"as",
"e",
":",
"print",
"(",
"\"An error occurred: {}\"",
".",
"format",
"(",
"e",
".",
"args",
"[",
"-",
"1",
"]",
")",
")",
"raise",
"e",
"except",
"Exception",
":",
"raise"
] |
Monkey - patch the multiprocessing . Process class with our own CrashReportingProcess . Any subsequent imports of multiprocessing . Process will reference CrashReportingProcess instead .
|
def enable_mp_crash_reporting ( ) : global mp_crash_reporting_enabled multiprocessing . Process = multiprocessing . process . Process = CrashReportingProcess mp_crash_reporting_enabled = True
| 4,208
|
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/process.py#L11-L20
|
[
"def",
"toggle",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"self",
".",
"set",
"(",
"section",
",",
"option",
",",
"not",
"self",
".",
"get",
"(",
"section",
",",
"option",
")",
")"
] |
Add new incoming data to buffer and try to process
|
def feed ( self , data ) : self . buffer += data while len ( self . buffer ) >= 6 : self . next_packet ( )
| 4,209
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L26-L32
|
[
"def",
"es_version_check",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cluster_ver",
"=",
"current_search",
".",
"cluster_version",
"[",
"0",
"]",
"client_ver",
"=",
"ES_VERSION",
"[",
"0",
"]",
"if",
"cluster_ver",
"!=",
"client_ver",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'Elasticsearch version mismatch. Invenio was installed with '",
"'Elasticsearch v{client_ver}.x support, but the cluster runs '",
"'Elasticsearch v{cluster_ver}.x.'",
".",
"format",
"(",
"client_ver",
"=",
"client_ver",
",",
"cluster_ver",
"=",
"cluster_ver",
",",
")",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner"
] |
Check if a valid header is waiting in buffer
|
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
| 4,210
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L34-L53
|
[
"def",
"matrix",
"(",
"self",
",",
"title",
"=",
"None",
")",
":",
"if",
"title",
"is",
"None",
":",
"return",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"toMatrixString\"",
",",
"\"()Ljava/lang/String;\"",
")",
"else",
":",
"return",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"toMatrixString\"",
",",
"\"(Ljava/lang/String;)Ljava/lang/String;\"",
",",
"title",
")"
] |
Check if a valid body is waiting in buffer
|
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
| 4,211
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L55-L75
|
[
"def",
"get_human_readable_type",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"ndarray",
",",
"MaskedArray",
")",
")",
":",
"return",
"item",
".",
"dtype",
".",
"name",
"elif",
"isinstance",
"(",
"item",
",",
"Image",
")",
":",
"return",
"\"Image\"",
"else",
":",
"text",
"=",
"get_type_string",
"(",
"item",
")",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"to_text_string",
"(",
"'unknown'",
")",
"else",
":",
"return",
"text",
"[",
"text",
".",
"find",
"(",
"'.'",
")",
"+",
"1",
":",
"]"
] |
Process next packet if present
|
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 )
| 4,212
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L77-L93
|
[
"def",
"_openResources",
"(",
"self",
")",
":",
"try",
":",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"ex",
")",
"logger",
".",
"warning",
"(",
"\"Unable to read wav with memmory mapping. Trying without now.\"",
")",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"False",
")",
"self",
".",
"_array",
"=",
"data",
"self",
".",
"attributes",
"[",
"'rate'",
"]",
"=",
"rate"
] |
Extract packet from buffer
|
def extract_packet ( self ) : packet_size = velbus . MINIMUM_MESSAGE_SIZE + ( self . buffer [ 3 ] & 0x0F ) packet = self . buffer [ 0 : packet_size ] return packet
| 4,213
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L95-L102
|
[
"def",
"load_plugins",
"(",
"self",
",",
"plugin_class_name",
")",
":",
"# imp.findmodule('atomic_reactor') doesn't work",
"plugins_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'plugins'",
")",
"logger",
".",
"debug",
"(",
"\"loading plugins from dir '%s'\"",
",",
"plugins_dir",
")",
"files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"plugins_dir",
",",
"f",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"plugins_dir",
")",
"if",
"f",
".",
"endswith",
"(",
"\".py\"",
")",
"]",
"if",
"self",
".",
"plugin_files",
":",
"logger",
".",
"debug",
"(",
"\"loading additional plugins from files '%s'\"",
",",
"self",
".",
"plugin_files",
")",
"files",
"+=",
"self",
".",
"plugin_files",
"plugin_class",
"=",
"globals",
"(",
")",
"[",
"plugin_class_name",
"]",
"plugin_classes",
"=",
"{",
"}",
"for",
"f",
"in",
"files",
":",
"module_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"# Do not reload plugins",
"if",
"module_name",
"in",
"sys",
".",
"modules",
":",
"f_module",
"=",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"else",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"\"load file '%s'\"",
",",
"f",
")",
"f_module",
"=",
"imp",
".",
"load_source",
"(",
"module_name",
",",
"f",
")",
"except",
"(",
"IOError",
",",
"OSError",
",",
"ImportError",
",",
"SyntaxError",
")",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"\"can't load module '%s': %r\"",
",",
"f",
",",
"ex",
")",
"continue",
"for",
"name",
"in",
"dir",
"(",
"f_module",
")",
":",
"binding",
"=",
"getattr",
"(",
"f_module",
",",
"name",
",",
"None",
")",
"try",
":",
"# if you try to compare binding and PostBuildPlugin, python won't match them",
"# if you call this script directly b/c:",
"# ! <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class",
"# '__main__.PostBuildPlugin'>",
"# but",
"# <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class",
"# 'atomic_reactor.plugin.PostBuildPlugin'>",
"is_sub",
"=",
"issubclass",
"(",
"binding",
",",
"plugin_class",
")",
"except",
"TypeError",
":",
"is_sub",
"=",
"False",
"if",
"binding",
"and",
"is_sub",
"and",
"plugin_class",
".",
"__name__",
"!=",
"binding",
".",
"__name__",
":",
"plugin_classes",
"[",
"binding",
".",
"key",
"]",
"=",
"binding",
"return",
"plugin_classes"
] |
Helper function for extract_values figures out string length from format string .
|
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 ) )
| 4,214
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L309-L320
|
[
"def",
"sync_status",
"(",
"self",
")",
":",
"status",
"=",
"None",
"try",
":",
"try",
":",
"self",
".",
"api",
".",
"doi_get",
"(",
"self",
".",
"pid",
".",
"pid_value",
")",
"status",
"=",
"PIDStatus",
".",
"REGISTERED",
"except",
"DataCiteGoneError",
":",
"status",
"=",
"PIDStatus",
".",
"DELETED",
"except",
"DataCiteNoContentError",
":",
"status",
"=",
"PIDStatus",
".",
"REGISTERED",
"except",
"DataCiteNotFoundError",
":",
"pass",
"if",
"status",
"is",
"None",
":",
"try",
":",
"self",
".",
"api",
".",
"metadata_get",
"(",
"self",
".",
"pid",
".",
"pid_value",
")",
"status",
"=",
"PIDStatus",
".",
"RESERVED",
"except",
"DataCiteGoneError",
":",
"status",
"=",
"PIDStatus",
".",
"DELETED",
"except",
"DataCiteNoContentError",
":",
"status",
"=",
"PIDStatus",
".",
"REGISTERED",
"except",
"DataCiteNotFoundError",
":",
"pass",
"except",
"(",
"DataCiteError",
",",
"HttpError",
")",
":",
"logger",
".",
"exception",
"(",
"\"Failed to sync status from DataCite\"",
",",
"extra",
"=",
"dict",
"(",
"pid",
"=",
"self",
".",
"pid",
")",
")",
"raise",
"if",
"status",
"is",
"None",
":",
"status",
"=",
"PIDStatus",
".",
"NEW",
"self",
".",
"pid",
".",
"sync_status",
"(",
"status",
")",
"logger",
".",
"info",
"(",
"\"Successfully synced status from DataCite\"",
",",
"extra",
"=",
"dict",
"(",
"pid",
"=",
"self",
".",
"pid",
")",
")",
"return",
"True"
] |
Retrieve parse definition from the format string fmt .
|
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
| 4,215
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L354-L362
|
[
"def",
"client_connected",
"(",
"self",
",",
"reader",
":",
"asyncio",
".",
"StreamReader",
",",
"writer",
":",
"asyncio",
".",
"StreamWriter",
")",
"->",
"None",
":",
"self",
".",
"reader",
"=",
"reader",
"self",
".",
"writer",
"=",
"writer"
] |
Generate a fake data dictionary to fill in the provided format string .
|
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
| 4,216
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L472-L524
|
[
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",
"query",
"[",
"'workspace_members'",
"]",
"=",
"userid",
"workspaces",
"=",
"[",
"IWorkspace",
"(",
"b",
".",
"_unrestrictedGetObject",
"(",
")",
")",
"for",
"b",
"in",
"catalog",
".",
"unrestrictedSearchResults",
"(",
"query",
")",
"]",
"for",
"workspace",
"in",
"workspaces",
":",
"workspace",
".",
"remove_from_team",
"(",
"userid",
")"
] |
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 .
|
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
| 4,217
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L527-L558
|
[
"def",
"get_torrent_download_limit",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/getTorrentsDlLimit'",
",",
"data",
"=",
"data",
")"
] |
Apply conversions mentioned above .
|
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
| 4,218
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L123-L134
|
[
"def",
"retrieve_secret_id",
"(",
"url",
",",
"token",
")",
":",
"import",
"hvac",
"client",
"=",
"hvac",
".",
"Client",
"(",
"url",
"=",
"url",
",",
"token",
"=",
"token",
")",
"response",
"=",
"client",
".",
"_post",
"(",
"'/v1/sys/wrapping/unwrap'",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"data",
"[",
"'data'",
"]",
"[",
"'secret_id'",
"]"
] |
Escape bad characters for regular expressions .
|
def _escape ( self , s ) : for ch , r_ch in self . ESCAPE_SETS : s = s . replace ( ch , r_ch ) return s
| 4,219
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L196-L204
|
[
"def",
"get_api_version",
"(",
"base_url",
",",
"api_version",
"=",
"None",
",",
"timeout",
"=",
"10",
",",
"verify",
"=",
"True",
")",
":",
"versions",
"=",
"available_api_versions",
"(",
"base_url",
",",
"timeout",
",",
"verify",
")",
"newest_version",
"=",
"max",
"(",
"[",
"float",
"(",
"i",
")",
"for",
"i",
"in",
"versions",
"]",
")",
"if",
"api_version",
"is",
"None",
":",
"# Use latest",
"api_version",
"=",
"newest_version",
"else",
":",
"if",
"api_version",
"not",
"in",
"versions",
":",
"api_version",
"=",
"newest_version",
"return",
"api_version"
] |
Make an attempt at converting a format spec to a regular expression .
|
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 )
| 4,220
|
https://github.com/pytroll/trollsift/blob/d0e5b6006e248974d806d0dd8e20cc6641d778fb/trollsift/parser.py#L235-L271
|
[
"def",
"configure_url",
"(",
"url",
")",
":",
"app",
".",
"config",
"[",
"'COIL_URL'",
"]",
"=",
"_site",
".",
"config",
"[",
"'SITE_URL'",
"]",
"=",
"_site",
".",
"config",
"[",
"'BASE_URL'",
"]",
"=",
"_site",
".",
"GLOBAL_CONTEXT",
"[",
"'blog_url'",
"]",
"=",
"site",
".",
"config",
"[",
"'SITE_URL'",
"]",
"=",
"site",
".",
"config",
"[",
"'BASE_URL'",
"]",
"=",
"url"
] |
Feed parser with new data
|
def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . parser . feed ( data )
| 4,221
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L49-L56
|
[
"def",
"normaliseURL",
"(",
"url",
")",
":",
"url",
"=",
"unicode_safe",
"(",
"url",
")",
".",
"strip",
"(",
")",
"# XXX: brutal hack",
"url",
"=",
"unescape",
"(",
"url",
")",
"pu",
"=",
"list",
"(",
"urlparse",
"(",
"url",
")",
")",
"segments",
"=",
"pu",
"[",
"2",
"]",
".",
"split",
"(",
"'/'",
")",
"while",
"segments",
"and",
"segments",
"[",
"0",
"]",
"in",
"(",
"''",
",",
"'..'",
")",
":",
"del",
"segments",
"[",
"0",
"]",
"pu",
"[",
"2",
"]",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"segments",
")",
"# remove leading '&' from query",
"if",
"pu",
"[",
"4",
"]",
".",
"startswith",
"(",
"'&'",
")",
":",
"pu",
"[",
"4",
"]",
"=",
"pu",
"[",
"4",
"]",
"[",
"1",
":",
"]",
"# remove anchor",
"pu",
"[",
"5",
"]",
"=",
"\"\"",
"return",
"urlunparse",
"(",
"pu",
")"
] |
Scan the bus and call the callback when a new module is discovered
|
def scan ( self , callback = 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 )
| 4,222
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L96-L121
|
[
"def",
"create_pax_header",
"(",
"self",
",",
"info",
",",
"encoding",
")",
":",
"info",
"[",
"\"magic\"",
"]",
"=",
"POSIX_MAGIC",
"pax_headers",
"=",
"self",
".",
"pax_headers",
".",
"copy",
"(",
")",
"# Test string fields for values that exceed the field length or cannot",
"# be represented in ASCII encoding.",
"for",
"name",
",",
"hname",
",",
"length",
"in",
"(",
"(",
"\"name\"",
",",
"\"path\"",
",",
"LENGTH_NAME",
")",
",",
"(",
"\"linkname\"",
",",
"\"linkpath\"",
",",
"LENGTH_LINK",
")",
",",
"(",
"\"uname\"",
",",
"\"uname\"",
",",
"32",
")",
",",
"(",
"\"gname\"",
",",
"\"gname\"",
",",
"32",
")",
")",
":",
"if",
"hname",
"in",
"pax_headers",
":",
"# The pax header has priority.",
"continue",
"# Try to encode the string as ASCII.",
"try",
":",
"info",
"[",
"name",
"]",
".",
"encode",
"(",
"\"ascii\"",
",",
"\"strict\"",
")",
"except",
"UnicodeEncodeError",
":",
"pax_headers",
"[",
"hname",
"]",
"=",
"info",
"[",
"name",
"]",
"continue",
"if",
"len",
"(",
"info",
"[",
"name",
"]",
")",
">",
"length",
":",
"pax_headers",
"[",
"hname",
"]",
"=",
"info",
"[",
"name",
"]",
"# Test number fields for values that exceed the field limit or values",
"# that like to be stored as float.",
"for",
"name",
",",
"digits",
"in",
"(",
"(",
"\"uid\"",
",",
"8",
")",
",",
"(",
"\"gid\"",
",",
"8",
")",
",",
"(",
"\"size\"",
",",
"12",
")",
",",
"(",
"\"mtime\"",
",",
"12",
")",
")",
":",
"if",
"name",
"in",
"pax_headers",
":",
"# The pax header has priority. Avoid overflow.",
"info",
"[",
"name",
"]",
"=",
"0",
"continue",
"val",
"=",
"info",
"[",
"name",
"]",
"if",
"not",
"0",
"<=",
"val",
"<",
"8",
"**",
"(",
"digits",
"-",
"1",
")",
"or",
"isinstance",
"(",
"val",
",",
"float",
")",
":",
"pax_headers",
"[",
"name",
"]",
"=",
"str",
"(",
"val",
")",
"info",
"[",
"name",
"]",
"=",
"0",
"# Create a pax extended header if necessary.",
"if",
"pax_headers",
":",
"buf",
"=",
"self",
".",
"_create_pax_generic_header",
"(",
"pax_headers",
",",
"XHDTYPE",
",",
"encoding",
")",
"else",
":",
"buf",
"=",
"b\"\"",
"return",
"buf",
"+",
"self",
".",
"_create_header",
"(",
"info",
",",
"USTAR_FORMAT",
",",
"\"ascii\"",
",",
"\"replace\"",
")"
] |
This will send all the needed messages to sync the cloc
|
def sync_clock ( self ) : self . send ( velbus . SetRealtimeClock ( ) ) self . send ( velbus . SetDate ( ) ) self . send ( velbus . SetDaylightSaving ( ) )
| 4,223
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L167-L173
|
[
"def",
"mask_and_mean_loss",
"(",
"input_tensor",
",",
"binary_tensor",
",",
"axis",
"=",
"None",
")",
":",
"return",
"mean_on_masked",
"(",
"mask_loss",
"(",
"input_tensor",
",",
"binary_tensor",
")",
",",
"binary_tensor",
",",
"axis",
"=",
"axis",
")"
] |
Look up the value of an object in a traceback by a dot - lookup string . ie . self . crashreporter . application_name
|
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
| 4,224
|
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L28-L70
|
[
"def",
"set_header",
"(",
"self",
",",
"port",
",",
"channel",
")",
":",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"channel",
"=",
"channel",
"self",
".",
"_update_header",
"(",
")"
] |
Find the values of referenced attributes of objects within the traceback scope .
|
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
| 4,225
|
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L73-L91
|
[
"def",
"simple_parse_file",
"(",
"filename",
":",
"str",
")",
"->",
"Feed",
":",
"pairs",
"=",
"(",
"(",
"rss",
".",
"parse_rss_file",
",",
"_adapt_rss_channel",
")",
",",
"(",
"atom",
".",
"parse_atom_file",
",",
"_adapt_atom_feed",
")",
",",
"(",
"json_feed",
".",
"parse_json_feed_file",
",",
"_adapt_json_feed",
")",
")",
"return",
"_simple_parse",
"(",
"pairs",
",",
"filename",
")"
] |
Find the values of the local variables within the traceback scope .
|
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
| 4,226
|
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L94-L113
|
[
"def",
"simple_parse_file",
"(",
"filename",
":",
"str",
")",
"->",
"Feed",
":",
"pairs",
"=",
"(",
"(",
"rss",
".",
"parse_rss_file",
",",
"_adapt_rss_channel",
")",
",",
"(",
"atom",
".",
"parse_atom_file",
",",
"_adapt_atom_feed",
")",
",",
"(",
"json_feed",
".",
"parse_json_feed_file",
",",
"_adapt_json_feed",
")",
")",
"return",
"_simple_parse",
"(",
"pairs",
",",
"filename",
")"
] |
Extract trace back information into a list of dictionaries .
|
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
| 4,227
|
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L155-L183
|
[
"def",
"_get_site_dummy_variables",
"(",
"self",
",",
"vs30",
")",
":",
"s_b",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"s_c",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"s_d",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"s_b",
"[",
"np",
".",
"logical_and",
"(",
"vs30",
">=",
"360.",
",",
"vs30",
"<",
"800.",
")",
"]",
"=",
"1.0",
"s_c",
"[",
"np",
".",
"logical_and",
"(",
"vs30",
">=",
"180.",
",",
"vs30",
"<",
"360.",
")",
"]",
"=",
"1.0",
"s_d",
"[",
"vs30",
"<",
"180",
"]",
"=",
"1.0",
"return",
"s_b",
",",
"s_c",
",",
"s_d"
] |
Log the read configs if debug is enabled .
|
def log_configs ( self ) : for sec in self . config . sections ( ) : LOG . debug ( ' %s: %s' , sec , self . config . options ( sec ) )
| 4,228
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L51-L54
|
[
"def",
"surname",
"(",
"self",
",",
"gender",
":",
"Optional",
"[",
"Gender",
"]",
"=",
"None",
")",
"->",
"str",
":",
"surnames",
"=",
"self",
".",
"_data",
"[",
"'surnames'",
"]",
"# Surnames separated by gender.",
"if",
"isinstance",
"(",
"surnames",
",",
"dict",
")",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"gender",
",",
"Gender",
")",
"surnames",
"=",
"surnames",
"[",
"key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"surnames",
")"
] |
Read some environment variables and set them on the config .
|
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 ) )
| 4,229
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L56-L81
|
[
"def",
"create_pgroup_snapshot",
"(",
"self",
",",
"source",
",",
"*",
"*",
"kwargs",
")",
":",
"# In REST 1.4, support was added for snapshotting multiple pgroups. As a",
"# result, the endpoint response changed from an object to an array of",
"# objects. To keep the response type consistent between REST versions,",
"# we unbox the response when creating a single snapshot.",
"result",
"=",
"self",
".",
"create_pgroup_snapshots",
"(",
"[",
"source",
"]",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"_rest_version",
">=",
"LooseVersion",
"(",
"\"1.4\"",
")",
":",
"headers",
"=",
"result",
".",
"headers",
"result",
"=",
"ResponseDict",
"(",
"result",
"[",
"0",
"]",
")",
"result",
".",
"headers",
"=",
"headers",
"return",
"result"
] |
Create a empty config file .
|
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 )
| 4,230
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L84-L89
|
[
"def",
"Nu_vertical_cylinder",
"(",
"Pr",
",",
"Gr",
",",
"L",
"=",
"None",
",",
"D",
"=",
"None",
",",
"Method",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"for",
"key",
",",
"values",
"in",
"vertical_cylinder_correlations",
".",
"items",
"(",
")",
":",
"if",
"values",
"[",
"4",
"]",
"or",
"all",
"(",
"(",
"L",
",",
"D",
")",
")",
":",
"methods",
".",
"append",
"(",
"key",
")",
"if",
"'Popiel & Churchill'",
"in",
"methods",
":",
"methods",
".",
"remove",
"(",
"'Popiel & Churchill'",
")",
"methods",
".",
"insert",
"(",
"0",
",",
"'Popiel & Churchill'",
")",
"elif",
"'McAdams, Weiss & Saunders'",
"in",
"methods",
":",
"methods",
".",
"remove",
"(",
"'McAdams, Weiss & Saunders'",
")",
"methods",
".",
"insert",
"(",
"0",
",",
"'McAdams, Weiss & Saunders'",
")",
"return",
"methods",
"if",
"AvailableMethods",
":",
"return",
"list_methods",
"(",
")",
"if",
"not",
"Method",
":",
"Method",
"=",
"list_methods",
"(",
")",
"[",
"0",
"]",
"if",
"Method",
"in",
"vertical_cylinder_correlations",
":",
"if",
"vertical_cylinder_correlations",
"[",
"Method",
"]",
"[",
"4",
"]",
":",
"return",
"vertical_cylinder_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"Pr",
"=",
"Pr",
",",
"Gr",
"=",
"Gr",
")",
"else",
":",
"return",
"vertical_cylinder_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"Pr",
"=",
"Pr",
",",
"Gr",
"=",
"Gr",
",",
"L",
"=",
"L",
",",
"D",
"=",
"D",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Correlation name not recognized; see the \"",
"\"documentation for the available options.\"",
")"
] |
Save the token on the config 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 )
| 4,231
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L91-L108
|
[
"def",
"_infer_binary_broadcast_shape",
"(",
"shape1",
",",
"shape2",
",",
"given_output_shape",
"=",
"None",
")",
":",
"shape1",
"=",
"convert_to_shape",
"(",
"shape1",
")",
"shape2",
"=",
"convert_to_shape",
"(",
"shape2",
")",
"given_output_shape",
"=",
"convert_to_shape",
"(",
"given_output_shape",
")",
"if",
"given_output_shape",
"is",
"not",
"None",
":",
"return",
"given_output_shape",
"if",
"is_subsequence",
"(",
"shape1",
".",
"dims",
",",
"shape2",
".",
"dims",
")",
":",
"return",
"shape2",
"if",
"is_subsequence",
"(",
"shape2",
".",
"dims",
",",
"shape1",
".",
"dims",
")",
":",
"return",
"shape1",
"return",
"Shape",
"(",
"shape1",
".",
"dims",
"+",
"[",
"d",
"for",
"d",
"in",
"shape2",
".",
"dims",
"if",
"d",
"not",
"in",
"shape1",
".",
"dims",
"]",
")"
] |
Clear Token information on config 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 )
| 4,232
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/config.py#L110-L125
|
[
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Move the Part model to target parent .
|
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
| 4,233
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L42-L117
|
[
"def",
"post",
"(",
"self",
",",
"command",
",",
"data",
"=",
"None",
")",
":",
"now",
"=",
"calendar",
".",
"timegm",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"timetuple",
"(",
")",
")",
"if",
"now",
">",
"self",
".",
"expiration",
":",
"auth",
"=",
"self",
".",
"__open",
"(",
"\"/oauth/token\"",
",",
"data",
"=",
"self",
".",
"oauth",
")",
"self",
".",
"__sethead",
"(",
"auth",
"[",
"'access_token'",
"]",
")",
"return",
"self",
".",
"__open",
"(",
"\"%s%s\"",
"%",
"(",
"self",
".",
"api",
",",
"command",
")",
",",
"headers",
"=",
"self",
".",
"head",
",",
"data",
"=",
"data",
")"
] |
Move the Part instance to target parent .
|
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
| 4,234
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L137-L172
|
[
"def",
"_generateForOAuthSecurity",
"(",
"self",
",",
"client_id",
",",
"secret_id",
",",
"token_url",
"=",
"None",
")",
":",
"grant_type",
"=",
"\"client_credentials\"",
"if",
"token_url",
"is",
"None",
":",
"token_url",
"=",
"\"https://www.arcgis.com/sharing/rest/oauth2/token\"",
"params",
"=",
"{",
"\"client_id\"",
":",
"client_id",
",",
"\"client_secret\"",
":",
"secret_id",
",",
"\"grant_type\"",
":",
"grant_type",
",",
"\"f\"",
":",
"\"json\"",
"}",
"token",
"=",
"self",
".",
"_post",
"(",
"url",
"=",
"token_url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"None",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
")",
"if",
"'access_token'",
"in",
"token",
":",
"self",
".",
"_token",
"=",
"token",
"[",
"'access_token'",
"]",
"self",
".",
"_expires_in",
"=",
"token",
"[",
"'expires_in'",
"]",
"self",
".",
"_token_created_on",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"_token_expires_on",
"=",
"self",
".",
"_token_created_on",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"token",
"[",
"'expires_in'",
"]",
")",
")",
"self",
".",
"_valid",
"=",
"True",
"self",
".",
"_message",
"=",
"\"Token Generated\"",
"else",
":",
"self",
".",
"_token",
"=",
"None",
"self",
".",
"_expires_in",
"=",
"None",
"self",
".",
"_token_created_on",
"=",
"None",
"self",
".",
"_token_expires_on",
"=",
"None",
"self",
".",
"_valid",
"=",
"False",
"self",
".",
"_message",
"=",
"token"
] |
Move the Part instance to target parent and updates the properties based on the original part 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
| 4,235
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L175-L235
|
[
"def",
"revoke_token",
"(",
"self",
",",
"token",
")",
":",
"resp",
",",
"resp_body",
"=",
"self",
".",
"method_delete",
"(",
"\"tokens/%s\"",
"%",
"token",
",",
"admin",
"=",
"True",
")",
"if",
"resp",
".",
"status_code",
"in",
"(",
"401",
",",
"403",
")",
":",
"raise",
"exc",
".",
"AuthorizationFailure",
"(",
"\"You must be an admin to make this \"",
"\"call.\"",
")",
"return",
"200",
"<=",
"resp",
".",
"status_code",
"<",
"300"
] |
Update the newly created part and its properties based on the original one .
|
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
| 4,236
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L238-L276
|
[
"def",
"get_free_gpus",
"(",
"max_procs",
"=",
"0",
")",
":",
"# Try connect with NVIDIA drivers",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"py3nvml",
".",
"nvmlInit",
"(",
")",
"except",
":",
"str_",
"=",
"\"\"\"Couldn't connect to nvml drivers. Check they are installed correctly.\"\"\"",
"warnings",
".",
"warn",
"(",
"str_",
",",
"RuntimeWarning",
")",
"logger",
".",
"warn",
"(",
"str_",
")",
"return",
"[",
"]",
"num_gpus",
"=",
"py3nvml",
".",
"nvmlDeviceGetCount",
"(",
")",
"gpu_free",
"=",
"[",
"False",
"]",
"*",
"num_gpus",
"for",
"i",
"in",
"range",
"(",
"num_gpus",
")",
":",
"try",
":",
"h",
"=",
"py3nvml",
".",
"nvmlDeviceGetHandleByIndex",
"(",
"i",
")",
"except",
":",
"continue",
"procs",
"=",
"try_get_info",
"(",
"py3nvml",
".",
"nvmlDeviceGetComputeRunningProcesses",
",",
"h",
",",
"[",
"'something'",
"]",
")",
"if",
"len",
"(",
"procs",
")",
"<=",
"max_procs",
":",
"gpu_free",
"[",
"i",
"]",
"=",
"True",
"py3nvml",
".",
"nvmlShutdown",
"(",
")",
"return",
"gpu_free"
] |
Map the id of the original part with the Part object of the newly created one .
|
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 ]
| 4,237
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/extra_utils.py#L279-L298
|
[
"def",
"list_storage_accounts_rg",
"(",
"access_token",
",",
"subscription_id",
",",
"rgname",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourcegroups/'",
",",
"rgname",
",",
"'/providers/Microsoft.Storage/storageAccounts'",
",",
"'?api-version='",
",",
"STORAGE_API",
"]",
")",
"return",
"do_get",
"(",
"endpoint",
",",
"access_token",
")"
] |
Ask a question and get the input values .
|
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
| 4,238
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/users.py#L81-L116
|
[
"def",
"detail_dict",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"dict",
"def",
"aug_col",
"(",
"c",
")",
":",
"d",
"=",
"c",
".",
"dict",
"d",
"[",
"'stats'",
"]",
"=",
"[",
"s",
".",
"dict",
"for",
"s",
"in",
"c",
".",
"stats",
"]",
"return",
"d",
"d",
"[",
"'table'",
"]",
"=",
"self",
".",
"table",
".",
"dict",
"d",
"[",
"'table'",
"]",
"[",
"'columns'",
"]",
"=",
"[",
"aug_col",
"(",
"c",
")",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
"]",
"return",
"d"
] |
Static asset management in python .
|
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 )
| 4,239
|
https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/cli.py#L18-L43
|
[
"def",
"purge",
"(",
"context",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"'%s/%s/purge'",
"%",
"(",
"context",
".",
"dci_cs_api",
",",
"resource",
")",
"if",
"'force'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'force'",
"]",
":",
"r",
"=",
"context",
".",
"session",
".",
"post",
"(",
"uri",
",",
"timeout",
"=",
"HTTP_TIMEOUT",
")",
"else",
":",
"r",
"=",
"context",
".",
"session",
".",
"get",
"(",
"uri",
",",
"timeout",
"=",
"HTTP_TIMEOUT",
")",
"return",
"r"
] |
Retrieve the part that holds this Property .
|
def part ( self ) : part_id = self . _json_data [ 'part' ] return self . _client . part ( pk = part_id , category = self . _json_data [ 'category' ] )
| 4,240
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L110-L118
|
[
"def",
"_find_rtd_version",
"(",
")",
":",
"vstr",
"=",
"'latest'",
"try",
":",
"import",
"ginga",
"from",
"bs4",
"import",
"BeautifulSoup",
"except",
"ImportError",
":",
"return",
"vstr",
"# No active doc build before this release, just use latest.",
"if",
"not",
"minversion",
"(",
"ginga",
",",
"'2.6.0'",
")",
":",
"return",
"vstr",
"# Get RTD download listing.",
"url",
"=",
"'https://readthedocs.org/projects/ginga/downloads/'",
"with",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
"as",
"r",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"r",
",",
"'html.parser'",
")",
"# Compile a list of available HTML doc versions for download.",
"all_rtd_vernums",
"=",
"[",
"]",
"for",
"link",
"in",
"soup",
".",
"find_all",
"(",
"'a'",
")",
":",
"href",
"=",
"link",
".",
"get",
"(",
"'href'",
")",
"if",
"'htmlzip'",
"not",
"in",
"href",
":",
"continue",
"s",
"=",
"href",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"2",
"]",
"if",
"s",
".",
"startswith",
"(",
"'v'",
")",
":",
"# Ignore latest and stable",
"all_rtd_vernums",
".",
"append",
"(",
"s",
")",
"all_rtd_vernums",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"# Find closest match.",
"ginga_ver",
"=",
"ginga",
".",
"__version__",
"for",
"rtd_ver",
"in",
"all_rtd_vernums",
":",
"if",
"ginga_ver",
">",
"rtd_ver",
"[",
"1",
":",
"]",
":",
"# Ignore \"v\" in comparison",
"break",
"else",
":",
"vstr",
"=",
"rtd_ver",
"return",
"vstr"
] |
Delete this property .
|
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 ) )
| 4,241
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L120-L130
|
[
"def",
"_get_container_dirs",
"(",
"source_dir",
",",
"manifest_dir",
")",
":",
"base",
"=",
"\"/tmp/samcli\"",
"result",
"=",
"{",
"\"source_dir\"",
":",
"\"{}/source\"",
".",
"format",
"(",
"base",
")",
",",
"\"artifacts_dir\"",
":",
"\"{}/artifacts\"",
".",
"format",
"(",
"base",
")",
",",
"\"scratch_dir\"",
":",
"\"{}/scratch\"",
".",
"format",
"(",
"base",
")",
",",
"\"manifest_dir\"",
":",
"\"{}/manifest\"",
".",
"format",
"(",
"base",
")",
"}",
"if",
"pathlib",
".",
"PurePath",
"(",
"source_dir",
")",
"==",
"pathlib",
".",
"PurePath",
"(",
"manifest_dir",
")",
":",
"# It is possible that the manifest resides within the source. In that case, we won't mount the manifest",
"# directory separately.",
"result",
"[",
"\"manifest_dir\"",
"]",
"=",
"result",
"[",
"\"source_dir\"",
"]",
"return",
"result"
] |
Create a property based on the json data .
|
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 )
| 4,242
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L143-L170
|
[
"def",
"get_booking",
"(",
"request",
")",
":",
"booking",
"=",
"None",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"try",
":",
"booking",
"=",
"Booking",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
",",
"booking_status__slug",
"=",
"'inprogress'",
")",
"except",
"Booking",
".",
"DoesNotExist",
":",
"# The user does not have any open bookings",
"pass",
"else",
":",
"session",
"=",
"Session",
".",
"objects",
".",
"get",
"(",
"session_key",
"=",
"request",
".",
"session",
".",
"session_key",
")",
"try",
":",
"booking",
"=",
"Booking",
".",
"objects",
".",
"get",
"(",
"session",
"=",
"session",
")",
"except",
"Booking",
".",
"DoesNotExist",
":",
"# The user does not have any bookings in his session",
"pass",
"return",
"booking"
] |
Parse the validator in the options to validators .
|
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 ) )
| 4,243
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L242-L247
|
[
"def",
"updateMedShockProcess",
"(",
"self",
")",
":",
"MedShkDstn",
"=",
"[",
"]",
"# empty list for medical shock distribution each period",
"for",
"t",
"in",
"range",
"(",
"self",
".",
"T_cycle",
")",
":",
"MedShkAvgNow",
"=",
"self",
".",
"MedShkAvg",
"[",
"t",
"]",
"# get shock distribution parameters",
"MedShkStdNow",
"=",
"self",
".",
"MedShkStd",
"[",
"t",
"]",
"MedShkDstnNow",
"=",
"approxLognormal",
"(",
"mu",
"=",
"np",
".",
"log",
"(",
"MedShkAvgNow",
")",
"-",
"0.5",
"*",
"MedShkStdNow",
"**",
"2",
",",
"sigma",
"=",
"MedShkStdNow",
",",
"N",
"=",
"self",
".",
"MedShkCount",
",",
"tail_N",
"=",
"self",
".",
"MedShkCountTail",
",",
"tail_bound",
"=",
"[",
"0",
",",
"0.9",
"]",
")",
"MedShkDstnNow",
"=",
"addDiscreteOutcomeConstantMean",
"(",
"MedShkDstnNow",
",",
"0.0",
",",
"0.0",
",",
"sort",
"=",
"True",
")",
"# add point at zero with no probability",
"MedShkDstn",
".",
"append",
"(",
"MedShkDstnNow",
")",
"self",
".",
"MedShkDstn",
"=",
"MedShkDstn",
"self",
".",
"addToTimeVary",
"(",
"'MedShkDstn'",
")"
] |
Dump the validators as json inside the _options dictionary with the key validators .
|
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
| 4,244
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L249-L265
|
[
"def",
"_to_epoch",
"(",
"self",
",",
"ts",
")",
":",
"year",
"=",
"self",
".",
"year",
"tmpts",
"=",
"\"%s %s\"",
"%",
"(",
"ts",
",",
"str",
"(",
"self",
".",
"year",
")",
")",
"new_time",
"=",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"time",
".",
"strptime",
"(",
"tmpts",
",",
"\"%b %d %H:%M:%S %Y\"",
")",
")",
")",
"# If adding the year puts it in the future, this log must be from last year",
"if",
"new_time",
">",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
":",
"year",
"-=",
"1",
"tmpts",
"=",
"\"%s %s\"",
"%",
"(",
"ts",
",",
"str",
"(",
"year",
")",
")",
"new_time",
"=",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"time",
".",
"strptime",
"(",
"tmpts",
",",
"\"%b %d %H:%M:%S %Y\"",
")",
")",
")",
"return",
"new_time"
] |
Determine if the value in the property is valid .
|
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 )
| 4,245
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property.py#L268-L286
|
[
"def",
"correspondence",
"(",
"soup",
")",
":",
"correspondence",
"=",
"[",
"]",
"author_notes_nodes",
"=",
"raw_parser",
".",
"author_notes",
"(",
"soup",
")",
"if",
"author_notes_nodes",
":",
"corresp_nodes",
"=",
"raw_parser",
".",
"corresp",
"(",
"author_notes_nodes",
")",
"for",
"tag",
"in",
"corresp_nodes",
":",
"correspondence",
".",
"append",
"(",
"tag",
".",
"text",
")",
"return",
"correspondence"
] |
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 .
|
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 )
| 4,246
|
https://github.com/fprimex/zdeskcfg/blob/4283733123a62c0ab7679ca8aba0d4b02e6bb8d7/zdeskcfg.py#L165-L171
|
[
"def",
"add_category",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"_categories",
"=",
"self",
".",
"_ensure_append",
"(",
"category",
",",
"self",
".",
"_categories",
")"
] |
Bandpass filter with a bandpass setting of 5 to 15 Hz
|
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 )
| 4,247
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L365-L385
|
[
"def",
"version",
"(",
")",
":",
"ret",
"=",
"_client_wrapper",
"(",
"'version'",
")",
"version_re",
"=",
"re",
".",
"compile",
"(",
"VERSION_RE",
")",
"if",
"'Version'",
"in",
"ret",
":",
"match",
"=",
"version_re",
".",
"match",
"(",
"six",
".",
"text_type",
"(",
"ret",
"[",
"'Version'",
"]",
")",
")",
"if",
"match",
":",
"ret",
"[",
"'VersionInfo'",
"]",
"=",
"tuple",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"match",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"'.'",
")",
"]",
")",
"if",
"'ApiVersion'",
"in",
"ret",
":",
"match",
"=",
"version_re",
".",
"match",
"(",
"six",
".",
"text_type",
"(",
"ret",
"[",
"'ApiVersion'",
"]",
")",
")",
"if",
"match",
":",
"ret",
"[",
"'ApiVersionInfo'",
"]",
"=",
"tuple",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"match",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"'.'",
")",
"]",
")",
"return",
"ret"
] |
Moving window integration . N is the number of samples in the width of the integration window
|
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
| 4,248
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L428-L452
|
[
"def",
"add_connection_args",
"(",
"parser",
":",
"FileAwareParser",
",",
"strong_config_file",
":",
"bool",
"=",
"True",
")",
"->",
"FileAwareParser",
":",
"# TODO: Decide what to do with this",
"parser",
".",
"add_file_argument",
"(",
"\"--conf\"",
",",
"metavar",
"=",
"\"CONFIG FILE\"",
",",
"help",
"=",
"\"Configuration file\"",
",",
"action",
"=",
"ConfigFile",
"if",
"strong_config_file",
"else",
"None",
")",
"parser",
".",
"add_argument",
"(",
"\"-db\"",
",",
"\"--dburl\"",
",",
"help",
"=",
"\"Default database URL\"",
",",
"default",
"=",
"Default_DB_Connection",
")",
"parser",
".",
"add_argument",
"(",
"\"--user\"",
",",
"help",
"=",
"\"Default user name\"",
",",
"default",
"=",
"Default_User",
")",
"parser",
".",
"add_argument",
"(",
"\"--password\"",
",",
"help",
"=",
"\"Default password\"",
",",
"default",
"=",
"Default_Password",
")",
"parser",
".",
"add_argument",
"(",
"\"--crcdb\"",
",",
"help",
"=",
"\"CRC database URL. (default: dburl)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--crcuser\"",
",",
"help",
"=",
"\"User name for CRC database. (default: user)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--crcpassword\"",
",",
"help",
"=",
"\"Password for CRC database. (default: password)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--ontodb\"",
",",
"help",
"=",
"\"Ontology database URL. (default: dburl)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--ontouser\"",
",",
"help",
"=",
"\"User name for ontology database. (default: user)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--ontopassword\"",
",",
"help",
"=",
"\"Password for ontology database. (default: password)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--onttable\"",
",",
"metavar",
"=",
"\"ONTOLOGY TABLE NAME\"",
",",
"help",
"=",
"\"Ontology table name (default: {})\"",
".",
"format",
"(",
"DEFAULT_ONTOLOGY_TABLE",
")",
",",
"default",
"=",
"DEFAULT_ONTOLOGY_TABLE",
")",
"return",
"parser"
] |
Initializes the buffer with eight 1s intervals
|
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
| 4,249
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L455-L493
|
[
"async",
"def",
"mount",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_filesystem",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not mounting {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"if",
"device",
".",
"is_mounted",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not mounting {0}: already mounted'",
",",
"device",
")",
")",
"return",
"True",
"options",
"=",
"match_config",
"(",
"self",
".",
"_config",
",",
"device",
",",
"'options'",
",",
"None",
")",
"kwargs",
"=",
"dict",
"(",
"options",
"=",
"options",
")",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'mounting {0} with {1}'",
",",
"device",
",",
"kwargs",
")",
")",
"self",
".",
"_check_device_before_mount",
"(",
"device",
")",
"mount_path",
"=",
"await",
"device",
".",
"mount",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'mounted {0} on {1}'",
",",
"device",
",",
"mount_path",
")",
")",
"return",
"True"
] |
Detects peaks from local maximum
|
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
| 4,250
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L521-L570
|
[
"def",
"StartGuiSession",
"(",
"self",
")",
":",
"from",
"UcsBase",
"import",
"WriteUcsWarning",
",",
"UcsUtils",
",",
"UcsValidationException",
"import",
"urllib",
",",
"tempfile",
",",
"fileinput",
",",
"os",
",",
"subprocess",
",",
"platform",
"osSupport",
"=",
"[",
"\"Windows\"",
",",
"\"Linux\"",
",",
"\"Microsoft\"",
"]",
"if",
"platform",
".",
"system",
"(",
")",
"not",
"in",
"osSupport",
":",
"raise",
"UcsValidationException",
"(",
"\"Currently works with Windows OS and Ubuntu\"",
")",
"# raise Exception(\"Currently works with Windows OS and Ubuntu\")",
"try",
":",
"javawsPath",
"=",
"UcsUtils",
".",
"GetJavaInstallationPath",
"(",
")",
"# print r\"%s\" %(javawsPath)",
"if",
"javawsPath",
"!=",
"None",
":",
"url",
"=",
"\"%s/ucsm/ucsm.jnlp\"",
"%",
"(",
"self",
".",
"Uri",
"(",
")",
")",
"source",
"=",
"urllib",
".",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
"jnlpdir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"jnlpfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"jnlpdir",
",",
"\"temp.jnlp\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"jnlpfile",
")",
":",
"os",
".",
"remove",
"(",
"jnlpfile",
")",
"jnlpFH",
"=",
"open",
"(",
"jnlpfile",
",",
"\"w+\"",
")",
"jnlpFH",
".",
"write",
"(",
"source",
")",
"jnlpFH",
".",
"close",
"(",
")",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"jnlpfile",
",",
"inplace",
"=",
"1",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'^\\s*</resources>\\s*$'",
",",
"line",
")",
":",
"print",
"'\\t<property name=\"log.show.encrypted\" value=\"true\"/>'",
"print",
"line",
",",
"subprocess",
".",
"call",
"(",
"[",
"javawsPath",
",",
"jnlpfile",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"jnlpfile",
")",
":",
"os",
".",
"remove",
"(",
"jnlpfile",
")",
"else",
":",
"return",
"None",
"except",
"Exception",
",",
"err",
":",
"fileinput",
".",
"close",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"jnlpfile",
")",
":",
"os",
".",
"remove",
"(",
"jnlpfile",
")",
"raise"
] |
Check each peak according to thresholds
|
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
| 4,251
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L573-L638
|
[
"def",
"create",
"(",
"self",
")",
":",
"# Ensure that an existing document will not be \"updated\"",
"doc",
"=",
"dict",
"(",
"self",
")",
"if",
"doc",
".",
"get",
"(",
"'_rev'",
")",
"is",
"not",
"None",
":",
"doc",
".",
"__delitem__",
"(",
"'_rev'",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"resp",
"=",
"self",
".",
"r_session",
".",
"post",
"(",
"self",
".",
"_database",
".",
"database_url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"doc",
",",
"cls",
"=",
"self",
".",
"encoder",
")",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"response_to_json_dict",
"(",
"resp",
")",
"super",
"(",
"Document",
",",
"self",
")",
".",
"__setitem__",
"(",
"'_id'",
",",
"data",
"[",
"'id'",
"]",
")",
"super",
"(",
"Document",
",",
"self",
")",
".",
"__setitem__",
"(",
"'_rev'",
",",
"data",
"[",
"'rev'",
"]",
")"
] |
Private function intended to insert a new RR interval in the 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
| 4,252
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L641-L678
|
[
"def",
"cublasGetVersion",
"(",
"handle",
")",
":",
"version",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcublas",
".",
"cublasGetVersion_v2",
"(",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"version",
")",
")",
"cublasCheckStatus",
"(",
"status",
")",
"return",
"version",
".",
"value"
] |
Function for generation of ECG Tachogram .
|
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
| 4,253
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/detect.py#L704-L750
|
[
"def",
"_place_secondary_files",
"(",
"inp_tool",
",",
"inp_binding",
"=",
"None",
")",
":",
"def",
"_is_file",
"(",
"val",
")",
":",
"return",
"(",
"val",
"==",
"\"File\"",
"or",
"(",
"isinstance",
"(",
"val",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"(",
"\"File\"",
"in",
"val",
"or",
"any",
"(",
"isinstance",
"(",
"x",
",",
"dict",
")",
"and",
"_is_file",
"(",
"val",
")",
")",
"for",
"x",
"in",
"val",
")",
")",
")",
"secondary_files",
"=",
"inp_tool",
".",
"pop",
"(",
"\"secondaryFiles\"",
",",
"None",
")",
"if",
"secondary_files",
":",
"key",
"=",
"[",
"]",
"while",
"(",
"not",
"_is_file",
"(",
"tz",
".",
"get_in",
"(",
"key",
"+",
"[",
"\"type\"",
"]",
",",
"inp_tool",
")",
")",
"and",
"not",
"_is_file",
"(",
"tz",
".",
"get_in",
"(",
"key",
"+",
"[",
"\"items\"",
"]",
",",
"inp_tool",
")",
")",
"and",
"not",
"_is_file",
"(",
"tz",
".",
"get_in",
"(",
"key",
"+",
"[",
"\"items\"",
",",
"\"items\"",
"]",
",",
"inp_tool",
")",
")",
")",
":",
"key",
".",
"append",
"(",
"\"type\"",
")",
"if",
"tz",
".",
"get_in",
"(",
"key",
",",
"inp_tool",
")",
":",
"inp_tool",
"[",
"\"secondaryFiles\"",
"]",
"=",
"secondary_files",
"elif",
"inp_binding",
":",
"nested_inp_binding",
"=",
"copy",
".",
"deepcopy",
"(",
"inp_binding",
")",
"nested_inp_binding",
"[",
"\"prefix\"",
"]",
"=",
"\"ignore=\"",
"nested_inp_binding",
"[",
"\"secondaryFiles\"",
"]",
"=",
"secondary_files",
"inp_tool",
"=",
"tz",
".",
"update_in",
"(",
"inp_tool",
",",
"key",
",",
"lambda",
"x",
":",
"nested_inp_binding",
")",
"return",
"inp_tool"
] |
Close serial port .
|
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 )
| 4,254
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L77-L85
|
[
"def",
"create_atomic_wrapper",
"(",
"cls",
",",
"wrapped_func",
")",
":",
"def",
"_create_atomic_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Actual wrapper.\"\"\"",
"# When a view call fails due to a permissions error, it raises an exception.",
"# An uncaught exception breaks the DB transaction for any following DB operations",
"# unless it's wrapped in a atomic() decorator or context manager.",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"return",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_create_atomic_wrapper"
] |
Parse received message .
|
def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . controller . feed_parser ( data )
| 4,255
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L87-L90
|
[
"def",
"requires_open_handle",
"(",
"method",
")",
":",
"# pylint: disable=invalid-name",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper_requiring_open_handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"The wrapper to be returned.\"\"\"",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"raise",
"usb_exceptions",
".",
"HandleClosedError",
"(",
")",
"return",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper_requiring_open_handle"
] |
Add message to write queue .
|
def send ( self , message , callback = None ) : assert isinstance ( message , velbus . Message ) self . _write_queue . put_nowait ( ( message , callback ) )
| 4,256
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L92-L95
|
[
"def",
"fingerprint",
"(",
"self",
",",
"option_type",
",",
"option_val",
")",
":",
"if",
"option_val",
"is",
"None",
":",
"return",
"None",
"# Wrapping all other values in a list here allows us to easily handle single-valued and",
"# list-valued options uniformly. For non-list-valued options, this will be a singleton list",
"# (with the exception of dict, which is not modified). This dict exception works because we do",
"# not currently have any \"list of dict\" type, so there is no ambiguity.",
"if",
"not",
"isinstance",
"(",
"option_val",
",",
"(",
"list",
",",
"tuple",
",",
"dict",
")",
")",
":",
"option_val",
"=",
"[",
"option_val",
"]",
"if",
"option_type",
"==",
"target_option",
":",
"return",
"self",
".",
"_fingerprint_target_specs",
"(",
"option_val",
")",
"elif",
"option_type",
"==",
"dir_option",
":",
"return",
"self",
".",
"_fingerprint_dirs",
"(",
"option_val",
")",
"elif",
"option_type",
"==",
"file_option",
":",
"return",
"self",
".",
"_fingerprint_files",
"(",
"option_val",
")",
"elif",
"option_type",
"==",
"dict_with_files_option",
":",
"return",
"self",
".",
"_fingerprint_dict_with_files",
"(",
"option_val",
")",
"else",
":",
"return",
"self",
".",
"_fingerprint_primitives",
"(",
"option_val",
")"
] |
Write thread .
|
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 ( )
| 4,257
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/connections/serial.py#L97-L106
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Set path locations from kytosd API .
|
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' ) )
| 4,258
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L69-L83
|
[
"def",
"_add_section",
"(",
"self",
",",
"section",
")",
":",
"section",
".",
"rid",
"=",
"0",
"plen",
"=",
"0",
"while",
"self",
".",
"_merge",
"and",
"self",
".",
"_sections",
"and",
"plen",
"!=",
"len",
"(",
"self",
".",
"_sections",
")",
":",
"plen",
"=",
"len",
"(",
"self",
".",
"_sections",
")",
"self",
".",
"_sections",
"=",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"_sections",
"if",
"not",
"section",
".",
"join",
"(",
"s",
")",
"]",
"self",
".",
"_sections",
".",
"append",
"(",
"section",
")"
] |
Set info about NApp .
|
def set_napp ( self , user , napp , version = None ) : self . user = user self . napp = napp self . version = version or 'latest'
| 4,259
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L85-L95
|
[
"def",
"delete_entity",
"(",
"self",
",",
"entity_id",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"'/v1/{mount_point}/entity/id/{id}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"id",
"=",
"entity_id",
",",
")",
"return",
"self",
".",
"_adapter",
".",
"delete",
"(",
"url",
"=",
"api_path",
",",
")"
] |
Get napp_dependencies from install NApp .
|
def dependencies ( self , user = None , napp = None ) : napps = self . _get_napp_key ( 'napp_dependencies' , user , napp ) return [ tuple ( napp . split ( '/' ) ) for napp in napps ]
| 4,260
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L129-L141
|
[
"def",
"compare_values",
"(",
"values0",
",",
"values1",
")",
":",
"values0",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values0",
"}",
"values1",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values1",
"}",
"created",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values1",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values0",
"]",
"deleted",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values1",
"]",
"modified",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"v",
"!=",
"values1",
".",
"get",
"(",
"k",
",",
"None",
")",
"]",
"return",
"created",
",",
"deleted",
",",
"modified"
] |
Return a value from kytos . json .
|
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 ''
| 4,261
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L151-L173
|
[
"def",
"sql_column_like_drug",
"(",
"self",
",",
"column_name",
":",
"str",
")",
"->",
"str",
":",
"clauses",
"=",
"[",
"\"{col} LIKE {fragment}\"",
".",
"format",
"(",
"col",
"=",
"column_name",
",",
"fragment",
"=",
"sql_string_literal",
"(",
"f",
")",
")",
"for",
"f",
"in",
"self",
".",
"sql_like_fragments",
"]",
"return",
"\"({})\"",
".",
"format",
"(",
"\" OR \"",
".",
"join",
"(",
"clauses",
")",
")"
] |
Disable a NApp if it is enabled .
|
def disable ( self ) : core_napps_manager = CoreNAppsManager ( base_path = self . _enabled ) core_napps_manager . disable ( self . user , self . napp )
| 4,262
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L175-L178
|
[
"def",
"decrypt_pillar",
"(",
"self",
",",
"pillar",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'decrypt_pillar'",
")",
":",
"decrypt_pillar",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar'",
"]",
"if",
"not",
"isinstance",
"(",
"decrypt_pillar",
",",
"dict",
")",
":",
"decrypt_pillar",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"repack_dictlist",
"(",
"self",
".",
"opts",
"[",
"'decrypt_pillar'",
"]",
")",
"if",
"not",
"decrypt_pillar",
":",
"errors",
".",
"append",
"(",
"'decrypt_pillar config option is malformed'",
")",
"for",
"key",
",",
"rend",
"in",
"six",
".",
"iteritems",
"(",
"decrypt_pillar",
")",
":",
"ptr",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict",
"(",
"pillar",
",",
"key",
",",
"default",
"=",
"None",
",",
"delimiter",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar_delimiter'",
"]",
")",
"if",
"ptr",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'Pillar key %s not present'",
",",
"key",
")",
"continue",
"try",
":",
"hash",
"(",
"ptr",
")",
"immutable",
"=",
"True",
"except",
"TypeError",
":",
"immutable",
"=",
"False",
"try",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"crypt",
".",
"decrypt",
"(",
"ptr",
",",
"rend",
"or",
"self",
".",
"opts",
"[",
"'decrypt_pillar_default'",
"]",
",",
"renderers",
"=",
"self",
".",
"rend",
",",
"opts",
"=",
"self",
".",
"opts",
",",
"valid_rend",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar_renderers'",
"]",
")",
"if",
"immutable",
":",
"# Since the key pointed to an immutable type, we need",
"# to replace it in the pillar dict. First we will find",
"# the parent, and then we will replace the child key",
"# with the return data from the renderer.",
"parent",
",",
"_",
",",
"child",
"=",
"key",
".",
"rpartition",
"(",
"self",
".",
"opts",
"[",
"'decrypt_pillar_delimiter'",
"]",
")",
"if",
"not",
"parent",
":",
"# key is a top-level key, so the pointer to the",
"# parent is the pillar dict itself.",
"ptr",
"=",
"pillar",
"else",
":",
"ptr",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict",
"(",
"pillar",
",",
"parent",
",",
"default",
"=",
"None",
",",
"delimiter",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar_delimiter'",
"]",
")",
"if",
"ptr",
"is",
"not",
"None",
":",
"ptr",
"[",
"child",
"]",
"=",
"ret",
"except",
"Exception",
"as",
"exc",
":",
"msg",
"=",
"'Failed to decrypt pillar key \\'{0}\\': {1}'",
".",
"format",
"(",
"key",
",",
"exc",
")",
"errors",
".",
"append",
"(",
"msg",
")",
"log",
".",
"error",
"(",
"msg",
",",
"exc_info",
"=",
"True",
")",
"return",
"errors"
] |
Enable a NApp if not already enabled .
|
def enable ( self ) : core_napps_manager = CoreNAppsManager ( base_path = self . _enabled ) core_napps_manager . enable ( self . user , self . napp )
| 4,263
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L188-L197
|
[
"def",
"decrypt_pillar",
"(",
"self",
",",
"pillar",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'decrypt_pillar'",
")",
":",
"decrypt_pillar",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar'",
"]",
"if",
"not",
"isinstance",
"(",
"decrypt_pillar",
",",
"dict",
")",
":",
"decrypt_pillar",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"repack_dictlist",
"(",
"self",
".",
"opts",
"[",
"'decrypt_pillar'",
"]",
")",
"if",
"not",
"decrypt_pillar",
":",
"errors",
".",
"append",
"(",
"'decrypt_pillar config option is malformed'",
")",
"for",
"key",
",",
"rend",
"in",
"six",
".",
"iteritems",
"(",
"decrypt_pillar",
")",
":",
"ptr",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict",
"(",
"pillar",
",",
"key",
",",
"default",
"=",
"None",
",",
"delimiter",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar_delimiter'",
"]",
")",
"if",
"ptr",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'Pillar key %s not present'",
",",
"key",
")",
"continue",
"try",
":",
"hash",
"(",
"ptr",
")",
"immutable",
"=",
"True",
"except",
"TypeError",
":",
"immutable",
"=",
"False",
"try",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"crypt",
".",
"decrypt",
"(",
"ptr",
",",
"rend",
"or",
"self",
".",
"opts",
"[",
"'decrypt_pillar_default'",
"]",
",",
"renderers",
"=",
"self",
".",
"rend",
",",
"opts",
"=",
"self",
".",
"opts",
",",
"valid_rend",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar_renderers'",
"]",
")",
"if",
"immutable",
":",
"# Since the key pointed to an immutable type, we need",
"# to replace it in the pillar dict. First we will find",
"# the parent, and then we will replace the child key",
"# with the return data from the renderer.",
"parent",
",",
"_",
",",
"child",
"=",
"key",
".",
"rpartition",
"(",
"self",
".",
"opts",
"[",
"'decrypt_pillar_delimiter'",
"]",
")",
"if",
"not",
"parent",
":",
"# key is a top-level key, so the pointer to the",
"# parent is the pillar dict itself.",
"ptr",
"=",
"pillar",
"else",
":",
"ptr",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict",
"(",
"pillar",
",",
"parent",
",",
"default",
"=",
"None",
",",
"delimiter",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar_delimiter'",
"]",
")",
"if",
"ptr",
"is",
"not",
"None",
":",
"ptr",
"[",
"child",
"]",
"=",
"ret",
"except",
"Exception",
"as",
"exc",
":",
"msg",
"=",
"'Failed to decrypt pillar key \\'{0}\\': {1}'",
".",
"format",
"(",
"key",
",",
"exc",
")",
"errors",
".",
"append",
"(",
"msg",
")",
"log",
".",
"error",
"(",
"msg",
",",
"exc_info",
"=",
"True",
")",
"return",
"errors"
] |
Delete code inside NApp directory if existent .
|
def uninstall ( self ) : if self . is_installed ( ) : installed = self . installed_dir ( ) if installed . is_symlink ( ) : installed . unlink ( ) else : shutil . rmtree ( str ( installed ) )
| 4,264
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L203-L210
|
[
"def",
"_wrap_tracebackexception_format",
"(",
"redact",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
")",
":",
"original_format",
"=",
"getattr",
"(",
"TracebackException",
",",
"'_original'",
",",
"None",
")",
"if",
"original_format",
"is",
"None",
":",
"original_format",
"=",
"TracebackException",
".",
"format",
"setattr",
"(",
"TracebackException",
",",
"'_original'",
",",
"original_format",
")",
"@",
"wraps",
"(",
"original_format",
")",
"def",
"tracebackexception_format",
"(",
"self",
",",
"*",
",",
"chain",
"=",
"True",
")",
":",
"for",
"line",
"in",
"original_format",
"(",
"self",
",",
"chain",
"=",
"chain",
")",
":",
"yield",
"redact",
"(",
"line",
")",
"setattr",
"(",
"TracebackException",
",",
"'format'",
",",
"tracebackexception_format",
")"
] |
Render Jinja2 template for a NApp structure .
|
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 )
| 4,265
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L223-L229
|
[
"def",
"split",
"(",
"self",
",",
"verbose",
"=",
"None",
",",
"end_in_new_line",
"=",
"None",
")",
":",
"elapsed_time",
"=",
"self",
".",
"get_elapsed_time",
"(",
")",
"self",
".",
"split_elapsed_time",
".",
"append",
"(",
"elapsed_time",
")",
"self",
".",
"_cumulative_elapsed_time",
"+=",
"elapsed_time",
"self",
".",
"_elapsed_time",
"=",
"datetime",
".",
"timedelta",
"(",
")",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose_end",
"if",
"verbose",
":",
"if",
"end_in_new_line",
"is",
"None",
":",
"end_in_new_line",
"=",
"self",
".",
"end_in_new_line",
"if",
"end_in_new_line",
":",
"self",
".",
"log",
"(",
"\"{} done in {}\"",
".",
"format",
"(",
"self",
".",
"description",
",",
"elapsed_time",
")",
")",
"else",
":",
"self",
".",
"log",
"(",
"\" done in {}\"",
".",
"format",
"(",
"elapsed_time",
")",
")",
"self",
".",
"_start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")"
] |
Search all server NApps matching pattern .
|
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 ) ]
| 4,266
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L232-L249
|
[
"def",
"store",
"(",
"self",
",",
"correlation_id",
",",
"key",
",",
"credential",
")",
":",
"if",
"credential",
"!=",
"None",
":",
"self",
".",
"_items",
".",
"put",
"(",
"key",
",",
"credential",
")",
"else",
":",
"self",
".",
"_items",
".",
"remove",
"(",
"key",
")"
] |
Make a symlink in install folder to a local NApp .
|
def install_local ( self ) : folder = self . _get_local_folder ( ) installed = self . installed_dir ( ) self . _check_module ( installed . parent ) installed . symlink_to ( folder . resolve ( ) )
| 4,267
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L251-L261
|
[
"def",
"load_toml_rest_api_config",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Skipping rest api loading from non-existent config file: %s\"",
",",
"filename",
")",
"return",
"RestApiConfig",
"(",
")",
"LOGGER",
".",
"info",
"(",
"\"Loading rest api information from config: %s\"",
",",
"filename",
")",
"try",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fd",
":",
"raw_config",
"=",
"fd",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"RestApiConfigurationError",
"(",
"\"Unable to load rest api configuration file: {}\"",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"toml_config",
"=",
"toml",
".",
"loads",
"(",
"raw_config",
")",
"invalid_keys",
"=",
"set",
"(",
"toml_config",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"[",
"'bind'",
",",
"'connect'",
",",
"'timeout'",
",",
"'opentsdb_db'",
",",
"'opentsdb_url'",
",",
"'opentsdb_username'",
",",
"'opentsdb_password'",
",",
"'client_max_size'",
"]",
")",
"if",
"invalid_keys",
":",
"raise",
"RestApiConfigurationError",
"(",
"\"Invalid keys in rest api config: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"list",
"(",
"invalid_keys",
")",
")",
")",
")",
")",
"config",
"=",
"RestApiConfig",
"(",
"bind",
"=",
"toml_config",
".",
"get",
"(",
"\"bind\"",
",",
"None",
")",
",",
"connect",
"=",
"toml_config",
".",
"get",
"(",
"'connect'",
",",
"None",
")",
",",
"timeout",
"=",
"toml_config",
".",
"get",
"(",
"'timeout'",
",",
"None",
")",
",",
"opentsdb_url",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_url'",
",",
"None",
")",
",",
"opentsdb_db",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_db'",
",",
"None",
")",
",",
"opentsdb_username",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_username'",
",",
"None",
")",
",",
"opentsdb_password",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_password'",
",",
"None",
")",
",",
"client_max_size",
"=",
"toml_config",
".",
"get",
"(",
"'client_max_size'",
",",
"None",
")",
")",
"return",
"config"
] |
Return local NApp root folder .
|
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.' )
| 4,268
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L263-L290
|
[
"def",
"get_active_token",
"(",
"self",
")",
":",
"expire_time",
"=",
"self",
".",
"store_handler",
".",
"has_value",
"(",
"\"expires\"",
")",
"access_token",
"=",
"self",
".",
"store_handler",
".",
"has_value",
"(",
"\"access_token\"",
")",
"if",
"expire_time",
"and",
"access_token",
":",
"expire_time",
"=",
"self",
".",
"store_handler",
".",
"get_value",
"(",
"\"expires\"",
")",
"if",
"not",
"datetime",
".",
"now",
"(",
")",
"<",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",
"expire_time",
")",
")",
":",
"self",
".",
"store_handler",
".",
"delete_value",
"(",
"\"access_token\"",
")",
"self",
".",
"store_handler",
".",
"delete_value",
"(",
"\"expires\"",
")",
"logger",
".",
"info",
"(",
"'Access token expired, going to get new token'",
")",
"self",
".",
"auth",
"(",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Access token noy expired yet'",
")",
"else",
":",
"self",
".",
"auth",
"(",
")",
"return",
"self",
".",
"store_handler",
".",
"get_value",
"(",
"\"access_token\"",
")"
] |
Download extract and install NApp .
|
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 ) )
| 4,269
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L292-L307
|
[
"def",
"on_response",
"(",
"self",
",",
"ch",
",",
"method_frame",
",",
"props",
",",
"body",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"rabbitmq.Requester.on_response\"",
")",
"if",
"self",
".",
"corr_id",
"==",
"props",
".",
"correlation_id",
":",
"self",
".",
"response",
"=",
"{",
"'props'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
"else",
":",
"LOGGER",
".",
"warn",
"(",
"\"rabbitmq.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"props",
".",
"correlation_id",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
")",
")"
] |
Download NApp package from server .
|
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 ]
| 4,270
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L309-L322
|
[
"async",
"def",
"_notify_event_internal",
"(",
"self",
",",
"conn_string",
",",
"name",
",",
"event",
")",
":",
"try",
":",
"self",
".",
"_currently_notifying",
"=",
"True",
"conn_id",
"=",
"self",
".",
"_get_conn_id",
"(",
"conn_string",
")",
"event_maps",
"=",
"self",
".",
"_monitors",
".",
"get",
"(",
"conn_string",
",",
"{",
"}",
")",
"wildcard_maps",
"=",
"self",
".",
"_monitors",
".",
"get",
"(",
"None",
",",
"{",
"}",
")",
"wildcard_handlers",
"=",
"wildcard_maps",
".",
"get",
"(",
"name",
",",
"{",
"}",
")",
"event_handlers",
"=",
"event_maps",
".",
"get",
"(",
"name",
",",
"{",
"}",
")",
"for",
"handler",
",",
"func",
"in",
"itertools",
".",
"chain",
"(",
"event_handlers",
".",
"items",
"(",
")",
",",
"wildcard_handlers",
".",
"items",
"(",
")",
")",
":",
"try",
":",
"result",
"=",
"func",
"(",
"conn_string",
",",
"conn_id",
",",
"name",
",",
"event",
")",
"if",
"inspect",
".",
"isawaitable",
"(",
"result",
")",
":",
"await",
"result",
"except",
":",
"#pylint:disable=bare-except;This is a background function and we are logging exceptions",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"Error calling notification callback id=%s, func=%s\"",
",",
"handler",
",",
"func",
",",
"exc_info",
"=",
"True",
")",
"finally",
":",
"for",
"action",
"in",
"self",
".",
"_deferred_adjustments",
":",
"self",
".",
"_adjust_monitor_internal",
"(",
"*",
"action",
")",
"self",
".",
"_deferred_adjustments",
"=",
"[",
"]",
"self",
".",
"_currently_notifying",
"=",
"False"
] |
Extract package to a temporary folder .
|
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 )
| 4,271
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L325-L337
|
[
"def",
"keyPressEvent",
"(",
"self",
",",
"evt",
")",
":",
"incr",
"=",
"0",
"if",
"evt",
".",
"modifiers",
"(",
")",
"==",
"Qt",
".",
"ControlModifier",
":",
"n",
"=",
"self",
".",
"tabWidget",
".",
"count",
"(",
")",
"if",
"evt",
".",
"key",
"(",
")",
"in",
"[",
"Qt",
".",
"Key_PageUp",
",",
"Qt",
".",
"Key_Backtab",
"]",
":",
"incr",
"=",
"-",
"1",
"elif",
"evt",
".",
"key",
"(",
")",
"in",
"[",
"Qt",
".",
"Key_PageDown",
",",
"Qt",
".",
"Key_Tab",
"]",
":",
"incr",
"=",
"1",
"if",
"incr",
"!=",
"0",
":",
"new_index",
"=",
"self",
".",
"_get_tab_index",
"(",
")",
"+",
"incr",
"if",
"new_index",
"<",
"0",
":",
"new_index",
"=",
"n",
"-",
"1",
"elif",
"new_index",
">=",
"n",
":",
"new_index",
"=",
"0",
"self",
".",
"tabWidget",
".",
"setCurrentIndex",
"(",
"new_index",
")"
] |
Bootstrap a basic NApp structure for you to develop your NApp .
|
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!' )
| 4,272
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L340-L412
|
[
"def",
"get_last_components_by_type",
"(",
"component_types",
",",
"topic_id",
",",
"db_conn",
"=",
"None",
")",
":",
"db_conn",
"=",
"db_conn",
"or",
"flask",
".",
"g",
".",
"db_conn",
"schedule_components_ids",
"=",
"[",
"]",
"for",
"ct",
"in",
"component_types",
":",
"where_clause",
"=",
"sql",
".",
"and_",
"(",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"type",
"==",
"ct",
",",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"topic_id",
"==",
"topic_id",
",",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"export_control",
"==",
"True",
",",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"state",
"==",
"'active'",
")",
"# noqa",
"query",
"=",
"(",
"sql",
".",
"select",
"(",
"[",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"id",
"]",
")",
".",
"where",
"(",
"where_clause",
")",
".",
"order_by",
"(",
"sql",
".",
"desc",
"(",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"created_at",
")",
")",
")",
"cmpt_id",
"=",
"db_conn",
".",
"execute",
"(",
"query",
")",
".",
"fetchone",
"(",
")",
"if",
"cmpt_id",
"is",
"None",
":",
"msg",
"=",
"'Component of type \"%s\" not found or not exported.'",
"%",
"ct",
"raise",
"dci_exc",
".",
"DCIException",
"(",
"msg",
",",
"status_code",
"=",
"412",
")",
"cmpt_id",
"=",
"cmpt_id",
"[",
"0",
"]",
"if",
"cmpt_id",
"in",
"schedule_components_ids",
":",
"msg",
"=",
"(",
"'Component types %s malformed: type %s duplicated.'",
"%",
"(",
"component_types",
",",
"ct",
")",
")",
"raise",
"dci_exc",
".",
"DCIException",
"(",
"msg",
",",
"status_code",
"=",
"412",
")",
"schedule_components_ids",
".",
"append",
"(",
"cmpt_id",
")",
"return",
"schedule_components_ids"
] |
Create the ui directory structure .
|
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 )
| 4,273
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L415-L430
|
[
"def",
"add_item",
"(",
"self",
",",
"item_url",
",",
"item_metadata",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"DELETE FROM items WHERE url=?\"",
",",
"(",
"str",
"(",
"item_url",
")",
",",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"c",
".",
"execute",
"(",
"\"INSERT INTO items VALUES (?, ?, ?)\"",
",",
"(",
"str",
"(",
"item_url",
")",
",",
"item_metadata",
",",
"self",
".",
"__now_iso_8601",
"(",
")",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"c",
".",
"close",
"(",
")"
] |
Build the . napp file to be sent to the napps server .
|
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
| 4,274
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L444-L478
|
[
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",
"query",
"[",
"'workspace_members'",
"]",
"=",
"userid",
"workspaces",
"=",
"[",
"IWorkspace",
"(",
"b",
".",
"_unrestrictedGetObject",
"(",
")",
")",
"for",
"b",
"in",
"catalog",
".",
"unrestrictedSearchResults",
"(",
"query",
")",
"]",
"for",
"workspace",
"in",
"workspaces",
":",
"workspace",
".",
"remove_from_team",
"(",
"userid",
")"
] |
Generate the metadata to send the napp package .
|
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
| 4,275
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L481-L510
|
[
"def",
"removeAllChildrenAtIndex",
"(",
"self",
",",
"parentIndex",
")",
":",
"if",
"not",
"parentIndex",
".",
"isValid",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"No valid item selected for deletion (ignored).\"",
")",
"return",
"parentItem",
"=",
"self",
".",
"getItem",
"(",
"parentIndex",
",",
"None",
")",
"logger",
".",
"debug",
"(",
"\"Removing children of {!r}\"",
".",
"format",
"(",
"parentItem",
")",
")",
"assert",
"parentItem",
",",
"\"parentItem not found\"",
"#firstChildRow = self.index(0, 0, parentIndex).row()",
"#lastChildRow = self.index(parentItem.nChildren()-1, 0, parentIndex).row()",
"#logger.debug(\"Removing rows: {} to {}\".format(firstChildRow, lastChildRow))",
"#self.beginRemoveRows(parentIndex, firstChildRow, lastChildRow)",
"self",
".",
"beginRemoveRows",
"(",
"parentIndex",
",",
"0",
",",
"parentItem",
".",
"nChildren",
"(",
")",
"-",
"1",
")",
"try",
":",
"parentItem",
".",
"removeAllChildren",
"(",
")",
"finally",
":",
"self",
".",
"endRemoveRows",
"(",
")",
"logger",
".",
"debug",
"(",
"\"removeAllChildrenAtIndex completed\"",
")"
] |
Create package and upload it to NApps Server .
|
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 )
| 4,276
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L512-L523
|
[
"def",
"fromjson",
"(",
"cls",
",",
"json_string",
":",
"str",
")",
"->",
"'Event'",
":",
"obj",
"=",
"json",
".",
"loads",
"(",
"json_string",
")",
"return",
"cls",
"(",
"UUID",
"(",
"obj",
"[",
"'event_id'",
"]",
")",
",",
"obj",
"[",
"'event_type'",
"]",
",",
"obj",
"[",
"'schema_name'",
"]",
",",
"obj",
"[",
"'table_name'",
"]",
",",
"obj",
"[",
"'row_id'",
"]",
")"
] |
Prepare NApp to be uploaded by creating openAPI skeleton .
|
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 ( )
| 4,277
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L536-L543
|
[
"def",
"get_teb_address",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_teb_ptr",
"except",
"AttributeError",
":",
"try",
":",
"hThread",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"THREAD_QUERY_INFORMATION",
")",
"tbi",
"=",
"win32",
".",
"NtQueryInformationThread",
"(",
"hThread",
",",
"win32",
".",
"ThreadBasicInformation",
")",
"address",
"=",
"tbi",
".",
"TebBaseAddress",
"except",
"WindowsError",
":",
"address",
"=",
"self",
".",
"get_linear_address",
"(",
"'SegFs'",
",",
"0",
")",
"# fs:[0]",
"if",
"not",
"address",
":",
"raise",
"self",
".",
"_teb_ptr",
"=",
"address",
"return",
"address"
] |
Reload a NApp or all NApps .
|
def reload ( self , napps = None ) : client = NAppsClient ( self . _config ) client . reload_napps ( napps )
| 4,278
|
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L565-L575
|
[
"def",
"_run_cmdfinalization_hooks",
"(",
"self",
",",
"stop",
":",
"bool",
",",
"statement",
":",
"Optional",
"[",
"Statement",
"]",
")",
"->",
"bool",
":",
"with",
"self",
".",
"sigint_protection",
":",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
"and",
"self",
".",
"stdout",
".",
"isatty",
"(",
")",
":",
"# Before the next command runs, fix any terminal problems like those",
"# caused by certain binary characters having been printed to it.",
"import",
"subprocess",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'stty'",
",",
"'sane'",
"]",
")",
"proc",
".",
"communicate",
"(",
")",
"try",
":",
"data",
"=",
"plugin",
".",
"CommandFinalizationData",
"(",
"stop",
",",
"statement",
")",
"for",
"func",
"in",
"self",
".",
"_cmdfinalization_hooks",
":",
"data",
"=",
"func",
"(",
"data",
")",
"# retrieve the final value of stop, ignoring any",
"# modifications to the statement",
"return",
"data",
".",
"stop",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"perror",
"(",
"ex",
")"
] |
Given a large image return the thumbnail url
|
def _get_thumbnail_url ( image ) : lhs , rhs = splitext ( image . url ) lhs += THUMB_EXT thumb_url = f'{lhs}{rhs}' return thumb_url
| 4,279
|
https://github.com/manikos/django-progressiveimagefield/blob/a432c79d23d87ea8944ac252ae7d15df1e4f3072/progressiveimagefield/templatetags/progressive_tags.py#L24-L29
|
[
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Create a client from environment variable settings .
|
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
| 4,280
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L107-L151
|
[
"def",
"uunion1d",
"(",
"arr1",
",",
"arr2",
")",
":",
"v",
"=",
"np",
".",
"union1d",
"(",
"arr1",
",",
"arr2",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v",
",",
"[",
"arr1",
",",
"arr2",
"]",
")",
"return",
"v"
] |
Build the correct API url .
|
def _build_url ( self , resource , * * kwargs ) : # type: (str, **str) -> str return urljoin ( self . api_root , API_PATH [ resource ] . format ( * * kwargs ) )
| 4,281
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L184-L187
|
[
"def",
"_generate_noise_system",
"(",
"dimensions_tr",
",",
"spatial_sd",
",",
"temporal_sd",
",",
"spatial_noise_type",
"=",
"'gaussian'",
",",
"temporal_noise_type",
"=",
"'gaussian'",
",",
")",
":",
"def",
"noise_volume",
"(",
"dimensions",
",",
"noise_type",
",",
")",
":",
"if",
"noise_type",
"==",
"'rician'",
":",
"# Generate the Rician noise (has an SD of 1)",
"noise",
"=",
"stats",
".",
"rice",
".",
"rvs",
"(",
"b",
"=",
"0",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1.527",
",",
"size",
"=",
"dimensions",
")",
"elif",
"noise_type",
"==",
"'exponential'",
":",
"# Make an exponential distribution (has an SD of 1)",
"noise",
"=",
"stats",
".",
"expon",
".",
"rvs",
"(",
"0",
",",
"scale",
"=",
"1",
",",
"size",
"=",
"dimensions",
")",
"elif",
"noise_type",
"==",
"'gaussian'",
":",
"noise",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"np",
".",
"prod",
"(",
"dimensions",
")",
")",
".",
"reshape",
"(",
"dimensions",
")",
"# Return the noise",
"return",
"noise",
"# Get just the xyz coordinates",
"dimensions",
"=",
"np",
".",
"asarray",
"(",
"[",
"dimensions_tr",
"[",
"0",
"]",
",",
"dimensions_tr",
"[",
"1",
"]",
",",
"dimensions_tr",
"[",
"2",
"]",
",",
"1",
"]",
")",
"# Generate noise",
"spatial_noise",
"=",
"noise_volume",
"(",
"dimensions",
",",
"spatial_noise_type",
")",
"temporal_noise",
"=",
"noise_volume",
"(",
"dimensions_tr",
",",
"temporal_noise_type",
")",
"# Make the system noise have a specific spatial variability",
"spatial_noise",
"*=",
"spatial_sd",
"# Set the size of the noise",
"temporal_noise",
"*=",
"temporal_sd",
"# The mean in time of system noise needs to be zero, so subtract the",
"# means of the temporal noise in time",
"temporal_noise_mean",
"=",
"np",
".",
"mean",
"(",
"temporal_noise",
",",
"3",
")",
".",
"reshape",
"(",
"dimensions",
"[",
"0",
"]",
",",
"dimensions",
"[",
"1",
"]",
",",
"dimensions",
"[",
"2",
"]",
",",
"1",
")",
"temporal_noise",
"=",
"temporal_noise",
"-",
"temporal_noise_mean",
"# Save the combination",
"system_noise",
"=",
"spatial_noise",
"+",
"temporal_noise",
"return",
"system_noise"
] |
Retrieve user objects of the entire administration .
|
def _retrieve_users ( self ) : users_url = self . _build_url ( 'users' ) response = self . _request ( 'GET' , users_url ) users = response . json ( ) return users
| 4,282
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L189-L201
|
[
"def",
"stop_capture",
"(",
"self",
")",
":",
"if",
"self",
".",
"_capture_node",
":",
"yield",
"from",
"self",
".",
"_capture_node",
"[",
"\"node\"",
"]",
".",
"post",
"(",
"\"/adapters/{adapter_number}/ports/{port_number}/stop_capture\"",
".",
"format",
"(",
"adapter_number",
"=",
"self",
".",
"_capture_node",
"[",
"\"adapter_number\"",
"]",
",",
"port_number",
"=",
"self",
".",
"_capture_node",
"[",
"\"port_number\"",
"]",
")",
")",
"self",
".",
"_capture_node",
"=",
"None",
"yield",
"from",
"super",
"(",
")",
".",
"stop_capture",
"(",
")"
] |
Perform the request on the API .
|
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
| 4,283
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L203-L214
|
[
"def",
"upload_cbn_dir",
"(",
"dir_path",
",",
"manager",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"jfg_path",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"if",
"not",
"jfg_path",
".",
"endswith",
"(",
"'.jgf'",
")",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"jfg_path",
")",
"log",
".",
"info",
"(",
"'opening %s'",
",",
"path",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"cbn_jgif_dict",
"=",
"json",
".",
"load",
"(",
"f",
")",
"graph",
"=",
"pybel",
".",
"from_cbn_jgif",
"(",
"cbn_jgif_dict",
")",
"out_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"jfg_path",
".",
"replace",
"(",
"'.jgf'",
",",
"'.bel'",
")",
")",
"with",
"open",
"(",
"out_path",
",",
"'w'",
")",
"as",
"o",
":",
"pybel",
".",
"to_bel",
"(",
"graph",
",",
"o",
")",
"strip_annotations",
"(",
"graph",
")",
"enrich_pubmed_citations",
"(",
"manager",
"=",
"manager",
",",
"graph",
"=",
"graph",
")",
"pybel",
".",
"to_database",
"(",
"graph",
",",
"manager",
"=",
"manager",
")",
"log",
".",
"info",
"(",
"''",
")",
"log",
".",
"info",
"(",
"'done in %.2f'",
",",
"time",
".",
"time",
"(",
")",
"-",
"t",
")"
] |
List of the versions of the internal KE - chain app modules .
|
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
| 4,284
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L217-L233
|
[
"def",
"_groups_or_na_fun",
"(",
"regex",
")",
":",
"if",
"regex",
".",
"groups",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"pattern contains no capture groups\"",
")",
"empty_row",
"=",
"[",
"np",
".",
"nan",
"]",
"*",
"regex",
".",
"groups",
"def",
"f",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"empty_row",
"m",
"=",
"regex",
".",
"search",
"(",
"x",
")",
"if",
"m",
":",
"return",
"[",
"np",
".",
"nan",
"if",
"item",
"is",
"None",
"else",
"item",
"for",
"item",
"in",
"m",
".",
"groups",
"(",
")",
"]",
"else",
":",
"return",
"empty_row",
"return",
"f"
] |
Match app version against a semantic version string .
|
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' ) ) )
| 4,285
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L235-L288
|
[
"def",
"sys_wait_for_event",
"(",
"mask",
":",
"int",
",",
"k",
":",
"Optional",
"[",
"Key",
"]",
",",
"m",
":",
"Optional",
"[",
"Mouse",
"]",
",",
"flush",
":",
"bool",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_sys_wait_for_event",
"(",
"mask",
",",
"k",
".",
"key_p",
"if",
"k",
"else",
"ffi",
".",
"NULL",
",",
"m",
".",
"mouse_p",
"if",
"m",
"else",
"ffi",
".",
"NULL",
",",
"flush",
",",
")",
")"
] |
Reload an object from server . This method is immutable and will return a new object .
|
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 )
| 4,286
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L290-L310
|
[
"def",
"correspondence",
"(",
"soup",
")",
":",
"correspondence",
"=",
"[",
"]",
"author_notes_nodes",
"=",
"raw_parser",
".",
"author_notes",
"(",
"soup",
")",
"if",
"author_notes_nodes",
":",
"corresp_nodes",
"=",
"raw_parser",
".",
"corresp",
"(",
"author_notes_nodes",
")",
"for",
"tag",
"in",
"corresp_nodes",
":",
"correspondence",
".",
"append",
"(",
"tag",
".",
"text",
")",
"return",
"correspondence"
] |
Return a single scope based on the provided name .
|
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 ]
| 4,287
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L362-L380
|
[
"def",
"generate_http_manifest",
"(",
"self",
")",
":",
"base_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"translate_path",
"(",
"self",
".",
"path",
")",
")",
"self",
".",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"base_path",
")",
"admin_metadata_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"\".dtool\"",
",",
"\"dtool\"",
")",
"with",
"open",
"(",
"admin_metadata_fpath",
")",
"as",
"fh",
":",
"admin_metadata",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"http_manifest",
"=",
"{",
"\"admin_metadata\"",
":",
"admin_metadata",
",",
"\"manifest_url\"",
":",
"self",
".",
"generate_url",
"(",
"\".dtool/manifest.json\"",
")",
",",
"\"readme_url\"",
":",
"self",
".",
"generate_url",
"(",
"\"README.yml\"",
")",
",",
"\"overlays\"",
":",
"self",
".",
"generate_overlay_urls",
"(",
")",
",",
"\"item_urls\"",
":",
"self",
".",
"generate_item_urls",
"(",
")",
"}",
"return",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"http_manifest",
")",
",",
"\"utf-8\"",
")"
] |
Search for activities with optional name pk and scope filter .
|
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' ] ]
| 4,288
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L382-L425
|
[
"def",
"generate_http_manifest",
"(",
"self",
")",
":",
"base_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"translate_path",
"(",
"self",
".",
"path",
")",
")",
"self",
".",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"base_path",
")",
"admin_metadata_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"\".dtool\"",
",",
"\"dtool\"",
")",
"with",
"open",
"(",
"admin_metadata_fpath",
")",
"as",
"fh",
":",
"admin_metadata",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"http_manifest",
"=",
"{",
"\"admin_metadata\"",
":",
"admin_metadata",
",",
"\"manifest_url\"",
":",
"self",
".",
"generate_url",
"(",
"\".dtool/manifest.json\"",
")",
",",
"\"readme_url\"",
":",
"self",
".",
"generate_url",
"(",
"\"README.yml\"",
")",
",",
"\"overlays\"",
":",
"self",
".",
"generate_overlay_urls",
"(",
")",
",",
"\"item_urls\"",
":",
"self",
".",
"generate_item_urls",
"(",
")",
"}",
"return",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"http_manifest",
")",
",",
"\"utf-8\"",
")"
] |
Search for a single activity .
|
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 ]
| 4,289
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L427-L451
|
[
"def",
"_fetch_secrets",
"(",
"vault_url",
",",
"path",
",",
"token",
")",
":",
"url",
"=",
"_url_joiner",
"(",
"vault_url",
",",
"'v1'",
",",
"path",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"VaultLoader",
".",
"_get_headers",
"(",
"token",
")",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"resp",
".",
"json",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'errors'",
")",
":",
"raise",
"VaultException",
"(",
"u'Error fetching Vault secrets from path {}: {}'",
".",
"format",
"(",
"path",
",",
"data",
"[",
"'errors'",
"]",
")",
")",
"return",
"data",
"[",
"'data'",
"]"
] |
Retrieve multiple KE - chain 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 # 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 ) )
| 4,290
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L453-L551
|
[
"def",
"check_with_uniform",
"(",
"uf",
",",
"arg_shapes",
",",
"dim",
"=",
"None",
",",
"npuf",
"=",
"None",
",",
"rmin",
"=",
"-",
"10",
",",
"type_list",
"=",
"[",
"np",
".",
"float32",
"]",
")",
":",
"if",
"isinstance",
"(",
"arg_shapes",
",",
"int",
")",
":",
"assert",
"dim",
"shape",
"=",
"tuple",
"(",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"int",
"(",
"1000",
"**",
"(",
"1.0",
"/",
"dim",
")",
")",
",",
"size",
"=",
"dim",
")",
")",
"arg_shapes",
"=",
"[",
"shape",
"]",
"*",
"arg_shapes",
"for",
"dtype",
"in",
"type_list",
":",
"ndarray_arg",
"=",
"[",
"]",
"numpy_arg",
"=",
"[",
"]",
"for",
"s",
"in",
"arg_shapes",
":",
"npy",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"rmin",
",",
"10",
",",
"s",
")",
".",
"astype",
"(",
"dtype",
")",
"narr",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"npy",
",",
"dtype",
"=",
"dtype",
")",
"ndarray_arg",
".",
"append",
"(",
"narr",
")",
"numpy_arg",
".",
"append",
"(",
"npy",
")",
"out1",
"=",
"uf",
"(",
"*",
"ndarray_arg",
")",
"if",
"npuf",
"is",
"None",
":",
"out2",
"=",
"uf",
"(",
"*",
"numpy_arg",
")",
".",
"astype",
"(",
"dtype",
")",
"else",
":",
"out2",
"=",
"npuf",
"(",
"*",
"numpy_arg",
")",
".",
"astype",
"(",
"dtype",
")",
"assert",
"out1",
".",
"shape",
"==",
"out2",
".",
"shape",
"if",
"isinstance",
"(",
"out1",
",",
"mx",
".",
"nd",
".",
"NDArray",
")",
":",
"out1",
"=",
"out1",
".",
"asnumpy",
"(",
")",
"if",
"dtype",
"==",
"np",
".",
"float16",
":",
"assert",
"reldiff",
"(",
"out1",
",",
"out2",
")",
"<",
"2e-3",
"else",
":",
"assert",
"reldiff",
"(",
"out1",
",",
"out2",
")",
"<",
"1e-6"
] |
Retrieve single KE - chain part .
|
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 ]
| 4,291
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L553-L574
|
[
"def",
"check_with_uniform",
"(",
"uf",
",",
"arg_shapes",
",",
"dim",
"=",
"None",
",",
"npuf",
"=",
"None",
",",
"rmin",
"=",
"-",
"10",
",",
"type_list",
"=",
"[",
"np",
".",
"float32",
"]",
")",
":",
"if",
"isinstance",
"(",
"arg_shapes",
",",
"int",
")",
":",
"assert",
"dim",
"shape",
"=",
"tuple",
"(",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"int",
"(",
"1000",
"**",
"(",
"1.0",
"/",
"dim",
")",
")",
",",
"size",
"=",
"dim",
")",
")",
"arg_shapes",
"=",
"[",
"shape",
"]",
"*",
"arg_shapes",
"for",
"dtype",
"in",
"type_list",
":",
"ndarray_arg",
"=",
"[",
"]",
"numpy_arg",
"=",
"[",
"]",
"for",
"s",
"in",
"arg_shapes",
":",
"npy",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"rmin",
",",
"10",
",",
"s",
")",
".",
"astype",
"(",
"dtype",
")",
"narr",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"npy",
",",
"dtype",
"=",
"dtype",
")",
"ndarray_arg",
".",
"append",
"(",
"narr",
")",
"numpy_arg",
".",
"append",
"(",
"npy",
")",
"out1",
"=",
"uf",
"(",
"*",
"ndarray_arg",
")",
"if",
"npuf",
"is",
"None",
":",
"out2",
"=",
"uf",
"(",
"*",
"numpy_arg",
")",
".",
"astype",
"(",
"dtype",
")",
"else",
":",
"out2",
"=",
"npuf",
"(",
"*",
"numpy_arg",
")",
".",
"astype",
"(",
"dtype",
")",
"assert",
"out1",
".",
"shape",
"==",
"out2",
".",
"shape",
"if",
"isinstance",
"(",
"out1",
",",
"mx",
".",
"nd",
".",
"NDArray",
")",
":",
"out1",
"=",
"out1",
".",
"asnumpy",
"(",
")",
"if",
"dtype",
"==",
"np",
".",
"float16",
":",
"assert",
"reldiff",
"(",
"out1",
",",
"out2",
")",
"<",
"2e-3",
"else",
":",
"assert",
"reldiff",
"(",
"out1",
",",
"out2",
")",
"<",
"1e-6"
] |
Retrieve single KE - chain part model .
|
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 ]
| 4,292
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L576-L598
|
[
"def",
"interpoled_resampling",
"(",
"W",
",",
"x",
")",
":",
"N",
"=",
"W",
".",
"shape",
"[",
"0",
"]",
"idx",
"=",
"np",
".",
"argsort",
"(",
"x",
")",
"xs",
"=",
"x",
"[",
"idx",
"]",
"ws",
"=",
"W",
"[",
"idx",
"]",
"cs",
"=",
"np",
".",
"cumsum",
"(",
"avg_n_nplusone",
"(",
"ws",
")",
")",
"u",
"=",
"random",
".",
"rand",
"(",
"N",
")",
"xrs",
"=",
"np",
".",
"empty",
"(",
"N",
")",
"where",
"=",
"np",
".",
"searchsorted",
"(",
"cs",
",",
"u",
")",
"# costs O(N log(N)) but algorithm has O(N log(N)) complexity anyway",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"m",
"=",
"where",
"[",
"n",
"]",
"if",
"m",
"==",
"0",
":",
"xrs",
"[",
"n",
"]",
"=",
"xs",
"[",
"0",
"]",
"elif",
"m",
"==",
"N",
":",
"xrs",
"[",
"n",
"]",
"=",
"xs",
"[",
"-",
"1",
"]",
"else",
":",
"xrs",
"[",
"n",
"]",
"=",
"interpol",
"(",
"cs",
"[",
"m",
"-",
"1",
"]",
",",
"cs",
"[",
"m",
"]",
",",
"xs",
"[",
"m",
"-",
"1",
"]",
",",
"xs",
"[",
"m",
"]",
",",
"u",
"[",
"n",
"]",
")",
"return",
"xrs"
] |
Retrieve single KE - chain Property .
|
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 ]
| 4,293
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L600-L621
|
[
"def",
"_generate_examples_validation",
"(",
"self",
",",
"archive",
",",
"labels",
")",
":",
"# Get the current random seeds.",
"numpy_st0",
"=",
"np",
".",
"random",
".",
"get_state",
"(",
")",
"# Set new random seeds.",
"np",
".",
"random",
".",
"seed",
"(",
"135",
")",
"logging",
".",
"warning",
"(",
"'Overwriting cv2 RNG seed.'",
")",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"setRNGSeed",
"(",
"357",
")",
"for",
"example",
"in",
"super",
"(",
"Imagenet2012Corrupted",
",",
"self",
")",
".",
"_generate_examples_validation",
"(",
"archive",
",",
"labels",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"tf_img",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"example",
"[",
"'image'",
"]",
".",
"read",
"(",
")",
",",
"channels",
"=",
"3",
")",
"image_np",
"=",
"tfds",
".",
"as_numpy",
"(",
"tf_img",
")",
"example",
"[",
"'image'",
"]",
"=",
"self",
".",
"_get_corrupted_example",
"(",
"image_np",
")",
"yield",
"example",
"# Reset the seeds back to their original values.",
"np",
".",
"random",
".",
"set_state",
"(",
"numpy_st0",
")"
] |
Retrieve properties .
|
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' ] ]
| 4,294
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L623-L656
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Retrieve Services .
|
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' ] ]
| 4,295
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L658-L690
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Retrieve single KE - chain Service .
|
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 ]
| 4,296
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L692-L718
|
[
"def",
"mergeDQarray",
"(",
"maskname",
",",
"dqarr",
")",
":",
"maskarr",
"=",
"None",
"if",
"maskname",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"maskname",
",",
"str",
")",
":",
"# working with file on disk (default case)",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"maskname",
")",
":",
"mask",
"=",
"fileutil",
".",
"openImage",
"(",
"maskname",
",",
"memmap",
"=",
"False",
")",
"maskarr",
"=",
"mask",
"[",
"0",
"]",
".",
"data",
".",
"astype",
"(",
"np",
".",
"bool",
")",
"mask",
".",
"close",
"(",
")",
"else",
":",
"if",
"isinstance",
"(",
"maskname",
",",
"fits",
".",
"HDUList",
")",
":",
"# working with a virtual input file",
"maskarr",
"=",
"maskname",
"[",
"0",
"]",
".",
"data",
".",
"astype",
"(",
"np",
".",
"bool",
")",
"else",
":",
"maskarr",
"=",
"maskname",
".",
"data",
".",
"astype",
"(",
"np",
".",
"bool",
")",
"if",
"maskarr",
"is",
"not",
"None",
":",
"# merge array with dqarr now",
"np",
".",
"bitwise_and",
"(",
"dqarr",
",",
"maskarr",
",",
"dqarr",
")"
] |
Retrieve Service Executions .
|
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' ] ]
| 4,297
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L720-L755
|
[
"def",
"create_bundle",
"(",
"self",
",",
"bundleId",
",",
"data",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
"}",
"url",
"=",
"self",
".",
"__get_base_bundle_url",
"(",
")",
"+",
"\"/\"",
"+",
"bundleId",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'sourceLanguage'",
"]",
"=",
"'en'",
"data",
"[",
"'targetLanguages'",
"]",
"=",
"[",
"]",
"data",
"[",
"'notes'",
"]",
"=",
"[",
"]",
"data",
"[",
"'metadata'",
"]",
"=",
"{",
"}",
"data",
"[",
"'partner'",
"]",
"=",
"''",
"data",
"[",
"'segmentSeparatorPattern'",
"]",
"=",
"''",
"data",
"[",
"'noTranslationPattern'",
"]",
"=",
"''",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"response",
"=",
"self",
".",
"__perform_rest_call",
"(",
"requestURL",
"=",
"url",
",",
"restType",
"=",
"'PUT'",
",",
"body",
"=",
"json_data",
",",
"headers",
"=",
"headers",
")",
"return",
"response"
] |
Retrieve single KE - chain ServiceExecution .
|
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 ]
| 4,298
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L757-L786
|
[
"def",
"mergeDQarray",
"(",
"maskname",
",",
"dqarr",
")",
":",
"maskarr",
"=",
"None",
"if",
"maskname",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"maskname",
",",
"str",
")",
":",
"# working with file on disk (default case)",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"maskname",
")",
":",
"mask",
"=",
"fileutil",
".",
"openImage",
"(",
"maskname",
",",
"memmap",
"=",
"False",
")",
"maskarr",
"=",
"mask",
"[",
"0",
"]",
".",
"data",
".",
"astype",
"(",
"np",
".",
"bool",
")",
"mask",
".",
"close",
"(",
")",
"else",
":",
"if",
"isinstance",
"(",
"maskname",
",",
"fits",
".",
"HDUList",
")",
":",
"# working with a virtual input file",
"maskarr",
"=",
"maskname",
"[",
"0",
"]",
".",
"data",
".",
"astype",
"(",
"np",
".",
"bool",
")",
"else",
":",
"maskarr",
"=",
"maskname",
".",
"data",
".",
"astype",
"(",
"np",
".",
"bool",
")",
"if",
"maskarr",
"is",
"not",
"None",
":",
"# merge array with dqarr now",
"np",
".",
"bitwise_and",
"(",
"dqarr",
",",
"maskarr",
",",
"dqarr",
")"
] |
Users of KE - chain .
|
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' ] ]
| 4,299
|
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L788-L816
|
[
"def",
"_generate_examples_validation",
"(",
"self",
",",
"archive",
",",
"labels",
")",
":",
"# Get the current random seeds.",
"numpy_st0",
"=",
"np",
".",
"random",
".",
"get_state",
"(",
")",
"# Set new random seeds.",
"np",
".",
"random",
".",
"seed",
"(",
"135",
")",
"logging",
".",
"warning",
"(",
"'Overwriting cv2 RNG seed.'",
")",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"setRNGSeed",
"(",
"357",
")",
"for",
"example",
"in",
"super",
"(",
"Imagenet2012Corrupted",
",",
"self",
")",
".",
"_generate_examples_validation",
"(",
"archive",
",",
"labels",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"tf_img",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"example",
"[",
"'image'",
"]",
".",
"read",
"(",
")",
",",
"channels",
"=",
"3",
")",
"image_np",
"=",
"tfds",
".",
"as_numpy",
"(",
"tf_img",
")",
"example",
"[",
"'image'",
"]",
"=",
"self",
".",
"_get_corrupted_example",
"(",
"image_np",
")",
"yield",
"example",
"# Reset the seeds back to their original values.",
"np",
".",
"random",
".",
"set_state",
"(",
"numpy_st0",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.