idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
28,100 | def _setup_dmtf_schema ( self ) : def print_verbose ( msg ) : """ Inner method prints msg if self.verbose is `True`. """ if self . verbose : print ( msg ) if not os . path . isdir ( self . schema_root_dir ) : print_verbose ( _format ( "Creating directory for CIM Schema archive: {0}" , self . schema_root_dir ) ) os . mkdir ( self . schema_root_dir ) if not os . path . isfile ( self . schema_zip_file ) : print_verbose ( _format ( "Downloading CIM Schema archive from: {0}" , self . schema_zip_url ) ) try : ufo = urlopen ( self . schema_zip_url ) except IOError as ie : os . rmdir ( self . schema_root_dir ) raise ValueError ( _format ( "DMTF Schema archive not found at url {0}: {1}" , self . schema_zip_url , ie ) ) with open ( self . schema_zip_file , 'wb' ) as fp : for data in ufo : fp . write ( data ) if not os . path . isdir ( self . schema_mof_dir ) : print_verbose ( _format ( "Creating directory for CIM Schema MOF files: {0}" , self . schema_mof_dir ) ) os . mkdir ( self . schema_mof_dir ) if not os . path . isfile ( self . _schema_mof_file ) : print_verbose ( _format ( "Unpacking CIM Schema archive: {0}" , self . schema_zip_file ) ) zfp = None try : zfp = ZipFile ( self . schema_zip_file , 'r' ) nlist = zfp . namelist ( ) for file_ in nlist : dfile = os . path . join ( self . schema_mof_dir , file_ ) if dfile [ - 1 ] == '/' : if not os . path . exists ( dfile ) : os . mkdir ( dfile ) else : with open ( dfile , 'w+b' ) as dfp : dfp . write ( zfp . read ( file_ ) ) finally : if zfp : zfp . close ( ) | Install the DMTF CIM schema from the DMTF web site if it is not already installed . This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by schema_mof_dir . | 518 | 54 |
28,101 | def clean ( self ) : if os . path . isdir ( self . schema_mof_dir ) : shutil . rmtree ( self . schema_mof_dir ) | Remove all of the MOF files and the schema_mof_dir for the defined schema . This is useful because while the downloaded schema is a single compressed zip file it creates several thousand MOF files that take up considerable space . | 40 | 47 |
28,102 | def remove ( self ) : self . clean ( ) if os . path . isfile ( self . schema_zip_file ) : os . remove ( self . schema_zip_file ) if os . path . isdir ( self . schema_root_dir ) and os . listdir ( self . schema_root_dir ) == [ ] : os . rmdir ( self . schema_root_dir ) | The schema_mof_dir directory is removed if it esists and the schema_zip_file is removed if it exists . If the schema_root_dir is empty after these removals that directory is removed . | 88 | 46 |
28,103 | def print_table ( title , headers , rows , sort_columns = None ) : if sort_columns is not None : if isinstance ( sort_columns , int ) : rows = sorted ( rows , key = itemgetter ( sort_columns ) ) elif isinstance ( sort_columns , ( list , tuple ) ) : rows = sorted ( rows , key = itemgetter ( * sort_columns ) ) else : assert False , "Sort_columns must be int or list/tuple of int" if title : print ( '\n%s:' % title ) else : print ( '' ) print ( tabulate . tabulate ( rows , headers , tablefmt = 'simple' ) ) print ( '' ) | Print a table of rows with headers using tabulate . | 160 | 11 |
28,104 | def fold_list ( input_list , max_width = None ) : if not input_list : return "" if not isinstance ( input_list [ 0 ] , six . string_types ) : input_list = [ str ( item ) for item in input_list ] if max_width : mystr = ", " . join ( input_list ) return fold_string ( mystr , max_width ) return "\n" . join ( input_list ) | Fold the entries in input_list . If max_width is not None fold only if it is longer than max_width . Otherwise fold each entry . | 99 | 32 |
28,105 | def fold_string ( input_string , max_width ) : new_string = input_string if isinstance ( input_string , six . string_types ) : if max_width < len ( input_string ) : # use textwrap to fold the string new_string = textwrap . fill ( input_string , max_width ) return new_string | Fold a string within a maximum width . | 77 | 9 |
28,106 | def path_wo_ns ( obj ) : if isinstance ( obj , pywbem . CIMInstance ) : path = obj . path . copy ( ) elif isinstance ( obj , pywbem . CIMInstanceName ) : path = obj . copy ( ) else : assert False path . host = None path . namespace = None return path | Return path of an instance or instance path without host or namespace . Creates copy of the object so the original is not changed . | 74 | 26 |
28,107 | def connect ( nickname , server_def , debug = None , timeout = 10 ) : url = server_def . url conn = pywbem . WBEMConnection ( url , ( server_def . user , server_def . password ) , default_namespace = server_def . implementation_namespace , no_verification = server_def . no_verification , timeout = timeout ) if debug : conn . debug = True ns = server_def . implementation_namespace if server_def . implementation_namespace else 'interop' try : conn . GetQualifier ( 'Association' , namespace = ns ) return conn except pywbem . ConnectionError as exc : print ( "Test server {0} at {1!r} cannot be reached. {2}: {3}" . format ( nickname , url , exc . __class__ . __name__ , exc ) ) return None except pywbem . AuthError as exc : print ( "Test server {0} at {1!r} cannot be authenticated with. " "{2}: {3}" . format ( nickname , url , exc . __class__ . __name__ , exc ) ) return None except pywbem . CIMError as ce : if ce . status_code == pywbem . CIM_ERR_NAMESPACE_NOT_FOUND or ce . status . code == pywbem . CIM_ERR_NOT_FOUND : return conn else : return None except pywbem . Error as exc : print ( "Test server {0} at {1!r} returned exception. {2}: {3}" . format ( nickname , url , exc . __class__ . __name__ , exc ) ) return None | Connect and confirm server works by testing for a known class in the default namespace or if there is no default namespace defined in all the possible interop namespaces . | 367 | 32 |
28,108 | def overview ( name , server ) : print ( '%s OVERVIEW' % name ) print ( " Interop namespace: %s" % server . interop_ns ) print ( " Brand: %s" % server . brand ) print ( " Version: %s" % server . version ) print ( " Namespaces: %s" % ", " . join ( server . namespaces ) ) print ( ' namespace_classname: %s' % server . namespace_classname ) if VERBOSE : print ( 'cimom_inst:\n%s' % server . cimom_inst . tomof ( ) ) print ( 'server__str__: %s' % server ) print ( 'server__repr__: %r' % server ) try : insts = server . conn . EnumerateInstances ( 'CIM_Namespace' , namespace = server . interop_ns ) print ( '%s: Instances of CIM_Namespace' % name ) for inst in insts : print ( '%r' % inst ) except pywbem . Error as er : print ( 'ERROR: %s: Enum CIM_Namespace failed %s' % ( name , er ) ) try : insts = server . conn . EnumerateInstances ( '__Namespace' , namespace = server . interop_ns ) print ( '%s: Instances of __Namespace' % name ) for inst in insts : print ( '%r' % inst ) except pywbem . Error as er : print ( 'ERROR: %s: Enum __Namespace failed %s' % ( name , er ) ) | Overview of the server as seen through the properties of the server class . | 358 | 14 |
28,109 | def get_references ( profile_path , role , profile_name , server ) : references_for_profile = server . conn . References ( ObjectName = profile_path , ResultClass = "CIM_ReferencedProfile" , Role = role ) if VERBOSE : print ( 'References for profile=%s, path=%s, ResultClass=' 'CIM_ReferencedProfile, Role=%s' % ( profile_name , profile_path , role ) ) for ref in references_for_profile : print ( 'Reference for %s get_role=%s cn=%s\n antecedent=%s\n ' 'dependent=%s' % ( profile_name , role , ref . classname , ref [ 'Antecedent' ] , ref [ 'Dependent' ] ) ) return references_for_profile | Get display and return the References for the path provided ResultClass CIM_ReferencedProfile and the role provided . | 187 | 24 |
28,110 | def show_profiles ( name , server , org_vm ) : rows = [ ] for profile_inst in server . profiles : pn = profile_name ( org_vm , profile_inst ) deps = get_associated_profile_names ( profile_inst . path , "dependent" , org_vm , server , include_classnames = False ) dep_refs = get_references ( profile_inst . path , "antecedent" , pn , server ) ants = get_associated_profile_names ( profile_inst . path , "antecedent" , org_vm , server , include_classnames = False ) ant_refs = get_references ( profile_inst . path , "dependent" , profile_name , server ) # get unique class names dep_ref_clns = set ( [ ref . classname for ref in dep_refs ] ) ant_ref_clns = set ( [ ref . classname for ref in ant_refs ] ) row = ( pn , fold_list ( deps ) , fold_list ( list ( dep_ref_clns ) ) , fold_list ( ants ) , fold_list ( list ( ant_ref_clns ) ) ) rows . append ( row ) # append this server to the dict of servers for this profile SERVERS_FOR_PROFILE [ profile_name ] . append ( name ) title = '%s: Advertised profiles showing Profiles associations' 'Dependencies are Associators, AssocClass=CIM_ReferencedProfile' 'This table shows the results for ' % name headers = [ 'Profile' , 'Assoc CIMReferencedProfile\nResultRole\nDependent' , 'Ref classes References\nRole=Dependent' , 'Assoc CIMReferencedProfile\nResultRole\nAntecedent' , 'Ref classesReferences\nRole=Dependent' ] print_table ( title , headers , rows , sort_columns = [ 1 , 0 ] ) | Create a table of info about the profiles based on getting the references etc . both in the dependent and antecedent direction . | 441 | 25 |
28,111 | def fold_path ( path , width = 30 ) : assert isinstance ( path , six . string_types ) if len ( path ) > width : path . replace ( "." , ".\n " ) return path | Fold a string form of a path so that each element is on separate line | 46 | 16 |
28,112 | def count_ref_associators ( nickname , server , profile_insts , org_vm ) : def get_assoc_count ( server , profile_inst ) : """ Execute Associator names with ResultRole as 'Dependent' and then as 'Antecedent' and return the count of associations returned for each operation """ deps = server . conn . AssociatorNames ( ObjectName = profile_inst . path , AssocClass = "CIM_ReferencedProfile" , ResultRole = 'Dependent' ) ants = server . conn . AssociatorNames ( ObjectName = profile_inst . path , AssocClass = "CIM_ReferencedProfile" , ResultRole = 'Antecedent' ) return ( len ( deps ) , len ( ants ) ) assoc_dict = { } for profile_inst in profile_insts : deps_count , ants_count = get_assoc_count ( server , profile_inst ) pn = profile_name ( org_vm , profile_inst ) assoc_dict [ pn ] = ( deps_count , ants_count ) title = 'Display antecedent and dependent counts for possible ' 'autonomous profiles using slow algorithm.\n' 'Displays the number of instances returned by\n' 'Associators request on profile for possible autonomous profiles' rows = [ ( key , value [ 0 ] , value [ 1 ] ) for key , value in assoc_dict . items ( ) ] print_table ( title , [ 'profile' , 'Dependent\nCount' , 'Antecedent\nCount' ] , rows , sort_columns = 0 ) # add rows to the global list for table of g_rows = [ ( nickname , key , value [ 0 ] , value [ 1 ] ) for key , value in assoc_dict . items ( ) ] ASSOC_PROPERTY_COUNTS . extend ( g_rows ) return assoc_dict | Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list . This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile instance in profile_insts with the result Role set to Dependent and then Antecedent to get the count of objects returned . | 426 | 75 |
28,113 | def fast_count_associators ( server ) : try : ref_insts = server . conn . EnumerateInstances ( "CIM_ReferencedProfile" , namespace = server . interop_ns ) # Remove host from responses since the host causes confusion # with the enum of registered profile. Enums do not return host but # the associator properties contain host for ref_inst in ref_insts : for prop in ref_inst . values ( ) : prop . host = None except pywbem . Error as er : print ( 'CIM_ReferencedProfile failed for conn=%s\nexception=%s' % ( server , er ) ) raise # Create dict with the following characteristics: # key = associator source object path # value = {'dep' : count of associations, # 'ant' : count of associations} # where: an association is a reference property that does not have same # value as the source object path but for which the source object # path is the value of one of the properties association_dict = { } # We are counting too many. Have same properties for class and subclass # but appear to count that one twice. Looks like we need one more piece. # for each. If association_dict[profile_key] not in some list for profile in server . profiles : profile_key = profile . path ant_dict = { } dep_dict = { } for ref_inst in ref_insts : # These dictionaries insure that there are no duplicates in # the result. Some servers duplicate the references in subclasses. if profile_key not in association_dict : association_dict [ profile_key ] = { 'dep' : 0 , 'ant' : 0 } ant = ref_inst [ 'antecedent' ] dep = ref_inst [ 'dependent' ] if profile_key != ant and profile_key != dep : continue if dep != profile_key : if dep not in dep_dict : dep_dict [ dep ] = True association_dict [ profile_key ] [ 'dep' ] += 1 if ant != profile_key : if ant not in ant_dict : ant_dict [ ant ] = True association_dict [ profile_key ] [ 'ant' ] += 1 return association_dict | Create count of associators for CIM_ReferencedProfile using the antecedent and dependent reference properties as ResultRole for each profile defined in server . profiles and return a dictionary of the count . This code does a shortcut in executing EnumerateInstances to get CIM_ReferencedProfile and processing the association locally . | 484 | 68 |
28,114 | def show_instances ( server , cim_class ) : if cim_class == 'CIM_RegisteredProfile' : for inst in server . profiles : print ( inst . tomof ( ) ) return for ns in server . namespaces : try : insts = server . conn . EnumerateInstances ( cim_class , namespace = ns ) if len ( insts ) : print ( 'INSTANCES OF %s ns=%s' % ( cim_class , ns ) ) for inst in insts : print ( inst . tomof ( ) ) except pywbem . Error as er : if er . status_code != pywbem . CIM_ERR_INVALID_CLASS : print ( '%s namespace %s Enumerate failed for conn=%s\n' 'exception=%s' % ( cim_class , ns , server , er ) ) | Display the instances of the CIM_Class defined by cim_class . If the namespace is None use the interop namespace . Search all namespaces for instances except for CIM_RegisteredProfile | 196 | 40 |
28,115 | def get_profiles_in_svr ( nickname , server , all_profiles_dict , org_vm , add_error_list = False ) : profiles_in_dict = [ ] for profile_inst in server . profiles : pn = profile_name ( org_vm , profile_inst , short = True ) if pn in all_profiles_dict : profiles_in_dict . append ( profile_inst ) else : if add_error_list : print ( 'PROFILES_WITH_NO_DEFINITIONS svr=%s: %s' % ( nickname , pn ) ) PROFILES_WITH_NO_DEFINITIONS [ nickname ] = pn return profiles_in_dict | Test all profiles in server . profiles to determine if profile is in the all_profiles_dict . | 163 | 21 |
28,116 | def possible_target_profiles ( nickname , server , all_profiles_dict , org_vm , autonomous = True , output = 'path' ) : assert output in [ 'path' , 'name' ] profiles_in_svr = get_profiles_in_svr ( nickname , server , all_profiles_dict , org_vm ) # list of possible autonomous profiles for testing possible_profiles = [ ] for profile_inst in profiles_in_svr : profile_org_name = profile_name ( org_vm , profile_inst , short = True ) if autonomous : if all_profiles_dict [ profile_org_name ] . type == 'autonomous' : possible_profiles . append ( profile_inst ) else : if not all_profiles_dict [ profile_org_name ] . type == 'component' : possible_profiles . append ( profile_inst ) if output == 'path' : possible_profiles = [ inst . path for inst in possible_profiles ] elif output == 'name' : possible_profiles = [ profile_name ( org_vm , inst ) for inst in possible_profiles ] return possible_profiles | Get list of possible autonomous or component profiles based on the list of all profiles and the list of profiles in the defined server . | 259 | 25 |
28,117 | def show_tree ( nickname , server , org_vm , reference_direction = 'snia' ) : scoping_result_role = "Dependent" if reference_direction == 'snia' else "Antecedent" profiles = server . profiles reg_profiles = { } for profile in profiles : reg_profiles [ profile . path . to_wbem_uri ( format = "canonical" ) ] = profile # defines element to subelement tree_dict = defaultdict ( list ) for profile in profiles : paths = server . conn . AssociatorNames ( profile . path , AssocClass = 'CIM_ElementConformsToProfile' , ResultClass = "CIM_RegisteredProfile" , ResultRole = "ManagedElement" ) if paths : print ( '%s: associators ELEMENTCONFORMSTO %s' % ( nickname , profile . path . to_wbem_uri ( format = "canonical" ) ) ) for path in paths : print ( " %s" % path ) profile . path . host = None profile_path_str = profile . path . to_wbem_uri ( format = "canonical" ) for path in paths : tree_dict [ profile_path_str ] . append ( path . to_wbem_uri ( format = "canonical" ) ) # Go down one level on the profile side, to the scoping profile referenced_profile_paths = server . conn . AssociatorNames ( ObjectName = profile . path , AssocClass = "CIM_ReferencedProfile" , ResultRole = scoping_result_role ) if referenced_profile_paths : print ( '%s AssocNames CIM_ReferencedProfile %s' % ( nickname , profile . path . to_wbem_uri ( format = "canonical" ) ) ) for path in referenced_profile_paths : print ( " %s" % path . to_wbem_uri ( format = "canonical" ) ) for path in referenced_profile_paths : path . host = None tree_dict [ profile_path_str ] . append ( path . to_wbem_uri ( format = "canonical" ) ) for key , values in tree_dict . items ( ) : print ( '%s\n %s' % ( key , "\n " . join ( values ) ) ) name_dict = { } for key , values in tree_dict . items ( ) : prof = reg_profiles [ key ] pn = profile_name ( org_vm , prof ) pvalues = [ ] for value in values : profx = reg_profiles [ value ] pvalues . append ( profile_name ( org_vm , profx ) ) name_dict [ pn ] = pvalues for key , values in name_dict . items ( ) : print ( '%s\n %s' % ( key , "\n " . join ( values ) ) ) | sShow a tree view of the registered profiles using the ECTP and referencedprofile associations to define the tree . Starts with SMI - S if it iexists | 638 | 34 |
28,118 | def display_servers ( server_definitions_filename ) : servers = ServerDefinitionFile2 ( server_definitions_filename ) title = 'List of all servers that can be tested' headers = [ 'Name' , 'Url' , 'Default_namespace' ] rows = [ ] for server in servers . list_all_servers ( ) : # specifically does not show server user and pw rows . append ( ( server . nickname , server . url , server . default_namespace ) ) print_table ( title , headers , rows , sort_columns = 0 ) | display the defined servers information as a table . | 124 | 9 |
28,119 | def elapsed_ms ( self ) : dt = datetime . datetime . now ( ) - self . start_time return ( ( dt . days * 24 * 3600 ) + dt . seconds ) * 1000 + dt . microseconds / 1000.0 | Get the elapsed time in milliseconds . returns floating point representation of elapsed time in seconds . | 57 | 17 |
28,120 | def list_servers ( self , nicknames = None ) : if not nicknames : return self . list_all_servers ( ) if isinstance ( nicknames , six . string_types ) : nicknames = [ nicknames ] sd_list = [ ] sd_nick_list = [ ] for nickname in nicknames : if nickname in self . _servers : sd_list . append ( self . get_server ( nickname ) ) elif nickname in self . _server_groups : for item_nick in self . _server_groups [ nickname ] : for sd in self . list_servers ( item_nick ) : if sd . nickname not in sd_nick_list : sd_nick_list . append ( sd . nickname ) sd_list . append ( sd ) else : raise ValueError ( "Server group or server nickname {0!r} not found in WBEM " "server definition file {1!r}" . format ( nickname , self . _filepath ) ) return sd_list | Iterate through the servers of the server group with the specified nicknames or the single server with the specified nickname and yield a ServerDefinition object for each server . | 216 | 32 |
28,121 | def print_profile_info ( org_vm , profile_instance ) : org = org_vm . tovalues ( profile_instance [ 'RegisteredOrganization' ] ) name = profile_instance [ 'RegisteredName' ] vers = profile_instance [ 'RegisteredVersion' ] print ( " %s %s Profile %s" % ( org , name , vers ) ) | Print information on a profile defined by profile_instance . | 78 | 11 |
28,122 | def create_indication_data ( msg_id , sequence_number , source_id , delta_time , protocol_ver ) : data_template = """<?xml version="1.0" encoding="utf-8" ?> <CIM CIMVERSION="2.0" DTDVERSION="2.4"> <MESSAGE ID="%(msg_id)s" PROTOCOLVERSION="%(protocol_ver)s"> <SIMPLEEXPREQ> <EXPMETHODCALL NAME="ExportIndication"> <EXPPARAMVALUE NAME="NewIndication"> <INSTANCE CLASSNAME="CIM_AlertIndication"> <PROPERTY NAME="Severity" TYPE="string"> <VALUE>high</VALUE> </PROPERTY> <PROPERTY NAME="SequenceNumber" TYPE="string"> <VALUE>%(sequence_number)s</VALUE> </PROPERTY> <PROPERTY NAME="SourceId" TYPE="string"> <VALUE>%(source_id)s</VALUE> </PROPERTY> <PROPERTY NAME="DELTA_TIME" TYPE="string"> <VALUE>%(delta_time)s</VALUE> </PROPERTY> </INSTANCE> </EXPPARAMVALUE> </EXPMETHODCALL> </SIMPLEEXPREQ> </MESSAGE> </CIM>""" data = { 'sequence_number' : sequence_number , 'source_id' : source_id , 'delta_time' : delta_time , 'protocol_ver' : protocol_ver , 'msg_id' : msg_id } return data_template % data | Create a singled indication XML from the template and the included sequence_number delta_time and protocol_ver | 363 | 21 |
28,123 | def send_indication ( url , headers , payload , verbose , verify = None , keyfile = None , timeout = 4 ) : try : response = requests . post ( url , headers = headers , data = payload , timeout = timeout , verify = verify ) except Exception as ex : print ( 'Exception %s' % ex ) return False # validate response status code and xml if verbose or response . status_code != 200 : print ( '\nResponse code=%s headers=%s data=%s' % ( response . status_code , response . headers , response . text ) ) root = ET . fromstring ( response . text ) if ( root . tag != 'CIM' ) or ( root . attrib [ 'CIMVERSION' ] != '2.0' ) or ( root . attrib [ 'DTDVERSION' ] != '2.4' ) : print ( 'Invalid XML\nResponse code=%s headers=%s data=%s' % ( response . status_code , response . headers , response . text ) ) return False for child in root : if child . tag != 'MESSAGE' or child . attrib [ 'PROTOCOLVERSION' ] != '1.4' : print ( 'Invalid child\nResponse code=%s headers=%s data=%s' % ( response . status_code , response . headers , response . text ) ) return False return True if ( response . status_code == 200 ) else False | Send indication using requests module . | 321 | 6 |
28,124 | def _get_required_attribute ( node , attr ) : if not node . hasAttribute ( attr ) : raise ParseError ( 'Expecting %s attribute in element %s' % ( attr , node . tagName ) ) return node . getAttribute ( attr ) | Return an attribute by name . Raise ParseError if not present . | 61 | 14 |
28,125 | def _get_end_event ( parser , tagName ) : ( event , node ) = six . next ( parser ) if event != pulldom . END_ELEMENT or node . tagName != tagName : raise ParseError ( 'Expecting %s end tag, got %s %s' % ( tagName , event , node . tagName ) ) | Check that the next event is the end of a particular XML tag . | 78 | 14 |
28,126 | def make_parser ( stream_or_string ) : if isinstance ( stream_or_string , six . string_types ) : # XXX: the pulldom.parseString() function doesn't seem to # like operating on unicode strings! return pulldom . parseString ( str ( stream_or_string ) ) else : return pulldom . parse ( stream_or_string ) | Create a xml . dom . pulldom parser . | 82 | 10 |
28,127 | def parse_any ( stream_or_string ) : parser = make_parser ( stream_or_string ) ( event , node ) = six . next ( parser ) if event != pulldom . START_DOCUMENT : raise ParseError ( 'Expecting document start' ) ( event , node ) = six . next ( parser ) if event != pulldom . START_ELEMENT : raise ParseError ( 'Expecting element start' ) fn_name = 'parse_%s' % node . tagName . lower ( ) . replace ( '.' , '_' ) fn = globals ( ) . get ( fn_name ) if fn is None : raise ParseError ( 'No parser for element %s' % node . tagName ) return fn ( parser , event , node ) | Parse any XML string or stream . This function fabricates the names of the parser functions by prepending parse_ to the node name and then calling that function . | 171 | 33 |
28,128 | def _process_indication ( indication , host ) : global RECEIVED_INDICATION_DICT COUNTER_LOCK . acquire ( ) if host in RECEIVED_INDICATION_DICT : RECEIVED_INDICATION_DICT [ host ] += 1 else : RECEIVED_INDICATION_DICT [ host ] = 1 COUNTER_LOCK . release ( ) listener . logger . info ( "Consumed CIM indication #%s: host=%s\n%s" , RECEIVED_INDICATION_DICT , host , indication . tomof ( ) ) | This function gets called when an indication is received . | 136 | 10 |
28,129 | def _get_argv ( index , default = None ) : return _sys . argv [ index ] if len ( _sys . argv ) > index else default | get the argv input argument defined by index . Return the default attribute if that argument does not exist | 36 | 20 |
28,130 | def status ( reset = None ) : global RECEIVED_INDICATION_DICT for host , count in six . iteritems ( RECEIVED_INDICATION_DICT ) : print ( 'Host %s Received %s indications' % ( host , count ) ) if reset : for host in RECEIVED_INDICATION_DICT : RECEIVED_INDICATION_DICT [ host ] = 0 print ( 'Host %s Reset: Received %s indications' % ( host , RECEIVED_INDICATION_DICT [ host ] ) ) print ( 'counts reset to 0' ) | Show status of indications received . If optional reset attribute is True reset the counter . | 138 | 16 |
28,131 | def _get_members ( self , class_obj , member_type , include_in_public = None ) : try : app = self . state . document . settings . env . app except AttributeError : app = None if not include_in_public : include_in_public = [ ] all_members = [ ] for member_name in dir ( class_obj ) : try : documenter = get_documenter ( app , safe_getattr ( class_obj , member_name ) , class_obj ) except AttributeError : continue if documenter . objtype == member_type : all_members . append ( member_name ) public_members = [ x for x in all_members if x in include_in_public or not x . startswith ( '_' ) ] return public_members , all_members | Return class members of the specified type . | 180 | 8 |
28,132 | def _get_def_class ( self , class_obj , member_name ) : member_obj = getattr ( class_obj , member_name ) for def_class_obj in inspect . getmro ( class_obj ) : if member_name in def_class_obj . __dict__ : if def_class_obj . __name__ in self . _excluded_classes : return class_obj # Fall back to input class return def_class_obj self . _logger . warning ( "%s: Definition class not found for member %s.%s, " "defaulting to class %s" , self . _log_prefix , class_obj . __name__ , member_name , class_obj . __name__ ) return class_obj | Return the class object in MRO order that defines a member . | 166 | 13 |
28,133 | def reset ( self ) : self . _count = 0 self . _exception_count = 0 self . _stat_start_time = None self . _time_sum = float ( 0 ) self . _time_min = float ( 'inf' ) self . _time_max = float ( 0 ) self . _server_time_sum = float ( 0 ) self . _server_time_min = float ( 'inf' ) self . _server_time_max = float ( 0 ) self . _server_time_stored = False self . _request_len_sum = float ( 0 ) self . _request_len_min = float ( 'inf' ) self . _request_len_max = float ( 0 ) self . _reply_len_sum = float ( 0 ) self . _reply_len_min = float ( 'inf' ) self . _reply_len_max = float ( 0 ) | Reset the statistics data for this object . | 200 | 9 |
28,134 | def start_timer ( self ) : if self . container . enabled : self . _start_time = time . time ( ) if not self . _stat_start_time : self . _stat_start_time = self . _start_time | This is a low - level method that is called by pywbem at the begin of an operation . It starts the measurement for that operation if statistics is enabled for the connection . | 53 | 36 |
28,135 | def stop_timer ( self , request_len , reply_len , server_time = None , exception = False ) : if not self . container . enabled : return None # stop the timer if self . _start_time is None : raise RuntimeError ( 'stop_timer() called without preceding ' 'start_timer()' ) dt = time . time ( ) - self . _start_time self . _start_time = None self . _count += 1 self . _time_sum += dt self . _request_len_sum += request_len self . _reply_len_sum += reply_len if exception : self . _exception_count += 1 if dt > self . _time_max : self . _time_max = dt if dt < self . _time_min : self . _time_min = dt if server_time : self . _server_time_stored = True self . _server_time_sum += server_time if dt > self . _server_time_max : self . _server_time_max = server_time if dt < self . _server_time_min : self . _server_time_min = server_time if request_len > self . _request_len_max : self . _request_len_max = request_len if request_len < self . _request_len_min : self . _request_len_min = request_len if reply_len > self . _reply_len_max : self . _reply_len_max = reply_len if reply_len < self . _reply_len_min : self . _reply_len_min = reply_len return dt | This is a low - level method is called by pywbem at the end of an operation . It completes the measurement for that operation by capturing the needed data and updates the statistics data if statistics is enabled for the connection . | 369 | 45 |
28,136 | def formatted ( self , include_server_time ) : if include_server_time : # pylint: disable=no-else-return return ( '{0:5d} {1:5d} ' '{2:7.3f} {3:7.3f} {4:7.3f} ' '{5:7.3f} {6:7.3f} {7:7.3f} ' '{8:6.0f} {9:6.0f} {10:6.0f} ' '{11:8.0f} {12:8.0f} {13:8.0f} {14}\n' . format ( self . count , self . exception_count , self . avg_time , self . min_time , self . max_time , self . avg_server_time , self . min_server_time , self . max_server_time , self . avg_request_len , self . min_request_len , self . max_request_len , self . avg_reply_len , self . min_reply_len , self . max_reply_len , self . name ) ) else : return ( '{0:5d} {1:5d} ' '{2:7.3f} {3:7.3f} {4:7.3f} ' '{5:6.0f} {6:6.0f} {7:6.0f} ' '{8:6.0f} {9:8.0f} {10:8.0f} {11}\n' . format ( self . count , self . exception_count , self . avg_time , self . min_time , self . max_time , self . avg_request_len , self . min_request_len , self . max_request_len , self . avg_reply_len , self . min_reply_len , self . max_reply_len , self . name ) ) | Return a formatted one - line string with the statistics values for the operation for which this statistics object maintains data . | 447 | 22 |
28,137 | def formatted ( self ) : # pylint: disable=line-too-long # noqa: E501 # pylint: enable=line-too-long ret = "Statistics (times in seconds, lengths in Bytes):\n" if self . enabled : snapshot = sorted ( self . snapshot ( ) , key = lambda item : item [ 1 ] . avg_time , reverse = True ) # Test to see if any server time is non-zero include_svr = False for name , stats in snapshot : # pylint: disable=unused-variable # pylint: disable=protected-access if stats . _server_time_stored : include_svr = True # pylint: disable=protected-access if include_svr : ret += OperationStatistic . _formatted_header_w_svr else : ret += OperationStatistic . _formatted_header for name , stats in snapshot : # pylint: disable=unused-variable ret += stats . formatted ( include_svr ) else : ret += "Disabled" return ret . strip ( ) | Return a human readable string with the statistics for this container . The operations are sorted by decreasing average time . | 237 | 21 |
28,138 | def reset ( self ) : # Test for any stats being currently timed. for stat in six . itervalues ( self . _op_stats ) : if stat . _start_time is not None : # pylint: disable=protected-access return False # clear all statistics self . _op_stats = { } return True | Reset all statistics and clear any statistic names . All statistics must be inactive before a reset will execute | 71 | 20 |
28,139 | def remove_duplicate_metadata_dirs ( package_name ) : print ( "Removing duplicate metadata directories of package: %s" % package_name ) module = importlib . import_module ( package_name ) py_mn = "%s.%s" % ( sys . version_info [ 0 ] , sys . version_info [ 1 ] ) print ( "Current Python version: %s" % py_mn ) version = module . __version__ print ( "Version of imported %s package: %s" % ( package_name , version ) ) site_dir = os . path . dirname ( os . path . dirname ( module . __file__ ) ) print ( "Site packages directory of imported package: %s" % site_dir ) metadata_dirs = [ ] metadata_dirs . extend ( glob . glob ( os . path . join ( site_dir , '%s-*.dist-info' % package_name ) ) ) metadata_dirs . extend ( glob . glob ( os . path . join ( site_dir , '%s-*-py%s.egg-info' % ( package_name , py_mn ) ) ) ) for d in metadata_dirs : m = re . search ( r'/%s-([0-9.]+)(\.di|-py)' % package_name , d ) if not m : print ( "Warning: Could not parse metadata directory: %s" % d ) continue d_version = m . group ( 1 ) if d_version == version : print ( "Found matching metadata directory: %s" % d ) continue print ( "Removing duplicate metadata directory: %s" % d ) shutil . rmtree ( d ) | Remove duplicate metadata directories of a package . | 375 | 8 |
28,140 | def display_path_info ( descriptor , class_ , namespace ) : paths = CONN . EnumerateInstanceNames ( class_ , namespace = interop ) # noqa: F821 print ( '%ss: count=%s' % ( descriptor , len ( paths ) ) ) for path in paths : print ( '%s: %s' % ( descriptor , path ) ) return paths | Display info on the instance names of the class parameter retrieved from the interop namespace of the server defined by CONN . | 85 | 24 |
28,141 | def kids ( tup_tree ) : k = tup_tree [ 2 ] if k is None : return [ ] # pylint: disable=unidiomatic-typecheck return [ x for x in k if type ( x ) == tuple ] | Return a list with the child elements of tup_tree . | 54 | 13 |
28,142 | def pcdata ( self , tup_tree ) : try : data = u'' . join ( tup_tree [ 2 ] ) except TypeError : raise CIMXMLParseError ( _format ( "Element {0!A} has unexpected child elements: " "{1!A} (allowed is only text content)" , name ( tup_tree ) , tup_tree [ 2 ] ) , conn_id = self . conn_id ) return data | Return the concatenated character data within the child nodes of a tuple tree node as a unicode string . Whitespace is preserved . | 100 | 27 |
28,143 | def check_node ( self , tup_tree , nodename , required_attrs = None , optional_attrs = None , allowed_children = None , allow_pcdata = False ) : # pylint: disable=too-many-branches if name ( tup_tree ) != nodename : raise CIMXMLParseError ( _format ( "Unexpected element {0!A} (expecting element {1!A})" , name ( tup_tree ) , nodename ) , conn_id = self . conn_id ) # Check we have all the required attributes, and no unexpected ones tt_attrs = { } if attrs ( tup_tree ) is not None : tt_attrs = attrs ( tup_tree ) . copy ( ) if required_attrs : for attr in required_attrs : if attr not in tt_attrs : raise CIMXMLParseError ( _format ( "Element {0!A} missing required attribute " "{1!A} (only has attributes {2!A})" , name ( tup_tree ) , attr , attrs ( tup_tree ) . keys ( ) ) , conn_id = self . conn_id ) del tt_attrs [ attr ] if optional_attrs : for attr in optional_attrs : if attr in tt_attrs : del tt_attrs [ attr ] if tt_attrs : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid attribute(s) {1!A}" , name ( tup_tree ) , tt_attrs . keys ( ) ) , conn_id = self . conn_id ) if allowed_children is not None : invalid_children = [ ] for child in kids ( tup_tree ) : if name ( child ) not in allowed_children : invalid_children . append ( name ( child ) ) if invalid_children : if not allowed_children : allow_txt = "no child elements are allowed" else : allow_txt = _format ( "allowed are child elements {0!A}" , allowed_children ) raise CIMXMLParseError ( _format ( "Element {0!A} has invalid child element(s) " "{1!A} ({2})" , name ( tup_tree ) , set ( invalid_children ) , allow_txt ) , conn_id = self . conn_id ) if not allow_pcdata : for child in tup_tree [ 2 ] : if isinstance ( child , six . string_types ) : if child . lstrip ( ' \t\n' ) != '' : raise CIMXMLParseError ( _format ( "Element {0!A} has unexpected non-blank " "text content {1!A}" , name ( tup_tree ) , child ) , conn_id = self . conn_id ) | Check static local constraints on a tuple tree node . | 648 | 10 |
28,144 | def one_child ( self , tup_tree , acceptable ) : k = kids ( tup_tree ) if not k : raise CIMXMLParseError ( _format ( "Element {0!A} missing required child element {1!A}" , name ( tup_tree ) , acceptable ) , conn_id = self . conn_id ) if len ( k ) > 1 : raise CIMXMLParseError ( _format ( "Element {0!A} has too many child elements {1!A} " "(allowed is one child element {2!A})" , name ( tup_tree ) , [ name ( t ) for t in k ] , acceptable ) , conn_id = self . conn_id ) child = k [ 0 ] if name ( child ) not in acceptable : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid child element {1!A} " "(allowed is one child element {2!A})" , name ( tup_tree ) , name ( child ) , acceptable ) , conn_id = self . conn_id ) return self . parse_any ( child ) | Parse children of a node with exactly one child node . | 253 | 12 |
28,145 | def notimplemented ( self , tup_tree ) : raise CIMXMLParseError ( _format ( "Internal Error: Parsing support for element {0!A} is " "not implemented" , name ( tup_tree ) ) , conn_id = self . conn_id ) | Raise exception for not implemented function . | 66 | 8 |
28,146 | def parse_value ( self , tup_tree ) : self . check_node ( tup_tree , 'VALUE' , ( ) , ( ) , ( ) , allow_pcdata = True ) return self . pcdata ( tup_tree ) | Parse a VALUE element and return its text content as a unicode string . Whitespace is preserved . | 55 | 22 |
28,147 | def parse_value_array ( self , tup_tree ) : self . check_node ( tup_tree , 'VALUE.ARRAY' ) children = self . list_of_various ( tup_tree , ( 'VALUE' , 'VALUE.NULL' ) ) return children | Parse a VALUE . ARRAY element and return the items in the array as a list of unicode strings or None for NULL items . Whitespace is preserved . | 63 | 34 |
28,148 | def parse_value_reference ( self , tup_tree ) : self . check_node ( tup_tree , 'VALUE.REFERENCE' ) child = self . one_child ( tup_tree , ( 'CLASSPATH' , 'LOCALCLASSPATH' , 'CLASSNAME' , 'INSTANCEPATH' , 'LOCALINSTANCEPATH' , 'INSTANCENAME' ) ) return child | Parse a VALUE . REFERENCE element and return the instance path or class path it represents as a CIMInstanceName or CIMClassName object respectively . | 93 | 34 |
28,149 | def parse_value_refarray ( self , tup_tree ) : self . check_node ( tup_tree , 'VALUE.REFARRAY' ) children = self . list_of_various ( tup_tree , ( 'VALUE.REFERENCE' , 'VALUE.NULL' ) ) return children | Parse a VALUE . REFARRAY element and return the array of instance paths or class paths it represents as a list of CIMInstanceName or CIMClassName objects respectively . | 69 | 39 |
28,150 | def parse_value_instancewithpath ( self , tup_tree ) : self . check_node ( tup_tree , 'VALUE.INSTANCEWITHPATH' ) k = kids ( tup_tree ) if len ( k ) != 2 : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(INSTANCEPATH, INSTANCE))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) inst_path = self . parse_instancepath ( k [ 0 ] ) instance = self . parse_instance ( k [ 1 ] ) instance . path = inst_path return instance | The VALUE . INSTANCEWITHPATH is used to define a value that comprises a single CIMInstance with additional information that defines the absolute path to that object . | 162 | 34 |
28,151 | def parse_localnamespacepath ( self , tup_tree ) : self . check_node ( tup_tree , 'LOCALNAMESPACEPATH' , ( ) , ( ) , ( 'NAMESPACE' , ) ) if not kids ( tup_tree ) : raise CIMXMLParseError ( _format ( "Element {0!A} missing child elements (expecting one " "or more child elements 'NAMESPACE')" , name ( tup_tree ) ) , conn_id = self . conn_id ) # self.list_of_various() has the same effect as self.list_of_same() # when used with a single allowed child element, but is a little # faster. ns_list = self . list_of_various ( tup_tree , ( 'NAMESPACE' , ) ) return u'/' . join ( ns_list ) | Parse a LOCALNAMESPACEPATH element and return the namespace it represents as a unicode string . | 202 | 23 |
28,152 | def parse_host ( self , tup_tree ) : self . check_node ( tup_tree , 'HOST' , ( ) , ( ) , ( ) , allow_pcdata = True ) return self . pcdata ( tup_tree ) | Parse a HOST element and return its text content as a unicode string . | 56 | 17 |
28,153 | def parse_classpath ( self , tup_tree ) : self . check_node ( tup_tree , 'CLASSPATH' ) k = kids ( tup_tree ) if len ( k ) != 2 : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, CLASSNAME))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) host , namespace = self . parse_namespacepath ( k [ 0 ] ) class_path = self . parse_classname ( k [ 1 ] ) class_path . host = host class_path . namespace = namespace return class_path | Parse a CLASSPATH element and return the class path it represents as a CIMClassName object . | 172 | 23 |
28,154 | def parse_localclasspath ( self , tup_tree ) : self . check_node ( tup_tree , 'LOCALCLASSPATH' ) k = kids ( tup_tree ) if len ( k ) != 2 : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, CLASSNAME))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) namespace = self . parse_localnamespacepath ( k [ 0 ] ) class_path = self . parse_classname ( k [ 1 ] ) class_path . namespace = namespace return class_path | Parse a LOCALCLASSPATH element and return the class path it represents as a CIMClassName object . | 169 | 25 |
28,155 | def parse_classname ( self , tup_tree ) : self . check_node ( tup_tree , 'CLASSNAME' , ( 'NAME' , ) , ( ) , ( ) ) classname = attrs ( tup_tree ) [ 'NAME' ] class_path = CIMClassName ( classname ) return class_path | Parse a CLASSNAME element and return the class path it represents as a CIMClassName object . | 75 | 21 |
28,156 | def parse_instancepath ( self , tup_tree ) : self . check_node ( tup_tree , 'INSTANCEPATH' ) k = kids ( tup_tree ) if len ( k ) != 2 : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, INSTANCENAME))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) host , namespace = self . parse_namespacepath ( k [ 0 ] ) inst_path = self . parse_instancename ( k [ 1 ] ) inst_path . host = host inst_path . namespace = namespace return inst_path | Parse an INSTANCEPATH element and return the instance path it represents as a CIMInstanceName object . | 174 | 22 |
28,157 | def parse_localinstancepath ( self , tup_tree ) : self . check_node ( tup_tree , 'LOCALINSTANCEPATH' ) k = kids ( tup_tree ) if len ( k ) != 2 : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, INSTANCENAME))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) namespace = self . parse_localnamespacepath ( k [ 0 ] ) inst_path = self . parse_instancename ( k [ 1 ] ) inst_path . namespace = namespace return inst_path | Parse a LOCALINSTANCEPATH element and return the instance path it represents as a CIMInstanceName object . | 171 | 24 |
28,158 | def parse_instancename ( self , tup_tree ) : self . check_node ( tup_tree , 'INSTANCENAME' , ( 'CLASSNAME' , ) ) k = kids ( tup_tree ) if not k : # probably not ever going to see this, but it's valid # according to the grammar return CIMInstanceName ( attrs ( tup_tree ) [ 'CLASSNAME' ] , { } ) kid0 = k [ 0 ] k0_name = name ( kid0 ) classname = attrs ( tup_tree ) [ 'CLASSNAME' ] if k0_name in ( 'KEYVALUE' , 'VALUE.REFERENCE' ) : if len ( k ) != 1 : raise CIMXMLParseError ( _format ( "Element {0!A} has more than one child element " "{1!A} (expecting child elements " "(KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?))" , name ( tup_tree ) , k0_name ) , conn_id = self . conn_id ) val = self . parse_any ( kid0 ) return CIMInstanceName ( classname , { None : val } ) if k0_name == 'KEYBINDING' : kbs = { } # self.list_of_various() has the same effect as self.list_of_same() # when used with a single allowed child element, but is a little # faster. for key_bind in self . list_of_various ( tup_tree , ( 'KEYBINDING' , ) ) : kbs . update ( key_bind ) return CIMInstanceName ( classname , kbs ) raise CIMXMLParseError ( _format ( "Element {0!A} has invalid child elements {1!A} " "(expecting child elements " "(KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?))" , name ( tup_tree ) , k ) , conn_id = self . conn_id ) | Parse an INSTANCENAME element and return the instance path it represents as a CIMInstanceName object . | 453 | 23 |
28,159 | def parse_keybinding ( self , tup_tree ) : self . check_node ( tup_tree , 'KEYBINDING' , ( 'NAME' , ) ) child = self . one_child ( tup_tree , ( 'KEYVALUE' , 'VALUE.REFERENCE' ) ) return { attrs ( tup_tree ) [ 'NAME' ] : child } | Parse a KEYBINDING element and return the keybinding as a one - item dictionary from name to value where the value is a CIM data type object based upon the type information in the child elements if present . If no type information is present numeric values are returned as int or float . | 85 | 60 |
28,160 | def parse_keyvalue ( self , tup_tree ) : self . check_node ( tup_tree , 'KEYVALUE' , ( ) , ( 'VALUETYPE' , 'TYPE' ) , ( ) , allow_pcdata = True ) data = self . pcdata ( tup_tree ) attrl = attrs ( tup_tree ) valuetype = attrl . get ( 'VALUETYPE' , None ) cimtype = attrl . get ( 'TYPE' , None ) # Tolerate that some WBEM servers return TYPE="" instead of omitting # TYPE (e.g. the WBEM Solutions server). if cimtype == '' : cimtype = None # Default the CIM type from VALUETYPE if not specified in TYPE if cimtype is None : if valuetype is None or valuetype == 'string' : cimtype = 'string' elif valuetype == 'boolean' : cimtype = 'boolean' elif valuetype == 'numeric' : pass else : raise CIMXMLParseError ( _format ( "Element {0!A} has invalid 'VALUETYPE' attribute " "value {1!A}" , name ( tup_tree ) , valuetype ) , conn_id = self . conn_id ) return self . unpack_single_value ( data , cimtype ) | Parse a KEYVALUE element and return the keybinding value as a CIM data type object based upon the type information in its VALUETYPE and TYPE attributes if present . | 317 | 37 |
28,161 | def parse_class ( self , tup_tree ) : # Doesn't check ordering of elements, but it's not very important self . check_node ( tup_tree , 'CLASS' , ( 'NAME' , ) , ( 'SUPERCLASS' , ) , ( 'QUALIFIER' , 'PROPERTY' , 'PROPERTY.REFERENCE' , 'PROPERTY.ARRAY' , 'METHOD' ) ) attrl = attrs ( tup_tree ) superclass = attrl . get ( 'SUPERCLASS' , None ) properties = self . list_of_matching ( tup_tree , ( 'PROPERTY' , 'PROPERTY.REFERENCE' , 'PROPERTY.ARRAY' ) ) qualifiers = self . list_of_matching ( tup_tree , ( 'QUALIFIER' , ) ) methods = self . list_of_matching ( tup_tree , ( 'METHOD' , ) ) return CIMClass ( attrl [ 'NAME' ] , superclass = superclass , properties = properties , qualifiers = qualifiers , methods = methods ) | Parse CLASS element returning a CIMClass if the parse was successful . | 246 | 15 |
28,162 | def parse_instance ( self , tup_tree ) : self . check_node ( tup_tree , 'INSTANCE' , ( 'CLASSNAME' , ) , ( 'xml:lang' , ) , ( 'QUALIFIER' , 'PROPERTY' , 'PROPERTY.ARRAY' , 'PROPERTY.REFERENCE' ) ) # The 'xml:lang' attribute is tolerated but ignored. # Note: The check above does not enforce the ordering constraint in the # DTD that QUALIFIER elements must appear before PROPERTY* elements. qualifiers = self . list_of_matching ( tup_tree , ( 'QUALIFIER' , ) ) props = self . list_of_matching ( tup_tree , ( 'PROPERTY.REFERENCE' , 'PROPERTY' , 'PROPERTY.ARRAY' ) ) obj = CIMInstance ( attrs ( tup_tree ) [ 'CLASSNAME' ] , qualifiers = qualifiers ) for prop in props : obj . __setitem__ ( prop . name , prop ) return obj | Return a CIMInstance . | 239 | 6 |
28,163 | def parse_scope ( self , tup_tree ) : self . check_node ( tup_tree , 'SCOPE' , ( ) , ( 'CLASS' , 'ASSOCIATION' , 'REFERENCE' , 'PROPERTY' , 'METHOD' , 'PARAMETER' , 'INDICATION' ) , ( ) ) # Even though XML attributes do not preserve order, we store the # scopes in an ordered dict to avoid a warning further down the # road. scopes = NocaseDict ( ) for k , v in attrs ( tup_tree ) . items ( ) : v_ = self . unpack_boolean ( v ) if v_ is None : raise CIMXMLParseError ( _format ( "Element {0!A} has an invalid value {1!A} for its " "boolean attribute {2!A}" , name ( tup_tree ) , v , k ) , conn_id = self . conn_id ) scopes [ k ] = v_ return scopes | Parse a SCOPE element and return a dictionary with an item for each specified scope attribute . | 229 | 19 |
28,164 | def parse_qualifier_declaration ( self , tup_tree ) : self . check_node ( tup_tree , 'QUALIFIER.DECLARATION' , ( 'NAME' , 'TYPE' ) , ( 'ISARRAY' , 'ARRAYSIZE' , 'OVERRIDABLE' , 'TOSUBCLASS' , 'TOINSTANCE' , 'TRANSLATABLE' ) , ( 'SCOPE' , 'VALUE' , 'VALUE.ARRAY' ) ) attrl = attrs ( tup_tree ) qname = attrl [ 'NAME' ] _type = attrl [ 'TYPE' ] is_array = self . unpack_boolean ( attrl . get ( 'ISARRAY' , 'false' ) ) array_size = attrl . get ( 'ARRAYSIZE' , None ) if array_size is not None : # Issue #1044: Clarify if hex support is needed. array_size = int ( array_size ) scopes = None value = None for child in kids ( tup_tree ) : if name ( child ) == 'SCOPE' : if scopes is not None : raise CIMXMLParseError ( _format ( "Element {0!A} has more than one child " "element {1!A} (allowed is only one)" , name ( tup_tree ) , name ( child ) ) , conn_id = self . conn_id ) scopes = self . parse_any ( child ) else : # name is 'VALUE' or 'VALUE.ARRAY' if value is not None : raise CIMXMLParseError ( _format ( "Element {0!A} has more than one child " "element {1!A} (allowed is only one)" , name ( tup_tree ) , name ( child ) ) , conn_id = self . conn_id ) value = self . unpack_value ( tup_tree ) overridable = self . unpack_boolean ( attrl . get ( 'OVERRIDABLE' , 'true' ) ) tosubclass = self . unpack_boolean ( attrl . get ( 'TOSUBCLASS' , 'true' ) ) toinstance = self . unpack_boolean ( attrl . get ( 'TOINSTANCE' , 'false' ) ) translatable = self . unpack_boolean ( attrl . get ( 'TRANSLATABLE' , 'false' ) ) qual_decl = CIMQualifierDeclaration ( qname , _type , value , is_array , array_size , scopes , overridable = overridable , tosubclass = tosubclass , toinstance = toinstance , translatable = translatable ) return qual_decl | Parse QUALIFIER . DECLARATION element . | 606 | 13 |
28,165 | def parse_qualifier ( self , tup_tree ) : self . check_node ( tup_tree , 'QUALIFIER' , ( 'NAME' , 'TYPE' ) , ( 'OVERRIDABLE' , 'TOSUBCLASS' , 'TOINSTANCE' , 'TRANSLATABLE' , 'PROPAGATED' , 'xml:lang' ) , ( 'VALUE' , 'VALUE.ARRAY' ) ) # The 'xml:lang' attribute is tolerated but ignored. attrl = attrs ( tup_tree ) qname = attrl [ 'NAME' ] _type = attrl [ 'TYPE' ] value = self . unpack_value ( tup_tree ) propagated = self . unpack_boolean ( attrl . get ( 'PROPAGATED' , 'false' ) ) overridable = self . unpack_boolean ( attrl . get ( 'OVERRIDABLE' , 'true' ) ) tosubclass = self . unpack_boolean ( attrl . get ( 'TOSUBCLASS' , 'true' ) ) toinstance = self . unpack_boolean ( attrl . get ( 'TOINSTANCE' , 'false' ) ) translatable = self . unpack_boolean ( attrl . get ( 'TRANSLATABLE' , 'false' ) ) qual = CIMQualifier ( qname , value , _type , propagated = propagated , overridable = overridable , tosubclass = tosubclass , toinstance = toinstance , translatable = translatable ) return qual | Parse QUALIFIER element returning CIMQualifier . | 353 | 13 |
28,166 | def parse_property ( self , tup_tree ) : self . check_node ( tup_tree , 'PROPERTY' , ( 'TYPE' , 'NAME' ) , ( 'CLASSORIGIN' , 'PROPAGATED' , 'EmbeddedObject' , 'EMBEDDEDOBJECT' , 'xml:lang' ) , ( 'QUALIFIER' , 'VALUE' ) ) # The 'xml:lang' attribute is tolerated but ignored. attrl = attrs ( tup_tree ) try : val = self . unpack_value ( tup_tree ) except ValueError as exc : msg = str ( exc ) raise CIMXMLParseError ( _format ( "Cannot parse content of 'VALUE' child element of " "'PROPERTY' element with name {0!A}: {1}" , attrl [ 'NAME' ] , msg ) , conn_id = self . conn_id ) qualifiers = self . list_of_matching ( tup_tree , ( 'QUALIFIER' , ) ) embedded_object = False if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl : try : embedded_object = attrl [ 'EmbeddedObject' ] except KeyError : embedded_object = attrl [ 'EMBEDDEDOBJECT' ] if embedded_object : val = self . parse_embeddedObject ( val ) return CIMProperty ( attrl [ 'NAME' ] , val , type = attrl [ 'TYPE' ] , is_array = False , class_origin = attrl . get ( 'CLASSORIGIN' , None ) , propagated = self . unpack_boolean ( attrl . get ( 'PROPAGATED' , 'false' ) ) , qualifiers = qualifiers , embedded_object = embedded_object ) | Parse PROPERTY into a CIMProperty object . | 404 | 12 |
28,167 | def parse_paramvalue ( self , tup_tree ) : # Version 2.4 of DSP0201 added CLASSNAME, INSTANCENAME, CLASS, # INSTANCE, and VALUE.NAMEDINSTANCE. # Version 2.1.1 of DSP0201 lacks the %ParamType entity but it is # present as optional (for backwards compatibility) in version 2.2. # VMAX returns TYPE instead of PARAMTYPE, toleration support added to # use TYPE when present if PARAMTYPE is not present. self . check_node ( tup_tree , 'PARAMVALUE' , ( 'NAME' , ) , ( 'TYPE' , 'PARAMTYPE' , 'EmbeddedObject' , 'EMBEDDEDOBJECT' ) ) child = self . optional_child ( tup_tree , ( 'VALUE' , 'VALUE.REFERENCE' , 'VALUE.ARRAY' , 'VALUE.REFARRAY' , 'CLASSNAME' , 'INSTANCENAME' , 'CLASS' , 'INSTANCE' , 'VALUE.NAMEDINSTANCE' ) ) attrl = attrs ( tup_tree ) if 'PARAMTYPE' in attrl : paramtype = attrl [ 'PARAMTYPE' ] elif 'TYPE' in attrl : paramtype = attrl [ 'TYPE' ] else : paramtype = None if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl : child = self . parse_embeddedObject ( child ) return attrl [ 'NAME' ] , paramtype , child | Parse PARAMVALUE element . | 345 | 7 |
28,168 | def parse_expparamvalue ( self , tup_tree ) : self . check_node ( tup_tree , 'EXPPARAMVALUE' , ( 'NAME' , ) , ( ) , ( 'INSTANCE' , ) ) child = self . optional_child ( tup_tree , ( 'INSTANCE' , ) ) _name = attrs ( tup_tree ) [ 'NAME' ] return _name , child | Parse for EXPPARMVALUE Element . I . e . | 95 | 13 |
28,169 | def parse_simplersp ( self , tup_tree ) : self . check_node ( tup_tree , 'SIMPLERSP' ) child = self . one_child ( tup_tree , ( 'METHODRESPONSE' , 'IMETHODRESPONSE' ) ) return name ( tup_tree ) , attrs ( tup_tree ) , child | Parse for SIMPLERSP Element . | 85 | 9 |
28,170 | def parse_methodresponse ( self , tup_tree ) : self . check_node ( tup_tree , 'METHODRESPONSE' , ( 'NAME' , ) ) return ( name ( tup_tree ) , attrs ( tup_tree ) , self . list_of_various ( tup_tree , ( 'ERROR' , 'RETURNVALUE' , 'PARAMVALUE' ) ) ) | Parse expected METHODRESPONSE ELEMENT . I . e . | 92 | 16 |
28,171 | def parse_expmethodresponse ( self , tup_tree ) : # pylint: disable=unused-argument raise CIMXMLParseError ( _format ( "Internal Error: Parsing support for element {0!A} is not " "implemented" , name ( tup_tree ) ) , conn_id = self . conn_id ) | This function not implemented . | 80 | 5 |
28,172 | def parse_imethodresponse ( self , tup_tree ) : self . check_node ( tup_tree , 'IMETHODRESPONSE' , ( 'NAME' , ) ) return ( name ( tup_tree ) , attrs ( tup_tree ) , self . list_of_various ( tup_tree , ( 'ERROR' , 'IRETURNVALUE' , 'PARAMVALUE' ) ) ) | Parse the tuple for an IMETHODRESPONE Element . I . e . | 95 | 17 |
28,173 | def parse_returnvalue ( self , tup_tree ) : # Version 2.1.1 of the DTD lacks the %ParamType attribute but it # is present in version 2.2. Make it optional to be backwards # compatible. self . check_node ( tup_tree , 'RETURNVALUE' , ( ) , ( 'PARAMTYPE' , 'EmbeddedObject' , 'EMBEDDEDOBJECT' ) ) child = self . optional_child ( tup_tree , ( 'VALUE' , 'VALUE.REFERENCE' ) ) attrl = attrs ( tup_tree ) if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl : child = self . parse_embeddedObject ( child ) return name ( tup_tree ) , attrl , child | Parse the RETURNVALUE element . Returns name attributes and one child as a tuple . | 181 | 18 |
28,174 | def parse_ireturnvalue ( self , tup_tree ) : # Note: The self.check_node() below does not enforce any child elements # from the DTD, and the processing further down does not enforce that # VALUE.ARRAY and VALUE.REFERENCE may appear at most once. # Checking that at this level is not reasonable because the better # checks can be done in context of the intrinsic operation receiving # its return value. The DTD is so broad simply because it needs to # cover the possible return values of all intrinsic operations. self . check_node ( tup_tree , 'IRETURNVALUE' ) values = self . list_of_same ( tup_tree , ( 'CLASSNAME' , 'INSTANCENAME' , 'VALUE' , 'VALUE.OBJECTWITHPATH' , 'VALUE.OBJECTWITHLOCALPATH' , 'VALUE.OBJECT' , 'OBJECTPATH' , 'QUALIFIER.DECLARATION' , 'VALUE.ARRAY' , 'VALUE.REFERENCE' , 'CLASS' , 'INSTANCE' , 'INSTANCEPATH' , 'VALUE.NAMEDINSTANCE' , 'VALUE.INSTANCEWITHPATH' ) ) # Note: The caller needs to unpack the value. return name ( tup_tree ) , attrs ( tup_tree ) , values | Parse IRETURNVALUE element . Returns name attributes and values of the tup_tree . | 299 | 20 |
28,175 | def parse_iparamvalue ( self , tup_tree ) : self . check_node ( tup_tree , 'IPARAMVALUE' , ( 'NAME' , ) ) child = self . optional_child ( tup_tree , ( 'VALUE' , 'VALUE.ARRAY' , 'VALUE.REFERENCE' , 'INSTANCENAME' , 'CLASSNAME' , 'QUALIFIER.DECLARATION' , 'CLASS' , 'INSTANCE' , 'VALUE.NAMEDINSTANCE' ) ) _name = attrs ( tup_tree ) [ 'NAME' ] if isinstance ( child , six . string_types ) and _name . lower ( ) in ( 'deepinheritance' , 'localonly' , 'includequalifiers' , 'includeclassorigin' ) : if child . lower ( ) in ( 'true' , 'false' ) : child = ( child . lower ( ) == 'true' ) return _name , child | Parse expected IPARAMVALUE element . I . e . | 215 | 13 |
28,176 | def parse_embeddedObject ( self , val ) : # pylint: disable=invalid-name if type ( val ) == list : # pylint: disable=unidiomatic-typecheck return [ self . parse_embeddedObject ( obj ) for obj in val ] if val is None : return None # Perform the un-embedding (may raise XMLParseError) tup_tree = xml_to_tupletree_sax ( val , "embedded object" , self . conn_id ) if name ( tup_tree ) == 'INSTANCE' : return self . parse_instance ( tup_tree ) if name ( tup_tree ) == 'CLASS' : return self . parse_class ( tup_tree ) raise CIMXMLParseError ( _format ( "Invalid top-level element {0!A} in embedded object " "value" , name ( tup_tree ) ) , conn_id = self . conn_id ) | Parse and embedded instance or class and return the CIMInstance or CIMClass . | 215 | 18 |
28,177 | def unpack_value ( self , tup_tree ) : valtype = attrs ( tup_tree ) [ 'TYPE' ] raw_val = self . list_of_matching ( tup_tree , ( 'VALUE' , 'VALUE.ARRAY' ) ) if not raw_val : return None if len ( raw_val ) > 1 : raise CIMXMLParseError ( _format ( "Element {0!A} has too many child elements {1!A} " "(allowed is one of 'VALUE' or 'VALUE.ARRAY')" , name ( tup_tree ) ) , conn_id = self . conn_id ) raw_val = raw_val [ 0 ] if type ( raw_val ) == list : # pylint: disable=unidiomatic-typecheck return [ self . unpack_single_value ( data , valtype ) for data in raw_val ] return self . unpack_single_value ( raw_val , valtype ) | Find VALUE or VALUE . ARRAY under tup_tree and convert to a Python value . | 218 | 21 |
28,178 | def unpack_boolean ( self , data ) : if data is None : return None # CIM-XML says "These values MUST be treated as case-insensitive" # (even though the XML definition requires them to be lowercase.) data_ = data . strip ( ) . lower ( ) # ignore space if data_ == 'true' : return True if data_ == 'false' : return False if data_ == '' : warnings . warn ( "WBEM server sent invalid empty boolean value in a " "CIM-XML response." , ToleratedServerIssueWarning , stacklevel = _stacklevel_above_module ( __name__ ) ) return None raise CIMXMLParseError ( _format ( "Invalid boolean value {0!A}" , data ) , conn_id = self . conn_id ) | Unpack a string value of CIM type boolean and return its CIM data type object or None . | 178 | 21 |
28,179 | def unpack_numeric ( self , data , cimtype ) : if data is None : return None # DSP0201 defines numeric values to be whitespace-tolerant data = data . strip ( ) # Decode the CIM-XML string representation into a Python number # # Some notes: # * For integer numbers, only decimal and hexadecimal strings are # allowed - no binary or octal. # * In Python 2, int() automatically returns a long, if needed. # * For real values, DSP0201 defines a subset of the syntax supported # by Python float(), including the special states Inf, -Inf, NaN. The # only known difference is that DSP0201 requires a digit after the # decimal dot, while Python does not. if CIMXML_HEX_PATTERN . match ( data ) : value = int ( data , 16 ) else : try : value = int ( data ) except ValueError : try : value = float ( data ) except ValueError : raise CIMXMLParseError ( _format ( "Invalid numeric value {0!A}" , data ) , conn_id = self . conn_id ) # Convert the Python number into a CIM data type if cimtype is None : return value # int/long or float (used for keybindings) # The caller ensured a numeric type for cimtype CIMType = type_from_name ( cimtype ) try : value = CIMType ( value ) except ValueError as exc : raise CIMXMLParseError ( _format ( "Cannot convert value {0!A} to numeric CIM type {1}" , exc , CIMType ) , conn_id = self . conn_id ) return value | Unpack a string value of a numeric CIM type and return its CIM data type object or None . | 376 | 22 |
28,180 | def unpack_datetime ( self , data ) : if data is None : return None try : value = CIMDateTime ( data ) except ValueError as exc : raise CIMXMLParseError ( _format ( "Invalid datetime value: {0!A} ({1})" , data , exc ) , conn_id = self . conn_id ) return value | Unpack a CIM - XML string value of CIM type datetime and return it as a CIMDateTime object or None . | 81 | 28 |
28,181 | def unpack_char16 ( self , data ) : if data is None : return None len_data = len ( data ) if len_data == 0 : raise CIMXMLParseError ( "Char16 value is empty" , conn_id = self . conn_id ) if len_data > 1 : # More than one character, or one character from the UCS-4 set # in a narrow Python build (which represents it using # surrogates). raise CIMXMLParseError ( _format ( "Char16 value has more than one UCS-2 " "character: {0!A}" , data ) , conn_id = self . conn_id ) if ord ( data ) > 0xFFFF : # One character from the UCS-4 set in a wide Python build. raise CIMXMLParseError ( _format ( "Char16 value is a character outside of the " "UCS-2 range: {0!A}" , data ) , conn_id = self . conn_id ) return data | Unpack a CIM - XML string value of CIM type char16 and return it as a unicode string object or None . | 220 | 27 |
28,182 | def execute_request ( server_url , creds , namespace , classname ) : print ( 'Requesting url=%s, ns=%s, class=%s' % ( server_url , namespace , classname ) ) try : # Create a connection CONN = WBEMConnection ( server_url , creds , default_namespace = namespace , no_verification = True ) #Issue the request to EnumerateInstances on the defined class INSTANCES = CONN . EnumerateInstances ( classname ) #Display of characteristics of the result object print ( 'instances type=%s len=%s' % ( type ( INSTANCES ) , len ( INSTANCES ) ) ) #display the mof output for inst in INSTANCES : print ( 'path=%s\n' % inst . path ) print ( inst . tomof ( ) ) # handle any exception except Error as err : # If CIMError, display CIMError attributes if isinstance ( err , CIMError ) : print ( 'Operation Failed: CIMError: code=%s, Description=%s' % ( err . status_code_name , err . status_description ) ) else : print ( "Operation failed: %s" % err ) sys . exit ( 1 ) | Open a connection with the server_url and creds and enumerate instances defined by the functions namespace and classname arguments . Displays either the error return or the mof for instances returned . | 278 | 39 |
28,183 | def get_keys_from_class ( cc ) : return [ prop . name for prop in cc . properties . values ( ) if 'key' in prop . qualifiers ] | Return list of the key property names for a class | 36 | 10 |
28,184 | def build_instance_name ( inst , obj = None ) : if obj is None : for _ in inst . properties . values ( ) : inst . path . keybindings . __setitem__ ( _ . name , _ . value ) return inst . path if not isinstance ( obj , list ) : return build_instance_name ( inst , get_keys_from_class ( obj ) ) keys = { } for _ in obj : if _ not in inst . properties : raise pywbem . CIMError ( pywbem . CIM_ERR_FAILED , "Instance of %s is missing key property %s" % ( inst . classname , _ ) ) keys [ _ ] = inst [ _ ] inst . path = pywbem . CIMInstanceName ( classname = inst . classname , keybindings = keys , namespace = inst . path . namespace , host = inst . path . host ) return inst . path | Return an instance name from an instance and set instance . path | 203 | 12 |
28,185 | def set_instance ( self , env , instance , previous_instance , cim_class ) : raise pywbem . CIMError ( pywbem . CIM_ERR_NOT_SUPPORTED , "" ) | Return a newly created or modified instance . | 48 | 8 |
28,186 | def references ( self , env , object_name , model , assoc_class , result_class_name , role , result_role , keys_only ) : pass | Instrument Associations . | 36 | 5 |
28,187 | def MI_deleteInstance ( self , env , instanceName ) : # pylint: disable=invalid-name logger = env . get_logger ( ) logger . log_debug ( 'CIMProvider MI_deleteInstance called...' ) self . delete_instance ( env = env , instance_name = instanceName ) logger . log_debug ( 'CIMProvider MI_deleteInstance returning' ) | Delete a CIM instance | 87 | 5 |
28,188 | def cimtype ( obj ) : if isinstance ( obj , CIMType ) : return obj . cimtype if isinstance ( obj , bool ) : return 'boolean' if isinstance ( obj , ( six . binary_type , six . text_type ) ) : # accept both possible types return 'string' if isinstance ( obj , list ) : try : obj = obj [ 0 ] except IndexError : raise ValueError ( "Cannot determine CIM data type from empty array" ) return cimtype ( obj ) if isinstance ( obj , ( datetime , timedelta ) ) : return 'datetime' try : instancename_type = CIMInstanceName except NameError : # Defer import due to circular import dependencies: from pywbem . cim_obj import CIMInstanceName as instancename_type if isinstance ( obj , instancename_type ) : return 'reference' try : instance_type = CIMInstance except NameError : # Defer import due to circular import dependencies: from pywbem . cim_obj import CIMInstance as instance_type if isinstance ( obj , instance_type ) : # embedded instance return 'string' try : class_type = CIMClass except NameError : # Defer import due to circular import dependencies: from pywbem . cim_obj import CIMClass as class_type if isinstance ( obj , class_type ) : # embedded class return 'string' raise TypeError ( _format ( "Object does not have a valid CIM data type: {0!A}" , obj ) ) | Return the CIM data type name of a CIM typed object as a string . | 341 | 17 |
28,189 | def type_from_name ( type_name ) : if type_name == 'reference' : # Defer import due to circular import dependencies: from . cim_obj import CIMInstanceName return CIMInstanceName try : type_obj = _TYPE_FROM_NAME [ type_name ] except KeyError : raise ValueError ( _format ( "Unknown CIM data type name: {0!A}" , type_name ) ) return type_obj | Return the Python type object for a given CIM data type name . | 99 | 14 |
28,190 | def atomic_to_cim_xml ( obj ) : if obj is None : # pylint: disable=no-else-return return obj elif isinstance ( obj , six . text_type ) : return obj elif isinstance ( obj , six . binary_type ) : return _to_unicode ( obj ) elif isinstance ( obj , bool ) : return u'TRUE' if obj else u'FALSE' elif isinstance ( obj , ( CIMInt , six . integer_types , CIMDateTime ) ) : return six . text_type ( obj ) elif isinstance ( obj , datetime ) : return six . text_type ( CIMDateTime ( obj ) ) elif isinstance ( obj , Real32 ) : # DSP0201 requirements for representing real32: # The significand must be represented with at least 11 digits. # The special values must have the case: INF, -INF, NaN. s = u'{0:.11G}' . format ( obj ) if s == 'NAN' : s = u'NaN' elif s in ( 'INF' , '-INF' ) : pass elif '.' not in s : parts = s . split ( 'E' ) parts [ 0 ] = parts [ 0 ] + '.0' s = 'E' . join ( parts ) return s elif isinstance ( obj , ( Real64 , float ) ) : # DSP0201 requirements for representing real64: # The significand must be represented with at least 17 digits. # The special values must have the case: INF, -INF, NaN. s = u'{0:.17G}' . format ( obj ) if s == 'NAN' : s = u'NaN' elif s in ( 'INF' , '-INF' ) : pass elif '.' not in s : parts = s . split ( 'E' ) parts [ 0 ] = parts [ 0 ] + '.0' s = 'E' . join ( parts ) return s else : raise TypeError ( _format ( "Value {0!A} has invalid type {1} for conversion to a " "CIM-XML string" , obj , type ( obj ) ) ) | Convert an atomic scalar value to a CIM - XML string and return that string . | 495 | 19 |
28,191 | def __ordering_deprecated ( self ) : msg = _format ( "Ordering comparisons involving {0} objects are " "deprecated." , self . __class__ . __name__ ) if DEBUG_WARNING_ORIGIN : msg += "\nTraceback:\n" + '' . join ( traceback . format_stack ( ) ) warnings . warn ( msg , DeprecationWarning , stacklevel = 3 ) | Deprecated warning for pywbem CIM Objects | 90 | 10 |
28,192 | def _to_int ( value_str , min_value , rep_digit , field_name , dtarg ) : if '*' in value_str : first = value_str . index ( '*' ) after = value_str . rindex ( '*' ) + 1 if value_str [ first : after ] != '*' * ( after - first ) : raise ValueError ( _format ( "Asterisks in {0} field of CIM datetime value " "{1!A} are not consecutive: {2!A}" , field_name , dtarg , value_str ) ) if after != len ( value_str ) : raise ValueError ( _format ( "Asterisks in {0} field of CIM datetime value " "{1!A} do not end at end of field: {2!A}" , field_name , dtarg , value_str ) ) if rep_digit is None : # pylint: disable=no-else-return # Must be an all-asterisk field if first != 0 : raise ValueError ( _format ( "Asterisks in {0} field of CIM datetime value " "{1!A} do not start at begin of field: {2!A}" , field_name , dtarg , value_str ) ) return min_value else : value_str = value_str . replace ( '*' , rep_digit ) # Because the pattern and the asterisk replacement mechanism already # ensure only decimal digits, we expect the integer conversion to # always succeed. value = int ( value_str ) return value | Convert value_str into an integer replacing right - consecutive asterisks with rep_digit and an all - asterisk value with min_value . | 348 | 30 |
28,193 | def getContext ( self ) : ctx = SSL . Context ( SSL . SSLv23_METHOD ) ctx . use_certificate_file ( 'server.pem' ) ctx . use_privatekey_file ( 'server.pem' ) return ctx | Create an SSL context with a dodgy certificate . | 59 | 10 |
28,194 | def execute_request ( conn , classname , max_open , max_pull ) : start = ElapsedTimer ( ) result = conn . OpenEnumerateInstances ( classname , MaxObjectCount = max_open ) print ( 'open rtn eos=%s context=%s, count=%s time=%s ms' % ( result . eos , result . context , len ( result . instances ) , start . elapsed_ms ( ) ) ) # save instances since we reuse result insts = result . instances # loop to make pull requests until end_of_sequence received. pull_count = 0 while not result . eos : pull_count += 1 op_start = ElapsedTimer ( ) result = conn . PullInstancesWithPath ( result . context , MaxObjectCount = max_pull ) insts . extend ( result . instances ) print ( 'pull rtn eos=%s context=%s, insts=%s time=%s ms' % ( result . eos , result . context , len ( result . instances ) , op_start . elapsed_ms ( ) ) ) print ( 'Result instance count=%s pull count=%s time=%.2f sec' % ( len ( insts ) , pull_count , start . elapsed_sec ( ) ) ) return insts | Enumerate instances defined by the function s classname argument using the OpenEnumerateInstances and PullInstancesWithPath . | 286 | 27 |
28,195 | def _pcdata_nodes ( pcdata ) : nodelist = [ ] if _CDATA_ESCAPING and isinstance ( pcdata , six . string_types ) and ( pcdata . find ( "<" ) >= 0 or pcdata . find ( ">" ) >= 0 or pcdata . find ( "&" ) >= 0 ) : # noqa: E129 # In order to support nesting of CDATA sections, we represent pcdata # that already contains CDATA sections by multiple new CDATA sections # whose boundaries split the end marker of the already existing CDATA # sections. pcdata_part_list = pcdata . split ( "]]>" ) # ']]>' is the complete CDATA section end marker i = 0 for pcdata_part in pcdata_part_list : i += 1 left = "" if i == 1 else "]>" # ']>' is right part of CDATA section end marker right = "" if i == len ( pcdata_part_list ) else "]" # "]" is left part of CDATA section end marker # The following initialization approach requires Python 2.3 or # higher. node = CDATASection ( ) node . data = left + pcdata_part + right nodelist . append ( node ) else : # The following automatically uses XML entity references # for escaping. node = _text ( pcdata ) nodelist . append ( node ) return nodelist | Return a list of minidom nodes with the properly escaped pcdata inside . | 301 | 16 |
28,196 | def _uprint ( dest , text ) : if isinstance ( text , six . text_type ) : text = text + u'\n' elif isinstance ( text , six . binary_type ) : text = text + b'\n' else : raise TypeError ( "text must be a unicode or byte string, but is {0}" . format ( type ( text ) ) ) if dest is None : if six . PY2 : # On py2, stdout.write() requires byte strings if isinstance ( text , six . text_type ) : text = text . encode ( STDOUT_ENCODING , 'replace' ) else : # On py3, stdout.write() requires unicode strings if isinstance ( text , six . binary_type ) : text = text . decode ( 'utf-8' ) sys . stdout . write ( text ) elif isinstance ( dest , ( six . text_type , six . binary_type ) ) : if isinstance ( text , six . text_type ) : open_kwargs = dict ( mode = 'a' , encoding = 'utf-8' ) else : open_kwargs = dict ( mode = 'ab' ) if six . PY2 : # Open with codecs to be able to set text mode with codecs . open ( dest , * * open_kwargs ) as f : f . write ( text ) else : with open ( dest , * * open_kwargs ) as f : f . write ( text ) else : raise TypeError ( "dest must be None or a string, but is {0}" . format ( type ( text ) ) ) | Write text to dest adding a newline character . | 357 | 10 |
28,197 | def _pretty_xml ( xml_string ) : result_dom = minidom . parseString ( xml_string ) pretty_result = result_dom . toprettyxml ( indent = ' ' ) # remove extra empty lines return re . sub ( r'>( *[\r\n]+)+( *)<' , r'>\n\2<' , pretty_result ) | Common function to produce pretty xml string from an input xml_string . | 82 | 14 |
28,198 | def add_namespace ( self , namespace ) : if namespace is None : raise ValueError ( "Namespace argument must not be None" ) # Normalize the namespace name namespace = namespace . strip ( '/' ) if namespace in self . namespaces : raise CIMError ( CIM_ERR_ALREADY_EXISTS , _format ( "Namespace {0!A} already exists in the mock " "repository" , namespace ) ) self . namespaces [ namespace ] = True | Add a CIM namespace to the mock repository . | 107 | 10 |
28,199 | def _remove_namespace ( self , namespace ) : if namespace is None : raise ValueError ( "Namespace argument must not be None" ) # Normalize the namespace name namespace = namespace . strip ( '/' ) if namespace not in self . namespaces : raise CIMError ( CIM_ERR_NOT_FOUND , _format ( "Namespace {0!A} does not exist in the mock " "repository" , namespace ) ) if not self . _class_repo_empty ( namespace ) or not self . _instance_repo_empty ( namespace ) or not self . _qualifier_repo_empty ( namespace ) : raise CIMError ( CIM_ERR_NAMESPACE_NOT_EMPTY , _format ( "Namespace {0!A} is not empty" , namespace ) ) if namespace == self . default_namespace : raise CIMError ( CIM_ERR_NAMESPACE_NOT_EMPTY , _format ( "Connection default namespace {0!A} cannot be " "deleted from mock repository" , namespace ) ) del self . namespaces [ namespace ] | Remove a CIM namespace from the mock repository . | 247 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.