idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
4,200 | def extract_packet ( self ) : packet_size = velbus . MINIMUM_MESSAGE_SIZE + ( self . buffer [ 3 ] & 0x0F ) packet = self . buffer [ 0 : packet_size ] return packet | Extract packet from buffer | 54 | 5 |
4,201 | def _get_number_from_fmt ( fmt ) : if '%' in fmt : # its datetime return len ( ( "{0:" + fmt + "}" ) . format ( dt . datetime . now ( ) ) ) else : # its something else fmt = fmt . lstrip ( '0' ) return int ( re . search ( '[0-9]+' , fmt ) . group ( 0 ) ) | Helper function for extract_values figures out string length from format string . | 91 | 14 |
4,202 | def get_convert_dict ( fmt ) : convdef = { } for literal_text , field_name , format_spec , conversion in formatter . parse ( fmt ) : if field_name is None : continue # XXX: Do I need to include 'conversion'? convdef [ field_name ] = format_spec return convdef | Retrieve parse definition from the format string fmt . | 73 | 10 |
4,203 | def _generate_data_for_format ( fmt ) : # finally try some data, create some random data for the fmt. data = { } # keep track of how many "free_size" (wildcard) parameters we have # if we get two in a row then we know the pattern is invalid, meaning # we'll never be able to match the second wildcard field free_size_start = False for literal_text , field_name , format_spec , conversion in formatter . parse ( fmt ) : if literal_text : free_size_start = False if not field_name : free_size_start = False continue # encapsulating free size keys, # e.g. {:s}{:s} or {:s}{:4s}{:d} if not format_spec or format_spec == "s" or format_spec == "d" : if free_size_start : return None else : free_size_start = True # make some data for this key and format if format_spec and '%' in format_spec : # some datetime t = dt . datetime . now ( ) # run once through format to limit precision t = parse ( "{t:" + format_spec + "}" , compose ( "{t:" + format_spec + "}" , { 't' : t } ) ) [ 't' ] data [ field_name ] = t elif format_spec and 'd' in format_spec : # random number (with n sign. figures) if not format_spec . isalpha ( ) : n = _get_number_from_fmt ( format_spec ) else : # clearly bad return None data [ field_name ] = random . randint ( 0 , 99999999999999999 ) % ( 10 ** n ) else : # string type if format_spec is None : n = 4 elif format_spec . isalnum ( ) : n = _get_number_from_fmt ( format_spec ) else : n = 4 randstri = '' for x in range ( n ) : randstri += random . choice ( string . ascii_letters ) data [ field_name ] = randstri return data | Generate a fake data dictionary to fill in the provided format string . | 470 | 14 |
4,204 | def is_one2one ( fmt ) : data = _generate_data_for_format ( fmt ) if data is None : return False # run data forward once and back to data stri = compose ( fmt , data ) data2 = parse ( fmt , stri ) # check if data2 equal to original data if len ( data ) != len ( data2 ) : return False for key in data : if key not in data2 : return False if data2 [ key ] != data [ key ] : return False # all checks passed, so just return True return True | Runs a check to evaluate if the format string has a one to one correspondence . I . e . that successive composing and parsing opperations will result in the original data . In other words that input data maps to a string which then maps back to the original data without any change or loss in information . | 119 | 62 |
4,205 | def convert_field ( self , value , conversion ) : func = self . CONV_FUNCS . get ( conversion ) if func is not None : value = getattr ( value , func ) ( ) elif conversion not in [ 'R' ] : # default conversion ('r', 's') return super ( StringFormatter , self ) . convert_field ( value , conversion ) if conversion in [ 'h' , 'H' , 'R' ] : value = value . replace ( '-' , '' ) . replace ( '_' , '' ) . replace ( ':' , '' ) . replace ( ' ' , '' ) return value | Apply conversions mentioned above . | 136 | 5 |
4,206 | def _escape ( self , s ) : for ch , r_ch in self . ESCAPE_SETS : s = s . replace ( ch , r_ch ) return s | Escape bad characters for regular expressions . | 38 | 8 |
4,207 | def format_spec_to_regex ( field_name , format_spec ) : # NOTE: remove escaped backslashes so regex matches regex_match = fmt_spec_regex . match ( format_spec . replace ( '\\' , '' ) ) if regex_match is None : raise ValueError ( "Invalid format specification: '{}'" . format ( format_spec ) ) regex_dict = regex_match . groupdict ( ) fill = regex_dict [ 'fill' ] ftype = regex_dict [ 'type' ] width = regex_dict [ 'width' ] align = regex_dict [ 'align' ] # NOTE: does not properly handle `=` alignment if fill is None : if width is not None and width [ 0 ] == '0' : fill = '0' elif ftype in [ 's' , 'd' ] : fill = ' ' char_type = spec_regexes [ ftype ] if ftype == 's' and align and align . endswith ( '=' ) : raise ValueError ( "Invalid format specification: '{}'" . format ( format_spec ) ) final_regex = char_type if ftype in allow_multiple and ( not width or width == '0' ) : final_regex += r'*' elif width and width != '0' : if not fill : # we know we have exactly this many characters final_regex += r'{{{}}}' . format ( int ( width ) ) elif fill : # we don't know how many fill characters we have compared to # field characters so just match all characters and sort it out # later during type conversion. final_regex = r'.{{{}}}' . format ( int ( width ) ) elif ftype in allow_multiple : final_regex += r'*' return r'(?P<{}>{})' . format ( field_name , final_regex ) | Make an attempt at converting a format spec to a regular expression . | 421 | 13 |
4,208 | def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . parser . feed ( data ) | Feed parser with new data | 26 | 5 |
4,209 | 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 ) | Scan the bus and call the callback when a new module is discovered | 161 | 13 |
4,210 | def sync_clock ( self ) : self . send ( velbus . SetRealtimeClock ( ) ) self . send ( velbus . SetDate ( ) ) self . send ( velbus . SetDaylightSaving ( ) ) | This will send all the needed messages to sync the cloc | 49 | 12 |
4,211 | def string_variable_lookup ( tb , s ) : refs = [ ] dot_refs = s . split ( '.' ) DOT_LOOKUP = 0 DICT_LOOKUP = 1 for ii , ref in enumerate ( dot_refs ) : dict_refs = dict_lookup_regex . findall ( ref ) if dict_refs : bracket = ref . index ( '[' ) refs . append ( ( DOT_LOOKUP , ref [ : bracket ] ) ) refs . extend ( [ ( DICT_LOOKUP , t ) for t in dict_refs ] ) else : refs . append ( ( DOT_LOOKUP , ref ) ) scope = tb . tb_frame . f_locals . get ( refs [ 0 ] [ 1 ] , ValueError ) if scope is ValueError : return scope for lookup , ref in refs [ 1 : ] : try : if lookup == DOT_LOOKUP : scope = getattr ( scope , ref , ValueError ) else : scope = scope . get ( ref , ValueError ) except Exception as e : logging . error ( e ) scope = ValueError if scope is ValueError : return scope elif isinstance ( scope , ( FunctionType , MethodType , ModuleType , BuiltinMethodType , BuiltinFunctionType ) ) : return ValueError return scope | Look up the value of an object in a traceback by a dot - lookup string . ie . self . crashreporter . application_name | 296 | 29 |
4,212 | def get_object_references ( tb , source , max_string_length = 1000 ) : global obj_ref_regex referenced_attr = set ( ) for line in source . split ( '\n' ) : referenced_attr . update ( set ( re . findall ( obj_ref_regex , line ) ) ) referenced_attr = sorted ( referenced_attr ) info = [ ] for attr in referenced_attr : v = string_variable_lookup ( tb , attr ) if v is not ValueError : ref_string = format_reference ( v , max_string_length = max_string_length ) info . append ( ( attr , ref_string ) ) return info | Find the values of referenced attributes of objects within the traceback scope . | 154 | 14 |
4,213 | def get_local_references ( tb , max_string_length = 1000 ) : if 'self' in tb . tb_frame . f_locals : _locals = [ ( 'self' , repr ( tb . tb_frame . f_locals [ 'self' ] ) ) ] else : _locals = [ ] for k , v in tb . tb_frame . f_locals . iteritems ( ) : if k == 'self' : continue try : vstr = format_reference ( v , max_string_length = max_string_length ) _locals . append ( ( k , vstr ) ) except TypeError : pass return _locals | Find the values of the local variables within the traceback scope . | 154 | 13 |
4,214 | def analyze_traceback ( tb , inspection_level = None , limit = None ) : info = [ ] tb_level = tb extracted_tb = traceback . extract_tb ( tb , limit = limit ) for ii , ( filepath , line , module , code ) in enumerate ( extracted_tb ) : func_source , func_lineno = inspect . getsourcelines ( tb_level . tb_frame ) d = { "File" : filepath , "Error Line Number" : line , "Module" : module , "Error Line" : code , "Module Line Number" : func_lineno , "Custom Inspection" : { } , "Source Code" : '' } if inspection_level is None or len ( extracted_tb ) - ii <= inspection_level : # Perform advanced inspection on the last `inspection_level` tracebacks. d [ 'Source Code' ] = '' . join ( func_source ) d [ 'Local Variables' ] = get_local_references ( tb_level ) d [ 'Object Variables' ] = get_object_references ( tb_level , d [ 'Source Code' ] ) tb_level = getattr ( tb_level , 'tb_next' , None ) info . append ( d ) return info | Extract trace back information into a list of dictionaries . | 289 | 12 |
4,215 | def log_configs ( self ) : for sec in self . config . sections ( ) : LOG . debug ( ' %s: %s' , sec , self . config . options ( sec ) ) | Log the read configs if debug is enabled . | 43 | 10 |
4,216 | def set_env_or_defaults ( self ) : option = namedtuple ( 'Option' , [ 'section' , 'name' , 'env_var' , 'default_value' ] ) options = [ option ( 'auth' , 'user' , 'NAPPS_USER' , None ) , option ( 'auth' , 'token' , 'NAPPS_TOKEN' , None ) , option ( 'napps' , 'api' , 'NAPPS_API_URI' , 'https://napps.kytos.io/api/' ) , option ( 'napps' , 'repo' , 'NAPPS_REPO_URI' , 'https://napps.kytos.io/repo' ) , option ( 'kytos' , 'api' , 'KYTOS_API' , 'http://localhost:8181/' ) ] for option in options : if not self . config . has_option ( option . section , option . name ) : env_value = os . environ . get ( option . env_var , option . default_value ) if env_value : self . config . set ( option . section , option . name , env_value ) self . config . set ( 'global' , 'debug' , str ( self . debug ) ) | Read some environment variables and set them on the config . | 291 | 11 |
4,217 | def check_sections ( config ) : default_sections = [ 'global' , 'auth' , 'napps' , 'kytos' ] for section in default_sections : if not config . has_section ( section ) : config . add_section ( section ) | Create a empty config file . | 58 | 6 |
4,218 | def save_token ( self , user , token ) : self . config . set ( 'auth' , 'user' , user ) self . config . set ( 'auth' , 'token' , token ) # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser ( allow_no_value = True ) # Parse the config file. If no config file was found, then create some # default sections on the config variable. new_config . read ( self . config_file ) self . check_sections ( new_config ) new_config . set ( 'auth' , 'user' , user ) new_config . set ( 'auth' , 'token' , token ) filename = os . path . expanduser ( self . config_file ) with open ( filename , 'w' ) as out_file : os . chmod ( filename , 0o0600 ) new_config . write ( out_file ) | Save the token on the config file . | 208 | 8 |
4,219 | def clear_token ( self ) : # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser ( allow_no_value = True ) # Parse the config file. If no config file was found, then create some # default sections on the config variable. new_config . read ( self . config_file ) self . check_sections ( new_config ) new_config . remove_option ( 'auth' , 'user' ) new_config . remove_option ( 'auth' , 'token' ) filename = os . path . expanduser ( self . config_file ) with open ( filename , 'w' ) as out_file : os . chmod ( filename , 0o0600 ) new_config . write ( out_file ) | Clear Token information on config file . | 172 | 7 |
4,220 | def relocate_model ( part , target_parent , name = None , include_children = True ) : if target_parent . id in get_illegal_targets ( part , include = { part . id } ) : raise IllegalArgumentError ( 'cannot relocate part "{}" under target parent "{}", because the target is part of ' 'its descendants' . format ( part . name , target_parent . name ) ) # First, if the user doesn't provide the name, then just use the default "Clone - ..." name if not name : name = "CLONE - {}" . format ( part . name ) # The description cannot be added when creating a model, so edit the model after creation. part_desc = part . _json_data [ 'description' ] moved_part_model = target_parent . add_model ( name = name , multiplicity = part . multiplicity ) if part_desc : moved_part_model . edit ( description = str ( part_desc ) ) # Map the current part model id with newly created part model Object get_mapping_dictionary ( ) . update ( { part . id : moved_part_model } ) # Loop through properties and retrieve their type, description and unit list_of_properties_sorted_by_order = part . properties list_of_properties_sorted_by_order . sort ( key = lambda x : x . _json_data [ 'order' ] ) for prop in list_of_properties_sorted_by_order : prop_type = prop . _json_data . get ( 'property_type' ) desc = prop . _json_data . get ( 'description' ) unit = prop . _json_data . get ( 'unit' ) options = prop . _json_data . get ( 'options' ) # On "Part references" properties, the models referenced also need to be added if prop_type == PropertyType . REFERENCES_VALUE : referenced_part_ids = [ referenced_part . id for referenced_part in prop . value ] moved_prop = moved_part_model . add_property ( name = prop . name , description = desc , property_type = prop_type , default_value = referenced_part_ids ) # On "Attachment" properties, attachments needs to be downloaded and re-uploaded to the new property. elif prop_type == PropertyType . ATTACHMENT_VALUE : moved_prop = moved_part_model . add_property ( name = prop . name , description = desc , property_type = prop_type ) if prop . value : attachment_name = prop . _json_data [ 'value' ] . split ( '/' ) [ - 1 ] with temp_chdir ( ) as target_dir : full_path = os . path . join ( target_dir or os . getcwd ( ) , attachment_name ) prop . save_as ( filename = full_path ) moved_prop . upload ( full_path ) # Other properties are quite straightforward else : moved_prop = moved_part_model . add_property ( name = prop . name , description = desc , property_type = prop_type , default_value = prop . value , unit = unit , options = options ) # Map the current property model id with newly created property model Object get_mapping_dictionary ( ) [ prop . id ] = moved_prop # Now copy the sub-tree of the part if include_children : # Populate the part so multiple children retrieval is not needed part . populate_descendants ( ) # For each part, recursively run this function for sub_part in part . _cached_children : relocate_model ( part = sub_part , target_parent = moved_part_model , name = sub_part . name , include_children = include_children ) return moved_part_model | Move the Part model to target parent . | 834 | 8 |
4,221 | def relocate_instance ( part , target_parent , name = None , include_children = True ) : # First, if the user doesn't provide the name, then just use the default "Clone - ..." name if not name : name = "CLONE - {}" . format ( part . name ) # Initially the model of the part needs to be recreated under the model of the target_parent. Retrieve them. part_model = part . model ( ) target_parent_model = target_parent . model ( ) # Call the move_part() function for those models. relocate_model ( part = part_model , target_parent = target_parent_model , name = part_model . name , include_children = include_children ) # Populate the descendants of the Part (category=Instance), in order to avoid to retrieve children for every # level and save time. Only need it the children should be included. if include_children : part . populate_descendants ( ) # This function will move the part instance under the target_parent instance, and its children if required. moved_instance = move_part_instance ( part_instance = part , target_parent = target_parent , part_model = part_model , name = name , include_children = include_children ) return moved_instance | Move the Part instance to target parent . | 278 | 8 |
4,222 | def move_part_instance ( part_instance , target_parent , part_model , name = None , include_children = True ) : # If no specific name has been required, then call in as Clone of the part_instance. if not name : name = part_instance . name # Retrieve the model of the future part to be created moved_model = get_mapping_dictionary ( ) [ part_model . id ] # Now act based on multiplicity if moved_model . multiplicity == Multiplicity . ONE : # If multiplicity is 'Exactly 1', that means the instance was automatically created with the model, so just # retrieve it, map the original instance with the moved one and update the name and property values. moved_instance = moved_model . instances ( parent_id = target_parent . id ) [ 0 ] map_property_instances ( part_instance , moved_instance ) moved_instance = update_part_with_properties ( part_instance , moved_instance , name = str ( name ) ) elif moved_model . multiplicity == Multiplicity . ONE_MANY : # If multiplicity is '1 or more', that means one instance has automatically been created with the model, so # retrieve it, map the original instance with the moved one and update the name and property values. Store # the model in a list, in case there are multiple instance those need to be recreated. if target_parent . id not in get_edited_one_many ( ) : moved_instance = moved_model . instances ( parent_id = target_parent . id ) [ 0 ] map_property_instances ( part_instance , moved_instance ) moved_instance = update_part_with_properties ( part_instance , moved_instance , name = str ( name ) ) get_edited_one_many ( ) . append ( target_parent . id ) else : moved_instance = target_parent . add ( name = part_instance . name , model = moved_model , suppress_kevents = True ) map_property_instances ( part_instance , moved_instance ) moved_instance = update_part_with_properties ( part_instance , moved_instance , name = str ( name ) ) else : # If multiplicity is '0 or more' or '0 or 1', it means no instance has been created automatically with the # model, so then everything must be created and then updated. moved_instance = target_parent . add ( name = name , model = moved_model , suppress_kevents = True ) map_property_instances ( part_instance , moved_instance ) moved_instance = update_part_with_properties ( part_instance , moved_instance , name = str ( name ) ) # If include_children is True, then recursively call this function for every descendant. Keep the name of the # original sub-instance. if include_children : for sub_instance in part_instance . _cached_children : move_part_instance ( part_instance = sub_instance , target_parent = moved_instance , part_model = sub_instance . model ( ) , name = sub_instance . name , include_children = True ) return moved_instance | Move the Part instance to target parent and updates the properties based on the original part instance . | 693 | 18 |
4,223 | def update_part_with_properties ( part_instance , moved_instance , name = None ) : # Instantiate and empty dictionary later used to map {property.id: property.value} in order to update the part # in one go properties_id_dict = dict ( ) for prop_instance in part_instance . properties : # Do different magic if there is an attachment property and it has a value if prop_instance . _json_data [ 'property_type' ] == PropertyType . ATTACHMENT_VALUE : moved_prop = get_mapping_dictionary ( ) [ prop_instance . id ] if prop_instance . value : attachment_name = prop_instance . _json_data [ 'value' ] . split ( '/' ) [ - 1 ] with temp_chdir ( ) as target_dir : full_path = os . path . join ( target_dir or os . getcwd ( ) , attachment_name ) prop_instance . save_as ( filename = full_path ) moved_prop . upload ( full_path ) else : moved_prop . clear ( ) # For a reference value property, add the id's of the part referenced {property.id: [part1.id, part2.id, ...]}, # if there is part referenced at all. elif prop_instance . _json_data [ 'property_type' ] == PropertyType . REFERENCES_VALUE : if prop_instance . value : moved_prop_instance = get_mapping_dictionary ( ) [ prop_instance . id ] properties_id_dict [ moved_prop_instance . id ] = [ ref_part . id for ref_part in prop_instance . value ] else : moved_prop_instance = get_mapping_dictionary ( ) [ prop_instance . id ] properties_id_dict [ moved_prop_instance . id ] = prop_instance . value # Update the name and property values in one go. moved_instance . update ( name = str ( name ) , update_dict = properties_id_dict , bulk = True , suppress_kevents = True ) return moved_instance | Update the newly created part and its properties based on the original one . | 463 | 14 |
4,224 | def map_property_instances ( original_part , new_part ) : # Map the original part with the new one get_mapping_dictionary ( ) [ original_part . id ] = new_part # Do the same for each Property of original part instance, using the 'model' id and the get_mapping_dictionary for prop_original in original_part . properties : get_mapping_dictionary ( ) [ prop_original . id ] = [ prop_new for prop_new in new_part . properties if get_mapping_dictionary ( ) [ prop_original . _json_data [ 'model' ] ] . id == prop_new . _json_data [ 'model' ] ] [ 0 ] | Map the id of the original part with the Part object of the newly created one . | 160 | 17 |
4,225 | def ask_question ( self , field_name , pattern = NAME_PATTERN , is_required = False , password = False ) : input_value = "" question = ( "Insert the field using the pattern below:" "\n{}\n{}: " . format ( pattern [ 0 ] , field_name ) ) while not input_value : input_value = getpass ( question ) if password else input ( question ) if not ( input_value or is_required ) : break if password : confirm_password = getpass ( 'Confirm your password: ' ) if confirm_password != input_value : print ( "Password does not match" ) input_value = "" if not self . valid_attribute ( input_value , pattern [ 1 ] ) : error_message = "The content must fit the pattern: {}\n" print ( error_message . format ( pattern [ 0 ] ) ) input_value = "" return input_value | Ask a question and get the input values . | 201 | 9 |
4,226 | def cli ( action , config_file , debug , verbose ) : if verbose is True : log_level = 'DEBUG' elif verbose is False : log_level = 'WARNING' else : assert verbose is None log_level = 'INFO' setup_logging ( log_level ) try : grab = Grab ( config_file , debug = debug ) if action in { 'download' , None } : grab . download ( ) if action in { 'build' , None } : grab . build ( ) except GrablibError as e : click . secho ( 'Error: %s' % e , fg = 'red' ) sys . exit ( 2 ) | Static asset management in python . | 146 | 6 |
4,227 | def part ( self ) : part_id = self . _json_data [ 'part' ] return self . _client . part ( pk = part_id , category = self . _json_data [ 'category' ] ) | Retrieve the part that holds this Property . | 50 | 9 |
4,228 | def delete ( self ) : # type () -> () r = self . _client . _request ( 'DELETE' , self . _client . _build_url ( 'property' , property_id = self . id ) ) if r . status_code != requests . codes . no_content : # pragma: no cover raise APIError ( "Could not delete property: {} with id {}" . format ( self . name , self . id ) ) | Delete this property . | 98 | 4 |
4,229 | def create ( cls , json , * * kwargs ) : # type: (dict, **Any) -> Property property_type = json . get ( 'property_type' ) if property_type == PropertyType . ATTACHMENT_VALUE : from . property_attachment import AttachmentProperty return AttachmentProperty ( json , * * kwargs ) elif property_type == PropertyType . SINGLE_SELECT_VALUE : from . property_selectlist import SelectListProperty return SelectListProperty ( json , * * kwargs ) elif property_type == PropertyType . REFERENCE_VALUE : from . property_reference import ReferenceProperty return ReferenceProperty ( json , * * kwargs ) elif property_type == PropertyType . REFERENCES_VALUE : from . property_multi_reference import MultiReferenceProperty return MultiReferenceProperty ( json , * * kwargs ) else : return Property ( json , * * kwargs ) | Create a property based on the json data . | 205 | 9 |
4,230 | def __parse_validators ( self ) : self . _validators = [ ] validators_json = self . _options . get ( 'validators' ) for validator_json in validators_json : self . _validators . append ( PropertyValidator . parse ( json = validator_json ) ) | Parse the validator in the options to validators . | 68 | 12 |
4,231 | def __dump_validators ( self ) : if hasattr ( self , '_validators' ) : validators_json = [ ] for validator in self . _validators : if isinstance ( validator , PropertyValidator ) : validators_json . append ( validator . as_json ( ) ) else : raise APIError ( "validator is not a PropertyValidator: '{}'" . format ( validator ) ) if self . _options . get ( 'validators' , list ( ) ) == validators_json : # no change pass else : new_options = self . _options . copy ( ) # make a copy new_options . update ( { 'validators' : validators_json } ) validate ( new_options , options_json_schema ) self . _options = new_options | Dump the validators as json inside the _options dictionary with the key validators . | 179 | 18 |
4,232 | def is_valid ( self ) : # type: () -> Union[bool, None] if not hasattr ( self , '_validators' ) : return None else : self . validate ( reason = False ) if all ( [ vr is None for vr in self . _validation_results ] ) : return None else : return all ( self . _validation_results ) | Determine if the value in the property is valid . | 82 | 12 |
4,233 | def get_ini_config ( config = os . path . join ( os . path . expanduser ( '~' ) , '.zdeskcfg' ) , default_section = None , section = None ) : plac_ini . call ( __placeholder__ , config = config , default_section = default_section ) return __placeholder__ . getconfig ( section ) | This is a convenience function for getting the zdesk configuration from an ini file without the need to decorate and call your own function . Handy when using zdesk and zdeskcfg from the interactive prompt . | 80 | 46 |
4,234 | def _ecg_band_pass_filter ( data , sample_rate ) : nyquist_sample_rate = sample_rate / 2. normalized_cut_offs = [ 5 / nyquist_sample_rate , 15 / nyquist_sample_rate ] b_coeff , a_coeff = butter ( 2 , normalized_cut_offs , btype = 'bandpass' ) [ : 2 ] return filtfilt ( b_coeff , a_coeff , data , padlen = 150 ) | Bandpass filter with a bandpass setting of 5 to 15 Hz | 113 | 13 |
4,235 | def _integration ( data , sample_rate ) : wind_size = int ( 0.080 * sample_rate ) int_ecg = numpy . zeros_like ( data ) cum_sum = data . cumsum ( ) int_ecg [ wind_size : ] = ( cum_sum [ wind_size : ] - cum_sum [ : - wind_size ] ) / wind_size int_ecg [ : wind_size ] = cum_sum [ : wind_size ] / numpy . arange ( 1 , wind_size + 1 ) return int_ecg | Moving window integration . N is the number of samples in the width of the integration window | 129 | 17 |
4,236 | def _buffer_ini ( data , sample_rate ) : rr_buffer = [ 1 ] * 8 spk1 = max ( data [ sample_rate : 2 * sample_rate ] ) npk1 = 0 threshold = _buffer_update ( npk1 , spk1 ) return rr_buffer , spk1 , npk1 , threshold | Initializes the buffer with eight 1s intervals | 77 | 9 |
4,237 | def _detects_peaks ( ecg_integrated , sample_rate ) : # Minimum RR interval = 200 ms min_rr = ( sample_rate / 1000 ) * 200 # Computes all possible peaks and their amplitudes possible_peaks = [ i for i in range ( 0 , len ( ecg_integrated ) - 1 ) if ecg_integrated [ i - 1 ] < ecg_integrated [ i ] and ecg_integrated [ i ] > ecg_integrated [ i + 1 ] ] possible_amplitudes = [ ecg_integrated [ k ] for k in possible_peaks ] chosen_peaks = [ ] # Starts with first peak if not possible_peaks : raise Exception ( "No Peaks Detected." ) peak_candidate_i = possible_peaks [ 0 ] peak_candidate_amp = possible_amplitudes [ 0 ] for peak_i , peak_amp in zip ( possible_peaks , possible_amplitudes ) : if peak_i - peak_candidate_i <= min_rr and peak_amp > peak_candidate_amp : peak_candidate_i = peak_i peak_candidate_amp = peak_amp elif peak_i - peak_candidate_i > min_rr : chosen_peaks += [ peak_candidate_i - 6 ] # Delay of 6 samples peak_candidate_i = peak_i peak_candidate_amp = peak_amp else : pass return chosen_peaks , possible_peaks | Detects peaks from local maximum | 336 | 6 |
4,238 | def _checkup ( peaks , ecg_integrated , sample_rate , rr_buffer , spk1 , npk1 , threshold ) : peaks_amp = [ ecg_integrated [ peak ] for peak in peaks ] definitive_peaks = [ ] for i , peak in enumerate ( peaks ) : amp = peaks_amp [ i ] # accept if larger than threshold and slope in raw signal # is +-30% of previous slopes if amp > threshold : definitive_peaks , spk1 , rr_buffer = _acceptpeak ( peak , amp , definitive_peaks , spk1 , rr_buffer ) # accept as qrs if higher than half threshold, # but is 360 ms after last qrs and next peak # is more than 1.5 rr intervals away # just abandon it if there is no peak before # or after elif amp > threshold / 2 and list ( definitive_peaks ) and len ( peaks ) > i + 1 : mean_rr = numpy . mean ( rr_buffer ) last_qrs_ms = ( peak - definitive_peaks [ - 1 ] ) * ( 1000 / sample_rate ) last_qrs_to_next_peak = peaks [ i + 1 ] - definitive_peaks [ - 1 ] if last_qrs_ms > 360 and last_qrs_to_next_peak > 1.5 * mean_rr : definitive_peaks , spk1 , rr_buffer = _acceptpeak ( peak , amp , definitive_peaks , spk1 , rr_buffer ) else : npk1 = _noisepeak ( amp , npk1 ) # if not either of these it is noise else : npk1 = _noisepeak ( amp , npk1 ) threshold = _buffer_update ( npk1 , spk1 ) definitive_peaks = numpy . array ( definitive_peaks ) return definitive_peaks | Check each peak according to thresholds | 420 | 6 |
4,239 | def _acceptpeak ( peak , amp , definitive_peaks , spk1 , rr_buffer ) : definitive_peaks_out = definitive_peaks definitive_peaks_out = numpy . append ( definitive_peaks_out , peak ) spk1 = 0.125 * amp + 0.875 * spk1 # spk1 is the running estimate of the signal peak if len ( definitive_peaks_out ) > 1 : rr_buffer . pop ( 0 ) rr_buffer += [ definitive_peaks_out [ - 1 ] - definitive_peaks_out [ - 2 ] ] return numpy . array ( definitive_peaks_out ) , spk1 , rr_buffer | Private function intended to insert a new RR interval in the buffer . | 157 | 13 |
4,240 | def tachogram ( data , sample_rate , signal = False , in_seconds = False , out_seconds = False ) : if signal is False : # data is a list of R peaks position. data_copy = data time_axis = numpy . array ( data ) #.cumsum() if out_seconds is True and in_seconds is False : time_axis = time_axis / sample_rate else : # data is a ECG signal. # Detection of R peaks. data_copy = detect_r_peaks ( data , sample_rate , time_units = out_seconds , volts = False , resolution = None , plot_result = False ) [ 0 ] time_axis = data_copy # Generation of Tachogram. tachogram_data = numpy . diff ( time_axis ) tachogram_time = time_axis [ 1 : ] return tachogram_data , tachogram_time | Function for generation of ECG Tachogram . | 201 | 10 |
4,241 | def stop ( self ) : self . logger . warning ( "Stop executed" ) try : self . _reader . close ( ) except serial . serialutil . SerialException : self . logger . error ( "Error while closing device" ) raise VelbusException ( "Error while closing device" ) time . sleep ( 1 ) | Close serial port . | 67 | 4 |
4,242 | def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . controller . feed_parser ( data ) | Parse received message . | 28 | 5 |
4,243 | def send ( self , message , callback = None ) : assert isinstance ( message , velbus . Message ) self . _write_queue . put_nowait ( ( message , callback ) ) | Add message to write queue . | 41 | 6 |
4,244 | def write_daemon ( self ) : while True : ( message , callback ) = self . _write_queue . get ( block = True ) self . logger . info ( "Sending message on USB bus: %s" , str ( message ) ) self . logger . debug ( "Sending binary message: %s" , str ( message . to_binary ( ) ) ) self . _reader . write ( message . to_binary ( ) ) time . sleep ( self . SLEEP_TIME ) if callback : callback ( ) | Write thread . | 114 | 3 |
4,245 | def __require_kytos_config ( self ) : if self . __enabled is None : uri = self . _kytos_api + 'api/kytos/core/config/' try : options = json . loads ( urllib . request . urlopen ( uri ) . read ( ) ) except urllib . error . URLError : print ( 'Kytos is not running.' ) sys . exit ( ) self . __enabled = Path ( options . get ( 'napps' ) ) self . __installed = Path ( options . get ( 'installed_napps' ) ) | Set path locations from kytosd API . | 134 | 10 |
4,246 | def set_napp ( self , user , napp , version = None ) : self . user = user self . napp = napp self . version = version or 'latest' | Set info about NApp . | 39 | 6 |
4,247 | def dependencies ( self , user = None , napp = None ) : napps = self . _get_napp_key ( 'napp_dependencies' , user , napp ) return [ tuple ( napp . split ( '/' ) ) for napp in napps ] | Get napp_dependencies from install NApp . | 61 | 11 |
4,248 | def _get_napp_key ( self , key , user = None , napp = None ) : if user is None : user = self . user if napp is None : napp = self . napp kytos_json = self . _installed / user / napp / 'kytos.json' try : with kytos_json . open ( ) as file_descriptor : meta = json . load ( file_descriptor ) return meta [ key ] except ( FileNotFoundError , json . JSONDecodeError , KeyError ) : return '' | Return a value from kytos . json . | 125 | 10 |
4,249 | def disable ( self ) : core_napps_manager = CoreNAppsManager ( base_path = self . _enabled ) core_napps_manager . disable ( self . user , self . napp ) | Disable a NApp if it is enabled . | 45 | 9 |
4,250 | def enable ( self ) : core_napps_manager = CoreNAppsManager ( base_path = self . _enabled ) core_napps_manager . enable ( self . user , self . napp ) | Enable a NApp if not already enabled . | 45 | 9 |
4,251 | def uninstall ( self ) : if self . is_installed ( ) : installed = self . installed_dir ( ) if installed . is_symlink ( ) : installed . unlink ( ) else : shutil . rmtree ( str ( installed ) ) | Delete code inside NApp directory if existent . | 55 | 10 |
4,252 | def render_template ( templates_path , template_filename , context ) : template_env = Environment ( autoescape = False , trim_blocks = False , loader = FileSystemLoader ( str ( templates_path ) ) ) return template_env . get_template ( str ( template_filename ) ) . render ( context ) | Render Jinja2 template for a NApp structure . | 69 | 11 |
4,253 | def search ( pattern ) : def match ( napp ) : """Whether a NApp metadata matches the pattern.""" # WARNING: This will change for future versions, when 'author' will # be removed. username = napp . get ( 'username' , napp . get ( 'author' ) ) strings = [ '{}/{}' . format ( username , napp . get ( 'name' ) ) , napp . get ( 'description' ) ] + napp . get ( 'tags' ) return any ( pattern . match ( string ) for string in strings ) napps = NAppsClient ( ) . get_napps ( ) return [ napp for napp in napps if match ( napp ) ] | Search all server NApps matching pattern . | 156 | 8 |
4,254 | def install_local ( self ) : folder = self . _get_local_folder ( ) installed = self . installed_dir ( ) self . _check_module ( installed . parent ) installed . symlink_to ( folder . resolve ( ) ) | Make a symlink in install folder to a local NApp . | 54 | 14 |
4,255 | def _get_local_folder ( self , root = None ) : if root is None : root = Path ( ) for folders in [ '.' ] , [ self . user , self . napp ] : kytos_json = root / Path ( * folders ) / 'kytos.json' if kytos_json . exists ( ) : with kytos_json . open ( ) as file_descriptor : meta = json . load ( file_descriptor ) # WARNING: This will change in future versions, when # 'author' will be removed. username = meta . get ( 'username' , meta . get ( 'author' ) ) if username == self . user and meta . get ( 'name' ) == self . napp : return kytos_json . parent raise FileNotFoundError ( 'kytos.json not found.' ) | Return local NApp root folder . | 188 | 7 |
4,256 | def install_remote ( self ) : package , pkg_folder = None , None try : package = self . _download ( ) pkg_folder = self . _extract ( package ) napp_folder = self . _get_local_folder ( pkg_folder ) dst = self . _installed / self . user / self . napp self . _check_module ( dst . parent ) shutil . move ( str ( napp_folder ) , str ( dst ) ) finally : # Delete temporary files if package : Path ( package ) . unlink ( ) if pkg_folder and pkg_folder . exists ( ) : shutil . rmtree ( str ( pkg_folder ) ) | Download extract and install NApp . | 152 | 7 |
4,257 | def _download ( self ) : repo = self . _config . get ( 'napps' , 'repo' ) napp_id = '{}/{}-{}.napp' . format ( self . user , self . napp , self . version ) uri = os . path . join ( repo , napp_id ) return urllib . request . urlretrieve ( uri ) [ 0 ] | Download NApp package from server . | 92 | 7 |
4,258 | def _extract ( filename ) : random_string = '{:0d}' . format ( randint ( 0 , 10 ** 6 ) ) tmp = '/tmp/kytos-napp-' + Path ( filename ) . stem + '-' + random_string os . mkdir ( tmp ) with tarfile . open ( filename , 'r:xz' ) as tar : tar . extractall ( tmp ) return Path ( tmp ) | Extract package to a temporary folder . | 95 | 8 |
4,259 | def create_napp ( cls , meta_package = False ) : templates_path = SKEL_PATH / 'napp-structure/username/napp' ui_templates_path = os . path . join ( templates_path , 'ui' ) username = None napp_name = None print ( '--------------------------------------------------------------' ) print ( 'Welcome to the bootstrap process of your NApp.' ) print ( '--------------------------------------------------------------' ) print ( 'In order to answer both the username and the napp name,' ) print ( 'You must follow this naming rules:' ) print ( ' - name starts with a letter' ) print ( ' - name contains only letters, numbers or underscores' ) print ( ' - at least three characters' ) print ( '--------------------------------------------------------------' ) print ( '' ) while not cls . valid_name ( username ) : username = input ( 'Please, insert your NApps Server username: ' ) while not cls . valid_name ( napp_name ) : napp_name = input ( 'Please, insert your NApp name: ' ) description = input ( 'Please, insert a brief description for your' 'NApp [optional]: ' ) if not description : # pylint: disable=fixme description = '# TODO: <<<< Insert your NApp description here >>>>' # pylint: enable=fixme context = { 'username' : username , 'napp' : napp_name , 'description' : description } #: Creating the directory structure (username/napp_name) os . makedirs ( username , exist_ok = True ) #: Creating ``__init__.py`` files with open ( os . path . join ( username , '__init__.py' ) , 'w' ) as init_file : init_file . write ( f'"""Napps for the user {username}.""""' ) os . makedirs ( os . path . join ( username , napp_name ) ) #: Creating the other files based on the templates templates = os . listdir ( templates_path ) templates . remove ( 'ui' ) templates . remove ( 'openapi.yml.template' ) if meta_package : templates . remove ( 'main.py.template' ) templates . remove ( 'settings.py.template' ) for tmp in templates : fname = os . path . join ( username , napp_name , tmp . rsplit ( '.template' ) [ 0 ] ) with open ( fname , 'w' ) as file : content = cls . render_template ( templates_path , tmp , context ) file . write ( content ) if not meta_package : NAppsManager . create_ui_structure ( username , napp_name , ui_templates_path , context ) print ( ) print ( f'Congratulations! Your NApp has been bootstrapped!\nNow you ' 'can go to the directory {username}/{napp_name} and begin to ' 'code your NApp.' ) print ( 'Have fun!' ) | Bootstrap a basic NApp structure for you to develop your NApp . | 661 | 15 |
4,260 | def create_ui_structure ( cls , username , napp_name , ui_templates_path , context ) : for section in [ 'k-info-panel' , 'k-toolbar' , 'k-action-menu' ] : os . makedirs ( os . path . join ( username , napp_name , 'ui' , section ) ) templates = os . listdir ( ui_templates_path ) for tmp in templates : fname = os . path . join ( username , napp_name , 'ui' , tmp . rsplit ( '.template' ) [ 0 ] ) with open ( fname , 'w' ) as file : content = cls . render_template ( ui_templates_path , tmp , context ) file . write ( content ) | Create the ui directory structure . | 176 | 7 |
4,261 | def build_napp_package ( napp_name ) : ignored_extensions = [ '.swp' , '.pyc' , '.napp' ] ignored_dirs = [ '__pycache__' , '.git' , '.tox' ] files = os . listdir ( ) for filename in files : if os . path . isfile ( filename ) and '.' in filename and filename . rsplit ( '.' , 1 ) [ 1 ] in ignored_extensions : files . remove ( filename ) elif os . path . isdir ( filename ) and filename in ignored_dirs : files . remove ( filename ) # Create the '.napp' package napp_file = tarfile . open ( napp_name + '.napp' , 'x:xz' ) for local_f in files : napp_file . add ( local_f ) napp_file . close ( ) # Get the binary payload of the package file_payload = open ( napp_name + '.napp' , 'rb' ) # remove the created package from the filesystem os . remove ( napp_name + '.napp' ) return file_payload | Build the . napp file to be sent to the napps server . | 253 | 15 |
4,262 | def create_metadata ( * args , * * kwargs ) : # pylint: disable=unused-argument json_filename = kwargs . get ( 'json_filename' , 'kytos.json' ) readme_filename = kwargs . get ( 'readme_filename' , 'README.rst' ) ignore_json = kwargs . get ( 'ignore_json' , False ) metadata = { } if not ignore_json : try : with open ( json_filename ) as json_file : metadata = json . load ( json_file ) except FileNotFoundError : print ( "ERROR: Could not access kytos.json file." ) sys . exit ( 1 ) try : with open ( readme_filename ) as readme_file : metadata [ 'readme' ] = readme_file . read ( ) except FileNotFoundError : metadata [ 'readme' ] = '' try : yaml = YAML ( typ = 'safe' ) openapi_dict = yaml . load ( Path ( 'openapi.yml' ) . open ( ) ) openapi = json . dumps ( openapi_dict ) except FileNotFoundError : openapi = '' metadata [ 'OpenAPI_Spec' ] = openapi return metadata | Generate the metadata to send the napp package . | 279 | 11 |
4,263 | def upload ( self , * args , * * kwargs ) : self . prepare ( ) metadata = self . create_metadata ( * args , * * kwargs ) package = self . build_napp_package ( metadata . get ( 'name' ) ) NAppsClient ( ) . upload_napp ( metadata , package ) | Create package and upload it to NApps Server . | 72 | 10 |
4,264 | def prepare ( cls ) : if cls . _ask_openapi ( ) : napp_path = Path ( ) tpl_path = SKEL_PATH / 'napp-structure/username/napp' OpenAPI ( napp_path , tpl_path ) . render_template ( ) print ( 'Please, update your openapi.yml file.' ) sys . exit ( ) | Prepare NApp to be uploaded by creating openAPI skeleton . | 88 | 13 |
4,265 | def reload ( self , napps = None ) : client = NAppsClient ( self . _config ) client . reload_napps ( napps ) | Reload a NApp or all NApps . | 32 | 10 |
4,266 | def _get_thumbnail_url ( image ) : lhs , rhs = splitext ( image . url ) lhs += THUMB_EXT thumb_url = f'{lhs}{rhs}' return thumb_url | Given a large image return the thumbnail url | 52 | 8 |
4,267 | def from_env ( cls , env_filename = None ) : # type: (Optional[str]) -> Client with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" , UserWarning ) env . read_envfile ( env_filename ) client = cls ( url = env ( KechainEnv . KECHAIN_URL ) ) if env ( KechainEnv . KECHAIN_TOKEN , None ) : client . login ( token = env ( KechainEnv . KECHAIN_TOKEN ) ) elif env ( KechainEnv . KECHAIN_USERNAME , None ) and env ( KechainEnv . KECHAIN_PASSWORD , None ) : client . login ( username = env ( KechainEnv . KECHAIN_USERNAME ) , password = env ( KechainEnv . KECHAIN_PASSWORD ) ) return client | Create a client from environment variable settings . | 210 | 8 |
4,268 | def _build_url ( self , resource , * * kwargs ) : # type: (str, **str) -> str return urljoin ( self . api_root , API_PATH [ resource ] . format ( * * kwargs ) ) | Build the correct API url . | 54 | 6 |
4,269 | def _retrieve_users ( self ) : users_url = self . _build_url ( 'users' ) response = self . _request ( 'GET' , users_url ) users = response . json ( ) return users | Retrieve user objects of the entire administration . | 49 | 9 |
4,270 | def _request ( self , method , url , * * kwargs ) : # type: (str, str, **Any) -> requests.Response self . last_request = None self . last_response = self . session . request ( method , url , auth = self . auth , headers = self . headers , * * kwargs ) self . last_request = self . last_response . request self . last_url = self . last_response . url if self . last_response . status_code == requests . codes . forbidden : raise ForbiddenError ( self . last_response . json ( ) [ 'results' ] [ 0 ] [ 'detail' ] ) return self . last_response | Perform the request on the API . | 149 | 8 |
4,271 | def app_versions ( self ) : if not self . _app_versions : app_versions_url = self . _build_url ( 'versions' ) response = self . _request ( 'GET' , app_versions_url ) if response . status_code == requests . codes . not_found : self . _app_versions = [ ] elif response . status_code == requests . codes . forbidden : raise ForbiddenError ( response . json ( ) [ 'results' ] [ 0 ] [ 'detail' ] ) elif response . status_code != requests . codes . ok : raise APIError ( "Could not retrieve app versions: {}" . format ( response ) ) else : self . _app_versions = response . json ( ) . get ( 'results' ) return self . _app_versions | List of the versions of the internal KE - chain app modules . | 173 | 13 |
4,272 | def match_app_version ( self , app = None , label = None , version = None , default = False ) : if not app or not label and not ( app and label ) : target_app = [ a for a in self . app_versions if a . get ( 'app' ) == app or a . get ( 'label' ) == label ] if not target_app and not isinstance ( default , bool ) : raise NotFoundError ( "Could not find the app or label provided" ) elif not target_app and isinstance ( default , bool ) : return default else : raise IllegalArgumentError ( "Please provide either app or label" ) if not version : raise IllegalArgumentError ( "Please provide semantic version string including operand eg: `>=1.0.0`" ) app_version = target_app [ 0 ] . get ( 'version' ) if target_app and app_version and version : import semver return semver . match ( app_version , version ) elif not app_version : if isinstance ( default , bool ) : return default else : raise NotFoundError ( "No version found on the app '{}'" . format ( target_app [ 0 ] . get ( 'app' ) ) ) | Match app version against a semantic version string . | 271 | 9 |
4,273 | def reload ( self , obj , extra_params = None ) : if not obj . _json_data . get ( 'url' ) : # pragma: no cover raise NotFoundError ( "Could not reload object, there is no url for object '{}' configured" . format ( obj ) ) response = self . _request ( 'GET' , obj . _json_data . get ( 'url' ) , params = extra_params ) if response . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not reload object ({})" . format ( response ) ) data = response . json ( ) return obj . __class__ ( data [ 'results' ] [ 0 ] , client = self ) | Reload an object from server . This method is immutable and will return a new object . | 162 | 18 |
4,274 | def scope ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Scope _scopes = self . scopes ( * args , * * kwargs ) if len ( _scopes ) == 0 : raise NotFoundError ( "No scope fits criteria" ) if len ( _scopes ) != 1 : raise MultipleFoundError ( "Multiple scopes fit criteria" ) return _scopes [ 0 ] | Return a single scope based on the provided name . | 96 | 10 |
4,275 | def activities ( self , name = None , pk = None , scope = None , * * kwargs ) : # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity] request_params = { 'id' : pk , 'name' : name , 'scope' : scope } # update the fields query params # for 'kechain.core.wim >= 2.0.0' add additional API params if self . match_app_version ( label = 'wim' , version = '>=2.0.0' , default = False ) : request_params . update ( API_EXTRA_PARAMS [ 'activity' ] ) if kwargs : request_params . update ( * * kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'activities' ) , params = request_params ) if response . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not retrieve activities. Server responded with {}" . format ( str ( response ) ) ) data = response . json ( ) # for 'kechain.core.wim >= 2.0.0' we return Activity2, otherwise Activity1 if self . match_app_version ( label = 'wim' , version = '<2.0.0' , default = True ) : # WIM1 return [ Activity ( a , client = self ) for a in data [ 'results' ] ] else : # WIM2 return [ Activity2 ( a , client = self ) for a in data [ 'results' ] ] | Search for activities with optional name pk and scope filter . | 358 | 12 |
4,276 | def activity ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Activity _activities = self . activities ( * args , * * kwargs ) if len ( _activities ) == 0 : raise NotFoundError ( "No activity fits criteria" ) if len ( _activities ) != 1 : raise MultipleFoundError ( "Multiple activities fit criteria" ) return _activities [ 0 ] | Search for a single activity . | 94 | 6 |
4,277 | def parts ( self , name = None , # type: Optional[str] pk = None , # type: Optional[str] model = None , # type: Optional[Part] category = Category . INSTANCE , # type: Optional[str] bucket = None , # type: Optional[str] parent = None , # type: Optional[str] activity = None , # type: Optional[str] limit = None , # type: Optional[int] batch = 100 , # type: int * * kwargs ) : # type: (...) -> PartSet # if limit is provided and the batchsize is bigger than the limit, ensure that the batch size is maximised if limit and limit < batch : batch = limit request_params = { 'id' : pk , 'name' : name , 'model' : model . id if model else None , 'category' : category , 'bucket' : bucket , 'parent' : parent , 'activity_id' : activity , 'limit' : batch } if kwargs : request_params . update ( * * kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'parts' ) , params = request_params ) if response . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not retrieve parts" ) data = response . json ( ) part_results = data [ 'results' ] if batch and data . get ( 'next' ) : while data [ 'next' ] : # respect the limit if set to > 0 if limit and len ( part_results ) >= limit : break response = self . _request ( 'GET' , data [ 'next' ] ) data = response . json ( ) part_results . extend ( data [ 'results' ] ) return PartSet ( ( Part ( p , client = self ) for p in part_results ) ) | Retrieve multiple KE - chain parts . | 411 | 8 |
4,278 | def part ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Part _parts = self . parts ( * args , * * kwargs ) if len ( _parts ) == 0 : raise NotFoundError ( "No part fits criteria" ) if len ( _parts ) != 1 : raise MultipleFoundError ( "Multiple parts fit criteria" ) return _parts [ 0 ] | Retrieve single KE - chain part . | 90 | 8 |
4,279 | def model ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Part kwargs [ 'category' ] = Category . MODEL _parts = self . parts ( * args , * * kwargs ) if len ( _parts ) == 0 : raise NotFoundError ( "No model fits criteria" ) if len ( _parts ) != 1 : raise MultipleFoundError ( "Multiple models fit criteria" ) return _parts [ 0 ] | Retrieve single KE - chain part model . | 103 | 9 |
4,280 | def property ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Property _properties = self . properties ( * args , * * kwargs ) if len ( _properties ) == 0 : raise NotFoundError ( "No property fits criteria" ) if len ( _properties ) != 1 : raise MultipleFoundError ( "Multiple properties fit criteria" ) return _properties [ 0 ] | Retrieve single KE - chain Property . | 90 | 8 |
4,281 | def properties ( self , name = None , pk = None , category = Category . INSTANCE , * * kwargs ) : # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Property] request_params = { 'name' : name , 'id' : pk , 'category' : category } if kwargs : request_params . update ( * * kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'properties' ) , params = request_params ) if response . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not retrieve properties" ) data = response . json ( ) return [ Property . create ( p , client = self ) for p in data [ 'results' ] ] | Retrieve properties . | 182 | 4 |
4,282 | def services ( self , name = None , pk = None , scope = None , * * kwargs ) : request_params = { 'name' : name , 'id' : pk , 'scope' : scope } if kwargs : request_params . update ( * * kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'services' ) , params = request_params ) if response . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not retrieve services" ) data = response . json ( ) return [ Service ( service , client = self ) for service in data [ 'results' ] ] | Retrieve Services . | 153 | 4 |
4,283 | def service ( self , name = None , pk = None , scope = None , * * kwargs ) : _services = self . services ( name = name , pk = pk , scope = scope , * * kwargs ) if len ( _services ) == 0 : raise NotFoundError ( "No service fits criteria" ) if len ( _services ) != 1 : raise MultipleFoundError ( "Multiple services fit criteria" ) return _services [ 0 ] | Retrieve single KE - chain Service . | 100 | 8 |
4,284 | def service_executions ( self , name = None , pk = None , scope = None , service = None , * * kwargs ) : request_params = { 'name' : name , 'id' : pk , 'service' : service , 'scope' : scope } if kwargs : request_params . update ( * * kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'service_executions' ) , params = request_params ) if r . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not retrieve service executions" ) data = r . json ( ) return [ ServiceExecution ( service_exeuction , client = self ) for service_exeuction in data [ 'results' ] ] | Retrieve Service Executions . | 178 | 6 |
4,285 | def service_execution ( self , name = None , pk = None , scope = None , service = None , * * kwargs ) : _service_executions = self . service_executions ( name = name , pk = pk , scope = scope , service = service , * * kwargs ) if len ( _service_executions ) == 0 : raise NotFoundError ( "No service execution fits criteria" ) if len ( _service_executions ) != 1 : raise MultipleFoundError ( "Multiple service executions fit criteria" ) return _service_executions [ 0 ] | Retrieve single KE - chain ServiceExecution . | 128 | 10 |
4,286 | def users ( self , username = None , pk = None , * * kwargs ) : request_params = { 'username' : username , 'pk' : pk , } if kwargs : request_params . update ( * * kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'users' ) , params = request_params ) if r . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not find users: '{}'" . format ( r . json ( ) ) ) data = r . json ( ) return [ User ( user , client = self ) for user in data [ 'results' ] ] | Users of KE - chain . | 158 | 6 |
4,287 | def user ( self , username = None , pk = None , * * kwargs ) : _users = self . users ( username = username , pk = pk , * * kwargs ) if len ( _users ) == 0 : raise NotFoundError ( "No user criteria matches" ) if len ( _users ) != 1 : raise MultipleFoundError ( "Multiple users fit criteria" ) return _users [ 0 ] | User of KE - chain . | 92 | 6 |
4,288 | def team ( self , name = None , id = None , is_hidden = False , * * kwargs ) : _teams = self . teams ( name = name , id = id , * * kwargs ) if len ( _teams ) == 0 : raise NotFoundError ( "No team criteria matches" ) if len ( _teams ) != 1 : raise MultipleFoundError ( "Multiple teams fit criteria" ) return _teams [ 0 ] | Team of KE - chain . | 99 | 6 |
4,289 | def teams ( self , name = None , id = None , is_hidden = False , * * kwargs ) : request_params = { 'name' : name , 'id' : id , 'is_hidden' : is_hidden } if kwargs : request_params . update ( * * kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'teams' ) , params = request_params ) if r . status_code != requests . codes . ok : # pragma: no cover raise NotFoundError ( "Could not find teams: '{}'" . format ( r . json ( ) ) ) data = r . json ( ) return [ Team ( team , client = self ) for team in data [ 'results' ] ] | Teams of KE - chain . | 171 | 7 |
4,290 | def _create_part ( self , action , data , * * kwargs ) : # suppress_kevents should be in the data (not the query_params) if 'suppress_kevents' in kwargs : data [ 'suppress_kevents' ] = kwargs . pop ( 'suppress_kevents' ) # prepare url query parameters query_params = kwargs query_params [ 'select_action' ] = action response = self . _request ( 'POST' , self . _build_url ( 'parts' ) , params = query_params , # {"select_action": action}, data = data ) if response . status_code != requests . codes . created : raise APIError ( "Could not create part, {}: {}" . format ( str ( response ) , response . content ) ) return Part ( response . json ( ) [ 'results' ] [ 0 ] , client = self ) | Create a part internal core function . | 204 | 7 |
4,291 | def create_part ( self , parent , model , name = None , * * kwargs ) : if parent . category != Category . INSTANCE : raise IllegalArgumentError ( "The parent should be an category 'INSTANCE'" ) if model . category != Category . MODEL : raise IllegalArgumentError ( "The models should be of category 'MODEL'" ) if not name : name = model . name data = { "name" : name , "parent" : parent . id , "model" : model . id } return self . _create_part ( action = "new_instance" , data = data , * * kwargs ) | Create a new part instance from a given model under a given parent . | 138 | 14 |
4,292 | def create_model ( self , parent , name , multiplicity = 'ZERO_MANY' , * * kwargs ) : if parent . category != Category . MODEL : raise IllegalArgumentError ( "The parent should be of category 'MODEL'" ) data = { "name" : name , "parent" : parent . id , "multiplicity" : multiplicity } return self . _create_part ( action = "create_child_model" , data = data , * * kwargs ) | Create a new child model under a given parent . | 110 | 10 |
4,293 | def _create_clone ( self , parent , part , * * kwargs ) : if part . category == Category . MODEL : select_action = 'clone_model' else : select_action = 'clone_instance' data = { "part" : part . id , "parent" : parent . id , "suppress_kevents" : kwargs . pop ( 'suppress_kevents' , None ) } # prepare url query parameters query_params = kwargs query_params [ 'select_action' ] = select_action response = self . _request ( 'POST' , self . _build_url ( 'parts' ) , params = query_params , data = data ) if response . status_code != requests . codes . created : raise APIError ( "Could not clone part, {}: {}" . format ( str ( response ) , response . content ) ) return Part ( response . json ( ) [ 'results' ] [ 0 ] , client = self ) | Create a new Part clone under the Parent . | 215 | 9 |
4,294 | def create_property ( self , model , name , description = None , property_type = PropertyType . CHAR_VALUE , default_value = None , unit = None , options = None ) : if model . category != Category . MODEL : raise IllegalArgumentError ( "The model should be of category MODEL" ) if not property_type . endswith ( '_VALUE' ) : warnings . warn ( "Please use the `PropertyType` enumeration to ensure providing correct " "values to the backend." , UserWarning ) property_type = '{}_VALUE' . format ( property_type . upper ( ) ) if property_type not in PropertyType . values ( ) : raise IllegalArgumentError ( "Please provide a valid propertytype, please use one of `enums.PropertyType`. " "Got: '{}'" . format ( property_type ) ) # because the references value only accepts a single 'model_id' in the default value, we need to convert this # to a single value from the list of values. if property_type in ( PropertyType . REFERENCE_VALUE , PropertyType . REFERENCES_VALUE ) and isinstance ( default_value , ( list , tuple ) ) and default_value : default_value = default_value [ 0 ] data = { "name" : name , "part" : model . id , "description" : description or '' , "property_type" : property_type . upper ( ) , "value" : default_value , "unit" : unit or '' , "options" : options or { } } # # We add options after the fact only if they are available, otherwise the options will be set to null in the # # request and that can't be handled by KE-chain. # if options: # data['options'] = options response = self . _request ( 'POST' , self . _build_url ( 'properties' ) , json = data ) if response . status_code != requests . codes . created : raise APIError ( "Could not create property" ) prop = Property . create ( response . json ( ) [ 'results' ] [ 0 ] , client = self ) model . properties . append ( prop ) return prop | Create a new property model under a given model . | 475 | 10 |
4,295 | def create_service ( self , name , scope , description = None , version = None , service_type = ServiceType . PYTHON_SCRIPT , environment_version = ServiceEnvironmentVersion . PYTHON_3_5 , pkg_path = None ) : if service_type not in ServiceType . values ( ) : raise IllegalArgumentError ( "The type should be of one of {}" . format ( ServiceType . values ( ) ) ) if environment_version not in ServiceEnvironmentVersion . values ( ) : raise IllegalArgumentError ( "The environment version should be of one of {}" . format ( ServiceEnvironmentVersion . values ( ) ) ) data = { "name" : name , "scope" : scope , "description" : description , "script_type" : service_type , "script_version" : version , "env_version" : environment_version , } response = self . _request ( 'POST' , self . _build_url ( 'services' ) , data = data ) if response . status_code != requests . codes . created : # pragma: no cover raise APIError ( "Could not create service ({})" . format ( ( response , response . json ( ) ) ) ) service = Service ( response . json ( ) . get ( 'results' ) [ 0 ] , client = self ) if pkg_path : # upload the package service . upload ( pkg_path ) # refresh service contents in place service . refresh ( ) return service | Create a Service . | 320 | 4 |
4,296 | def delete_scope ( self , scope ) : assert isinstance ( scope , Scope ) , 'Scope "{}" is not a scope!' . format ( scope . name ) response = self . _request ( 'DELETE' , self . _build_url ( 'scope' , scope_id = str ( scope . id ) ) ) if response . status_code != requests . codes . no_content : # pragma: no cover raise APIError ( "Could not delete scope, {}: {}" . format ( str ( response ) , response . content ) ) | Delete a scope . | 119 | 4 |
4,297 | def set_sort ( self , request ) : # Look for 'sort' in get request. If not available use default. sort_request = request . GET . get ( self . sort_parameter , self . default_sort ) if sort_request . startswith ( '-' ) : sort_order = '-' sort_field = sort_request . split ( '-' ) [ 1 ] else : sort_order = '' sort_field = sort_request # Invalid sort requests fail silently if not sort_field in self . _allowed_sort_fields : sort_order = self . default_sort_order sort_field = self . default_sort_field return ( sort_order , sort_field ) | Take the sort parameter from the get parameters and split it into the field and the prefix | 151 | 17 |
4,298 | def get_next_sort_string ( self , field ) : # self.sort_field is the currect sort field if field == self . sort_field : next_sort = self . toggle_sort_order ( ) + field else : default_order_for_field = self . _allowed_sort_fields [ field ] [ 'default_direction' ] next_sort = default_order_for_field + field return self . get_sort_string ( next_sort ) | If we re already sorted by the field then the sort query returned reverses the sort order . | 104 | 19 |
4,299 | def get_sort_indicator ( self , field ) : indicator = '' if field == self . sort_field : indicator = 'sort-asc' if self . sort_order == '-' : indicator = 'sort-desc' return indicator | Returns a sort class for the active sort only . That is if field is not sort_field then nothing will be returned becaues the sort is not active . | 51 | 33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.