repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_iparamvalue
def parse_iparamvalue(self, tup_tree): """ Parse expected IPARAMVALUE element. I.e. :: <!ELEMENT IPARAMVALUE (VALUE | VALUE.ARRAY | VALUE.REFERENCE | INSTANCENAME | CLASSNAME | QUALIFIER.DECLARATION | CLASS | INSTANCE | VALUE.NAMEDINSTANCE)?> <!ATTLIST IPARAMVALUE %CIMName;> :return: NAME, VALUE pair. """ 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
python
def parse_iparamvalue(self, tup_tree): """ Parse expected IPARAMVALUE element. I.e. :: <!ELEMENT IPARAMVALUE (VALUE | VALUE.ARRAY | VALUE.REFERENCE | INSTANCENAME | CLASSNAME | QUALIFIER.DECLARATION | CLASS | INSTANCE | VALUE.NAMEDINSTANCE)?> <!ATTLIST IPARAMVALUE %CIMName;> :return: NAME, VALUE pair. """ 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
[ "def", "parse_iparamvalue", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'IPARAMVALUE'", ",", "(", "'NAME'", ",", ")", ")", "child", "=", "self", ".", "optional_child", "(", "tup_tree", ",", "(", "'VALUE'", ",...
Parse expected IPARAMVALUE element. I.e. :: <!ELEMENT IPARAMVALUE (VALUE | VALUE.ARRAY | VALUE.REFERENCE | INSTANCENAME | CLASSNAME | QUALIFIER.DECLARATION | CLASS | INSTANCE | VALUE.NAMEDINSTANCE)?> <!ATTLIST IPARAMVALUE %CIMName;> :return: NAME, VALUE pair.
[ "Parse", "expected", "IPARAMVALUE", "element", ".", "I", ".", "e", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2030-L2061
train
28,300
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_embeddedObject
def parse_embeddedObject(self, val): # pylint: disable=invalid-name """ Parse and embedded instance or class and return the CIMInstance or CIMClass. Parameters: val (string): The string value that contains the embedded object in CIM-XML format. One level of XML entity references have already been unescaped. Example string value, for a doubly nested embedded instance. Note that in the CIM-XML payload, this string value is escaped one more level. :: <INSTANCE CLASSNAME="PyWBEM_Address"> <PROPERTY NAME="Street" TYPE="string"> <VALUE>Fritz &amp; &lt;the cat&gt; Ave</VALUE> </PROPERTY> <PROPERTY NAME="Town" TYPE="string" EmbeddedObject="instance"> <VALUE> &lt;INSTANCE CLASSNAME="PyWBEM_Town"&gt; &lt;PROPERTY NAME="Name" TYPE="string"&gt; &lt;VALUE&gt;Fritz &amp;amp; &amp;lt;the cat&amp;gt; Town&lt;/VALUE&gt; &lt;/PROPERTY&gt; &lt;PROPERTY NAME="Zip" TYPE="string"&gt; &lt;VALUE&gt;z12345&lt;/VALUE&gt; &lt;/PROPERTY&gt; &lt;/INSTANCE&gt; </VALUE> </PROPERTY> </INSTANCE> Returns: `None` if `val` is `None`. `CIMClass` or `CIMInstance` or a list of them, otherwise. Raises: CIMXMLParseError: There is an error in the XML. """ 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)
python
def parse_embeddedObject(self, val): # pylint: disable=invalid-name """ Parse and embedded instance or class and return the CIMInstance or CIMClass. Parameters: val (string): The string value that contains the embedded object in CIM-XML format. One level of XML entity references have already been unescaped. Example string value, for a doubly nested embedded instance. Note that in the CIM-XML payload, this string value is escaped one more level. :: <INSTANCE CLASSNAME="PyWBEM_Address"> <PROPERTY NAME="Street" TYPE="string"> <VALUE>Fritz &amp; &lt;the cat&gt; Ave</VALUE> </PROPERTY> <PROPERTY NAME="Town" TYPE="string" EmbeddedObject="instance"> <VALUE> &lt;INSTANCE CLASSNAME="PyWBEM_Town"&gt; &lt;PROPERTY NAME="Name" TYPE="string"&gt; &lt;VALUE&gt;Fritz &amp;amp; &amp;lt;the cat&amp;gt; Town&lt;/VALUE&gt; &lt;/PROPERTY&gt; &lt;PROPERTY NAME="Zip" TYPE="string"&gt; &lt;VALUE&gt;z12345&lt;/VALUE&gt; &lt;/PROPERTY&gt; &lt;/INSTANCE&gt; </VALUE> </PROPERTY> </INSTANCE> Returns: `None` if `val` is `None`. `CIMClass` or `CIMInstance` or a list of them, otherwise. Raises: CIMXMLParseError: There is an error in the XML. """ 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)
[ "def", "parse_embeddedObject", "(", "self", ",", "val", ")", ":", "# pylint: disable=invalid-name", "if", "type", "(", "val", ")", "==", "list", ":", "# pylint: disable=unidiomatic-typecheck", "return", "[", "self", ".", "parse_embeddedObject", "(", "obj", ")", "f...
Parse and embedded instance or class and return the CIMInstance or CIMClass. Parameters: val (string): The string value that contains the embedded object in CIM-XML format. One level of XML entity references have already been unescaped. Example string value, for a doubly nested embedded instance. Note that in the CIM-XML payload, this string value is escaped one more level. :: <INSTANCE CLASSNAME="PyWBEM_Address"> <PROPERTY NAME="Street" TYPE="string"> <VALUE>Fritz &amp; &lt;the cat&gt; Ave</VALUE> </PROPERTY> <PROPERTY NAME="Town" TYPE="string" EmbeddedObject="instance"> <VALUE> &lt;INSTANCE CLASSNAME="PyWBEM_Town"&gt; &lt;PROPERTY NAME="Name" TYPE="string"&gt; &lt;VALUE&gt;Fritz &amp;amp; &amp;lt;the cat&amp;gt; Town&lt;/VALUE&gt; &lt;/PROPERTY&gt; &lt;PROPERTY NAME="Zip" TYPE="string"&gt; &lt;VALUE&gt;z12345&lt;/VALUE&gt; &lt;/PROPERTY&gt; &lt;/INSTANCE&gt; </VALUE> </PROPERTY> </INSTANCE> Returns: `None` if `val` is `None`. `CIMClass` or `CIMInstance` or a list of them, otherwise. Raises: CIMXMLParseError: There is an error in the XML.
[ "Parse", "and", "embedded", "instance", "or", "class", "and", "return", "the", "CIMInstance", "or", "CIMClass", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2091-L2157
train
28,301
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.unpack_value
def unpack_value(self, tup_tree): """ Find VALUE or VALUE.ARRAY under tup_tree and convert to a Python value. Looks at the TYPE of the node to work out how to decode it. Handles nodes with no value (e.g. when representing NULL by omitting VALUE) """ 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)
python
def unpack_value(self, tup_tree): """ Find VALUE or VALUE.ARRAY under tup_tree and convert to a Python value. Looks at the TYPE of the node to work out how to decode it. Handles nodes with no value (e.g. when representing NULL by omitting VALUE) """ 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)
[ "def", "unpack_value", "(", "self", ",", "tup_tree", ")", ":", "valtype", "=", "attrs", "(", "tup_tree", ")", "[", "'TYPE'", "]", "raw_val", "=", "self", ".", "list_of_matching", "(", "tup_tree", ",", "(", "'VALUE'", ",", "'VALUE.ARRAY'", ")", ")", "if",...
Find VALUE or VALUE.ARRAY under tup_tree and convert to a Python value. Looks at the TYPE of the node to work out how to decode it. Handles nodes with no value (e.g. when representing NULL by omitting VALUE)
[ "Find", "VALUE", "or", "VALUE", ".", "ARRAY", "under", "tup_tree", "and", "convert", "to", "a", "Python", "value", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2159-L2188
train
28,302
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.unpack_boolean
def unpack_boolean(self, data): """ Unpack a string value of CIM type 'boolean' and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ 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)
python
def unpack_boolean(self, data): """ Unpack a string value of CIM type 'boolean' and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ 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)
[ "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", "....
Unpack a string value of CIM type 'boolean' and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned).
[ "Unpack", "a", "string", "value", "of", "CIM", "type", "boolean", "and", "return", "its", "CIM", "data", "type", "object", "or", "None", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2222-L2254
train
28,303
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.unpack_numeric
def unpack_numeric(self, data, cimtype): """ Unpack a string value of a numeric CIM type and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). cimtype (string): CIM data type name (e.g. 'uint8'), or None (in which case the value is returned as a Python int/long or float). """ 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
python
def unpack_numeric(self, data, cimtype): """ Unpack a string value of a numeric CIM type and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). cimtype (string): CIM data type name (e.g. 'uint8'), or None (in which case the value is returned as a Python int/long or float). """ 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
[ "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 re...
Unpack a string value of a numeric CIM type and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). cimtype (string): CIM data type name (e.g. 'uint8'), or None (in which case the value is returned as a Python int/long or float).
[ "Unpack", "a", "string", "value", "of", "a", "numeric", "CIM", "type", "and", "return", "its", "CIM", "data", "type", "object", "or", "None", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2256-L2310
train
28,304
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.unpack_datetime
def unpack_datetime(self, data): """ Unpack a CIM-XML string value of CIM type 'datetime' and return it as a CIMDateTime object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ 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
python
def unpack_datetime(self, data): """ Unpack a CIM-XML string value of CIM type 'datetime' and return it as a CIMDateTime object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ 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
[ "def", "unpack_datetime", "(", "self", ",", "data", ")", ":", "if", "data", "is", "None", ":", "return", "None", "try", ":", "value", "=", "CIMDateTime", "(", "data", ")", "except", "ValueError", "as", "exc", ":", "raise", "CIMXMLParseError", "(", "_form...
Unpack a CIM-XML string value of CIM type 'datetime' and return it as a CIMDateTime object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned).
[ "Unpack", "a", "CIM", "-", "XML", "string", "value", "of", "CIM", "type", "datetime", "and", "return", "it", "as", "a", "CIMDateTime", "object", "or", "None", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2312-L2330
train
28,305
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.unpack_char16
def unpack_char16(self, data): """ Unpack a CIM-XML string value of CIM type 'char16' and return it as a unicode string object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ 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
python
def unpack_char16(self, data): """ Unpack a CIM-XML string value of CIM type 'char16' and return it as a unicode string object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ 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
[ "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\"", ",", ...
Unpack a CIM-XML string value of CIM type 'char16' and return it as a unicode string object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned).
[ "Unpack", "a", "CIM", "-", "XML", "string", "value", "of", "CIM", "type", "char16", "and", "return", "it", "as", "a", "unicode", "string", "object", "or", "None", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L2332-L2367
train
28,306
pywbem/pywbem
examples/enuminstances.py
execute_request
def execute_request(server_url, creds, namespace, classname): """ 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. """ 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)
python
def execute_request(server_url, creds, namespace, classname): """ 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. """ 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)
[ "def", "execute_request", "(", "server_url", ",", "creds", ",", "namespace", ",", "classname", ")", ":", "print", "(", "'Requesting url=%s, ns=%s, class=%s'", "%", "(", "server_url", ",", "namespace", ",", "classname", ")", ")", "try", ":", "# Create a connection"...
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.
[ "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", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/enuminstances.py#L36-L72
train
28,307
pywbem/pywbem
attic/cim_provider.py
get_keys_from_class
def get_keys_from_class(cc): """Return list of the key property names for a class """ return [prop.name for prop in cc.properties.values() \ if 'key' in prop.qualifiers]
python
def get_keys_from_class(cc): """Return list of the key property names for a class """ return [prop.name for prop in cc.properties.values() \ if 'key' in prop.qualifiers]
[ "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
[ "Return", "list", "of", "the", "key", "property", "names", "for", "a", "class" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider.py#L1037-L1040
train
28,308
pywbem/pywbem
attic/cim_provider.py
build_instance_name
def build_instance_name(inst, obj=None): """Return an instance name from an instance, and set instance.path """ 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
python
def build_instance_name(inst, obj=None): """Return an instance name from an instance, and set instance.path """ 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
[ "def", "build_instance_name", "(", "inst", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "for", "_", "in", "inst", ".", "properties", ".", "values", "(", ")", ":", "inst", ".", "path", ".", "keybindings", ".", "__setitem__", "(",...
Return an instance name from an instance, and set instance.path
[ "Return", "an", "instance", "name", "from", "an", "instance", "and", "set", "instance", ".", "path" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider.py#L1042-L1061
train
28,309
pywbem/pywbem
attic/cim_provider.py
CIMProvider.set_instance
def set_instance(self, env, instance, previous_instance, cim_class): """Return a newly created or modified instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the properties on this instance have been filtered by the PropertyList from the request. previous_instance -- The previous pywbem.CIMInstance if modifying an existing instance. None if creating a new instance. cim_class -- The pywbem.CIMClass Return the new instance. The keys must be set on the new instance. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only valid if previous_instance is None, indicating that the operation was CreateInstance) CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid if previous_instance is not None, indicating that the operation was ModifyInstance) CIM_ERR_FAILED (some other unspecified error occurred) """ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, "")
python
def set_instance(self, env, instance, previous_instance, cim_class): """Return a newly created or modified instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the properties on this instance have been filtered by the PropertyList from the request. previous_instance -- The previous pywbem.CIMInstance if modifying an existing instance. None if creating a new instance. cim_class -- The pywbem.CIMClass Return the new instance. The keys must be set on the new instance. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only valid if previous_instance is None, indicating that the operation was CreateInstance) CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid if previous_instance is not None, indicating that the operation was ModifyInstance) CIM_ERR_FAILED (some other unspecified error occurred) """ raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, "")
[ "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. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the properties on this instance have been filtered by the PropertyList from the request. previous_instance -- The previous pywbem.CIMInstance if modifying an existing instance. None if creating a new instance. cim_class -- The pywbem.CIMClass Return the new instance. The keys must be set on the new instance. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only valid if previous_instance is None, indicating that the operation was CreateInstance) CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid if previous_instance is not None, indicating that the operation was ModifyInstance) CIM_ERR_FAILED (some other unspecified error occurred)
[ "Return", "a", "newly", "created", "or", "modified", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider.py#L328-L356
train
28,310
pywbem/pywbem
attic/cim_provider.py
CIMProvider.references
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): """Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_name -- A pywbem.CIMInstanceName that defines the source CIM Object whose associated Objects are to be returned. model -- A template pywbem.CIMInstance to serve as a model of the objects to be returned. Only properties present on this model need to be set. assoc_class -- The pywbem.CIMClass. result_class_name -- If not empty, this string acts as a filter on the returned set of Instances by mandating that each returned Instances MUST represent an association between object_name and an Instance of a Class whose name matches this parameter or a subclass. role -- If not empty, MUST be a valid Property name. It acts as a filter on the returned set of Instances by mandating that each returned Instance MUST refer to object_name via a Property whose name matches the value of this parameter. result_role -- If not empty, MUST be a valid Property name. It acts as a filter on the returned set of Instances by mandating that each returned Instance MUST represent associations of object_name to other Instances, where the other Instances play the specified result_role in the association (i.e. the name of the Property in the Association Class that refers to the Object related to object_name MUST match the value of this parameter). keys_only -- A boolean. True if only the key properties should be set on the generated instances. The following diagram may be helpful in understanding the role, result_role, and result_class_name parameters. +------------------------+ +-------------------+ | object_name.classname | | result_class_name | | ~~~~~~~~~~~~~~~~~~~~~ | | ~~~~~~~~~~~~~~~~~ | +------------------------+ +-------------------+ | +-----------------------------------+ | | | [Association] assoc_class | | | object_name | ~~~~~~~~~~~~~~~~~~~~~~~~~ | | +--------------+ object_name.classname REF role | | (CIMInstanceName) | result_class_name REF result_role +------+ | |(CIMInstanceName) +-----------------------------------+ Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_NAMESPACE CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_FAILED (some other unspecified error occurred) """ pass
python
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): """Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_name -- A pywbem.CIMInstanceName that defines the source CIM Object whose associated Objects are to be returned. model -- A template pywbem.CIMInstance to serve as a model of the objects to be returned. Only properties present on this model need to be set. assoc_class -- The pywbem.CIMClass. result_class_name -- If not empty, this string acts as a filter on the returned set of Instances by mandating that each returned Instances MUST represent an association between object_name and an Instance of a Class whose name matches this parameter or a subclass. role -- If not empty, MUST be a valid Property name. It acts as a filter on the returned set of Instances by mandating that each returned Instance MUST refer to object_name via a Property whose name matches the value of this parameter. result_role -- If not empty, MUST be a valid Property name. It acts as a filter on the returned set of Instances by mandating that each returned Instance MUST represent associations of object_name to other Instances, where the other Instances play the specified result_role in the association (i.e. the name of the Property in the Association Class that refers to the Object related to object_name MUST match the value of this parameter). keys_only -- A boolean. True if only the key properties should be set on the generated instances. The following diagram may be helpful in understanding the role, result_role, and result_class_name parameters. +------------------------+ +-------------------+ | object_name.classname | | result_class_name | | ~~~~~~~~~~~~~~~~~~~~~ | | ~~~~~~~~~~~~~~~~~ | +------------------------+ +-------------------+ | +-----------------------------------+ | | | [Association] assoc_class | | | object_name | ~~~~~~~~~~~~~~~~~~~~~~~~~ | | +--------------+ object_name.classname REF role | | (CIMInstanceName) | result_class_name REF result_role +------+ | |(CIMInstanceName) +-----------------------------------+ Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_NAMESPACE CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_FAILED (some other unspecified error occurred) """ pass
[ "def", "references", "(", "self", ",", "env", ",", "object_name", ",", "model", ",", "assoc_class", ",", "result_class_name", ",", "role", ",", "result_role", ",", "keys_only", ")", ":", "pass" ]
Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_name -- A pywbem.CIMInstanceName that defines the source CIM Object whose associated Objects are to be returned. model -- A template pywbem.CIMInstance to serve as a model of the objects to be returned. Only properties present on this model need to be set. assoc_class -- The pywbem.CIMClass. result_class_name -- If not empty, this string acts as a filter on the returned set of Instances by mandating that each returned Instances MUST represent an association between object_name and an Instance of a Class whose name matches this parameter or a subclass. role -- If not empty, MUST be a valid Property name. It acts as a filter on the returned set of Instances by mandating that each returned Instance MUST refer to object_name via a Property whose name matches the value of this parameter. result_role -- If not empty, MUST be a valid Property name. It acts as a filter on the returned set of Instances by mandating that each returned Instance MUST represent associations of object_name to other Instances, where the other Instances play the specified result_role in the association (i.e. the name of the Property in the Association Class that refers to the Object related to object_name MUST match the value of this parameter). keys_only -- A boolean. True if only the key properties should be set on the generated instances. The following diagram may be helpful in understanding the role, result_role, and result_class_name parameters. +------------------------+ +-------------------+ | object_name.classname | | result_class_name | | ~~~~~~~~~~~~~~~~~~~~~ | | ~~~~~~~~~~~~~~~~~ | +------------------------+ +-------------------+ | +-----------------------------------+ | | | [Association] assoc_class | | | object_name | ~~~~~~~~~~~~~~~~~~~~~~~~~ | | +--------------+ object_name.classname REF role | | (CIMInstanceName) | result_class_name REF result_role +------+ | |(CIMInstanceName) +-----------------------------------+ Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_NAMESPACE CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_FAILED (some other unspecified error occurred)
[ "Instrument", "Associations", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider.py#L381-L440
train
28,311
pywbem/pywbem
attic/cim_provider.py
CIMProvider.MI_deleteInstance
def MI_deleteInstance(self, env, instanceName): # pylint: disable=invalid-name """Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally override this method. """ 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')
python
def MI_deleteInstance(self, env, instanceName): # pylint: disable=invalid-name """Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally override this method. """ 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')
[ "def", "MI_deleteInstance", "(", "self", ",", "env", ",", "instanceName", ")", ":", "# pylint: disable=invalid-name", "logger", "=", "env", ".", "get_logger", "(", ")", "logger", ".", "log_debug", "(", "'CIMProvider MI_deleteInstance called...'", ")", "self", ".", ...
Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally override this method.
[ "Delete", "a", "CIM", "instance" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cim_provider.py#L661-L676
train
28,312
pywbem/pywbem
pywbem/cim_types.py
cimtype
def cimtype(obj): """ Return the CIM data type name of a CIM typed object, as a string. For an array, the type is determined from the first array element (CIM arrays must be homogeneous w.r.t. the type of their elements). If the array is empty, that is not possible and :exc:`~py:exceptions.ValueError` is raised. Note that Python :term:`numbers <number>` are not valid input objects because determining their CIM data type (e.g. :class:`~pywbem.Uint8`, :class:`~pywbem.Real32`) would require knowing the value range. Therefore, :exc:`~py:exceptions.TypeError` is raised in this case. Parameters: obj (:term:`CIM data type`): The object whose CIM data type name is returned. Returns: :term:`string`: The CIM data type name of the object (e.g. ``"uint8"``). Raises: TypeError: The object does not have a valid CIM data type. ValueError: Cannot determine CIM data type from an empty array. """ 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))
python
def cimtype(obj): """ Return the CIM data type name of a CIM typed object, as a string. For an array, the type is determined from the first array element (CIM arrays must be homogeneous w.r.t. the type of their elements). If the array is empty, that is not possible and :exc:`~py:exceptions.ValueError` is raised. Note that Python :term:`numbers <number>` are not valid input objects because determining their CIM data type (e.g. :class:`~pywbem.Uint8`, :class:`~pywbem.Real32`) would require knowing the value range. Therefore, :exc:`~py:exceptions.TypeError` is raised in this case. Parameters: obj (:term:`CIM data type`): The object whose CIM data type name is returned. Returns: :term:`string`: The CIM data type name of the object (e.g. ``"uint8"``). Raises: TypeError: The object does not have a valid CIM data type. ValueError: Cannot determine CIM data type from an empty array. """ 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))
[ "def", "cimtype", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "CIMType", ")", ":", "return", "obj", ".", "cimtype", "if", "isinstance", "(", "obj", ",", "bool", ")", ":", "return", "'boolean'", "if", "isinstance", "(", "obj", ",", "(",...
Return the CIM data type name of a CIM typed object, as a string. For an array, the type is determined from the first array element (CIM arrays must be homogeneous w.r.t. the type of their elements). If the array is empty, that is not possible and :exc:`~py:exceptions.ValueError` is raised. Note that Python :term:`numbers <number>` are not valid input objects because determining their CIM data type (e.g. :class:`~pywbem.Uint8`, :class:`~pywbem.Real32`) would require knowing the value range. Therefore, :exc:`~py:exceptions.TypeError` is raised in this case. Parameters: obj (:term:`CIM data type`): The object whose CIM data type name is returned. Returns: :term:`string`: The CIM data type name of the object (e.g. ``"uint8"``). Raises: TypeError: The object does not have a valid CIM data type. ValueError: Cannot determine CIM data type from an empty array.
[ "Return", "the", "CIM", "data", "type", "name", "of", "a", "CIM", "typed", "object", "as", "a", "string", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L997-L1071
train
28,313
pywbem/pywbem
pywbem/cim_types.py
type_from_name
def type_from_name(type_name): """ Return the Python type object for a given CIM data type name. For example, type name ``"uint8"`` will return type object :class:`~pywbem.Uint8`. For CIM data type names ``"string"`` and ``"char16"``, the :term:`unicode string` type is returned (Unicode strings are the preferred representation for these CIM data types). The returned type can be used as a constructor from a differently typed input value in many cases. Notable limitations are: * In Python 3, the :class:`py3:str` type is used to represent CIM string data types. When constructing such an object from a byte string, the resulting string is not a unicode-translated version of the byte string as one would assume (and as is the case in Python 2), but instead that results in a unicode string that is a `repr()` representation of the byte string:: string_type = type_from_name('string') # str s1 = b'abc' s2 = string_type(s1) # results in u"b'abc'", and not in u"abc" Use `decode()` and `encode()` for strings instead of type conversion syntax (in both Python 2 and 3, for consistency). Parameters: type_name (:term:`string`): The simple (=non-array) CIM data type name (e.g. ``"uint8"`` or ``"reference"``). Returns: The Python type object for the CIM data type (e.g. :class:`~pywbem.Uint8` or :class:`~pywbem.CIMInstanceName`). Raises: ValueError: Unknown CIM data 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
python
def type_from_name(type_name): """ Return the Python type object for a given CIM data type name. For example, type name ``"uint8"`` will return type object :class:`~pywbem.Uint8`. For CIM data type names ``"string"`` and ``"char16"``, the :term:`unicode string` type is returned (Unicode strings are the preferred representation for these CIM data types). The returned type can be used as a constructor from a differently typed input value in many cases. Notable limitations are: * In Python 3, the :class:`py3:str` type is used to represent CIM string data types. When constructing such an object from a byte string, the resulting string is not a unicode-translated version of the byte string as one would assume (and as is the case in Python 2), but instead that results in a unicode string that is a `repr()` representation of the byte string:: string_type = type_from_name('string') # str s1 = b'abc' s2 = string_type(s1) # results in u"b'abc'", and not in u"abc" Use `decode()` and `encode()` for strings instead of type conversion syntax (in both Python 2 and 3, for consistency). Parameters: type_name (:term:`string`): The simple (=non-array) CIM data type name (e.g. ``"uint8"`` or ``"reference"``). Returns: The Python type object for the CIM data type (e.g. :class:`~pywbem.Uint8` or :class:`~pywbem.CIMInstanceName`). Raises: ValueError: Unknown CIM data 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
[ "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...
Return the Python type object for a given CIM data type name. For example, type name ``"uint8"`` will return type object :class:`~pywbem.Uint8`. For CIM data type names ``"string"`` and ``"char16"``, the :term:`unicode string` type is returned (Unicode strings are the preferred representation for these CIM data types). The returned type can be used as a constructor from a differently typed input value in many cases. Notable limitations are: * In Python 3, the :class:`py3:str` type is used to represent CIM string data types. When constructing such an object from a byte string, the resulting string is not a unicode-translated version of the byte string as one would assume (and as is the case in Python 2), but instead that results in a unicode string that is a `repr()` representation of the byte string:: string_type = type_from_name('string') # str s1 = b'abc' s2 = string_type(s1) # results in u"b'abc'", and not in u"abc" Use `decode()` and `encode()` for strings instead of type conversion syntax (in both Python 2 and 3, for consistency). Parameters: type_name (:term:`string`): The simple (=non-array) CIM data type name (e.g. ``"uint8"`` or ``"reference"``). Returns: The Python type object for the CIM data type (e.g. :class:`~pywbem.Uint8` or :class:`~pywbem.CIMInstanceName`). Raises: ValueError: Unknown CIM data type name.
[ "Return", "the", "Python", "type", "object", "for", "a", "given", "CIM", "data", "type", "name", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L1093-L1145
train
28,314
pywbem/pywbem
pywbem/cim_types.py
atomic_to_cim_xml
def atomic_to_cim_xml(obj): """ Convert an "atomic" scalar value to a CIM-XML string and return that string. The returned CIM-XML string is ready for use as the text of a CIM-XML 'VALUE' element. Parameters: obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`): The "atomic" input value. May be `None`. Must not be an array/list/tuple. Must not be a :ref:`CIM object`. Returns: A :term:`unicode string` object in CIM-XML value format representing the input value. `None`, if the input value is `None`. Raises: TypeError """ 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)))
python
def atomic_to_cim_xml(obj): """ Convert an "atomic" scalar value to a CIM-XML string and return that string. The returned CIM-XML string is ready for use as the text of a CIM-XML 'VALUE' element. Parameters: obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`): The "atomic" input value. May be `None`. Must not be an array/list/tuple. Must not be a :ref:`CIM object`. Returns: A :term:`unicode string` object in CIM-XML value format representing the input value. `None`, if the input value is `None`. Raises: TypeError """ 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)))
[ "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"...
Convert an "atomic" scalar value to a CIM-XML string and return that string. The returned CIM-XML string is ready for use as the text of a CIM-XML 'VALUE' element. Parameters: obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`): The "atomic" input value. May be `None`. Must not be an array/list/tuple. Must not be a :ref:`CIM object`. Returns: A :term:`unicode string` object in CIM-XML value format representing the input value. `None`, if the input value is `None`. Raises: TypeError
[ "Convert", "an", "atomic", "scalar", "value", "to", "a", "CIM", "-", "XML", "string", "and", "return", "that", "string", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L1148-L1215
train
28,315
pywbem/pywbem
pywbem/cim_types.py
_CIMComparisonMixin.__ordering_deprecated
def __ordering_deprecated(self): """Deprecated warning for pywbem CIM Objects""" 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)
python
def __ordering_deprecated(self): """Deprecated warning for pywbem CIM Objects""" 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)
[ "def", "__ordering_deprecated", "(", "self", ")", ":", "msg", "=", "_format", "(", "\"Ordering comparisons involving {0} objects are \"", "\"deprecated.\"", ",", "self", ".", "__class__", ".", "__name__", ")", "if", "DEBUG_WARNING_ORIGIN", ":", "msg", "+=", "\"\\nTrac...
Deprecated warning for pywbem CIM Objects
[ "Deprecated", "warning", "for", "pywbem", "CIM", "Objects" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L131-L137
train
28,316
pywbem/pywbem
pywbem/cim_types.py
CIMDateTime._to_int
def _to_int(value_str, min_value, rep_digit, field_name, dtarg): """ Convert value_str into an integer, replacing right-consecutive asterisks with rep_digit, and an all-asterisk value with min_value. field_name and dtarg are passed only for informational purposes. """ 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
python
def _to_int(value_str, min_value, rep_digit, field_name, dtarg): """ Convert value_str into an integer, replacing right-consecutive asterisks with rep_digit, and an all-asterisk value with min_value. field_name and dtarg are passed only for informational purposes. """ 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
[ "def", "_to_int", "(", "value_str", ",", "min_value", ",", "rep_digit", ",", "field_name", ",", "dtarg", ")", ":", "if", "'*'", "in", "value_str", ":", "first", "=", "value_str", ".", "index", "(", "'*'", ")", "after", "=", "value_str", ".", "rindex", ...
Convert value_str into an integer, replacing right-consecutive asterisks with rep_digit, and an all-asterisk value with min_value. field_name and dtarg are passed only for informational purposes.
[ "Convert", "value_str", "into", "an", "integer", "replacing", "right", "-", "consecutive", "asterisks", "with", "rep_digit", "and", "an", "all", "-", "asterisk", "value", "with", "min_value", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L457-L491
train
28,317
pywbem/pywbem
attic/irecv/pycimlistener.py
ServerContextFactory.getContext
def getContext(self): """Create an SSL context with a dodgy certificate.""" ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_certificate_file('server.pem') ctx.use_privatekey_file('server.pem') return ctx
python
def getContext(self): """Create an SSL context with a dodgy certificate.""" ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_certificate_file('server.pem') ctx.use_privatekey_file('server.pem') return ctx
[ "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.
[ "Create", "an", "SSL", "context", "with", "a", "dodgy", "certificate", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/irecv/pycimlistener.py#L56-L61
train
28,318
pywbem/pywbem
examples/pullenuminstances.py
execute_request
def execute_request(conn, classname, max_open, max_pull): """ Enumerate instances defined by the function's classname argument using the OpenEnumerateInstances and PullInstancesWithPath. * classname - Classname for the enumeration. * max_open - defines the maximum number of instances for the server to return for the open *max_pull defines the maximum number of instances for the WBEM server to return for each pull operation. Displays results of each open or pull operation including size, return parameters, and time to execute. Any exception exits the function. """ 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
python
def execute_request(conn, classname, max_open, max_pull): """ Enumerate instances defined by the function's classname argument using the OpenEnumerateInstances and PullInstancesWithPath. * classname - Classname for the enumeration. * max_open - defines the maximum number of instances for the server to return for the open *max_pull defines the maximum number of instances for the WBEM server to return for each pull operation. Displays results of each open or pull operation including size, return parameters, and time to execute. Any exception exits the function. """ 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
[ "def", "execute_request", "(", "conn", ",", "classname", ",", "max_open", ",", "max_pull", ")", ":", "start", "=", "ElapsedTimer", "(", ")", "result", "=", "conn", ".", "OpenEnumerateInstances", "(", "classname", ",", "MaxObjectCount", "=", "max_open", ")", ...
Enumerate instances defined by the function's classname argument using the OpenEnumerateInstances and PullInstancesWithPath. * classname - Classname for the enumeration. * max_open - defines the maximum number of instances for the server to return for the open *max_pull defines the maximum number of instances for the WBEM server to return for each pull operation. Displays results of each open or pull operation including size, return parameters, and time to execute. Any exception exits the function.
[ "Enumerate", "instances", "defined", "by", "the", "function", "s", "classname", "argument", "using", "the", "OpenEnumerateInstances", "and", "PullInstancesWithPath", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/pullenuminstances.py#L60-L108
train
28,319
pywbem/pywbem
pywbem/cim_xml.py
_pcdata_nodes
def _pcdata_nodes(pcdata): """Return a list of minidom nodes with the properly escaped ``pcdata`` inside. The following special XML characters are escaped: * left angle bracket (<) * Right angle bracket (>) * Ampersand (&) By default, XML-based escaping is used for these characters. XML-based escaping will cause the corresponding XML entity references to be used (for example, the ampersand character ``&`` will be represented as ``&amp;``, and the returned list contains one text node with the escaped pcdata string. Nesting of escaped pcdata is naturally supported with XML-based escaping. For example, if the pcdata string is ``a&amp;b``, the XML-escaped string will be ``a&amp;amp;b``. If the ``cim_xml._CDATA_ESCAPING`` switch is set to True, CDATA-based escaping is used instead. CDATA-based escaping will cause a CDATA section to be used for the entire string, or consecutive CDATA sequences (see discussion of nesting, below). The returned node list contains only CDATA section nodes. Example: The pcdata string ``a<b>c`` will become ``<![CDATA[a<b>]]>``, allowing the special XML characters to be used unchanged inside of the CDATA section. Nesting of escaped pcdata is supported with CDATA-based escaping, by using the following approach: If the input pcdata string already contains CDATA sections, they are split into separate strings, splitting the CDATA end token string in the middle, and these part strings are CDATA-escaped separately. See https://en.wikipedia.org/wiki/CDATA#Nesting for details. Escaping of already escaped pcdata is needed in support of nested embedded instances. That requires that each level of escaping can lateron be unescaped, one at a time. """ 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
python
def _pcdata_nodes(pcdata): """Return a list of minidom nodes with the properly escaped ``pcdata`` inside. The following special XML characters are escaped: * left angle bracket (<) * Right angle bracket (>) * Ampersand (&) By default, XML-based escaping is used for these characters. XML-based escaping will cause the corresponding XML entity references to be used (for example, the ampersand character ``&`` will be represented as ``&amp;``, and the returned list contains one text node with the escaped pcdata string. Nesting of escaped pcdata is naturally supported with XML-based escaping. For example, if the pcdata string is ``a&amp;b``, the XML-escaped string will be ``a&amp;amp;b``. If the ``cim_xml._CDATA_ESCAPING`` switch is set to True, CDATA-based escaping is used instead. CDATA-based escaping will cause a CDATA section to be used for the entire string, or consecutive CDATA sequences (see discussion of nesting, below). The returned node list contains only CDATA section nodes. Example: The pcdata string ``a<b>c`` will become ``<![CDATA[a<b>]]>``, allowing the special XML characters to be used unchanged inside of the CDATA section. Nesting of escaped pcdata is supported with CDATA-based escaping, by using the following approach: If the input pcdata string already contains CDATA sections, they are split into separate strings, splitting the CDATA end token string in the middle, and these part strings are CDATA-escaped separately. See https://en.wikipedia.org/wiki/CDATA#Nesting for details. Escaping of already escaped pcdata is needed in support of nested embedded instances. That requires that each level of escaping can lateron be unescaped, one at a time. """ 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
[ "def", "_pcdata_nodes", "(", "pcdata", ")", ":", "nodelist", "=", "[", "]", "if", "_CDATA_ESCAPING", "and", "isinstance", "(", "pcdata", ",", "six", ".", "string_types", ")", "and", "(", "pcdata", ".", "find", "(", "\"<\"", ")", ">=", "0", "or", "pcdat...
Return a list of minidom nodes with the properly escaped ``pcdata`` inside. The following special XML characters are escaped: * left angle bracket (<) * Right angle bracket (>) * Ampersand (&) By default, XML-based escaping is used for these characters. XML-based escaping will cause the corresponding XML entity references to be used (for example, the ampersand character ``&`` will be represented as ``&amp;``, and the returned list contains one text node with the escaped pcdata string. Nesting of escaped pcdata is naturally supported with XML-based escaping. For example, if the pcdata string is ``a&amp;b``, the XML-escaped string will be ``a&amp;amp;b``. If the ``cim_xml._CDATA_ESCAPING`` switch is set to True, CDATA-based escaping is used instead. CDATA-based escaping will cause a CDATA section to be used for the entire string, or consecutive CDATA sequences (see discussion of nesting, below). The returned node list contains only CDATA section nodes. Example: The pcdata string ``a<b>c`` will become ``<![CDATA[a<b>]]>``, allowing the special XML characters to be used unchanged inside of the CDATA section. Nesting of escaped pcdata is supported with CDATA-based escaping, by using the following approach: If the input pcdata string already contains CDATA sections, they are split into separate strings, splitting the CDATA end token string in the middle, and these part strings are CDATA-escaped separately. See https://en.wikipedia.org/wiki/CDATA#Nesting for details. Escaping of already escaped pcdata is needed in support of nested embedded instances. That requires that each level of escaping can lateron be unescaped, one at a time.
[ "Return", "a", "list", "of", "minidom", "nodes", "with", "the", "properly", "escaped", "pcdata", "inside", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_xml.py#L89-L167
train
28,320
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
_uprint
def _uprint(dest, text): """ Write text to dest, adding a newline character. Text may be a unicode string, or a byte string in UTF-8 encoding. It must not be None. If dest is None, the text is encoded to a codepage suitable for the current stdout and is written to stdout. Otherwise, dest must be a file path, and the text is encoded to a UTF-8 Byte sequence and is appended to the file (opening and closing the file). """ 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)))
python
def _uprint(dest, text): """ Write text to dest, adding a newline character. Text may be a unicode string, or a byte string in UTF-8 encoding. It must not be None. If dest is None, the text is encoded to a codepage suitable for the current stdout and is written to stdout. Otherwise, dest must be a file path, and the text is encoded to a UTF-8 Byte sequence and is appended to the file (opening and closing the file). """ 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)))
[ "def", "_uprint", "(", "dest", ",", "text", ")", ":", "if", "isinstance", "(", "text", ",", "six", ".", "text_type", ")", ":", "text", "=", "text", "+", "u'\\n'", "elif", "isinstance", "(", "text", ",", "six", ".", "binary_type", ")", ":", "text", ...
Write text to dest, adding a newline character. Text may be a unicode string, or a byte string in UTF-8 encoding. It must not be None. If dest is None, the text is encoded to a codepage suitable for the current stdout and is written to stdout. Otherwise, dest must be a file path, and the text is encoded to a UTF-8 Byte sequence and is appended to the file (opening and closing the file).
[ "Write", "text", "to", "dest", "adding", "a", "newline", "character", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L94-L140
train
28,321
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
_pretty_xml
def _pretty_xml(xml_string): """ Common function to produce pretty xml string from an input xml_string. This function is NOT intended to be used in major code paths since it uses the minidom to produce the prettified xml and that uses a lot of memory """ 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)
python
def _pretty_xml(xml_string): """ Common function to produce pretty xml string from an input xml_string. This function is NOT intended to be used in major code paths since it uses the minidom to produce the prettified xml and that uses a lot of memory """ 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)
[ "def", "_pretty_xml", "(", "xml_string", ")", ":", "result_dom", "=", "minidom", ".", "parseString", "(", "xml_string", ")", "pretty_result", "=", "result_dom", ".", "toprettyxml", "(", "indent", "=", "' '", ")", "# remove extra empty lines", "return", "re", "....
Common function to produce pretty xml string from an input xml_string. This function is NOT intended to be used in major code paths since it uses the minidom to produce the prettified xml and that uses a lot of memory
[ "Common", "function", "to", "produce", "pretty", "xml", "string", "from", "an", "input", "xml_string", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L221-L234
train
28,322
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection.add_namespace
def add_namespace(self, namespace): """ Add a CIM namespace to the mock repository. The namespace must not yet exist in the mock repository. Note that the default connection namespace is automatically added to the mock repository upon creation of this object. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Any leading and trailing slash characters are split off from the provided string. Raises: ValueError: Namespace argument must not be None CIMError: CIM_ERR_ALREADY_EXISTS if the namespace already exists in the mock repository. """ 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
python
def add_namespace(self, namespace): """ Add a CIM namespace to the mock repository. The namespace must not yet exist in the mock repository. Note that the default connection namespace is automatically added to the mock repository upon creation of this object. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Any leading and trailing slash characters are split off from the provided string. Raises: ValueError: Namespace argument must not be None CIMError: CIM_ERR_ALREADY_EXISTS if the namespace already exists in the mock repository. """ 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
[ "def", "add_namespace", "(", "self", ",", "namespace", ")", ":", "if", "namespace", "is", "None", ":", "raise", "ValueError", "(", "\"Namespace argument must not be None\"", ")", "# Normalize the namespace name", "namespace", "=", "namespace", ".", "strip", "(", "'/...
Add a CIM namespace to the mock repository. The namespace must not yet exist in the mock repository. Note that the default connection namespace is automatically added to the mock repository upon creation of this object. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Any leading and trailing slash characters are split off from the provided string. Raises: ValueError: Namespace argument must not be None CIMError: CIM_ERR_ALREADY_EXISTS if the namespace already exists in the mock repository.
[ "Add", "a", "CIM", "namespace", "to", "the", "mock", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L416-L451
train
28,323
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._remove_namespace
def _remove_namespace(self, namespace): """ Remove a CIM namespace from the mock repository. The namespace must exist in the mock repository and must be empty. The default connection namespace cannot be removed. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Any leading and trailing slash characters are split off from the provided string. Raises: ValueError: Namespace argument must not be None CIMError: CIM_ERR_NOT_FOUND if the namespace does not exist in the mock repository. CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY if the namespace is not empty. CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY if the default connection namespace was attempted to be deleted. """ 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]
python
def _remove_namespace(self, namespace): """ Remove a CIM namespace from the mock repository. The namespace must exist in the mock repository and must be empty. The default connection namespace cannot be removed. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Any leading and trailing slash characters are split off from the provided string. Raises: ValueError: Namespace argument must not be None CIMError: CIM_ERR_NOT_FOUND if the namespace does not exist in the mock repository. CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY if the namespace is not empty. CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY if the default connection namespace was attempted to be deleted. """ 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]
[ "def", "_remove_namespace", "(", "self", ",", "namespace", ")", ":", "if", "namespace", "is", "None", ":", "raise", "ValueError", "(", "\"Namespace argument must not be None\"", ")", "# Normalize the namespace name", "namespace", "=", "namespace", ".", "strip", "(", ...
Remove a CIM namespace from the mock repository. The namespace must exist in the mock repository and must be empty. The default connection namespace cannot be removed. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Any leading and trailing slash characters are split off from the provided string. Raises: ValueError: Namespace argument must not be None CIMError: CIM_ERR_NOT_FOUND if the namespace does not exist in the mock repository. CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY if the namespace is not empty. CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY if the default connection namespace was attempted to be deleted.
[ "Remove", "a", "CIM", "namespace", "from", "the", "mock", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L453-L503
train
28,324
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection.compile_mof_string
def compile_mof_string(self, mof_str, namespace=None, search_paths=None, verbose=None): """ Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the mock repository. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. This method supports all MOF pragmas, and specifically the include pragma. If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises :exc:`~pywbem.CIMError`. If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises :exc:`~pywbem.CIMError`. In all cases where this method raises an exception, the mock repository remains unchanged. Parameters: mof_str (:term:`string`): A string with the MOF definitions to be compiled. namespace (:term:`string`): The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If `None`, the default namespace of the connection is used. search_paths (:term:`py:iterable` of :term:`string`): An iterable of directory path names where MOF dependent files will be looked up. See the description of the `search_path` init parameter of the :class:`~pywbem.MOFCompiler` class for more information on MOF dependent files. verbose (:class:`py:bool`): Controls whether to issue more detailed compiler messages. Raises: IOError: MOF file not found. :exc:`~pywbem.MOFParseError`: Compile error in the MOF. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the mock repository. """ namespace = namespace or self.default_namespace # if not self._validate_namespace(namespace): TODO # self.add_namespace(namespace) self._validate_namespace(namespace) mofcomp = MOFCompiler(_MockMOFWBEMConnection(self), search_paths=search_paths, verbose=verbose) mofcomp.compile_string(mof_str, namespace)
python
def compile_mof_string(self, mof_str, namespace=None, search_paths=None, verbose=None): """ Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the mock repository. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. This method supports all MOF pragmas, and specifically the include pragma. If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises :exc:`~pywbem.CIMError`. If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises :exc:`~pywbem.CIMError`. In all cases where this method raises an exception, the mock repository remains unchanged. Parameters: mof_str (:term:`string`): A string with the MOF definitions to be compiled. namespace (:term:`string`): The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If `None`, the default namespace of the connection is used. search_paths (:term:`py:iterable` of :term:`string`): An iterable of directory path names where MOF dependent files will be looked up. See the description of the `search_path` init parameter of the :class:`~pywbem.MOFCompiler` class for more information on MOF dependent files. verbose (:class:`py:bool`): Controls whether to issue more detailed compiler messages. Raises: IOError: MOF file not found. :exc:`~pywbem.MOFParseError`: Compile error in the MOF. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the mock repository. """ namespace = namespace or self.default_namespace # if not self._validate_namespace(namespace): TODO # self.add_namespace(namespace) self._validate_namespace(namespace) mofcomp = MOFCompiler(_MockMOFWBEMConnection(self), search_paths=search_paths, verbose=verbose) mofcomp.compile_string(mof_str, namespace)
[ "def", "compile_mof_string", "(", "self", ",", "mof_str", ",", "namespace", "=", "None", ",", "search_paths", "=", "None", ",", "verbose", "=", "None", ")", ":", "namespace", "=", "namespace", "or", "self", ".", "default_namespace", "# if not self._validate_name...
Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the mock repository. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. This method supports all MOF pragmas, and specifically the include pragma. If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises :exc:`~pywbem.CIMError`. If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises :exc:`~pywbem.CIMError`. In all cases where this method raises an exception, the mock repository remains unchanged. Parameters: mof_str (:term:`string`): A string with the MOF definitions to be compiled. namespace (:term:`string`): The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If `None`, the default namespace of the connection is used. search_paths (:term:`py:iterable` of :term:`string`): An iterable of directory path names where MOF dependent files will be looked up. See the description of the `search_path` init parameter of the :class:`~pywbem.MOFCompiler` class for more information on MOF dependent files. verbose (:class:`py:bool`): Controls whether to issue more detailed compiler messages. Raises: IOError: MOF file not found. :exc:`~pywbem.MOFParseError`: Compile error in the MOF. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the mock repository.
[ "Compile", "the", "MOF", "definitions", "in", "the", "specified", "string", "and", "add", "the", "resulting", "CIM", "objects", "to", "the", "specified", "CIM", "namespace", "of", "the", "mock", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L569-L633
train
28,325
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection.compile_dmtf_schema
def compile_dmtf_schema(self, schema_version, schema_root_dir, class_names, use_experimental=False, namespace=None, verbose=False): """ Compile the classes defined by `class_names` and their dependent classes from the DMTF CIM schema version defined by `schema_version` and keep the downloaded DMTF CIM schema in the directory defined by `schema_dir`. This method uses the :class:`~pywbem_mock.DMTFCIMSchema` class to download the DMTF CIM schema defined by `schema_version` from the DMTF, into the `schema_root_dir` directory, extract the MOF files, create a MOF file with the `#include pragma` statements for the files in `class_names` and attempt to compile this set of files. It automatically compiles all of the DMTF qualifier declarations that are in the files `qualifiers.mof` and `qualifiers_optional.mof`. The result of the compilation is added to the specified CIM namespace of the mock repository. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. Parameters: schema_version (tuple of 3 integers (m, n, u): Represents the DMTF CIM schema version where: * m is the DMTF CIM schema major version * n is the DMTF CIM schema minor version * u is the DMTF CIM schema update version This must represent a DMTF CIM schema that is available from the DMTF web site. schema_root_dir (:term:`string`): Directory into which the DMTF CIM schema is installed or will be installed. A single `schema_dir` can be used for multiple schema versions because subdirectories are uniquely defined by schema version and schema_type (i.e. Final or Experimental). Multiple DMTF CIM schemas may be maintained in the same `schema_root_dir` simultaneously because the MOF for each schema is extracted into a subdirectory identified by the schema version information. class_names (:term:`py:list` of :term:`string` or :term:`string`): List of class names from the DMTF CIM Schema to be included in the repository. A single class may be defined as a string not in a list. These must be classes in the defined DMTF CIM schema and can be a list of just the leaf classes required The MOF compiler will search the DMTF CIM schema MOF classes for superclasses, classes defined in reference properties, and classes defined in EmbeddedInstance qualifiers and compile them also. use_experimental (:class:`py:bool`): If `True` the expermental version of the DMTF CIM Schema is installed or to be installed. If `False` (default) the final version of the DMTF CIM Schema is installed or to be installed. namespace (:term:`string`): The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If `None`, the default namespace of the connection is used. verbose (:class:`py:bool`): If `True`, progress messages are output to stdout Raises: ValueError: The schema cannot be retrieved from the DMTF web site, the schema_version is invalid, or a class name cannot be found in the defined DMTF CIM schema. TypeError: The 'schema_version' is not a valid tuple with 3 integer components :exc:`~pywbem.MOFParseError`: Compile error in the MOF. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the mock repository. """ schema = DMTFCIMSchema(schema_version, schema_root_dir, use_experimental=use_experimental, verbose=verbose) schema_mof = schema.build_schema_mof(class_names) search_paths = schema.schema_mof_dir self.compile_mof_string(schema_mof, namespace=namespace, search_paths=[search_paths], verbose=verbose)
python
def compile_dmtf_schema(self, schema_version, schema_root_dir, class_names, use_experimental=False, namespace=None, verbose=False): """ Compile the classes defined by `class_names` and their dependent classes from the DMTF CIM schema version defined by `schema_version` and keep the downloaded DMTF CIM schema in the directory defined by `schema_dir`. This method uses the :class:`~pywbem_mock.DMTFCIMSchema` class to download the DMTF CIM schema defined by `schema_version` from the DMTF, into the `schema_root_dir` directory, extract the MOF files, create a MOF file with the `#include pragma` statements for the files in `class_names` and attempt to compile this set of files. It automatically compiles all of the DMTF qualifier declarations that are in the files `qualifiers.mof` and `qualifiers_optional.mof`. The result of the compilation is added to the specified CIM namespace of the mock repository. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. Parameters: schema_version (tuple of 3 integers (m, n, u): Represents the DMTF CIM schema version where: * m is the DMTF CIM schema major version * n is the DMTF CIM schema minor version * u is the DMTF CIM schema update version This must represent a DMTF CIM schema that is available from the DMTF web site. schema_root_dir (:term:`string`): Directory into which the DMTF CIM schema is installed or will be installed. A single `schema_dir` can be used for multiple schema versions because subdirectories are uniquely defined by schema version and schema_type (i.e. Final or Experimental). Multiple DMTF CIM schemas may be maintained in the same `schema_root_dir` simultaneously because the MOF for each schema is extracted into a subdirectory identified by the schema version information. class_names (:term:`py:list` of :term:`string` or :term:`string`): List of class names from the DMTF CIM Schema to be included in the repository. A single class may be defined as a string not in a list. These must be classes in the defined DMTF CIM schema and can be a list of just the leaf classes required The MOF compiler will search the DMTF CIM schema MOF classes for superclasses, classes defined in reference properties, and classes defined in EmbeddedInstance qualifiers and compile them also. use_experimental (:class:`py:bool`): If `True` the expermental version of the DMTF CIM Schema is installed or to be installed. If `False` (default) the final version of the DMTF CIM Schema is installed or to be installed. namespace (:term:`string`): The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If `None`, the default namespace of the connection is used. verbose (:class:`py:bool`): If `True`, progress messages are output to stdout Raises: ValueError: The schema cannot be retrieved from the DMTF web site, the schema_version is invalid, or a class name cannot be found in the defined DMTF CIM schema. TypeError: The 'schema_version' is not a valid tuple with 3 integer components :exc:`~pywbem.MOFParseError`: Compile error in the MOF. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the mock repository. """ schema = DMTFCIMSchema(schema_version, schema_root_dir, use_experimental=use_experimental, verbose=verbose) schema_mof = schema.build_schema_mof(class_names) search_paths = schema.schema_mof_dir self.compile_mof_string(schema_mof, namespace=namespace, search_paths=[search_paths], verbose=verbose)
[ "def", "compile_dmtf_schema", "(", "self", ",", "schema_version", ",", "schema_root_dir", ",", "class_names", ",", "use_experimental", "=", "False", ",", "namespace", "=", "None", ",", "verbose", "=", "False", ")", ":", "schema", "=", "DMTFCIMSchema", "(", "sc...
Compile the classes defined by `class_names` and their dependent classes from the DMTF CIM schema version defined by `schema_version` and keep the downloaded DMTF CIM schema in the directory defined by `schema_dir`. This method uses the :class:`~pywbem_mock.DMTFCIMSchema` class to download the DMTF CIM schema defined by `schema_version` from the DMTF, into the `schema_root_dir` directory, extract the MOF files, create a MOF file with the `#include pragma` statements for the files in `class_names` and attempt to compile this set of files. It automatically compiles all of the DMTF qualifier declarations that are in the files `qualifiers.mof` and `qualifiers_optional.mof`. The result of the compilation is added to the specified CIM namespace of the mock repository. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. Parameters: schema_version (tuple of 3 integers (m, n, u): Represents the DMTF CIM schema version where: * m is the DMTF CIM schema major version * n is the DMTF CIM schema minor version * u is the DMTF CIM schema update version This must represent a DMTF CIM schema that is available from the DMTF web site. schema_root_dir (:term:`string`): Directory into which the DMTF CIM schema is installed or will be installed. A single `schema_dir` can be used for multiple schema versions because subdirectories are uniquely defined by schema version and schema_type (i.e. Final or Experimental). Multiple DMTF CIM schemas may be maintained in the same `schema_root_dir` simultaneously because the MOF for each schema is extracted into a subdirectory identified by the schema version information. class_names (:term:`py:list` of :term:`string` or :term:`string`): List of class names from the DMTF CIM Schema to be included in the repository. A single class may be defined as a string not in a list. These must be classes in the defined DMTF CIM schema and can be a list of just the leaf classes required The MOF compiler will search the DMTF CIM schema MOF classes for superclasses, classes defined in reference properties, and classes defined in EmbeddedInstance qualifiers and compile them also. use_experimental (:class:`py:bool`): If `True` the expermental version of the DMTF CIM Schema is installed or to be installed. If `False` (default) the final version of the DMTF CIM Schema is installed or to be installed. namespace (:term:`string`): The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If `None`, the default namespace of the connection is used. verbose (:class:`py:bool`): If `True`, progress messages are output to stdout Raises: ValueError: The schema cannot be retrieved from the DMTF web site, the schema_version is invalid, or a class name cannot be found in the defined DMTF CIM schema. TypeError: The 'schema_version' is not a valid tuple with 3 integer components :exc:`~pywbem.MOFParseError`: Compile error in the MOF. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the mock repository.
[ "Compile", "the", "classes", "defined", "by", "class_names", "and", "their", "dependent", "classes", "from", "the", "DMTF", "CIM", "schema", "version", "defined", "by", "schema_version", "and", "keep", "the", "downloaded", "DMTF", "CIM", "schema", "in", "the", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L635-L731
train
28,326
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection.add_method_callback
def add_method_callback(self, classname, methodname, method_callback, namespace=None,): """ Register a callback function for a CIM method that will be called when the CIM method is invoked via `InvokeMethod`. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. Parameters: classname (:term:`string`): The CIM class name for which the callback function is registered. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. For method invocations on a target instance, this must be the class name of the creation class of the target instance. For method invocations on a target class, this must be the class name of the target class. methodname (:term:`string`): The CIM method name for which the callback function is registered. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. method_callback (:func:`~pywbem_mock.method_callback_interface`): The callback function. namespace (:term:`string`): The CIM namespace for which the callback function is registered. If `None`, the callback function is registered for the default namespace of the connection. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. Raises: ValueError: Duplicate method specification. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ if namespace is None: namespace = self.default_namespace # Validate namespace method_repo = self._get_method_repo(namespace) if classname not in method_repo: method_repo[classname] = NocaseDict() if methodname in method_repo[classname]: raise ValueError("Duplicate method specification") method_repo[classname][methodname] = method_callback
python
def add_method_callback(self, classname, methodname, method_callback, namespace=None,): """ Register a callback function for a CIM method that will be called when the CIM method is invoked via `InvokeMethod`. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. Parameters: classname (:term:`string`): The CIM class name for which the callback function is registered. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. For method invocations on a target instance, this must be the class name of the creation class of the target instance. For method invocations on a target class, this must be the class name of the target class. methodname (:term:`string`): The CIM method name for which the callback function is registered. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. method_callback (:func:`~pywbem_mock.method_callback_interface`): The callback function. namespace (:term:`string`): The CIM namespace for which the callback function is registered. If `None`, the callback function is registered for the default namespace of the connection. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. Raises: ValueError: Duplicate method specification. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ if namespace is None: namespace = self.default_namespace # Validate namespace method_repo = self._get_method_repo(namespace) if classname not in method_repo: method_repo[classname] = NocaseDict() if methodname in method_repo[classname]: raise ValueError("Duplicate method specification") method_repo[classname][methodname] = method_callback
[ "def", "add_method_callback", "(", "self", ",", "classname", ",", "methodname", ",", "method_callback", ",", "namespace", "=", "None", ",", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "self", ".", "default_namespace", "# Validate namespace"...
Register a callback function for a CIM method that will be called when the CIM method is invoked via `InvokeMethod`. If the namespace does not exist, :exc:`~pywbem.CIMError` with status CIM_ERR_INVALID_NAMESPACE is raised. Parameters: classname (:term:`string`): The CIM class name for which the callback function is registered. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. For method invocations on a target instance, this must be the class name of the creation class of the target instance. For method invocations on a target class, this must be the class name of the target class. methodname (:term:`string`): The CIM method name for which the callback function is registered. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. method_callback (:func:`~pywbem_mock.method_callback_interface`): The callback function. namespace (:term:`string`): The CIM namespace for which the callback function is registered. If `None`, the callback function is registered for the default namespace of the connection. The faked `InvokeMethod` implementation uses this information to look up the callback function from its parameters. Raises: ValueError: Duplicate method specification. :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
[ "Register", "a", "callback", "function", "for", "a", "CIM", "method", "that", "will", "be", "called", "when", "the", "CIM", "method", "is", "invoked", "via", "InvokeMethod", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L846-L905
train
28,327
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection.display_repository
def display_repository(self, namespaces=None, dest=None, summary=False, output_format='mof'): """ Display the namespaces and objects in the mock repository in one of multiple formats to a destination. Parameters: namespaces (:term:`string` or list of :term:`string`): Limits display output to the specified CIM namespace or namespaces. If `None`, all namespaces of the mock repository are displayed. dest (:term:`string`): File path of the output file. If `None`, the output is written to stdout. summary (:class:`py:bool`): Flag for summary mode. If `True`, only a summary count of CIM objects in the specified namespaces of the mock repository is produced. If `False`, both the summary count and the details of the CIM objects are produced. output_format (:term:`string`): Output format, one of: 'mof', 'xml', or 'repr'. """ if output_format == 'mof': cmt_begin = '# ' cmt_end = '' elif output_format == 'xml': cmt_begin = '<!-- ' cmt_end = ' ->' else: cmt_begin = '' cmt_end = '' if output_format not in OUTPUT_FORMATS: raise ValueError( _format("Invalid output format definition {0!A}. " "{1!A} are valid.", output_format, OUTPUT_FORMATS)) _uprint(dest, _format(u"{0}========Mock Repo Display fmt={1} " u"namespaces={2} ========={3}\n", cmt_begin, output_format, ('all' if namespaces is None else _format("{0!A}", namespaces)), cmt_end)) # get all namespaces repo_ns_set = set(self.namespaces.keys()) if namespaces: if isinstance(namespaces, six.string_types): namespaces = [namespaces] repo_ns_set = repo_ns_set.intersection(set(namespaces)) repo_ns_list = sorted(list(repo_ns_set)) for ns in repo_ns_list: _uprint(dest, _format(u"\n{0}NAMESPACE {1!A}{2}\n", cmt_begin, ns, cmt_end)) self._display_objects('Qualifier Declarations', self.qualifiers, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) self._display_objects('Classes', self.classes, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) self._display_objects('Instances', self.instances, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) self._display_objects('Methods', self.methods, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) _uprint(dest, u'============End Repository=================')
python
def display_repository(self, namespaces=None, dest=None, summary=False, output_format='mof'): """ Display the namespaces and objects in the mock repository in one of multiple formats to a destination. Parameters: namespaces (:term:`string` or list of :term:`string`): Limits display output to the specified CIM namespace or namespaces. If `None`, all namespaces of the mock repository are displayed. dest (:term:`string`): File path of the output file. If `None`, the output is written to stdout. summary (:class:`py:bool`): Flag for summary mode. If `True`, only a summary count of CIM objects in the specified namespaces of the mock repository is produced. If `False`, both the summary count and the details of the CIM objects are produced. output_format (:term:`string`): Output format, one of: 'mof', 'xml', or 'repr'. """ if output_format == 'mof': cmt_begin = '# ' cmt_end = '' elif output_format == 'xml': cmt_begin = '<!-- ' cmt_end = ' ->' else: cmt_begin = '' cmt_end = '' if output_format not in OUTPUT_FORMATS: raise ValueError( _format("Invalid output format definition {0!A}. " "{1!A} are valid.", output_format, OUTPUT_FORMATS)) _uprint(dest, _format(u"{0}========Mock Repo Display fmt={1} " u"namespaces={2} ========={3}\n", cmt_begin, output_format, ('all' if namespaces is None else _format("{0!A}", namespaces)), cmt_end)) # get all namespaces repo_ns_set = set(self.namespaces.keys()) if namespaces: if isinstance(namespaces, six.string_types): namespaces = [namespaces] repo_ns_set = repo_ns_set.intersection(set(namespaces)) repo_ns_list = sorted(list(repo_ns_set)) for ns in repo_ns_list: _uprint(dest, _format(u"\n{0}NAMESPACE {1!A}{2}\n", cmt_begin, ns, cmt_end)) self._display_objects('Qualifier Declarations', self.qualifiers, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) self._display_objects('Classes', self.classes, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) self._display_objects('Instances', self.instances, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) self._display_objects('Methods', self.methods, ns, cmt_begin, cmt_end, dest=dest, summary=summary, output_format=output_format) _uprint(dest, u'============End Repository=================')
[ "def", "display_repository", "(", "self", ",", "namespaces", "=", "None", ",", "dest", "=", "None", ",", "summary", "=", "False", ",", "output_format", "=", "'mof'", ")", ":", "if", "output_format", "==", "'mof'", ":", "cmt_begin", "=", "'# '", "cmt_end", ...
Display the namespaces and objects in the mock repository in one of multiple formats to a destination. Parameters: namespaces (:term:`string` or list of :term:`string`): Limits display output to the specified CIM namespace or namespaces. If `None`, all namespaces of the mock repository are displayed. dest (:term:`string`): File path of the output file. If `None`, the output is written to stdout. summary (:class:`py:bool`): Flag for summary mode. If `True`, only a summary count of CIM objects in the specified namespaces of the mock repository is produced. If `False`, both the summary count and the details of the CIM objects are produced. output_format (:term:`string`): Output format, one of: 'mof', 'xml', or 'repr'.
[ "Display", "the", "namespaces", "and", "objects", "in", "the", "mock", "repository", "in", "one", "of", "multiple", "formats", "to", "a", "destination", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L907-L981
train
28,328
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_inst_repo
def _get_inst_repo(self, namespace=None): """ Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None """ if namespace is None: namespace = self.default_namespace return self.instances[namespace]
python
def _get_inst_repo(self, namespace=None): """ Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None """ if namespace is None: namespace = self.default_namespace return self.instances[namespace]
[ "def", "_get_inst_repo", "(", "self", ",", "namespace", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "self", ".", "default_namespace", "return", "self", ".", "instances", "[", "namespace", "]" ]
Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None
[ "Test", "support", "method", "that", "returns", "instances", "from", "the", "repository", "with", "no", "processing", ".", "It", "uses", "the", "default", "namespace", "if", "input", "parameter", "for", "namespace", "is", "None" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1065-L1073
train
28,329
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._class_exists
def _class_exists(self, classname, namespace): """ Test if class defined by classname parameter exists in repository defined by namespace parameter. Returns `True` if class exists and `False` if it does not exist. Exception if the namespace does not exist """ class_repo = self._get_class_repo(namespace) return classname in class_repo
python
def _class_exists(self, classname, namespace): """ Test if class defined by classname parameter exists in repository defined by namespace parameter. Returns `True` if class exists and `False` if it does not exist. Exception if the namespace does not exist """ class_repo = self._get_class_repo(namespace) return classname in class_repo
[ "def", "_class_exists", "(", "self", ",", "classname", ",", "namespace", ")", ":", "class_repo", "=", "self", ".", "_get_class_repo", "(", "namespace", ")", "return", "classname", "in", "class_repo" ]
Test if class defined by classname parameter exists in repository defined by namespace parameter. Returns `True` if class exists and `False` if it does not exist. Exception if the namespace does not exist
[ "Test", "if", "class", "defined", "by", "classname", "parameter", "exists", "in", "repository", "defined", "by", "namespace", "parameter", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1130-L1140
train
28,330
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._remove_qualifiers
def _remove_qualifiers(obj): """ Remove all qualifiers from the input objectwhere the object may be an CIMInstance or CIMClass. Removes qualifiers from the object and from properties, methods, and parameters This is used to process the IncludeQualifier parameter for classes and instances """ assert isinstance(obj, (CIMInstance, CIMClass)) obj.qualifiers = NocaseDict() for prop in obj.properties: obj.properties[prop].qualifiers = NocaseDict() if isinstance(obj, CIMClass): for method in obj.methods: obj.methods[method].qualifiers = NocaseDict() for param in obj.methods[method].parameters: obj.methods[method].parameters[param].qualifiers = \ NocaseDict()
python
def _remove_qualifiers(obj): """ Remove all qualifiers from the input objectwhere the object may be an CIMInstance or CIMClass. Removes qualifiers from the object and from properties, methods, and parameters This is used to process the IncludeQualifier parameter for classes and instances """ assert isinstance(obj, (CIMInstance, CIMClass)) obj.qualifiers = NocaseDict() for prop in obj.properties: obj.properties[prop].qualifiers = NocaseDict() if isinstance(obj, CIMClass): for method in obj.methods: obj.methods[method].qualifiers = NocaseDict() for param in obj.methods[method].parameters: obj.methods[method].parameters[param].qualifiers = \ NocaseDict()
[ "def", "_remove_qualifiers", "(", "obj", ")", ":", "assert", "isinstance", "(", "obj", ",", "(", "CIMInstance", ",", "CIMClass", ")", ")", "obj", ".", "qualifiers", "=", "NocaseDict", "(", ")", "for", "prop", "in", "obj", ".", "properties", ":", "obj", ...
Remove all qualifiers from the input objectwhere the object may be an CIMInstance or CIMClass. Removes qualifiers from the object and from properties, methods, and parameters This is used to process the IncludeQualifier parameter for classes and instances
[ "Remove", "all", "qualifiers", "from", "the", "input", "objectwhere", "the", "object", "may", "be", "an", "CIMInstance", "or", "CIMClass", ".", "Removes", "qualifiers", "from", "the", "object", "and", "from", "properties", "methods", "and", "parameters" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1150-L1168
train
28,331
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._remove_classorigin
def _remove_classorigin(obj): """ Remove all ClassOrigin attributes from the input object. The object may be a CIMInstance or CIMClass. Used to process the IncludeClassOrigin parameter of requests """ assert isinstance(obj, (CIMInstance, CIMClass)) for prop in obj.properties: obj.properties[prop].class_origin = None if isinstance(obj, CIMClass): for method in obj.methods: obj.methods[method].class_origin = None
python
def _remove_classorigin(obj): """ Remove all ClassOrigin attributes from the input object. The object may be a CIMInstance or CIMClass. Used to process the IncludeClassOrigin parameter of requests """ assert isinstance(obj, (CIMInstance, CIMClass)) for prop in obj.properties: obj.properties[prop].class_origin = None if isinstance(obj, CIMClass): for method in obj.methods: obj.methods[method].class_origin = None
[ "def", "_remove_classorigin", "(", "obj", ")", ":", "assert", "isinstance", "(", "obj", ",", "(", "CIMInstance", ",", "CIMClass", ")", ")", "for", "prop", "in", "obj", ".", "properties", ":", "obj", ".", "properties", "[", "prop", "]", ".", "class_origin...
Remove all ClassOrigin attributes from the input object. The object may be a CIMInstance or CIMClass. Used to process the IncludeClassOrigin parameter of requests
[ "Remove", "all", "ClassOrigin", "attributes", "from", "the", "input", "object", ".", "The", "object", "may", "be", "a", "CIMInstance", "or", "CIMClass", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1171-L1183
train
28,332
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._validate_namespace
def _validate_namespace(self, namespace): """ Validate whether a CIM namespace exists in the mock repository. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ if namespace not in self.namespaces: raise CIMError( CIM_ERR_INVALID_NAMESPACE, _format("Namespace does not exist in mock repository: {0!A}", namespace))
python
def _validate_namespace(self, namespace): """ Validate whether a CIM namespace exists in the mock repository. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ if namespace not in self.namespaces: raise CIMError( CIM_ERR_INVALID_NAMESPACE, _format("Namespace does not exist in mock repository: {0!A}", namespace))
[ "def", "_validate_namespace", "(", "self", ",", "namespace", ")", ":", "if", "namespace", "not", "in", "self", ".", "namespaces", ":", "raise", "CIMError", "(", "CIM_ERR_INVALID_NAMESPACE", ",", "_format", "(", "\"Namespace does not exist in mock repository: {0!A}\"", ...
Validate whether a CIM namespace exists in the mock repository. Parameters: namespace (:term:`string`): The name of the CIM namespace in the mock repository. Must not be `None`. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
[ "Validate", "whether", "a", "CIM", "namespace", "exists", "in", "the", "mock", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1185-L1204
train
28,333
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_class_repo
def _get_class_repo(self, namespace): """ Returns the class repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the class repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of CIMClass: Class repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.classes: self.classes[namespace] = NocaseDict() return self.classes[namespace]
python
def _get_class_repo(self, namespace): """ Returns the class repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the class repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of CIMClass: Class repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.classes: self.classes[namespace] = NocaseDict() return self.classes[namespace]
[ "def", "_get_class_repo", "(", "self", ",", "namespace", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "if", "namespace", "not", "in", "self", ".", "classes", ":", "self", ".", "classes", "[", "namespace", "]", "=", "NocaseDict", "("...
Returns the class repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the class repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of CIMClass: Class repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
[ "Returns", "the", "class", "repository", "for", "the", "specified", "CIM", "namespace", "within", "the", "mock", "repository", ".", "This", "is", "the", "original", "instance", "variable", "so", "any", "modifications", "will", "change", "the", "mock", "repositor...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1206-L1233
train
28,334
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_instance_repo
def _get_instance_repo(self, namespace): """ Returns the instance repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the instance repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: list of CIMInstance: Instance repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.instances: self.instances[namespace] = [] return self.instances[namespace]
python
def _get_instance_repo(self, namespace): """ Returns the instance repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the instance repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: list of CIMInstance: Instance repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.instances: self.instances[namespace] = [] return self.instances[namespace]
[ "def", "_get_instance_repo", "(", "self", ",", "namespace", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "if", "namespace", "not", "in", "self", ".", "instances", ":", "self", ".", "instances", "[", "namespace", "]", "=", "[", "]", ...
Returns the instance repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the instance repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: list of CIMInstance: Instance repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
[ "Returns", "the", "instance", "repository", "for", "the", "specified", "CIM", "namespace", "within", "the", "mock", "repository", ".", "This", "is", "the", "original", "instance", "variable", "so", "any", "modifications", "will", "change", "the", "mock", "reposi...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1235-L1262
train
28,335
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_qualifier_repo
def _get_qualifier_repo(self, namespace): """ Returns the qualifier repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the qualifier repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of CIMQualifierDeclaration: Qualifier repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.qualifiers: self.qualifiers[namespace] = NocaseDict() return self.qualifiers[namespace]
python
def _get_qualifier_repo(self, namespace): """ Returns the qualifier repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the qualifier repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of CIMQualifierDeclaration: Qualifier repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.qualifiers: self.qualifiers[namespace] = NocaseDict() return self.qualifiers[namespace]
[ "def", "_get_qualifier_repo", "(", "self", ",", "namespace", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "if", "namespace", "not", "in", "self", ".", "qualifiers", ":", "self", ".", "qualifiers", "[", "namespace", "]", "=", "NocaseDi...
Returns the qualifier repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the qualifier repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of CIMQualifierDeclaration: Qualifier repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
[ "Returns", "the", "qualifier", "repository", "for", "the", "specified", "CIM", "namespace", "within", "the", "mock", "repository", ".", "This", "is", "the", "original", "instance", "variable", "so", "any", "modifications", "will", "change", "the", "mock", "repos...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1264-L1291
train
28,336
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_method_repo
def _get_method_repo(self, namespace=None): """ Returns the method repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the method repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of dict of method callback function: Method repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.methods: self.methods[namespace] = NocaseDict() return self.methods[namespace]
python
def _get_method_repo(self, namespace=None): """ Returns the method repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the method repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of dict of method callback function: Method repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist. """ self._validate_namespace(namespace) if namespace not in self.methods: self.methods[namespace] = NocaseDict() return self.methods[namespace]
[ "def", "_get_method_repo", "(", "self", ",", "namespace", "=", "None", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "if", "namespace", "not", "in", "self", ".", "methods", ":", "self", ".", "methods", "[", "namespace", "]", "=", "...
Returns the method repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the method repository does not contain the namespace yet, it is added. Parameters: namespace(:term:`string`): Namespace name. Must not be `None`. Returns: dict of dict of method callback function: Method repository. Raises: :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
[ "Returns", "the", "method", "repository", "for", "the", "specified", "CIM", "namespace", "within", "the", "mock", "repository", ".", "This", "is", "the", "original", "instance", "variable", "so", "any", "modifications", "will", "change", "the", "mock", "reposito...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1293-L1320
train
28,337
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_superclassnames
def _get_superclassnames(self, cn, namespace): """ Get list of superclasses names from the class repository for the defined classname in the namespace. Returns in order of descending class hiearchy. """ class_repo = self._get_class_repo(namespace) superclass_names = [] if cn is not None: cnwork = cn while cnwork: cnsuper = class_repo[cnwork].superclass if cnsuper: superclass_names.append(cnsuper) cnwork = cnsuper superclass_names.reverse() return superclass_names
python
def _get_superclassnames(self, cn, namespace): """ Get list of superclasses names from the class repository for the defined classname in the namespace. Returns in order of descending class hiearchy. """ class_repo = self._get_class_repo(namespace) superclass_names = [] if cn is not None: cnwork = cn while cnwork: cnsuper = class_repo[cnwork].superclass if cnsuper: superclass_names.append(cnsuper) cnwork = cnsuper superclass_names.reverse() return superclass_names
[ "def", "_get_superclassnames", "(", "self", ",", "cn", ",", "namespace", ")", ":", "class_repo", "=", "self", ".", "_get_class_repo", "(", "namespace", ")", "superclass_names", "=", "[", "]", "if", "cn", "is", "not", "None", ":", "cnwork", "=", "cn", "wh...
Get list of superclasses names from the class repository for the defined classname in the namespace. Returns in order of descending class hiearchy.
[ "Get", "list", "of", "superclasses", "names", "from", "the", "class", "repository", "for", "the", "defined", "classname", "in", "the", "namespace", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1379-L1396
train
28,338
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_subclass_names
def _get_subclass_names(self, classname, namespace, deep_inheritance): """ Get class names that are subclasses of the classname input parameter from the repository. If DeepInheritance is False, get only classes in the repository for the defined namespace for which this class is a direct super class. If deep_inheritance is `True`, get all direct and indirect subclasses. If false, get only a the next level of the hiearchy. Returns: list of strings with the names of all subclasses of `classname`. """ assert classname is None or isinstance(classname, (six.string_types, CIMClassName)) if isinstance(classname, CIMClassName): classname = classname.classname # retrieve first level of subclasses for which classname is superclass try: classes = self.classes[namespace] except KeyError: classes = NocaseDict() if classname is None: rtn_classnames = [ cl.classname for cl in six.itervalues(classes) if cl.superclass is None] else: rtn_classnames = [ cl.classname for cl in six.itervalues(classes) if cl.superclass and cl.superclass.lower() == classname.lower()] # recurse for next level of class hiearchy if deep_inheritance: subclass_names = [] if rtn_classnames: for cn in rtn_classnames: subclass_names.extend( self._get_subclass_names(cn, namespace, deep_inheritance)) rtn_classnames.extend(subclass_names) return rtn_classnames
python
def _get_subclass_names(self, classname, namespace, deep_inheritance): """ Get class names that are subclasses of the classname input parameter from the repository. If DeepInheritance is False, get only classes in the repository for the defined namespace for which this class is a direct super class. If deep_inheritance is `True`, get all direct and indirect subclasses. If false, get only a the next level of the hiearchy. Returns: list of strings with the names of all subclasses of `classname`. """ assert classname is None or isinstance(classname, (six.string_types, CIMClassName)) if isinstance(classname, CIMClassName): classname = classname.classname # retrieve first level of subclasses for which classname is superclass try: classes = self.classes[namespace] except KeyError: classes = NocaseDict() if classname is None: rtn_classnames = [ cl.classname for cl in six.itervalues(classes) if cl.superclass is None] else: rtn_classnames = [ cl.classname for cl in six.itervalues(classes) if cl.superclass and cl.superclass.lower() == classname.lower()] # recurse for next level of class hiearchy if deep_inheritance: subclass_names = [] if rtn_classnames: for cn in rtn_classnames: subclass_names.extend( self._get_subclass_names(cn, namespace, deep_inheritance)) rtn_classnames.extend(subclass_names) return rtn_classnames
[ "def", "_get_subclass_names", "(", "self", ",", "classname", ",", "namespace", ",", "deep_inheritance", ")", ":", "assert", "classname", "is", "None", "or", "isinstance", "(", "classname", ",", "(", "six", ".", "string_types", ",", "CIMClassName", ")", ")", ...
Get class names that are subclasses of the classname input parameter from the repository. If DeepInheritance is False, get only classes in the repository for the defined namespace for which this class is a direct super class. If deep_inheritance is `True`, get all direct and indirect subclasses. If false, get only a the next level of the hiearchy. Returns: list of strings with the names of all subclasses of `classname`.
[ "Get", "class", "names", "that", "are", "subclasses", "of", "the", "classname", "input", "parameter", "from", "the", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1398-L1444
train
28,339
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_class
def _get_class(self, classname, namespace, local_only=None, include_qualifiers=None, include_classorigin=None, property_list=None): # pylint: disable=invalid-name """ Get class from repository. Gets the class defined by classname from the repository, creates a copy, expands the copied class to include superclass properties if not localonly, and filters the class based on propertylist and includeClassOrigin. It also sets the propagated attribute. Parameters: classname (:term:`string`): Name of class to retrieve namespace (:term:`string`): Namespace from which to retrieve the class local_only (:class:`py:bool`): If `True`, only properties and methods in this specific class are returned. Otherwise properties and methods from the superclasses are included. include_qualifiers (:class:`py:bool`): If `True`, include qualifiers. Otherwise remove all qualifiers include_classorigin (:class:`py:bool`): If `True` return the class_origin attributes of properties and methods. property_list (): Properties to be included in returned class. If None, all properties are returned. If empty, no properties are returned Returns: Copy of the class if found with superclass properties installed and filtered per the keywords in params. Raises: CIMError: (CIM_ERR_NOT_FOUND) if class Not found in repository or CIMError: (CIM_ERR_INVALID_NAMESPACE) if namespace does not exist """ class_repo = self._get_class_repo(namespace) # try to get the target class and create a copy for response try: c = class_repo[classname] except KeyError: raise CIMError( CIM_ERR_NOT_FOUND, _format("Class {0!A} not found in namespace {1!A}.", classname, namespace)) cc = deepcopy(c) if local_only: for prop, pvalue in cc.properties.items(): if pvalue.propagated: del cc.properties[prop] for method, mvalue in cc.methods.items(): if mvalue.propagated: del cc.methods[method] self._filter_properties(cc, property_list) if not include_qualifiers: self._remove_qualifiers(cc) if not include_classorigin: self._remove_classorigin(cc) return cc
python
def _get_class(self, classname, namespace, local_only=None, include_qualifiers=None, include_classorigin=None, property_list=None): # pylint: disable=invalid-name """ Get class from repository. Gets the class defined by classname from the repository, creates a copy, expands the copied class to include superclass properties if not localonly, and filters the class based on propertylist and includeClassOrigin. It also sets the propagated attribute. Parameters: classname (:term:`string`): Name of class to retrieve namespace (:term:`string`): Namespace from which to retrieve the class local_only (:class:`py:bool`): If `True`, only properties and methods in this specific class are returned. Otherwise properties and methods from the superclasses are included. include_qualifiers (:class:`py:bool`): If `True`, include qualifiers. Otherwise remove all qualifiers include_classorigin (:class:`py:bool`): If `True` return the class_origin attributes of properties and methods. property_list (): Properties to be included in returned class. If None, all properties are returned. If empty, no properties are returned Returns: Copy of the class if found with superclass properties installed and filtered per the keywords in params. Raises: CIMError: (CIM_ERR_NOT_FOUND) if class Not found in repository or CIMError: (CIM_ERR_INVALID_NAMESPACE) if namespace does not exist """ class_repo = self._get_class_repo(namespace) # try to get the target class and create a copy for response try: c = class_repo[classname] except KeyError: raise CIMError( CIM_ERR_NOT_FOUND, _format("Class {0!A} not found in namespace {1!A}.", classname, namespace)) cc = deepcopy(c) if local_only: for prop, pvalue in cc.properties.items(): if pvalue.propagated: del cc.properties[prop] for method, mvalue in cc.methods.items(): if mvalue.propagated: del cc.methods[method] self._filter_properties(cc, property_list) if not include_qualifiers: self._remove_qualifiers(cc) if not include_classorigin: self._remove_classorigin(cc) return cc
[ "def", "_get_class", "(", "self", ",", "classname", ",", "namespace", ",", "local_only", "=", "None", ",", "include_qualifiers", "=", "None", ",", "include_classorigin", "=", "None", ",", "property_list", "=", "None", ")", ":", "# pylint: disable=invalid-name", ...
Get class from repository. Gets the class defined by classname from the repository, creates a copy, expands the copied class to include superclass properties if not localonly, and filters the class based on propertylist and includeClassOrigin. It also sets the propagated attribute. Parameters: classname (:term:`string`): Name of class to retrieve namespace (:term:`string`): Namespace from which to retrieve the class local_only (:class:`py:bool`): If `True`, only properties and methods in this specific class are returned. Otherwise properties and methods from the superclasses are included. include_qualifiers (:class:`py:bool`): If `True`, include qualifiers. Otherwise remove all qualifiers include_classorigin (:class:`py:bool`): If `True` return the class_origin attributes of properties and methods. property_list (): Properties to be included in returned class. If None, all properties are returned. If empty, no properties are returned Returns: Copy of the class if found with superclass properties installed and filtered per the keywords in params. Raises: CIMError: (CIM_ERR_NOT_FOUND) if class Not found in repository or CIMError: (CIM_ERR_INVALID_NAMESPACE) if namespace does not exist
[ "Get", "class", "from", "repository", ".", "Gets", "the", "class", "defined", "by", "classname", "from", "the", "repository", "creates", "a", "copy", "expands", "the", "copied", "class", "to", "include", "superclass", "properties", "if", "not", "localonly", "a...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1446-L1519
train
28,340
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_association_classes
def _get_association_classes(self, namespace): """ Return iterator of associator classes from the class repo Returns the classes that have associations qualifier. Does NOT copy so these are what is in repository. User functions MUST NOT modify these classes. Returns: Returns generator where each yield returns a single association class """ class_repo = self._get_class_repo(namespace) # associator_classes = [] for cl in six.itervalues(class_repo): if 'Association' in cl.qualifiers: yield cl return
python
def _get_association_classes(self, namespace): """ Return iterator of associator classes from the class repo Returns the classes that have associations qualifier. Does NOT copy so these are what is in repository. User functions MUST NOT modify these classes. Returns: Returns generator where each yield returns a single association class """ class_repo = self._get_class_repo(namespace) # associator_classes = [] for cl in six.itervalues(class_repo): if 'Association' in cl.qualifiers: yield cl return
[ "def", "_get_association_classes", "(", "self", ",", "namespace", ")", ":", "class_repo", "=", "self", ".", "_get_class_repo", "(", "namespace", ")", "# associator_classes = []", "for", "cl", "in", "six", ".", "itervalues", "(", "class_repo", ")", ":", "if", "...
Return iterator of associator classes from the class repo Returns the classes that have associations qualifier. Does NOT copy so these are what is in repository. User functions MUST NOT modify these classes. Returns: Returns generator where each yield returns a single association class
[ "Return", "iterator", "of", "associator", "classes", "from", "the", "class", "repo" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1521-L1538
train
28,341
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._find_instance
def _find_instance(iname, instance_repo): """ Find an instance in the instance repo by iname and return the index of that instance. Parameters: iname: CIMInstancename to find instance_repo: the instance repo to search Return (None, None if not found. Otherwise return tuple of index, instance Raises: CIMError: Failed if repo invalid. """ rtn_inst = None rtn_index = None for index, inst in enumerate(instance_repo): if iname == inst.path: if rtn_inst is not None: # TODO:ks Future Remove dup test since we should be # insuring no dups on instance creation raise CIMError( CIM_ERR_FAILED, _format("Invalid Repository. Multiple instances with " "same path {0!A}.", rtn_inst.path)) rtn_inst = inst rtn_index = index return(rtn_index, rtn_inst)
python
def _find_instance(iname, instance_repo): """ Find an instance in the instance repo by iname and return the index of that instance. Parameters: iname: CIMInstancename to find instance_repo: the instance repo to search Return (None, None if not found. Otherwise return tuple of index, instance Raises: CIMError: Failed if repo invalid. """ rtn_inst = None rtn_index = None for index, inst in enumerate(instance_repo): if iname == inst.path: if rtn_inst is not None: # TODO:ks Future Remove dup test since we should be # insuring no dups on instance creation raise CIMError( CIM_ERR_FAILED, _format("Invalid Repository. Multiple instances with " "same path {0!A}.", rtn_inst.path)) rtn_inst = inst rtn_index = index return(rtn_index, rtn_inst)
[ "def", "_find_instance", "(", "iname", ",", "instance_repo", ")", ":", "rtn_inst", "=", "None", "rtn_index", "=", "None", "for", "index", ",", "inst", "in", "enumerate", "(", "instance_repo", ")", ":", "if", "iname", "==", "inst", ".", "path", ":", "if",...
Find an instance in the instance repo by iname and return the index of that instance. Parameters: iname: CIMInstancename to find instance_repo: the instance repo to search Return (None, None if not found. Otherwise return tuple of index, instance Raises: CIMError: Failed if repo invalid.
[ "Find", "an", "instance", "in", "the", "instance", "repo", "by", "iname", "and", "return", "the", "index", "of", "that", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1541-L1573
train
28,342
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_instance
def _get_instance(self, iname, namespace, property_list, local_only, include_class_origin, include_qualifiers): """ Local method implements getinstance. This is generally used by other instance methods that need to get an instance from the repository. It attempts to get the instance, copies it, and filters it for input parameters like localonly, includequalifiers, and propertylist. Returns: CIMInstance copy from the repository with property_list filtered, and qualifers removed if include_qualifiers=False and class origin removed if include_class_origin False """ instance_repo = self._get_instance_repo(namespace) rtn_tup = self._find_instance(iname, instance_repo) inst = rtn_tup[1] if inst is None: raise CIMError( CIM_ERR_NOT_FOUND, _format("Instance not found in repository namespace {0!A}. " "Path={1!A}", namespace, iname)) rtn_inst = deepcopy(inst) # If local_only remove properties where class_origin # differs from class of target instance if local_only: for p in rtn_inst: class_origin = rtn_inst.properties[p].class_origin if class_origin and class_origin != inst.classname: del rtn_inst[p] # if not repo_lite test against class properties if not self._repo_lite and local_only: # gets class propertylist which may be local only or all # superclasses try: cl = self._get_class(iname.classname, namespace, local_only=local_only) except CIMError as ce: if ce.status_code == CIM_ERR_NOT_FOUND: raise CIMError( CIM_ERR_INVALID_CLASS, _format("Class {0!A} not found for instance {1!A} in " "namespace {2!A}.", iname.classname, iname, namespace)) class_pl = cl.properties.keys() for p in list(rtn_inst): if p not in class_pl: del rtn_inst[p] self._filter_properties(rtn_inst, property_list) if not include_qualifiers: self._remove_qualifiers(rtn_inst) if not include_class_origin: self._remove_classorigin(rtn_inst) return rtn_inst
python
def _get_instance(self, iname, namespace, property_list, local_only, include_class_origin, include_qualifiers): """ Local method implements getinstance. This is generally used by other instance methods that need to get an instance from the repository. It attempts to get the instance, copies it, and filters it for input parameters like localonly, includequalifiers, and propertylist. Returns: CIMInstance copy from the repository with property_list filtered, and qualifers removed if include_qualifiers=False and class origin removed if include_class_origin False """ instance_repo = self._get_instance_repo(namespace) rtn_tup = self._find_instance(iname, instance_repo) inst = rtn_tup[1] if inst is None: raise CIMError( CIM_ERR_NOT_FOUND, _format("Instance not found in repository namespace {0!A}. " "Path={1!A}", namespace, iname)) rtn_inst = deepcopy(inst) # If local_only remove properties where class_origin # differs from class of target instance if local_only: for p in rtn_inst: class_origin = rtn_inst.properties[p].class_origin if class_origin and class_origin != inst.classname: del rtn_inst[p] # if not repo_lite test against class properties if not self._repo_lite and local_only: # gets class propertylist which may be local only or all # superclasses try: cl = self._get_class(iname.classname, namespace, local_only=local_only) except CIMError as ce: if ce.status_code == CIM_ERR_NOT_FOUND: raise CIMError( CIM_ERR_INVALID_CLASS, _format("Class {0!A} not found for instance {1!A} in " "namespace {2!A}.", iname.classname, iname, namespace)) class_pl = cl.properties.keys() for p in list(rtn_inst): if p not in class_pl: del rtn_inst[p] self._filter_properties(rtn_inst, property_list) if not include_qualifiers: self._remove_qualifiers(rtn_inst) if not include_class_origin: self._remove_classorigin(rtn_inst) return rtn_inst
[ "def", "_get_instance", "(", "self", ",", "iname", ",", "namespace", ",", "property_list", ",", "local_only", ",", "include_class_origin", ",", "include_qualifiers", ")", ":", "instance_repo", "=", "self", ".", "_get_instance_repo", "(", "namespace", ")", "rtn_tup...
Local method implements getinstance. This is generally used by other instance methods that need to get an instance from the repository. It attempts to get the instance, copies it, and filters it for input parameters like localonly, includequalifiers, and propertylist. Returns: CIMInstance copy from the repository with property_list filtered, and qualifers removed if include_qualifiers=False and class origin removed if include_class_origin False
[ "Local", "method", "implements", "getinstance", ".", "This", "is", "generally", "used", "by", "other", "instance", "methods", "that", "need", "to", "get", "an", "instance", "from", "the", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1575-L1641
train
28,343
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_subclass_list_for_enums
def _get_subclass_list_for_enums(self, classname, namespace): """ Get class list (i.e names of subclasses for classname for the enumerateinstance methods. If conn.lite returns only classname but no subclasses. Returns NocaseDict where only the keys are important, This allows case insensitive matches of the names with Python "for cln in clns". """ if self._repo_lite: return NocaseDict({classname: classname}) if not self._class_exists(classname, namespace): raise CIMError( CIM_ERR_INVALID_CLASS, _format("Class {0!A} not found in namespace {1!A}.", classname, namespace)) if not self.classes: return NocaseDict() clnslist = self._get_subclass_names(classname, namespace, True) clnsdict = NocaseDict() for cln in clnslist: clnsdict[cln] = cln clnsdict[classname] = classname return clnsdict
python
def _get_subclass_list_for_enums(self, classname, namespace): """ Get class list (i.e names of subclasses for classname for the enumerateinstance methods. If conn.lite returns only classname but no subclasses. Returns NocaseDict where only the keys are important, This allows case insensitive matches of the names with Python "for cln in clns". """ if self._repo_lite: return NocaseDict({classname: classname}) if not self._class_exists(classname, namespace): raise CIMError( CIM_ERR_INVALID_CLASS, _format("Class {0!A} not found in namespace {1!A}.", classname, namespace)) if not self.classes: return NocaseDict() clnslist = self._get_subclass_names(classname, namespace, True) clnsdict = NocaseDict() for cln in clnslist: clnsdict[cln] = cln clnsdict[classname] = classname return clnsdict
[ "def", "_get_subclass_list_for_enums", "(", "self", ",", "classname", ",", "namespace", ")", ":", "if", "self", ".", "_repo_lite", ":", "return", "NocaseDict", "(", "{", "classname", ":", "classname", "}", ")", "if", "not", "self", ".", "_class_exists", "(",...
Get class list (i.e names of subclasses for classname for the enumerateinstance methods. If conn.lite returns only classname but no subclasses. Returns NocaseDict where only the keys are important, This allows case insensitive matches of the names with Python "for cln in clns".
[ "Get", "class", "list", "(", "i", ".", "e", "names", "of", "subclasses", "for", "classname", "for", "the", "enumerateinstance", "methods", ".", "If", "conn", ".", "lite", "returns", "only", "classname", "but", "no", "subclasses", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1643-L1668
train
28,344
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._filter_properties
def _filter_properties(obj, property_list): """ Remove properties from an instance or class that aren't in the plist parameter obj(:class:`~pywbem.CIMClass` or :class:`~pywbem.CIMInstance): The class or instance from which properties are to be filtered property_list(list of :term:`string`): List of properties which are to be included in the result. If None, remove nothing. If empty list, remove everything. else remove properties that are not in property_list. Duplicated names are allowed in the list and ignored. """ if property_list is not None: property_list = [p.lower() for p in property_list] for pname in obj.properties.keys(): if pname.lower() not in property_list: del obj.properties[pname]
python
def _filter_properties(obj, property_list): """ Remove properties from an instance or class that aren't in the plist parameter obj(:class:`~pywbem.CIMClass` or :class:`~pywbem.CIMInstance): The class or instance from which properties are to be filtered property_list(list of :term:`string`): List of properties which are to be included in the result. If None, remove nothing. If empty list, remove everything. else remove properties that are not in property_list. Duplicated names are allowed in the list and ignored. """ if property_list is not None: property_list = [p.lower() for p in property_list] for pname in obj.properties.keys(): if pname.lower() not in property_list: del obj.properties[pname]
[ "def", "_filter_properties", "(", "obj", ",", "property_list", ")", ":", "if", "property_list", "is", "not", "None", ":", "property_list", "=", "[", "p", ".", "lower", "(", ")", "for", "p", "in", "property_list", "]", "for", "pname", "in", "obj", ".", ...
Remove properties from an instance or class that aren't in the plist parameter obj(:class:`~pywbem.CIMClass` or :class:`~pywbem.CIMInstance): The class or instance from which properties are to be filtered property_list(list of :term:`string`): List of properties which are to be included in the result. If None, remove nothing. If empty list, remove everything. else remove properties that are not in property_list. Duplicated names are allowed in the list and ignored.
[ "Remove", "properties", "from", "an", "instance", "or", "class", "that", "aren", "t", "in", "the", "plist", "parameter" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1671-L1689
train
28,345
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._appendpath_unique
def _appendpath_unique(list_, path): """Append path to list if not already in list""" for p in list_: if p == path: return list_.append(path)
python
def _appendpath_unique(list_, path): """Append path to list if not already in list""" for p in list_: if p == path: return list_.append(path)
[ "def", "_appendpath_unique", "(", "list_", ",", "path", ")", ":", "for", "p", "in", "list_", ":", "if", "p", "==", "path", ":", "return", "list_", ".", "append", "(", "path", ")" ]
Append path to list if not already in list
[ "Append", "path", "to", "list", "if", "not", "already", "in", "list" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2583-L2588
train
28,346
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._return_assoc_tuple
def _return_assoc_tuple(self, objects): """ Create the property tuple for _imethod return of references, referencenames, associators, and associatornames methods. This is different than the get/enum imethod return tuples. It creates an OBJECTPATH for each object in the return list. _imethod call returns None when there are zero objects rather than a tuple with empty object path """ if objects: result = [(u'OBJECTPATH', {}, obj) for obj in objects] return self._make_tuple(result) return None
python
def _return_assoc_tuple(self, objects): """ Create the property tuple for _imethod return of references, referencenames, associators, and associatornames methods. This is different than the get/enum imethod return tuples. It creates an OBJECTPATH for each object in the return list. _imethod call returns None when there are zero objects rather than a tuple with empty object path """ if objects: result = [(u'OBJECTPATH', {}, obj) for obj in objects] return self._make_tuple(result) return None
[ "def", "_return_assoc_tuple", "(", "self", ",", "objects", ")", ":", "if", "objects", ":", "result", "=", "[", "(", "u'OBJECTPATH'", ",", "{", "}", ",", "obj", ")", "for", "obj", "in", "objects", "]", "return", "self", ".", "_make_tuple", "(", "result"...
Create the property tuple for _imethod return of references, referencenames, associators, and associatornames methods. This is different than the get/enum imethod return tuples. It creates an OBJECTPATH for each object in the return list. _imethod call returns None when there are zero objects rather than a tuple with empty object path
[ "Create", "the", "property", "tuple", "for", "_imethod", "return", "of", "references", "referencenames", "associators", "and", "associatornames", "methods", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2590-L2605
train
28,347
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._return_assoc_class_tuples
def _return_assoc_class_tuples(self, rtn_classnames, namespace, iq, ico, pl): """ Creates the correct tuples of for associator and references class level responses from a list of classnames. This is special because the class level references and associators return a tuple of CIMClassName and CIMClass for every entry. """ rtn_tups = [] for cn in rtn_classnames: rtn_tups.append((CIMClassName(cn, namespace=namespace, host=self.host), self._get_class(cn, namespace=namespace, include_qualifiers=iq, include_classorigin=ico, property_list=pl))) return self._return_assoc_tuple(rtn_tups)
python
def _return_assoc_class_tuples(self, rtn_classnames, namespace, iq, ico, pl): """ Creates the correct tuples of for associator and references class level responses from a list of classnames. This is special because the class level references and associators return a tuple of CIMClassName and CIMClass for every entry. """ rtn_tups = [] for cn in rtn_classnames: rtn_tups.append((CIMClassName(cn, namespace=namespace, host=self.host), self._get_class(cn, namespace=namespace, include_qualifiers=iq, include_classorigin=ico, property_list=pl))) return self._return_assoc_tuple(rtn_tups)
[ "def", "_return_assoc_class_tuples", "(", "self", ",", "rtn_classnames", ",", "namespace", ",", "iq", ",", "ico", ",", "pl", ")", ":", "rtn_tups", "=", "[", "]", "for", "cn", "in", "rtn_classnames", ":", "rtn_tups", ".", "append", "(", "(", "CIMClassName",...
Creates the correct tuples of for associator and references class level responses from a list of classnames. This is special because the class level references and associators return a tuple of CIMClassName and CIMClass for every entry.
[ "Creates", "the", "correct", "tuples", "of", "for", "associator", "and", "references", "class", "level", "responses", "from", "a", "list", "of", "classnames", ".", "This", "is", "special", "because", "the", "class", "level", "references", "and", "associators", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2607-L2624
train
28,348
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._classnamedict
def _classnamedict(self, classname, namespace): """Get from _classnamelist and cvt to NocaseDict""" clns = self._classnamelist(classname, namespace) rtn_dict = NocaseDict() for cln in clns: rtn_dict[cln] = cln return rtn_dict
python
def _classnamedict(self, classname, namespace): """Get from _classnamelist and cvt to NocaseDict""" clns = self._classnamelist(classname, namespace) rtn_dict = NocaseDict() for cln in clns: rtn_dict[cln] = cln return rtn_dict
[ "def", "_classnamedict", "(", "self", ",", "classname", ",", "namespace", ")", ":", "clns", "=", "self", ".", "_classnamelist", "(", "classname", ",", "namespace", ")", "rtn_dict", "=", "NocaseDict", "(", ")", "for", "cln", "in", "clns", ":", "rtn_dict", ...
Get from _classnamelist and cvt to NocaseDict
[ "Get", "from", "_classnamelist", "and", "cvt", "to", "NocaseDict" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2642-L2648
train
28,349
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._ref_prop_matches
def _ref_prop_matches(prop, target_classname, ref_classname, resultclass_names, role): """ Test filters for a reference property Returns `True` if matches the criteria. Returns `False` if it does not match. The match criteria are: - target_classname == prop_reference_class - if result_classes are not None, ref_classname is in result_classes - If role is not None, prop name matches role """ assert prop.type == 'reference' if prop.reference_class.lower() == target_classname.lower(): if resultclass_names and ref_classname not in resultclass_names: return False if role and prop.name.lower() != role: return False return True return False
python
def _ref_prop_matches(prop, target_classname, ref_classname, resultclass_names, role): """ Test filters for a reference property Returns `True` if matches the criteria. Returns `False` if it does not match. The match criteria are: - target_classname == prop_reference_class - if result_classes are not None, ref_classname is in result_classes - If role is not None, prop name matches role """ assert prop.type == 'reference' if prop.reference_class.lower() == target_classname.lower(): if resultclass_names and ref_classname not in resultclass_names: return False if role and prop.name.lower() != role: return False return True return False
[ "def", "_ref_prop_matches", "(", "prop", ",", "target_classname", ",", "ref_classname", ",", "resultclass_names", ",", "role", ")", ":", "assert", "prop", ".", "type", "==", "'reference'", "if", "prop", ".", "reference_class", ".", "lower", "(", ")", "==", "...
Test filters for a reference property Returns `True` if matches the criteria. Returns `False` if it does not match. The match criteria are: - target_classname == prop_reference_class - if result_classes are not None, ref_classname is in result_classes - If role is not None, prop name matches role
[ "Test", "filters", "for", "a", "reference", "property", "Returns", "True", "if", "matches", "the", "criteria", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2651-L2671
train
28,350
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._assoc_prop_matches
def _assoc_prop_matches(prop, ref_classname, assoc_classes, result_classes, result_role): """ Test filters of a reference property and its associated entity Returns `True` if matches the criteria. Returns `False` if it does not match. Matches if ref_classname in assoc_classes, and result_role matches property name """ assert prop.type == 'reference' if assoc_classes and ref_classname not in assoc_classes: return False if result_classes and prop.reference_class not in result_classes: return False if result_role and prop.name.lower() != result_role: return False return True
python
def _assoc_prop_matches(prop, ref_classname, assoc_classes, result_classes, result_role): """ Test filters of a reference property and its associated entity Returns `True` if matches the criteria. Returns `False` if it does not match. Matches if ref_classname in assoc_classes, and result_role matches property name """ assert prop.type == 'reference' if assoc_classes and ref_classname not in assoc_classes: return False if result_classes and prop.reference_class not in result_classes: return False if result_role and prop.name.lower() != result_role: return False return True
[ "def", "_assoc_prop_matches", "(", "prop", ",", "ref_classname", ",", "assoc_classes", ",", "result_classes", ",", "result_role", ")", ":", "assert", "prop", ".", "type", "==", "'reference'", "if", "assoc_classes", "and", "ref_classname", "not", "in", "assoc_class...
Test filters of a reference property and its associated entity Returns `True` if matches the criteria. Returns `False` if it does not match. Matches if ref_classname in assoc_classes, and result_role matches property name
[ "Test", "filters", "of", "a", "reference", "property", "and", "its", "associated", "entity", "Returns", "True", "if", "matches", "the", "criteria", ".", "Returns", "False", "if", "it", "does", "not", "match", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2674-L2692
train
28,351
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_reference_classnames
def _get_reference_classnames(self, classname, namespace, resultclass_name, role): """ Get list of classnames that are references for which this classname is a target filtered by the result_class and role parameters if they are none. This is a common method used by all of the other reference and associator methods to create a list of reference classnames Returns: list of classnames that satisfy the criteria. """ self._validate_namespace(namespace) result_classes = self._classnamedict(resultclass_name, namespace) rtn_classnames_set = set() role = role.lower() if role else role for cl in self._get_association_classes(namespace): for prop in six.itervalues(cl.properties): if prop.type == 'reference' and \ self._ref_prop_matches(prop, classname, cl.classname, result_classes, role): rtn_classnames_set.add(cl.classname) return list(rtn_classnames_set)
python
def _get_reference_classnames(self, classname, namespace, resultclass_name, role): """ Get list of classnames that are references for which this classname is a target filtered by the result_class and role parameters if they are none. This is a common method used by all of the other reference and associator methods to create a list of reference classnames Returns: list of classnames that satisfy the criteria. """ self._validate_namespace(namespace) result_classes = self._classnamedict(resultclass_name, namespace) rtn_classnames_set = set() role = role.lower() if role else role for cl in self._get_association_classes(namespace): for prop in six.itervalues(cl.properties): if prop.type == 'reference' and \ self._ref_prop_matches(prop, classname, cl.classname, result_classes, role): rtn_classnames_set.add(cl.classname) return list(rtn_classnames_set)
[ "def", "_get_reference_classnames", "(", "self", ",", "classname", ",", "namespace", ",", "resultclass_name", ",", "role", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "result_classes", "=", "self", ".", "_classnamedict", "(", "resultclass_...
Get list of classnames that are references for which this classname is a target filtered by the result_class and role parameters if they are none. This is a common method used by all of the other reference and associator methods to create a list of reference classnames Returns: list of classnames that satisfy the criteria.
[ "Get", "list", "of", "classnames", "that", "are", "references", "for", "which", "this", "classname", "is", "a", "target", "filtered", "by", "the", "result_class", "and", "role", "parameters", "if", "they", "are", "none", ".", "This", "is", "a", "common", "...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2694-L2722
train
28,352
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._get_associated_classnames
def _get_associated_classnames(self, classname, namespace, assoc_class, result_class, result_role, role): """ Get list of classnames that are associated classes for which this classname is a target filtered by the assoc_class, role, result_class, and result_role parameters if they are none. This is a common method used by all of the other reference and associator methods to create a list of reference classnames Returns: list of classnames that satisfy the criteria. """ class_repo = self._get_class_repo(namespace) result_classes = self._classnamedict(result_class, namespace) assoc_classes = self._classnamedict(assoc_class, namespace) rtn_classnames_set = set() role = role.lower() if role else role result_role = result_role.lower() if result_role else result_role ref_clns = self._get_reference_classnames(classname, namespace, assoc_class, role) cls = [class_repo[cln] for cln in ref_clns] for cl in cls: for prop in six.itervalues(cl.properties): if prop.type == 'reference': if self._assoc_prop_matches(prop, cl.classname, assoc_classes, result_classes, result_role): rtn_classnames_set.add(prop.reference_class) return list(rtn_classnames_set)
python
def _get_associated_classnames(self, classname, namespace, assoc_class, result_class, result_role, role): """ Get list of classnames that are associated classes for which this classname is a target filtered by the assoc_class, role, result_class, and result_role parameters if they are none. This is a common method used by all of the other reference and associator methods to create a list of reference classnames Returns: list of classnames that satisfy the criteria. """ class_repo = self._get_class_repo(namespace) result_classes = self._classnamedict(result_class, namespace) assoc_classes = self._classnamedict(assoc_class, namespace) rtn_classnames_set = set() role = role.lower() if role else role result_role = result_role.lower() if result_role else result_role ref_clns = self._get_reference_classnames(classname, namespace, assoc_class, role) cls = [class_repo[cln] for cln in ref_clns] for cl in cls: for prop in six.itervalues(cl.properties): if prop.type == 'reference': if self._assoc_prop_matches(prop, cl.classname, assoc_classes, result_classes, result_role): rtn_classnames_set.add(prop.reference_class) return list(rtn_classnames_set)
[ "def", "_get_associated_classnames", "(", "self", ",", "classname", ",", "namespace", ",", "assoc_class", ",", "result_class", ",", "result_role", ",", "role", ")", ":", "class_repo", "=", "self", ".", "_get_class_repo", "(", "namespace", ")", "result_classes", ...
Get list of classnames that are associated classes for which this classname is a target filtered by the assoc_class, role, result_class, and result_role parameters if they are none. This is a common method used by all of the other reference and associator methods to create a list of reference classnames Returns: list of classnames that satisfy the criteria.
[ "Get", "list", "of", "classnames", "that", "are", "associated", "classes", "for", "which", "this", "classname", "is", "a", "target", "filtered", "by", "the", "assoc_class", "role", "result_class", "and", "result_role", "parameters", "if", "they", "are", "none", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2766-L2804
train
28,353
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._make_pull_imethod_resp
def _make_pull_imethod_resp(objs, eos, context_id): """ Create the correct imethod response for the open and pull methods """ eos_tup = (u'EndOfSequence', None, eos) enum_ctxt_tup = (u'EnumerationContext', None, context_id) return [("IRETURNVALUE", {}, objs), enum_ctxt_tup, eos_tup]
python
def _make_pull_imethod_resp(objs, eos, context_id): """ Create the correct imethod response for the open and pull methods """ eos_tup = (u'EndOfSequence', None, eos) enum_ctxt_tup = (u'EnumerationContext', None, context_id) return [("IRETURNVALUE", {}, objs), enum_ctxt_tup, eos_tup]
[ "def", "_make_pull_imethod_resp", "(", "objs", ",", "eos", ",", "context_id", ")", ":", "eos_tup", "=", "(", "u'EndOfSequence'", ",", "None", ",", "eos", ")", "enum_ctxt_tup", "=", "(", "u'EnumerationContext'", ",", "None", ",", "context_id", ")", "return", ...
Create the correct imethod response for the open and pull methods
[ "Create", "the", "correct", "imethod", "response", "for", "the", "open", "and", "pull", "methods" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L3025-L3032
train
28,354
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._open_response
def _open_response(self, objects, namespace, pull_type, **params): """ Build an open... response once the objects have been extracted from the repository. """ max_obj_cnt = params['MaxObjectCount'] if max_obj_cnt is None: max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT default_server_timeout = 40 timeout = default_server_timeout if params['OperationTimeout'] is None \ else params['OperationTimeout'] if len(objects) <= max_obj_cnt: eos = u'TRUE' context_id = "" rtn_inst_names = objects else: eos = u'FALSE' context_id = self._create_contextid() # TODO:ks Future. Use the timeout along with response delay. Then # user could timeout pulls. This means adding timer test to # pulls and close. Timer should be used to close old contexts # also. self.enumeration_contexts[context_id] = {'pull_type': pull_type, 'data': objects, 'namespace': namespace, 'time': time.clock(), 'interoptimeout': timeout} rtn_inst_names = objects[0:max_obj_cnt] del objects[0: max_obj_cnt] return self._make_pull_imethod_resp(rtn_inst_names, eos, context_id)
python
def _open_response(self, objects, namespace, pull_type, **params): """ Build an open... response once the objects have been extracted from the repository. """ max_obj_cnt = params['MaxObjectCount'] if max_obj_cnt is None: max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT default_server_timeout = 40 timeout = default_server_timeout if params['OperationTimeout'] is None \ else params['OperationTimeout'] if len(objects) <= max_obj_cnt: eos = u'TRUE' context_id = "" rtn_inst_names = objects else: eos = u'FALSE' context_id = self._create_contextid() # TODO:ks Future. Use the timeout along with response delay. Then # user could timeout pulls. This means adding timer test to # pulls and close. Timer should be used to close old contexts # also. self.enumeration_contexts[context_id] = {'pull_type': pull_type, 'data': objects, 'namespace': namespace, 'time': time.clock(), 'interoptimeout': timeout} rtn_inst_names = objects[0:max_obj_cnt] del objects[0: max_obj_cnt] return self._make_pull_imethod_resp(rtn_inst_names, eos, context_id)
[ "def", "_open_response", "(", "self", ",", "objects", ",", "namespace", ",", "pull_type", ",", "*", "*", "params", ")", ":", "max_obj_cnt", "=", "params", "[", "'MaxObjectCount'", "]", "if", "max_obj_cnt", "is", "None", ":", "max_obj_cnt", "=", "_DEFAULT_MAX...
Build an open... response once the objects have been extracted from the repository.
[ "Build", "an", "open", "...", "response", "once", "the", "objects", "have", "been", "extracted", "from", "the", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L3034-L3066
train
28,355
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._pull_response
def _pull_response(self, namespace, req_type, **params): """ Common method for all of the Pull methods. Since all of the pull methods operate independent of the type of data, this single function severs as common code This method validates the namespace, gets data on the enumeration sequence from the enumeration_contexts table, validates the pull type, and returns the required number of objects. This method assumes the same context_id throughout the sequence. Raises: CIMError: CIM_ERR_INVALID_ENUMERATION_CONTEXT """ self._validate_namespace(namespace) context_id = params['EnumerationContext'] try: context_data = self.enumeration_contexts[context_id] except KeyError: raise CIMError( CIM_ERR_INVALID_ENUMERATION_CONTEXT, _format("EnumerationContext {0!A} not found in mock server " "enumeration contexts.", context_id)) if context_data['pull_type'] != req_type: raise CIMError( CIM_ERR_INVALID_ENUMERATION_CONTEXT, _format("Invalid pull operations {0!A} does not match " "expected {1!A} for EnumerationContext {2!A}", context_data['pull_type'], req_type, context_id)) objs_list = context_data['data'] max_obj_cnt = params['MaxObjectCount'] if not max_obj_cnt: max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT if len(objs_list) <= max_obj_cnt: eos = u'TRUE' rtn_objs_list = objs_list del self.enumeration_contexts[context_id] context_id = "" else: eos = u'FALSE' rtn_objs_list = objs_list[0: max_obj_cnt] del objs_list[0: max_obj_cnt] return self._make_pull_imethod_resp(rtn_objs_list, eos, context_id)
python
def _pull_response(self, namespace, req_type, **params): """ Common method for all of the Pull methods. Since all of the pull methods operate independent of the type of data, this single function severs as common code This method validates the namespace, gets data on the enumeration sequence from the enumeration_contexts table, validates the pull type, and returns the required number of objects. This method assumes the same context_id throughout the sequence. Raises: CIMError: CIM_ERR_INVALID_ENUMERATION_CONTEXT """ self._validate_namespace(namespace) context_id = params['EnumerationContext'] try: context_data = self.enumeration_contexts[context_id] except KeyError: raise CIMError( CIM_ERR_INVALID_ENUMERATION_CONTEXT, _format("EnumerationContext {0!A} not found in mock server " "enumeration contexts.", context_id)) if context_data['pull_type'] != req_type: raise CIMError( CIM_ERR_INVALID_ENUMERATION_CONTEXT, _format("Invalid pull operations {0!A} does not match " "expected {1!A} for EnumerationContext {2!A}", context_data['pull_type'], req_type, context_id)) objs_list = context_data['data'] max_obj_cnt = params['MaxObjectCount'] if not max_obj_cnt: max_obj_cnt = _DEFAULT_MAX_OBJECT_COUNT if len(objs_list) <= max_obj_cnt: eos = u'TRUE' rtn_objs_list = objs_list del self.enumeration_contexts[context_id] context_id = "" else: eos = u'FALSE' rtn_objs_list = objs_list[0: max_obj_cnt] del objs_list[0: max_obj_cnt] return self._make_pull_imethod_resp(rtn_objs_list, eos, context_id)
[ "def", "_pull_response", "(", "self", ",", "namespace", ",", "req_type", ",", "*", "*", "params", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "context_id", "=", "params", "[", "'EnumerationContext'", "]", "try", ":", "context_data", ...
Common method for all of the Pull methods. Since all of the pull methods operate independent of the type of data, this single function severs as common code This method validates the namespace, gets data on the enumeration sequence from the enumeration_contexts table, validates the pull type, and returns the required number of objects. This method assumes the same context_id throughout the sequence. Raises: CIMError: CIM_ERR_INVALID_ENUMERATION_CONTEXT
[ "Common", "method", "for", "all", "of", "the", "Pull", "methods", ".", "Since", "all", "of", "the", "pull", "methods", "operate", "independent", "of", "the", "type", "of", "data", "this", "single", "function", "severs", "as", "common", "code" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L3068-L3120
train
28,356
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._validate_open_params
def _validate_open_params(**params): """ Validate the fql parameters and if invalid, generate exception """ if not params['FilterQueryLanguage'] and params['FilterQuery']: raise CIMError( CIM_ERR_INVALID_PARAMETER, "FilterQuery without FilterQueryLanguage definition is " "invalid") if params['FilterQueryLanguage']: if params['FilterQueryLanguage'] != 'DMTF:FQL': raise CIMError( CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED, _format("FilterQueryLanguage {0!A} not supported", params['FilterQueryLanguage'])) ot = params['OperationTimeout'] if ot: if not isinstance(ot, six.integer_types) or ot < 0 \ or ot > OPEN_MAX_TIMEOUT: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("OperationTimeout {0!A }must be positive integer " "less than {1!A}", ot, OPEN_MAX_TIMEOUT))
python
def _validate_open_params(**params): """ Validate the fql parameters and if invalid, generate exception """ if not params['FilterQueryLanguage'] and params['FilterQuery']: raise CIMError( CIM_ERR_INVALID_PARAMETER, "FilterQuery without FilterQueryLanguage definition is " "invalid") if params['FilterQueryLanguage']: if params['FilterQueryLanguage'] != 'DMTF:FQL': raise CIMError( CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED, _format("FilterQueryLanguage {0!A} not supported", params['FilterQueryLanguage'])) ot = params['OperationTimeout'] if ot: if not isinstance(ot, six.integer_types) or ot < 0 \ or ot > OPEN_MAX_TIMEOUT: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("OperationTimeout {0!A }must be positive integer " "less than {1!A}", ot, OPEN_MAX_TIMEOUT))
[ "def", "_validate_open_params", "(", "*", "*", "params", ")", ":", "if", "not", "params", "[", "'FilterQueryLanguage'", "]", "and", "params", "[", "'FilterQuery'", "]", ":", "raise", "CIMError", "(", "CIM_ERR_INVALID_PARAMETER", ",", "\"FilterQuery without FilterQue...
Validate the fql parameters and if invalid, generate exception
[ "Validate", "the", "fql", "parameters", "and", "if", "invalid", "generate", "exception" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L3123-L3145
train
28,357
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._fake_openassociatorinstances
def _fake_openassociatorinstances(self, namespace, **params): """ Implements WBEM server responder for WBEMConnection.OpenAssociatorInstances with data from the instance repository. """ self._validate_namespace(namespace) self._validate_open_params(**params) params['ObjectName'] = params['InstanceName'] del params['InstanceName'] result = self._fake_associators(namespace, **params) objects = [] if result is None else [x[2] for x in result[0][2]] return self._open_response(objects, namespace, 'PullInstancesWithPath', **params)
python
def _fake_openassociatorinstances(self, namespace, **params): """ Implements WBEM server responder for WBEMConnection.OpenAssociatorInstances with data from the instance repository. """ self._validate_namespace(namespace) self._validate_open_params(**params) params['ObjectName'] = params['InstanceName'] del params['InstanceName'] result = self._fake_associators(namespace, **params) objects = [] if result is None else [x[2] for x in result[0][2]] return self._open_response(objects, namespace, 'PullInstancesWithPath', **params)
[ "def", "_fake_openassociatorinstances", "(", "self", ",", "namespace", ",", "*", "*", "params", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "self", ".", "_validate_open_params", "(", "*", "*", "params", ")", "params", "[", "'ObjectName...
Implements WBEM server responder for WBEMConnection.OpenAssociatorInstances with data from the instance repository.
[ "Implements", "WBEM", "server", "responder", "for", "WBEMConnection", ".", "OpenAssociatorInstances", "with", "data", "from", "the", "instance", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L3232-L3248
train
28,358
pywbem/pywbem
pywbem/_listener.py
ListenerRequestHandler.send_http_error
def send_http_error(self, http_code, cim_error=None, cim_error_details=None, headers=None): """ Send an HTTP response back to the WBEM server that indicates an error at the HTTP level. """ self.send_response(http_code, http_client.responses.get(http_code, '')) self.send_header("CIMExport", "MethodResponse") if cim_error is not None: self.send_header("CIMError", cim_error) if cim_error_details is not None: self.send_header("CIMErrorDetails", cim_error_details) if headers is not None: for header, value in headers: self.send_header(header, value) self.end_headers() self.log('%s: HTTP status %s; CIMError: %s, CIMErrorDetails: %s', (self._get_log_prefix(), http_code, cim_error, cim_error_details), logging.WARNING)
python
def send_http_error(self, http_code, cim_error=None, cim_error_details=None, headers=None): """ Send an HTTP response back to the WBEM server that indicates an error at the HTTP level. """ self.send_response(http_code, http_client.responses.get(http_code, '')) self.send_header("CIMExport", "MethodResponse") if cim_error is not None: self.send_header("CIMError", cim_error) if cim_error_details is not None: self.send_header("CIMErrorDetails", cim_error_details) if headers is not None: for header, value in headers: self.send_header(header, value) self.end_headers() self.log('%s: HTTP status %s; CIMError: %s, CIMErrorDetails: %s', (self._get_log_prefix(), http_code, cim_error, cim_error_details), logging.WARNING)
[ "def", "send_http_error", "(", "self", ",", "http_code", ",", "cim_error", "=", "None", ",", "cim_error_details", "=", "None", ",", "headers", "=", "None", ")", ":", "self", ".", "send_response", "(", "http_code", ",", "http_client", ".", "responses", ".", ...
Send an HTTP response back to the WBEM server that indicates an error at the HTTP level.
[ "Send", "an", "HTTP", "response", "back", "to", "the", "WBEM", "server", "that", "indicates", "an", "error", "at", "the", "HTTP", "level", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L407-L426
train
28,359
pywbem/pywbem
pywbem/_listener.py
ListenerRequestHandler.send_error_response
def send_error_response(self, msgid, methodname, status_code, status_desc, error_insts=None): """Send a CIM-XML response message back to the WBEM server that indicates error.""" resp_xml = cim_xml.CIM( cim_xml.MESSAGE( cim_xml.SIMPLEEXPRSP( cim_xml.EXPMETHODRESPONSE( methodname, cim_xml.ERROR( str(status_code), status_desc, error_insts), ), # noqa: E123 ), # noqa: E123 msgid, IMPLEMENTED_PROTOCOL_VERSION), IMPLEMENTED_CIM_VERSION, IMPLEMENTED_DTD_VERSION) resp_body = '<?xml version="1.0" encoding="utf-8" ?>\n' + \ resp_xml.toxml() if isinstance(resp_body, six.text_type): resp_body = resp_body.encode("utf-8") http_code = 200 self.send_response(http_code, http_client.responses.get(http_code, '')) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(resp_body))) self.send_header("CIMExport", "MethodResponse") self.end_headers() self.wfile.write(resp_body) self.log('%s: HTTP status %s; CIM error response: %s: %s', (self._get_log_prefix(), http_code, _statuscode2name(status_code), status_desc), logging.WARNING)
python
def send_error_response(self, msgid, methodname, status_code, status_desc, error_insts=None): """Send a CIM-XML response message back to the WBEM server that indicates error.""" resp_xml = cim_xml.CIM( cim_xml.MESSAGE( cim_xml.SIMPLEEXPRSP( cim_xml.EXPMETHODRESPONSE( methodname, cim_xml.ERROR( str(status_code), status_desc, error_insts), ), # noqa: E123 ), # noqa: E123 msgid, IMPLEMENTED_PROTOCOL_VERSION), IMPLEMENTED_CIM_VERSION, IMPLEMENTED_DTD_VERSION) resp_body = '<?xml version="1.0" encoding="utf-8" ?>\n' + \ resp_xml.toxml() if isinstance(resp_body, six.text_type): resp_body = resp_body.encode("utf-8") http_code = 200 self.send_response(http_code, http_client.responses.get(http_code, '')) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(resp_body))) self.send_header("CIMExport", "MethodResponse") self.end_headers() self.wfile.write(resp_body) self.log('%s: HTTP status %s; CIM error response: %s: %s', (self._get_log_prefix(), http_code, _statuscode2name(status_code), status_desc), logging.WARNING)
[ "def", "send_error_response", "(", "self", ",", "msgid", ",", "methodname", ",", "status_code", ",", "status_desc", ",", "error_insts", "=", "None", ")", ":", "resp_xml", "=", "cim_xml", ".", "CIM", "(", "cim_xml", ".", "MESSAGE", "(", "cim_xml", ".", "SIM...
Send a CIM-XML response message back to the WBEM server that indicates error.
[ "Send", "a", "CIM", "-", "XML", "response", "message", "back", "to", "the", "WBEM", "server", "that", "indicates", "error", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L428-L463
train
28,360
pywbem/pywbem
pywbem/_listener.py
ListenerRequestHandler.send_success_response
def send_success_response(self, msgid, methodname): """Send a CIM-XML response message back to the WBEM server that indicates success.""" resp_xml = cim_xml.CIM( cim_xml.MESSAGE( cim_xml.SIMPLEEXPRSP( cim_xml.EXPMETHODRESPONSE( methodname), ), # noqa: E123 msgid, IMPLEMENTED_PROTOCOL_VERSION), IMPLEMENTED_CIM_VERSION, IMPLEMENTED_DTD_VERSION) resp_body = '<?xml version="1.0" encoding="utf-8" ?>\n' + \ resp_xml.toxml() if isinstance(resp_body, six.text_type): resp_body = resp_body.encode("utf-8") http_code = 200 self.send_response(http_code, http_client.responses.get(http_code, '')) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(resp_body))) self.send_header("CIMExport", "MethodResponse") self.end_headers() self.wfile.write(resp_body)
python
def send_success_response(self, msgid, methodname): """Send a CIM-XML response message back to the WBEM server that indicates success.""" resp_xml = cim_xml.CIM( cim_xml.MESSAGE( cim_xml.SIMPLEEXPRSP( cim_xml.EXPMETHODRESPONSE( methodname), ), # noqa: E123 msgid, IMPLEMENTED_PROTOCOL_VERSION), IMPLEMENTED_CIM_VERSION, IMPLEMENTED_DTD_VERSION) resp_body = '<?xml version="1.0" encoding="utf-8" ?>\n' + \ resp_xml.toxml() if isinstance(resp_body, six.text_type): resp_body = resp_body.encode("utf-8") http_code = 200 self.send_response(http_code, http_client.responses.get(http_code, '')) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(resp_body))) self.send_header("CIMExport", "MethodResponse") self.end_headers() self.wfile.write(resp_body)
[ "def", "send_success_response", "(", "self", ",", "msgid", ",", "methodname", ")", ":", "resp_xml", "=", "cim_xml", ".", "CIM", "(", "cim_xml", ".", "MESSAGE", "(", "cim_xml", ".", "SIMPLEEXPRSP", "(", "cim_xml", ".", "EXPMETHODRESPONSE", "(", "methodname", ...
Send a CIM-XML response message back to the WBEM server that indicates success.
[ "Send", "a", "CIM", "-", "XML", "response", "message", "back", "to", "the", "WBEM", "server", "that", "indicates", "success", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L465-L489
train
28,361
pywbem/pywbem
pywbem/_listener.py
ListenerRequestHandler.log
def log(self, format_, args, level=logging.INFO): """ This function is called for anything that needs to get logged. It logs to the logger of this listener. It is not defined in the standard handler class; our version has an additional `level` argument that allows to control the logging level in the standard Python logging support. Another difference is that the variable arguments are passed in as a tuple. """ self.server.listener.logger.log(level, format_, *args)
python
def log(self, format_, args, level=logging.INFO): """ This function is called for anything that needs to get logged. It logs to the logger of this listener. It is not defined in the standard handler class; our version has an additional `level` argument that allows to control the logging level in the standard Python logging support. Another difference is that the variable arguments are passed in as a tuple. """ self.server.listener.logger.log(level, format_, *args)
[ "def", "log", "(", "self", ",", "format_", ",", "args", ",", "level", "=", "logging", ".", "INFO", ")", ":", "self", ".", "server", ".", "listener", ".", "logger", ".", "log", "(", "level", ",", "format_", ",", "*", "args", ")" ]
This function is called for anything that needs to get logged. It logs to the logger of this listener. It is not defined in the standard handler class; our version has an additional `level` argument that allows to control the logging level in the standard Python logging support. Another difference is that the variable arguments are passed in as a tuple.
[ "This", "function", "is", "called", "for", "anything", "that", "needs", "to", "get", "logged", ".", "It", "logs", "to", "the", "logger", "of", "this", "listener", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L547-L559
train
28,362
pywbem/pywbem
pywbem/_listener.py
WBEMListener.start
def start(self): """ Start the WBEM listener threads, if they are not yet running. A thread serving CIM-XML over HTTP is started if an HTTP port was specified for the listener. A thread serving CIM-XML over HTTPS is started if an HTTPS port was specified for the listener. These server threads will handle the ExportIndication export message described in :term:`DSP0200` and they will invoke the registered callback functions for any received CIM indications. The listener must be stopped again in order to free the TCP/IP port it listens on. The listener can be stopped explicitly using the :meth:`~pywbem.WBEMListener.stop` method. The listener will be automatically stopped when the main thread terminates (i.e. when the Python process terminates), or when :class:`~pywbem.WBEMListener` is used as a context manager when leaving its scope. Raises: :exc:`~py:exceptions.OSError`: with :attr:`~OSError.errno` = :data:`py:errno.EADDRINUSE` when the WBEM listener port is already in use. """ if self._http_port: if not self._http_server: try: server = ThreadedHTTPServer((self._host, self._http_port), ListenerRequestHandler) except Exception as exc: # Linux+py2: socket.error; Linux+py3: OSError; # Windows does not raise any exception. if getattr(exc, 'errno', None) == errno.EADDRINUSE: # Reraise with improved error message msg = _format("WBEM listener port {0} already in use", self._http_port) exc_type = OSError six.reraise(exc_type, exc_type(errno.EADDRINUSE, msg), sys.exc_info()[2]) raise # pylint: disable=attribute-defined-outside-init server.listener = self thread = threading.Thread(target=server.serve_forever) thread.daemon = True # Exit server thread upon main thread exit self._http_server = server self._http_thread = thread thread.start() else: # Just in case someone changed self._http_port after init... self._http_server = None self._http_thread = None if self._https_port: if not self._https_server: try: server = ThreadedHTTPServer((self._host, self._https_port), ListenerRequestHandler) except Exception as exc: # Linux+py2: socket.error; Linux+py3: OSError; # Windows does not raise any exception. if getattr(exc, 'errno', None) == errno.EADDRINUSE: # Reraise with improved error message msg = _format("WBEM listener port {0} already in use", self._http_port) exc_type = OSError six.reraise(exc_type, exc_type(errno.EADDRINUSE, msg), sys.exc_info()[2]) raise # pylint: disable=attribute-defined-outside-init server.listener = self server.socket = ssl.wrap_socket(server.socket, certfile=self._certfile, keyfile=self._keyfile, server_side=True) thread = threading.Thread(target=server.serve_forever) thread.daemon = True # Exit server thread upon main thread exit self._https_server = server self._https_thread = thread thread.start() else: # Just in case someone changed self._https_port after init... self._https_server = None self._https_thread = None
python
def start(self): """ Start the WBEM listener threads, if they are not yet running. A thread serving CIM-XML over HTTP is started if an HTTP port was specified for the listener. A thread serving CIM-XML over HTTPS is started if an HTTPS port was specified for the listener. These server threads will handle the ExportIndication export message described in :term:`DSP0200` and they will invoke the registered callback functions for any received CIM indications. The listener must be stopped again in order to free the TCP/IP port it listens on. The listener can be stopped explicitly using the :meth:`~pywbem.WBEMListener.stop` method. The listener will be automatically stopped when the main thread terminates (i.e. when the Python process terminates), or when :class:`~pywbem.WBEMListener` is used as a context manager when leaving its scope. Raises: :exc:`~py:exceptions.OSError`: with :attr:`~OSError.errno` = :data:`py:errno.EADDRINUSE` when the WBEM listener port is already in use. """ if self._http_port: if not self._http_server: try: server = ThreadedHTTPServer((self._host, self._http_port), ListenerRequestHandler) except Exception as exc: # Linux+py2: socket.error; Linux+py3: OSError; # Windows does not raise any exception. if getattr(exc, 'errno', None) == errno.EADDRINUSE: # Reraise with improved error message msg = _format("WBEM listener port {0} already in use", self._http_port) exc_type = OSError six.reraise(exc_type, exc_type(errno.EADDRINUSE, msg), sys.exc_info()[2]) raise # pylint: disable=attribute-defined-outside-init server.listener = self thread = threading.Thread(target=server.serve_forever) thread.daemon = True # Exit server thread upon main thread exit self._http_server = server self._http_thread = thread thread.start() else: # Just in case someone changed self._http_port after init... self._http_server = None self._http_thread = None if self._https_port: if not self._https_server: try: server = ThreadedHTTPServer((self._host, self._https_port), ListenerRequestHandler) except Exception as exc: # Linux+py2: socket.error; Linux+py3: OSError; # Windows does not raise any exception. if getattr(exc, 'errno', None) == errno.EADDRINUSE: # Reraise with improved error message msg = _format("WBEM listener port {0} already in use", self._http_port) exc_type = OSError six.reraise(exc_type, exc_type(errno.EADDRINUSE, msg), sys.exc_info()[2]) raise # pylint: disable=attribute-defined-outside-init server.listener = self server.socket = ssl.wrap_socket(server.socket, certfile=self._certfile, keyfile=self._keyfile, server_side=True) thread = threading.Thread(target=server.serve_forever) thread.daemon = True # Exit server thread upon main thread exit self._https_server = server self._https_thread = thread thread.start() else: # Just in case someone changed self._https_port after init... self._https_server = None self._https_thread = None
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "_http_port", ":", "if", "not", "self", ".", "_http_server", ":", "try", ":", "server", "=", "ThreadedHTTPServer", "(", "(", "self", ".", "_host", ",", "self", ".", "_http_port", ")", ",", "Li...
Start the WBEM listener threads, if they are not yet running. A thread serving CIM-XML over HTTP is started if an HTTP port was specified for the listener. A thread serving CIM-XML over HTTPS is started if an HTTPS port was specified for the listener. These server threads will handle the ExportIndication export message described in :term:`DSP0200` and they will invoke the registered callback functions for any received CIM indications. The listener must be stopped again in order to free the TCP/IP port it listens on. The listener can be stopped explicitly using the :meth:`~pywbem.WBEMListener.stop` method. The listener will be automatically stopped when the main thread terminates (i.e. when the Python process terminates), or when :class:`~pywbem.WBEMListener` is used as a context manager when leaving its scope. Raises: :exc:`~py:exceptions.OSError`: with :attr:`~OSError.errno` = :data:`py:errno.EADDRINUSE` when the WBEM listener port is already in use.
[ "Start", "the", "WBEM", "listener", "threads", "if", "they", "are", "not", "yet", "running", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L839-L927
train
28,363
pywbem/pywbem
pywbem/_listener.py
WBEMListener.stop
def stop(self): """ Stop the WBEM listener threads, if they are running. """ # Stopping the server will cause its `serve_forever()` method # to return, which will cause the server thread to terminate. # TODO: Describe how the processing threads terminate. if self._http_server: self._http_server.shutdown() self._http_server.server_close() self._http_server = None self._http_thread = None if self._https_server: self._https_server.shutdown() self._https_server.server_close() self._https_server = None self._https_thread = None
python
def stop(self): """ Stop the WBEM listener threads, if they are running. """ # Stopping the server will cause its `serve_forever()` method # to return, which will cause the server thread to terminate. # TODO: Describe how the processing threads terminate. if self._http_server: self._http_server.shutdown() self._http_server.server_close() self._http_server = None self._http_thread = None if self._https_server: self._https_server.shutdown() self._https_server.server_close() self._https_server = None self._https_thread = None
[ "def", "stop", "(", "self", ")", ":", "# Stopping the server will cause its `serve_forever()` method", "# to return, which will cause the server thread to terminate.", "# TODO: Describe how the processing threads terminate.", "if", "self", ".", "_http_server", ":", "self", ".", "_htt...
Stop the WBEM listener threads, if they are running.
[ "Stop", "the", "WBEM", "listener", "threads", "if", "they", "are", "running", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L929-L948
train
28,364
pywbem/pywbem
pywbem/_listener.py
WBEMListener.deliver_indication
def deliver_indication(self, indication, host): """ This function is called by the listener threads for each received indication. It is not supposed to be called by the user. It delivers the indication to all callback functions that have been added to the listener. If a callback function raises any exception this is logged as an error using the listener logger and the next registered callback function is called. Parameters: indication (:class:`~pywbem.CIMInstance`): Representation of the CIM indication to be delivered. host (:term:`string`): Host name or IP address of WBEM server sending the indication. """ for callback in self._callbacks: try: callback(indication, host) except Exception as exc: # pylint: disable=broad-except self.logger.log(logging.ERROR, "Indication delivery callback " "function raised %s: %s", exc.__class__.__name__, exc)
python
def deliver_indication(self, indication, host): """ This function is called by the listener threads for each received indication. It is not supposed to be called by the user. It delivers the indication to all callback functions that have been added to the listener. If a callback function raises any exception this is logged as an error using the listener logger and the next registered callback function is called. Parameters: indication (:class:`~pywbem.CIMInstance`): Representation of the CIM indication to be delivered. host (:term:`string`): Host name or IP address of WBEM server sending the indication. """ for callback in self._callbacks: try: callback(indication, host) except Exception as exc: # pylint: disable=broad-except self.logger.log(logging.ERROR, "Indication delivery callback " "function raised %s: %s", exc.__class__.__name__, exc)
[ "def", "deliver_indication", "(", "self", ",", "indication", ",", "host", ")", ":", "for", "callback", "in", "self", ".", "_callbacks", ":", "try", ":", "callback", "(", "indication", ",", "host", ")", "except", "Exception", "as", "exc", ":", "# pylint: di...
This function is called by the listener threads for each received indication. It is not supposed to be called by the user. It delivers the indication to all callback functions that have been added to the listener. If a callback function raises any exception this is logged as an error using the listener logger and the next registered callback function is called. Parameters: indication (:class:`~pywbem.CIMInstance`): Representation of the CIM indication to be delivered. host (:term:`string`): Host name or IP address of WBEM server sending the indication.
[ "This", "function", "is", "called", "by", "the", "listener", "threads", "for", "each", "received", "indication", ".", "It", "is", "not", "supposed", "to", "be", "called", "by", "the", "user", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L950-L976
train
28,365
pywbem/pywbem
pywbem/_listener.py
WBEMListener.add_callback
def add_callback(self, callback): """ Add a callback function to the listener. The callback function will be called for each indication this listener receives from any WBEM server. If the callback function is already known to the listener, it will not be added. Parameters: callback (:func:`~pywbem.callback_interface`): Callable that is being called for each CIM indication that is received while the listener threads are running. """ if callback not in self._callbacks: self._callbacks.append(callback)
python
def add_callback(self, callback): """ Add a callback function to the listener. The callback function will be called for each indication this listener receives from any WBEM server. If the callback function is already known to the listener, it will not be added. Parameters: callback (:func:`~pywbem.callback_interface`): Callable that is being called for each CIM indication that is received while the listener threads are running. """ if callback not in self._callbacks: self._callbacks.append(callback)
[ "def", "add_callback", "(", "self", ",", "callback", ")", ":", "if", "callback", "not", "in", "self", ".", "_callbacks", ":", "self", ".", "_callbacks", ".", "append", "(", "callback", ")" ]
Add a callback function to the listener. The callback function will be called for each indication this listener receives from any WBEM server. If the callback function is already known to the listener, it will not be added. Parameters: callback (:func:`~pywbem.callback_interface`): Callable that is being called for each CIM indication that is received while the listener threads are running.
[ "Add", "a", "callback", "function", "to", "the", "listener", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_listener.py#L978-L995
train
28,366
pywbem/pywbem
pywbem/cim_obj.py
cmpname
def cmpname(name1, name2): """ Compare two CIM names for equality and ordering. The comparison is performed case-insensitively. One or both of the items may be `None`, and `None` is considered the lowest possible value. The implementation delegates to the '==' and '<' operators of the name datatypes. If name1 == name2, 0 is returned. If name1 < name2, -1 is returned. Otherwise, +1 is returned. """ if name1 is None and name2 is None: return 0 if name1 is None: return -1 if name2 is None: return 1 lower_name1 = name1.lower() lower_name2 = name2.lower() if lower_name1 == lower_name2: return 0 return -1 if lower_name1 < lower_name2 else 1
python
def cmpname(name1, name2): """ Compare two CIM names for equality and ordering. The comparison is performed case-insensitively. One or both of the items may be `None`, and `None` is considered the lowest possible value. The implementation delegates to the '==' and '<' operators of the name datatypes. If name1 == name2, 0 is returned. If name1 < name2, -1 is returned. Otherwise, +1 is returned. """ if name1 is None and name2 is None: return 0 if name1 is None: return -1 if name2 is None: return 1 lower_name1 = name1.lower() lower_name2 = name2.lower() if lower_name1 == lower_name2: return 0 return -1 if lower_name1 < lower_name2 else 1
[ "def", "cmpname", "(", "name1", ",", "name2", ")", ":", "if", "name1", "is", "None", "and", "name2", "is", "None", ":", "return", "0", "if", "name1", "is", "None", ":", "return", "-", "1", "if", "name2", "is", "None", ":", "return", "1", "lower_nam...
Compare two CIM names for equality and ordering. The comparison is performed case-insensitively. One or both of the items may be `None`, and `None` is considered the lowest possible value. The implementation delegates to the '==' and '<' operators of the name datatypes. If name1 == name2, 0 is returned. If name1 < name2, -1 is returned. Otherwise, +1 is returned.
[ "Compare", "two", "CIM", "names", "for", "equality", "and", "ordering", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L341-L367
train
28,367
pywbem/pywbem
pywbem/cim_obj.py
_qualifiers_tomof
def _qualifiers_tomof(qualifiers, indent, maxline=MAX_MOF_LINE): """ Return a MOF string with the qualifier values, including the surrounding square brackets. The qualifiers are ordered by their name. Return empty string if no qualifiers. Normally multiline output and may fold qualifiers into multiple lines. The order of qualifiers is preserved. Parameters: qualifiers (NocaseDict): Qualifiers to format. indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted to the opening bracket in the first line. Returns: :term:`unicode string`: MOF string. """ if not qualifiers: return u'' mof = [] mof.append(_indent_str(indent)) mof.append(u'[') line_pos = indent + 1 mof_quals = [] for q in qualifiers.itervalues(): mof_quals.append(q.tomof(indent + 1 + MOF_INDENT, maxline, line_pos)) delim = ',\n' + _indent_str(indent + 1) mof.append(delim.join(mof_quals)) mof.append(u']\n') return u''.join(mof)
python
def _qualifiers_tomof(qualifiers, indent, maxline=MAX_MOF_LINE): """ Return a MOF string with the qualifier values, including the surrounding square brackets. The qualifiers are ordered by their name. Return empty string if no qualifiers. Normally multiline output and may fold qualifiers into multiple lines. The order of qualifiers is preserved. Parameters: qualifiers (NocaseDict): Qualifiers to format. indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted to the opening bracket in the first line. Returns: :term:`unicode string`: MOF string. """ if not qualifiers: return u'' mof = [] mof.append(_indent_str(indent)) mof.append(u'[') line_pos = indent + 1 mof_quals = [] for q in qualifiers.itervalues(): mof_quals.append(q.tomof(indent + 1 + MOF_INDENT, maxline, line_pos)) delim = ',\n' + _indent_str(indent + 1) mof.append(delim.join(mof_quals)) mof.append(u']\n') return u''.join(mof)
[ "def", "_qualifiers_tomof", "(", "qualifiers", ",", "indent", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "if", "not", "qualifiers", ":", "return", "u''", "mof", "=", "[", "]", "mof", ".", "append", "(", "_indent_str", "(", "indent", ")", ")", "mof", ...
Return a MOF string with the qualifier values, including the surrounding square brackets. The qualifiers are ordered by their name. Return empty string if no qualifiers. Normally multiline output and may fold qualifiers into multiple lines. The order of qualifiers is preserved. Parameters: qualifiers (NocaseDict): Qualifiers to format. indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted to the opening bracket in the first line. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "qualifier", "values", "including", "the", "surrounding", "square", "brackets", ".", "The", "qualifiers", "are", "ordered", "by", "their", "name", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L415-L455
train
28,368
pywbem/pywbem
pywbem/cim_obj.py
_mof_escaped
def _mof_escaped(strvalue): # Note: This is a raw docstring because it shows many backslashes, and # that avoids having to double them. r""" Return a MOF-escaped string from the input string. Parameters: strvalue (:term:`unicode string`): The string value. Must not be `None`. Special characters must not be backslash-escaped. Details on backslash-escaping: `DSP0004` defines that the character repertoire for MOF string constants is the entire repertoire for the CIM string datatype. That is, the entire Unicode character repertoire except for U+0000. The only character for which `DSP0004` requires the use of a MOF escape sequence in a MOF string constant, is the double quote (because a MOF string constant is enclosed in double quotes). `DSP0004` defines MOF escape sequences for several more characters, but it does not require their use in MOF. For example, it is valid for a MOF string constant to contain the (unescaped) characters U+000D (newline) or U+0009 (horizontal tab), and others. Processing the MOF escape sequences as unescaped characters may not be supported by MOF-related tools, and therefore this function plays it safe and uses the MOF escape sequences defined in `DSP0004` as much as possible. The following table shows the MOF escape sequences defined in `DSP0004` and whether they are used (i.e. generated) by this function: ========== ==== =========================================================== MOF escape Used Character sequence ========== ==== =========================================================== \b yes U+0008: Backspace \t yes U+0009: Horizontal tab \n yes U+000A: Line feed \f yes U+000C: Form feed \r yes U+000D: Carriage return \" yes U+0022: Double quote (") (required to be used) \' yes U+0027: Single quote (') \\ yes U+005C: Backslash (\) \x<hex> (1) U+<hex>: Any UCS-2 character, where <hex> is one to four hex digits, representing its UCS code position (this form is limited to the UCS-2 character repertoire) \X<hex> no U+<hex>: Any UCS-2 character, where <hex> is one to four hex digits, representing its UCS code position (this form is limited to the UCS-2 character repertoire) ========== ==== =========================================================== (1) Yes, for all other characters in the so called "control range" U+0001..U+001F. """ escaped_str = strvalue # Escape backslash (\) escaped_str = escaped_str.replace('\\', '\\\\') # Escape \b, \t, \n, \f, \r # Note, the Python escape sequences happen to be the same as in MOF escaped_str = escaped_str.\ replace('\b', '\\b').\ replace('\t', '\\t').\ replace('\n', '\\n').\ replace('\f', '\\f').\ replace('\r', '\\r') # Escape remaining control characters (U+0001...U+001F), skipping # U+0008, U+0009, U+000A, U+000C, U+000D that are already handled. # We hard code it to be faster, plus we can easily skip already handled # chars. # The generic code would be (not skipping already handled chars): # for cp in range(1, 32): # c = six.unichr(cp) # esc = '\\x{0:04X}'.format(cp) # escaped_str = escaped_str.replace(c, esc) escaped_str = escaped_str.\ replace(u'\u0001', '\\x0001').\ replace(u'\u0002', '\\x0002').\ replace(u'\u0003', '\\x0003').\ replace(u'\u0004', '\\x0004').\ replace(u'\u0005', '\\x0005').\ replace(u'\u0006', '\\x0006').\ replace(u'\u0007', '\\x0007').\ replace(u'\u000B', '\\x000B').\ replace(u'\u000E', '\\x000E').\ replace(u'\u000F', '\\x000F').\ replace(u'\u0010', '\\x0010').\ replace(u'\u0011', '\\x0011').\ replace(u'\u0012', '\\x0012').\ replace(u'\u0013', '\\x0013').\ replace(u'\u0014', '\\x0014').\ replace(u'\u0015', '\\x0015').\ replace(u'\u0016', '\\x0016').\ replace(u'\u0017', '\\x0017').\ replace(u'\u0018', '\\x0018').\ replace(u'\u0019', '\\x0019').\ replace(u'\u001A', '\\x001A').\ replace(u'\u001B', '\\x001B').\ replace(u'\u001C', '\\x001C').\ replace(u'\u001D', '\\x001D').\ replace(u'\u001E', '\\x001E').\ replace(u'\u001F', '\\x001F') # Escape single and double quote escaped_str = escaped_str.replace('"', '\\"') escaped_str = escaped_str.replace("'", "\\'") return escaped_str
python
def _mof_escaped(strvalue): # Note: This is a raw docstring because it shows many backslashes, and # that avoids having to double them. r""" Return a MOF-escaped string from the input string. Parameters: strvalue (:term:`unicode string`): The string value. Must not be `None`. Special characters must not be backslash-escaped. Details on backslash-escaping: `DSP0004` defines that the character repertoire for MOF string constants is the entire repertoire for the CIM string datatype. That is, the entire Unicode character repertoire except for U+0000. The only character for which `DSP0004` requires the use of a MOF escape sequence in a MOF string constant, is the double quote (because a MOF string constant is enclosed in double quotes). `DSP0004` defines MOF escape sequences for several more characters, but it does not require their use in MOF. For example, it is valid for a MOF string constant to contain the (unescaped) characters U+000D (newline) or U+0009 (horizontal tab), and others. Processing the MOF escape sequences as unescaped characters may not be supported by MOF-related tools, and therefore this function plays it safe and uses the MOF escape sequences defined in `DSP0004` as much as possible. The following table shows the MOF escape sequences defined in `DSP0004` and whether they are used (i.e. generated) by this function: ========== ==== =========================================================== MOF escape Used Character sequence ========== ==== =========================================================== \b yes U+0008: Backspace \t yes U+0009: Horizontal tab \n yes U+000A: Line feed \f yes U+000C: Form feed \r yes U+000D: Carriage return \" yes U+0022: Double quote (") (required to be used) \' yes U+0027: Single quote (') \\ yes U+005C: Backslash (\) \x<hex> (1) U+<hex>: Any UCS-2 character, where <hex> is one to four hex digits, representing its UCS code position (this form is limited to the UCS-2 character repertoire) \X<hex> no U+<hex>: Any UCS-2 character, where <hex> is one to four hex digits, representing its UCS code position (this form is limited to the UCS-2 character repertoire) ========== ==== =========================================================== (1) Yes, for all other characters in the so called "control range" U+0001..U+001F. """ escaped_str = strvalue # Escape backslash (\) escaped_str = escaped_str.replace('\\', '\\\\') # Escape \b, \t, \n, \f, \r # Note, the Python escape sequences happen to be the same as in MOF escaped_str = escaped_str.\ replace('\b', '\\b').\ replace('\t', '\\t').\ replace('\n', '\\n').\ replace('\f', '\\f').\ replace('\r', '\\r') # Escape remaining control characters (U+0001...U+001F), skipping # U+0008, U+0009, U+000A, U+000C, U+000D that are already handled. # We hard code it to be faster, plus we can easily skip already handled # chars. # The generic code would be (not skipping already handled chars): # for cp in range(1, 32): # c = six.unichr(cp) # esc = '\\x{0:04X}'.format(cp) # escaped_str = escaped_str.replace(c, esc) escaped_str = escaped_str.\ replace(u'\u0001', '\\x0001').\ replace(u'\u0002', '\\x0002').\ replace(u'\u0003', '\\x0003').\ replace(u'\u0004', '\\x0004').\ replace(u'\u0005', '\\x0005').\ replace(u'\u0006', '\\x0006').\ replace(u'\u0007', '\\x0007').\ replace(u'\u000B', '\\x000B').\ replace(u'\u000E', '\\x000E').\ replace(u'\u000F', '\\x000F').\ replace(u'\u0010', '\\x0010').\ replace(u'\u0011', '\\x0011').\ replace(u'\u0012', '\\x0012').\ replace(u'\u0013', '\\x0013').\ replace(u'\u0014', '\\x0014').\ replace(u'\u0015', '\\x0015').\ replace(u'\u0016', '\\x0016').\ replace(u'\u0017', '\\x0017').\ replace(u'\u0018', '\\x0018').\ replace(u'\u0019', '\\x0019').\ replace(u'\u001A', '\\x001A').\ replace(u'\u001B', '\\x001B').\ replace(u'\u001C', '\\x001C').\ replace(u'\u001D', '\\x001D').\ replace(u'\u001E', '\\x001E').\ replace(u'\u001F', '\\x001F') # Escape single and double quote escaped_str = escaped_str.replace('"', '\\"') escaped_str = escaped_str.replace("'", "\\'") return escaped_str
[ "def", "_mof_escaped", "(", "strvalue", ")", ":", "# Note: This is a raw docstring because it shows many backslashes, and", "# that avoids having to double them.", "escaped_str", "=", "strvalue", "# Escape backslash (\\)", "escaped_str", "=", "escaped_str", ".", "replace", "(", "...
r""" Return a MOF-escaped string from the input string. Parameters: strvalue (:term:`unicode string`): The string value. Must not be `None`. Special characters must not be backslash-escaped. Details on backslash-escaping: `DSP0004` defines that the character repertoire for MOF string constants is the entire repertoire for the CIM string datatype. That is, the entire Unicode character repertoire except for U+0000. The only character for which `DSP0004` requires the use of a MOF escape sequence in a MOF string constant, is the double quote (because a MOF string constant is enclosed in double quotes). `DSP0004` defines MOF escape sequences for several more characters, but it does not require their use in MOF. For example, it is valid for a MOF string constant to contain the (unescaped) characters U+000D (newline) or U+0009 (horizontal tab), and others. Processing the MOF escape sequences as unescaped characters may not be supported by MOF-related tools, and therefore this function plays it safe and uses the MOF escape sequences defined in `DSP0004` as much as possible. The following table shows the MOF escape sequences defined in `DSP0004` and whether they are used (i.e. generated) by this function: ========== ==== =========================================================== MOF escape Used Character sequence ========== ==== =========================================================== \b yes U+0008: Backspace \t yes U+0009: Horizontal tab \n yes U+000A: Line feed \f yes U+000C: Form feed \r yes U+000D: Carriage return \" yes U+0022: Double quote (") (required to be used) \' yes U+0027: Single quote (') \\ yes U+005C: Backslash (\) \x<hex> (1) U+<hex>: Any UCS-2 character, where <hex> is one to four hex digits, representing its UCS code position (this form is limited to the UCS-2 character repertoire) \X<hex> no U+<hex>: Any UCS-2 character, where <hex> is one to four hex digits, representing its UCS code position (this form is limited to the UCS-2 character repertoire) ========== ==== =========================================================== (1) Yes, for all other characters in the so called "control range" U+0001..U+001F.
[ "r", "Return", "a", "MOF", "-", "escaped", "string", "from", "the", "input", "string", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L466-L577
train
28,369
pywbem/pywbem
pywbem/cim_obj.py
_scalar_value_tomof
def _scalar_value_tomof( value, type, indent=0, maxline=MAX_MOF_LINE, line_pos=0, end_space=0, avoid_splits=False): # pylint: disable=line-too-long,redefined-builtin """ Return a MOF string representing a scalar CIM-typed value. `None` is returned as 'NULL'. Parameters: value (:term:`CIM data type`, :term:`number`, :class:`~pywbem.CIMInstance`, :class:`~pywbem.CIMClass`): The scalar CIM-typed value. May be `None`. Must not be an array/list/tuple. Must not be a :ref:`CIM object` other than those listed. type (string): CIM data type name. indent (:term:`integer`): Number of spaces to indent any new lines that are generated. maxline (:term:`integer`): Maximum line length for the generated MOF. line_pos (:term:`integer`): Length of content already on the current line. end_space (:term:`integer`): Length of space to be left free on the last line. avoid_splits (bool): Avoid splits at the price of starting a new line instead of using the current line. Returns: tuple of * :term:`unicode string`: MOF string. * new line_pos """ # noqa: E501 if value is None: return mofval(u'NULL', indent, maxline, line_pos, end_space) if type == 'string': # pylint: disable=no-else-raise if isinstance(value, six.string_types): return mofstr(value, indent, maxline, line_pos, end_space, avoid_splits) if isinstance(value, (CIMInstance, CIMClass)): # embedded instance or class return mofstr(value.tomof(), indent, maxline, line_pos, end_space, avoid_splits) raise TypeError( _format("Scalar value of CIM type {0} has invalid Python type " "type {1} for conversion to a MOF string", type, builtin_type(value))) elif type == 'char16': return mofstr(value, indent, maxline, line_pos, end_space, avoid_splits, quote_char=u"'") elif type == 'boolean': val = u'true' if value else u'false' return mofval(val, indent, maxline, line_pos, end_space) elif type == 'datetime': val = six.text_type(value) return mofstr(val, indent, maxline, line_pos, end_space, avoid_splits) elif type == 'reference': val = value.to_wbem_uri() return mofstr(val, indent, maxline, line_pos, end_space, avoid_splits) elif isinstance(value, (CIMFloat, CIMInt, int, _Longint)): val = six.text_type(value) return mofval(val, indent, maxline, line_pos, end_space) else: assert isinstance(value, float), \ _format("Scalar value of CIM type {0} has invalid Python type {1} " "for conversion to a MOF string", type, builtin_type(value)) val = repr(value) return mofval(val, indent, maxline, line_pos, end_space)
python
def _scalar_value_tomof( value, type, indent=0, maxline=MAX_MOF_LINE, line_pos=0, end_space=0, avoid_splits=False): # pylint: disable=line-too-long,redefined-builtin """ Return a MOF string representing a scalar CIM-typed value. `None` is returned as 'NULL'. Parameters: value (:term:`CIM data type`, :term:`number`, :class:`~pywbem.CIMInstance`, :class:`~pywbem.CIMClass`): The scalar CIM-typed value. May be `None`. Must not be an array/list/tuple. Must not be a :ref:`CIM object` other than those listed. type (string): CIM data type name. indent (:term:`integer`): Number of spaces to indent any new lines that are generated. maxline (:term:`integer`): Maximum line length for the generated MOF. line_pos (:term:`integer`): Length of content already on the current line. end_space (:term:`integer`): Length of space to be left free on the last line. avoid_splits (bool): Avoid splits at the price of starting a new line instead of using the current line. Returns: tuple of * :term:`unicode string`: MOF string. * new line_pos """ # noqa: E501 if value is None: return mofval(u'NULL', indent, maxline, line_pos, end_space) if type == 'string': # pylint: disable=no-else-raise if isinstance(value, six.string_types): return mofstr(value, indent, maxline, line_pos, end_space, avoid_splits) if isinstance(value, (CIMInstance, CIMClass)): # embedded instance or class return mofstr(value.tomof(), indent, maxline, line_pos, end_space, avoid_splits) raise TypeError( _format("Scalar value of CIM type {0} has invalid Python type " "type {1} for conversion to a MOF string", type, builtin_type(value))) elif type == 'char16': return mofstr(value, indent, maxline, line_pos, end_space, avoid_splits, quote_char=u"'") elif type == 'boolean': val = u'true' if value else u'false' return mofval(val, indent, maxline, line_pos, end_space) elif type == 'datetime': val = six.text_type(value) return mofstr(val, indent, maxline, line_pos, end_space, avoid_splits) elif type == 'reference': val = value.to_wbem_uri() return mofstr(val, indent, maxline, line_pos, end_space, avoid_splits) elif isinstance(value, (CIMFloat, CIMInt, int, _Longint)): val = six.text_type(value) return mofval(val, indent, maxline, line_pos, end_space) else: assert isinstance(value, float), \ _format("Scalar value of CIM type {0} has invalid Python type {1} " "for conversion to a MOF string", type, builtin_type(value)) val = repr(value) return mofval(val, indent, maxline, line_pos, end_space)
[ "def", "_scalar_value_tomof", "(", "value", ",", "type", ",", "indent", "=", "0", ",", "maxline", "=", "MAX_MOF_LINE", ",", "line_pos", "=", "0", ",", "end_space", "=", "0", ",", "avoid_splits", "=", "False", ")", ":", "# pylint: disable=line-too-long,redefine...
Return a MOF string representing a scalar CIM-typed value. `None` is returned as 'NULL'. Parameters: value (:term:`CIM data type`, :term:`number`, :class:`~pywbem.CIMInstance`, :class:`~pywbem.CIMClass`): The scalar CIM-typed value. May be `None`. Must not be an array/list/tuple. Must not be a :ref:`CIM object` other than those listed. type (string): CIM data type name. indent (:term:`integer`): Number of spaces to indent any new lines that are generated. maxline (:term:`integer`): Maximum line length for the generated MOF. line_pos (:term:`integer`): Length of content already on the current line. end_space (:term:`integer`): Length of space to be left free on the last line. avoid_splits (bool): Avoid splits at the price of starting a new line instead of using the current line. Returns: tuple of * :term:`unicode string`: MOF string. * new line_pos
[ "Return", "a", "MOF", "string", "representing", "a", "scalar", "CIM", "-", "typed", "value", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L771-L849
train
28,370
pywbem/pywbem
pywbem/cim_obj.py
_infer_type
def _infer_type(value, element_kind, element_name): """ Infer the CIM type name of the value, based upon its Python type. """ if value is None: raise ValueError( _format("Cannot infer CIM type of {0} {1!A} from its value when " "the value is None", element_kind, element_name)) try: return cimtype(value) except TypeError as exc: raise ValueError( _format("Cannot infer CIM type of {0} {1!A} from its value: {2!A}", element_kind, element_name, exc))
python
def _infer_type(value, element_kind, element_name): """ Infer the CIM type name of the value, based upon its Python type. """ if value is None: raise ValueError( _format("Cannot infer CIM type of {0} {1!A} from its value when " "the value is None", element_kind, element_name)) try: return cimtype(value) except TypeError as exc: raise ValueError( _format("Cannot infer CIM type of {0} {1!A} from its value: {2!A}", element_kind, element_name, exc))
[ "def", "_infer_type", "(", "value", ",", "element_kind", ",", "element_name", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "_format", "(", "\"Cannot infer CIM type of {0} {1!A} from its value when \"", "\"the value is None\"", ",", "element_ki...
Infer the CIM type name of the value, based upon its Python type.
[ "Infer", "the", "CIM", "type", "name", "of", "the", "value", "based", "upon", "its", "Python", "type", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L8153-L8168
train
28,371
pywbem/pywbem
pywbem/cim_obj.py
_check_array_parms
def _check_array_parms(is_array, array_size, value, element_kind, element_name): # pylint: disable=unused-argument # The array_size argument is unused. """ Check whether array-related parameters are ok. """ # The following case has been disabled because it cannot happen given # how this check function is used: # if array_size and is_array is False: # raise ValueError( # _format("The array_size parameter of {0} {1!A} is {2!A} but the " # "is_array parameter is False.", # element_kind, element_name, array_size)) if value is not None: value_is_array = isinstance(value, (list, tuple)) if not is_array and value_is_array: raise ValueError( _format("The is_array parameter of {0} {1!A} is False but " "value {2!A} is an array.", element_kind, element_name, value)) if is_array and not value_is_array: raise ValueError( _format("The is_array parameter of {0} {1!A} is True but " "value {2!A} is not an array.", element_kind, element_name, value))
python
def _check_array_parms(is_array, array_size, value, element_kind, element_name): # pylint: disable=unused-argument # The array_size argument is unused. """ Check whether array-related parameters are ok. """ # The following case has been disabled because it cannot happen given # how this check function is used: # if array_size and is_array is False: # raise ValueError( # _format("The array_size parameter of {0} {1!A} is {2!A} but the " # "is_array parameter is False.", # element_kind, element_name, array_size)) if value is not None: value_is_array = isinstance(value, (list, tuple)) if not is_array and value_is_array: raise ValueError( _format("The is_array parameter of {0} {1!A} is False but " "value {2!A} is an array.", element_kind, element_name, value)) if is_array and not value_is_array: raise ValueError( _format("The is_array parameter of {0} {1!A} is True but " "value {2!A} is not an array.", element_kind, element_name, value))
[ "def", "_check_array_parms", "(", "is_array", ",", "array_size", ",", "value", ",", "element_kind", ",", "element_name", ")", ":", "# pylint: disable=unused-argument", "# The array_size argument is unused.", "# The following case has been disabled because it cannot happen given", "...
Check whether array-related parameters are ok.
[ "Check", "whether", "array", "-", "related", "parameters", "are", "ok", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L8184-L8211
train
28,372
pywbem/pywbem
pywbem/cim_obj.py
_check_embedded_object
def _check_embedded_object(embedded_object, type, value, element_kind, element_name): # pylint: disable=redefined-builtin """ Check whether embedded-object-related parameters are ok. """ if embedded_object not in ('instance', 'object'): raise ValueError( _format("{0} {1!A} specifies an invalid value for " "embedded_object: {2!A} (must be 'instance' or 'object')", element_kind, element_name, embedded_object)) if type != 'string': raise ValueError( _format("{0} {1!A} specifies embedded_object {2!A} but its CIM " "type is invalid: {3!A} (must be 'string')", element_kind, element_name, embedded_object, type)) if value is not None: if isinstance(value, list): if value: v0 = value[0] # Check the first array element if v0 is not None and \ not isinstance(v0, (CIMInstance, CIMClass)): raise ValueError( _format("Array {0} {1!A} specifies embedded_object " "{2!A} but the Python type of its first array " "value is invalid: {3} (must be CIMInstance " "or CIMClass)", element_kind, element_name, embedded_object, builtin_type(v0))) else: if not isinstance(value, (CIMInstance, CIMClass)): raise ValueError( _format("{0} {1!A} specifies embedded_object {2!A} but " "the Python type of its value is invalid: {3} " "(must be CIMInstance or CIMClass)", element_kind, element_name, embedded_object, builtin_type(value)))
python
def _check_embedded_object(embedded_object, type, value, element_kind, element_name): # pylint: disable=redefined-builtin """ Check whether embedded-object-related parameters are ok. """ if embedded_object not in ('instance', 'object'): raise ValueError( _format("{0} {1!A} specifies an invalid value for " "embedded_object: {2!A} (must be 'instance' or 'object')", element_kind, element_name, embedded_object)) if type != 'string': raise ValueError( _format("{0} {1!A} specifies embedded_object {2!A} but its CIM " "type is invalid: {3!A} (must be 'string')", element_kind, element_name, embedded_object, type)) if value is not None: if isinstance(value, list): if value: v0 = value[0] # Check the first array element if v0 is not None and \ not isinstance(v0, (CIMInstance, CIMClass)): raise ValueError( _format("Array {0} {1!A} specifies embedded_object " "{2!A} but the Python type of its first array " "value is invalid: {3} (must be CIMInstance " "or CIMClass)", element_kind, element_name, embedded_object, builtin_type(v0))) else: if not isinstance(value, (CIMInstance, CIMClass)): raise ValueError( _format("{0} {1!A} specifies embedded_object {2!A} but " "the Python type of its value is invalid: {3} " "(must be CIMInstance or CIMClass)", element_kind, element_name, embedded_object, builtin_type(value)))
[ "def", "_check_embedded_object", "(", "embedded_object", ",", "type", ",", "value", ",", "element_kind", ",", "element_name", ")", ":", "# pylint: disable=redefined-builtin", "if", "embedded_object", "not", "in", "(", "'instance'", ",", "'object'", ")", ":", "raise"...
Check whether embedded-object-related parameters are ok.
[ "Check", "whether", "embedded", "-", "object", "-", "related", "parameters", "are", "ok", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L8244-L8283
train
28,373
pywbem/pywbem
pywbem/cim_obj.py
CIMInstanceName._kbstr_to_cimval
def _kbstr_to_cimval(key, val): """ Convert a keybinding value string as found in a WBEM URI into a CIM object or CIM data type, and return it. """ if val[0] == '"' and val[-1] == '"': # A double quoted key value. This could be any of these CIM types: # * string (see stringValue in DSP00004) # * datetime (see datetimeValue in DSP0207) # * reference (see referenceValue in DSP0207) # Note: The actual definition of referenceValue is missing in # DSP0207, see issue #929. Pywbem implements: # referenceValue = WBEM-URI-UntypedInstancePath. # Note: The definition of stringValue in DSP0004 allows multiple # quoted parts (as in MOF), see issue #931. Pywbem implements only # a single quoted part. # We use slicing instead of strip() for removing the surrounding # double quotes, because there could be an escaped double quote # before the terminating double quote. cimval = val[1:-1] # Unescape the backslash-escaped string value cimval = re.sub(r'\\(.)', r'\1', cimval) # Try all possibilities. Note that this means that string-typed # properties that happen to contain a datetime value will be # converted to datetime, and string-typed properties that happen to # contain a reference value will be converted to a reference. # This is a general limitation of untyped WBEM URIs as defined in # DSP0207 and cannot be solved by using a different parsing logic. try: cimval = CIMInstanceName.from_wbem_uri(cimval) except ValueError: try: cimval = CIMDateTime(cimval) except ValueError: cimval = _ensure_unicode(cimval) return cimval if val[0] == "'" and val[-1] == "'": # A single quoted key value. This must be CIM type: # * char16 (see charValue in DSP00004) # Note: The definition of charValue in DSP0004 allows for integer # numbers in addition to single quoted strings, see issue #932. # Pywbem implements only single quoted strings. cimval = val[1:-1] cimval = re.sub(r'\\(.)', r'\1', cimval) cimval = _ensure_unicode(cimval) if len(cimval) != 1: raise ValueError( _format("WBEM URI has a char16 keybinding with an " "incorrect length: {0!A}={1!A}", key, val)) return cimval if val.lower() in ('true', 'false'): # The key value must be CIM type: # * boolean (see booleanValue in DSP00004) cimval = val.lower() == 'true' return cimval # Try CIM types uint<NN> or sint<NN> (see integerValue in DSP00004). # * For integer keybindings in an untyped WBEM URI, it is # not possible to detect the exact CIM data type. Therefore, pywbem # stores the value as a Python int type (or long in Python 2, # if needed). cimval = _integerValue_to_int(val) if cimval is not None: return cimval # Try CIM types real32/64 (see realValue in DSP00004). # * For real/float keybindings in an untyped WBEM URI, it is not # possible to detect the exact CIM data type. Therefore, pywbem # stores the value as a Python float type. cimval = _realValue_to_float(val) if cimval is not None: return cimval # Try datetime types. # At this point, all CIM types have been processed, except: # * datetime, without quotes (see datetimeValue in DSP0207) # DSP0207 requires double quotes around datetime strings, but because # earlier versions of pywbem supported them without double quotes, # pywbem continues to support that, but issues a warning. try: cimval = CIMDateTime(val) except ValueError: raise ValueError( _format("WBEM URI has invalid value format in a keybinding: " "{0!A}={1!A}", key, val)) warnings.warn( _format("Tolerating datetime value without surrounding double " "quotes in WBEM URI keybinding: {0!A}={1!A}", key, val), UserWarning) return cimval
python
def _kbstr_to_cimval(key, val): """ Convert a keybinding value string as found in a WBEM URI into a CIM object or CIM data type, and return it. """ if val[0] == '"' and val[-1] == '"': # A double quoted key value. This could be any of these CIM types: # * string (see stringValue in DSP00004) # * datetime (see datetimeValue in DSP0207) # * reference (see referenceValue in DSP0207) # Note: The actual definition of referenceValue is missing in # DSP0207, see issue #929. Pywbem implements: # referenceValue = WBEM-URI-UntypedInstancePath. # Note: The definition of stringValue in DSP0004 allows multiple # quoted parts (as in MOF), see issue #931. Pywbem implements only # a single quoted part. # We use slicing instead of strip() for removing the surrounding # double quotes, because there could be an escaped double quote # before the terminating double quote. cimval = val[1:-1] # Unescape the backslash-escaped string value cimval = re.sub(r'\\(.)', r'\1', cimval) # Try all possibilities. Note that this means that string-typed # properties that happen to contain a datetime value will be # converted to datetime, and string-typed properties that happen to # contain a reference value will be converted to a reference. # This is a general limitation of untyped WBEM URIs as defined in # DSP0207 and cannot be solved by using a different parsing logic. try: cimval = CIMInstanceName.from_wbem_uri(cimval) except ValueError: try: cimval = CIMDateTime(cimval) except ValueError: cimval = _ensure_unicode(cimval) return cimval if val[0] == "'" and val[-1] == "'": # A single quoted key value. This must be CIM type: # * char16 (see charValue in DSP00004) # Note: The definition of charValue in DSP0004 allows for integer # numbers in addition to single quoted strings, see issue #932. # Pywbem implements only single quoted strings. cimval = val[1:-1] cimval = re.sub(r'\\(.)', r'\1', cimval) cimval = _ensure_unicode(cimval) if len(cimval) != 1: raise ValueError( _format("WBEM URI has a char16 keybinding with an " "incorrect length: {0!A}={1!A}", key, val)) return cimval if val.lower() in ('true', 'false'): # The key value must be CIM type: # * boolean (see booleanValue in DSP00004) cimval = val.lower() == 'true' return cimval # Try CIM types uint<NN> or sint<NN> (see integerValue in DSP00004). # * For integer keybindings in an untyped WBEM URI, it is # not possible to detect the exact CIM data type. Therefore, pywbem # stores the value as a Python int type (or long in Python 2, # if needed). cimval = _integerValue_to_int(val) if cimval is not None: return cimval # Try CIM types real32/64 (see realValue in DSP00004). # * For real/float keybindings in an untyped WBEM URI, it is not # possible to detect the exact CIM data type. Therefore, pywbem # stores the value as a Python float type. cimval = _realValue_to_float(val) if cimval is not None: return cimval # Try datetime types. # At this point, all CIM types have been processed, except: # * datetime, without quotes (see datetimeValue in DSP0207) # DSP0207 requires double quotes around datetime strings, but because # earlier versions of pywbem supported them without double quotes, # pywbem continues to support that, but issues a warning. try: cimval = CIMDateTime(val) except ValueError: raise ValueError( _format("WBEM URI has invalid value format in a keybinding: " "{0!A}={1!A}", key, val)) warnings.warn( _format("Tolerating datetime value without surrounding double " "quotes in WBEM URI keybinding: {0!A}={1!A}", key, val), UserWarning) return cimval
[ "def", "_kbstr_to_cimval", "(", "key", ",", "val", ")", ":", "if", "val", "[", "0", "]", "==", "'\"'", "and", "val", "[", "-", "1", "]", "==", "'\"'", ":", "# A double quoted key value. This could be any of these CIM types:", "# * string (see stringValue in DSP00004...
Convert a keybinding value string as found in a WBEM URI into a CIM object or CIM data type, and return it.
[ "Convert", "a", "keybinding", "value", "string", "as", "found", "in", "a", "WBEM", "URI", "into", "a", "CIM", "object", "or", "CIM", "data", "type", "and", "return", "it", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L1716-L1816
train
28,374
pywbem/pywbem
pywbem/cim_obj.py
CIMInstance.update
def update(self, *args, **kwargs): """ Update the properties of this CIM instance. Existing properties will be updated, and new properties will be added. Parameters: *args (list): Properties for updating the properties of the instance, specified as positional arguments. Each positional argument must be a tuple (key, value), where key and value are described for setting the :attr:`~pywbem.CIMInstance.properties` property. **kwargs (dict): Properties for updating the properties of the instance, specified as keyword arguments. The name and value of the keyword arguments are described as key and value for setting the :attr:`~pywbem.CIMInstance.properties` property. """ for mapping in args: if hasattr(mapping, 'items'): for key, value in mapping.items(): self[key] = value else: for (key, value) in mapping: self[key] = value for key, value in kwargs.items(): self[key] = value
python
def update(self, *args, **kwargs): """ Update the properties of this CIM instance. Existing properties will be updated, and new properties will be added. Parameters: *args (list): Properties for updating the properties of the instance, specified as positional arguments. Each positional argument must be a tuple (key, value), where key and value are described for setting the :attr:`~pywbem.CIMInstance.properties` property. **kwargs (dict): Properties for updating the properties of the instance, specified as keyword arguments. The name and value of the keyword arguments are described as key and value for setting the :attr:`~pywbem.CIMInstance.properties` property. """ for mapping in args: if hasattr(mapping, 'items'): for key, value in mapping.items(): self[key] = value else: for (key, value) in mapping: self[key] = value for key, value in kwargs.items(): self[key] = value
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "mapping", "in", "args", ":", "if", "hasattr", "(", "mapping", ",", "'items'", ")", ":", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")"...
Update the properties of this CIM instance. Existing properties will be updated, and new properties will be added. Parameters: *args (list): Properties for updating the properties of the instance, specified as positional arguments. Each positional argument must be a tuple (key, value), where key and value are described for setting the :attr:`~pywbem.CIMInstance.properties` property. **kwargs (dict): Properties for updating the properties of the instance, specified as keyword arguments. The name and value of the keyword arguments are described as key and value for setting the :attr:`~pywbem.CIMInstance.properties` property.
[ "Update", "the", "properties", "of", "this", "CIM", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L2703-L2732
train
28,375
pywbem/pywbem
pywbem/cim_obj.py
CIMInstance.update_existing
def update_existing(self, *args, **kwargs): """ Update already existing properties of this CIM instance. Existing properties will be updated, and new properties will be ignored without further notice. Parameters: *args (list): Properties for updating the properties of the instance, specified as positional arguments. Each positional argument must be a tuple (key, value), where key and value are described for setting the :attr:`~pywbem.CIMInstance.properties` property. **kwargs (dict): Properties for updating the properties of the instance, specified as keyword arguments. The name and value of the keyword arguments are described as key and value for setting the :attr:`~pywbem.CIMInstance.properties` property. """ for mapping in args: if hasattr(mapping, 'items'): for key, value in mapping.items(): try: prop = self.properties[key] except KeyError: continue prop.value = value else: for (key, value) in mapping: try: prop = self.properties[key] except KeyError: continue prop.value = value for key, value in kwargs.items(): try: prop = self.properties[key] except KeyError: continue prop.value = value
python
def update_existing(self, *args, **kwargs): """ Update already existing properties of this CIM instance. Existing properties will be updated, and new properties will be ignored without further notice. Parameters: *args (list): Properties for updating the properties of the instance, specified as positional arguments. Each positional argument must be a tuple (key, value), where key and value are described for setting the :attr:`~pywbem.CIMInstance.properties` property. **kwargs (dict): Properties for updating the properties of the instance, specified as keyword arguments. The name and value of the keyword arguments are described as key and value for setting the :attr:`~pywbem.CIMInstance.properties` property. """ for mapping in args: if hasattr(mapping, 'items'): for key, value in mapping.items(): try: prop = self.properties[key] except KeyError: continue prop.value = value else: for (key, value) in mapping: try: prop = self.properties[key] except KeyError: continue prop.value = value for key, value in kwargs.items(): try: prop = self.properties[key] except KeyError: continue prop.value = value
[ "def", "update_existing", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "mapping", "in", "args", ":", "if", "hasattr", "(", "mapping", ",", "'items'", ")", ":", "for", "key", ",", "value", "in", "mapping", ".", "items", "...
Update already existing properties of this CIM instance. Existing properties will be updated, and new properties will be ignored without further notice. Parameters: *args (list): Properties for updating the properties of the instance, specified as positional arguments. Each positional argument must be a tuple (key, value), where key and value are described for setting the :attr:`~pywbem.CIMInstance.properties` property. **kwargs (dict): Properties for updating the properties of the instance, specified as keyword arguments. The name and value of the keyword arguments are described as key and value for setting the :attr:`~pywbem.CIMInstance.properties` property.
[ "Update", "already", "existing", "properties", "of", "this", "CIM", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L2734-L2776
train
28,376
pywbem/pywbem
pywbem/cim_obj.py
CIMInstance.get
def get(self, key, default=None): """ Return the value of a particular property of this CIM instance, or a default value. *New in pywbem 0.8.* Parameters: key (:term:`string`): Name of the property (in any lexical case). default (:term:`CIM data type`): Default value that is returned if a property with the specified name does not exist in the instance. Returns: :term:`CIM data type`: Value of the property, or the default value. """ prop = self.properties.get(key, None) return default if prop is None else prop.value
python
def get(self, key, default=None): """ Return the value of a particular property of this CIM instance, or a default value. *New in pywbem 0.8.* Parameters: key (:term:`string`): Name of the property (in any lexical case). default (:term:`CIM data type`): Default value that is returned if a property with the specified name does not exist in the instance. Returns: :term:`CIM data type`: Value of the property, or the default value. """ prop = self.properties.get(key, None) return default if prop is None else prop.value
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "prop", "=", "self", ".", "properties", ".", "get", "(", "key", ",", "None", ")", "return", "default", "if", "prop", "is", "None", "else", "prop", ".", "value" ]
Return the value of a particular property of this CIM instance, or a default value. *New in pywbem 0.8.* Parameters: key (:term:`string`): Name of the property (in any lexical case). default (:term:`CIM data type`): Default value that is returned if a property with the specified name does not exist in the instance. Returns: :term:`CIM data type`: Value of the property, or the default value.
[ "Return", "the", "value", "of", "a", "particular", "property", "of", "this", "CIM", "instance", "or", "a", "default", "value", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L2794-L2814
train
28,377
pywbem/pywbem
pywbem/cim_obj.py
CIMInstance.items
def items(self): """ Return a copied list of the property names and values of this CIM instance. Each item in the returned list is a tuple of property name (in the original lexical case) and property value. The order of properties is preserved. """ return [(key, v.value) for key, v in self.properties.items()]
python
def items(self): """ Return a copied list of the property names and values of this CIM instance. Each item in the returned list is a tuple of property name (in the original lexical case) and property value. The order of properties is preserved. """ return [(key, v.value) for key, v in self.properties.items()]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "key", ",", "v", ".", "value", ")", "for", "key", ",", "v", "in", "self", ".", "properties", ".", "items", "(", ")", "]" ]
Return a copied list of the property names and values of this CIM instance. Each item in the returned list is a tuple of property name (in the original lexical case) and property value. The order of properties is preserved.
[ "Return", "a", "copied", "list", "of", "the", "property", "names", "and", "values", "of", "this", "CIM", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L2834-L2844
train
28,378
pywbem/pywbem
pywbem/cim_obj.py
CIMInstance.iteritems
def iteritems(self): """ Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved. """ for key, val in self.properties.iteritems(): yield (key, val.value)
python
def iteritems(self): """ Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved. """ for key, val in self.properties.iteritems(): yield (key, val.value)
[ "def", "iteritems", "(", "self", ")", ":", "for", "key", ",", "val", "in", "self", ".", "properties", ".", "iteritems", "(", ")", ":", "yield", "(", "key", ",", "val", ".", "value", ")" ]
Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved.
[ "Iterate", "through", "the", "property", "names", "and", "values", "of", "this", "CIM", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L2865-L2875
train
28,379
pywbem/pywbem
pywbem/cim_obj.py
CIMInstance.tomof
def tomof(self, indent=0, maxline=MAX_MOF_LINE): """ Return a MOF string with the specification of this CIM instance. The returned MOF string conforms to the ``instanceDeclaration`` ABNF rule defined in :term:`DSP0004`, with the following limitations: * Pywbem does not support instance aliases, so the returned MOF string does not define an alias name for the instance. * Even though pywbem supports qualifiers on :class:`~pywbem.CIMInstance` objects, and on :class:`~pywbem.CIMProperty` objects that are used as property values within an instance, the returned MOF string does not contain any qualifier values on the instance or on its property values. The order of properties and qualifiers is preserved. Parameters: indent (:term:`integer`): This parameter has been deprecated in pywbem 0.12. A value other than 0 causes a deprecation warning to be issued. Otherwise, the parameter is ignored and the returned MOF instance specification is not indented. Returns: :term:`unicode string`: MOF string. """ if indent != 0: msg = "The 'indent' parameter of CIMInstance.tomof() is " \ "deprecated." if DEBUG_WARNING_ORIGIN: msg += "\nTraceback:\n" + ''.join(traceback.format_stack()) warnings.warn(msg, DeprecationWarning, stacklevel=_stacklevel_above_module(__name__)) mof = [] mof.append(u'instance of ') mof.append(self.classname) mof.append(u' {\n') for p in self.properties.itervalues(): mof.append(p.tomof(True, MOF_INDENT, maxline)) mof.append(u'};\n') return u''.join(mof)
python
def tomof(self, indent=0, maxline=MAX_MOF_LINE): """ Return a MOF string with the specification of this CIM instance. The returned MOF string conforms to the ``instanceDeclaration`` ABNF rule defined in :term:`DSP0004`, with the following limitations: * Pywbem does not support instance aliases, so the returned MOF string does not define an alias name for the instance. * Even though pywbem supports qualifiers on :class:`~pywbem.CIMInstance` objects, and on :class:`~pywbem.CIMProperty` objects that are used as property values within an instance, the returned MOF string does not contain any qualifier values on the instance or on its property values. The order of properties and qualifiers is preserved. Parameters: indent (:term:`integer`): This parameter has been deprecated in pywbem 0.12. A value other than 0 causes a deprecation warning to be issued. Otherwise, the parameter is ignored and the returned MOF instance specification is not indented. Returns: :term:`unicode string`: MOF string. """ if indent != 0: msg = "The 'indent' parameter of CIMInstance.tomof() is " \ "deprecated." if DEBUG_WARNING_ORIGIN: msg += "\nTraceback:\n" + ''.join(traceback.format_stack()) warnings.warn(msg, DeprecationWarning, stacklevel=_stacklevel_above_module(__name__)) mof = [] mof.append(u'instance of ') mof.append(self.classname) mof.append(u' {\n') for p in self.properties.itervalues(): mof.append(p.tomof(True, MOF_INDENT, maxline)) mof.append(u'};\n') return u''.join(mof)
[ "def", "tomof", "(", "self", ",", "indent", "=", "0", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "if", "indent", "!=", "0", ":", "msg", "=", "\"The 'indent' parameter of CIMInstance.tomof() is \"", "\"deprecated.\"", "if", "DEBUG_WARNING_ORIGIN", ":", "msg", ...
Return a MOF string with the specification of this CIM instance. The returned MOF string conforms to the ``instanceDeclaration`` ABNF rule defined in :term:`DSP0004`, with the following limitations: * Pywbem does not support instance aliases, so the returned MOF string does not define an alias name for the instance. * Even though pywbem supports qualifiers on :class:`~pywbem.CIMInstance` objects, and on :class:`~pywbem.CIMProperty` objects that are used as property values within an instance, the returned MOF string does not contain any qualifier values on the instance or on its property values. The order of properties and qualifiers is preserved. Parameters: indent (:term:`integer`): This parameter has been deprecated in pywbem 0.12. A value other than 0 causes a deprecation warning to be issued. Otherwise, the parameter is ignored and the returned MOF instance specification is not indented. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "specification", "of", "this", "CIM", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L2987-L3037
train
28,380
pywbem/pywbem
pywbem/cim_obj.py
CIMClass.tomof
def tomof(self, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM class. The returned MOF string conforms to the ``classDeclaration`` ABNF rule defined in :term:`DSP0004`. The order of properties, methods, parameters, and qualifiers is preserved. The :attr:`~pywbem.CIMClass.path` attribute of this object will not be included in the returned MOF string. Consistent with that, class path information is not included in the returned MOF string. Returns: :term:`unicode string`: MOF string. """ mof = [] mof.append(_qualifiers_tomof(self.qualifiers, MOF_INDENT, maxline)) mof.append(u'class ') mof.append(self.classname) mof.append(u' ') if self.superclass is not None: mof.append(u': ') mof.append(self.superclass) mof.append(u' ') mof.append(u'{\n') for p in self.properties.itervalues(): mof.append(u'\n') mof.append(p.tomof(False, MOF_INDENT, maxline)) for m in self.methods.itervalues(): mof.append(u'\n') mof.append(m.tomof(MOF_INDENT, maxline)) mof.append(u'\n};\n') return u''.join(mof)
python
def tomof(self, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM class. The returned MOF string conforms to the ``classDeclaration`` ABNF rule defined in :term:`DSP0004`. The order of properties, methods, parameters, and qualifiers is preserved. The :attr:`~pywbem.CIMClass.path` attribute of this object will not be included in the returned MOF string. Consistent with that, class path information is not included in the returned MOF string. Returns: :term:`unicode string`: MOF string. """ mof = [] mof.append(_qualifiers_tomof(self.qualifiers, MOF_INDENT, maxline)) mof.append(u'class ') mof.append(self.classname) mof.append(u' ') if self.superclass is not None: mof.append(u': ') mof.append(self.superclass) mof.append(u' ') mof.append(u'{\n') for p in self.properties.itervalues(): mof.append(u'\n') mof.append(p.tomof(False, MOF_INDENT, maxline)) for m in self.methods.itervalues(): mof.append(u'\n') mof.append(m.tomof(MOF_INDENT, maxline)) mof.append(u'\n};\n') return u''.join(mof)
[ "def", "tomof", "(", "self", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "mof", "=", "[", "]", "mof", ".", "append", "(", "_qualifiers_tomof", "(", "self", ".", "qualifiers", ",", "MOF_INDENT", ",", "maxline", ")", ")", "mof", ".", "append", "(", ...
Return a MOF string with the declaration of this CIM class. The returned MOF string conforms to the ``classDeclaration`` ABNF rule defined in :term:`DSP0004`. The order of properties, methods, parameters, and qualifiers is preserved. The :attr:`~pywbem.CIMClass.path` attribute of this object will not be included in the returned MOF string. Consistent with that, class path information is not included in the returned MOF string. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "declaration", "of", "this", "CIM", "class", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L4240-L4286
train
28,381
pywbem/pywbem
pywbem/cim_obj.py
CIMProperty.tomof
def tomof( self, is_instance=True, indent=0, maxline=MAX_MOF_LINE, line_pos=0): """ Return a MOF string with the declaration of this CIM property for use in a CIM class, or the specification of this CIM property for use in a CIM instance. *New in pywbem 0.9.* Even though pywbem supports qualifiers on :class:`~pywbem.CIMProperty` objects that are used as property values within an instance, the returned MOF string for property values in instances does not contain any qualifier values. The order of qualifiers is preserved. Parameters: is_instance (bool): If `True`, return MOF for a property value in a CIM instance. Else, return MOF for a property definition in a CIM class. indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the property name. Returns: :term:`unicode string`: MOF string. """ mof = [] if is_instance: # Property value in an instance mof.append(_indent_str(indent)) mof.append(self.name) else: # Property declaration in a class if self.qualifiers: mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT, maxline)) mof.append(_indent_str(indent)) mof.append(moftype(self.type, self.reference_class)) mof.append(u' ') mof.append(self.name) if self.is_array: mof.append(u'[') if self.array_size is not None: mof.append(six.text_type(self.array_size)) mof.append(u']') # Generate the property value (nearly common for property values and # property declarations). if self.value is not None or is_instance: mof.append(u' =') if isinstance(self.value, list): mof.append(u' {') mof_str = u''.join(mof) line_pos = len(mof_str) - mof_str.rfind('\n') - 1 # Assume in line_pos that the extra space would be needed val_str, line_pos = _value_tomof( self.value, self.type, indent + MOF_INDENT, maxline, line_pos + 1, 1, True) # Empty arrays are represented as val_str='' if val_str and val_str[0] != '\n': # The extra space was actually needed mof.append(u' ') else: # Adjust by the extra space that was not needed line_pos -= 1 mof.append(val_str) mof.append(u' }') else: mof_str = u''.join(mof) line_pos = len(mof_str) - mof_str.rfind('\n') - 1 # Assume in line_pos that the extra space would be needed val_str, line_pos = _value_tomof( self.value, self.type, indent + MOF_INDENT, maxline, line_pos + 1, 1, True) # Scalars cannot be represented as val_str='' if val_str[0] != '\n': # The extra space was actually needed mof.append(u' ') else: # Adjust by the extra space that was not needed line_pos -= 1 mof.append(val_str) mof.append(';\n') return u''.join(mof)
python
def tomof( self, is_instance=True, indent=0, maxline=MAX_MOF_LINE, line_pos=0): """ Return a MOF string with the declaration of this CIM property for use in a CIM class, or the specification of this CIM property for use in a CIM instance. *New in pywbem 0.9.* Even though pywbem supports qualifiers on :class:`~pywbem.CIMProperty` objects that are used as property values within an instance, the returned MOF string for property values in instances does not contain any qualifier values. The order of qualifiers is preserved. Parameters: is_instance (bool): If `True`, return MOF for a property value in a CIM instance. Else, return MOF for a property definition in a CIM class. indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the property name. Returns: :term:`unicode string`: MOF string. """ mof = [] if is_instance: # Property value in an instance mof.append(_indent_str(indent)) mof.append(self.name) else: # Property declaration in a class if self.qualifiers: mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT, maxline)) mof.append(_indent_str(indent)) mof.append(moftype(self.type, self.reference_class)) mof.append(u' ') mof.append(self.name) if self.is_array: mof.append(u'[') if self.array_size is not None: mof.append(six.text_type(self.array_size)) mof.append(u']') # Generate the property value (nearly common for property values and # property declarations). if self.value is not None or is_instance: mof.append(u' =') if isinstance(self.value, list): mof.append(u' {') mof_str = u''.join(mof) line_pos = len(mof_str) - mof_str.rfind('\n') - 1 # Assume in line_pos that the extra space would be needed val_str, line_pos = _value_tomof( self.value, self.type, indent + MOF_INDENT, maxline, line_pos + 1, 1, True) # Empty arrays are represented as val_str='' if val_str and val_str[0] != '\n': # The extra space was actually needed mof.append(u' ') else: # Adjust by the extra space that was not needed line_pos -= 1 mof.append(val_str) mof.append(u' }') else: mof_str = u''.join(mof) line_pos = len(mof_str) - mof_str.rfind('\n') - 1 # Assume in line_pos that the extra space would be needed val_str, line_pos = _value_tomof( self.value, self.type, indent + MOF_INDENT, maxline, line_pos + 1, 1, True) # Scalars cannot be represented as val_str='' if val_str[0] != '\n': # The extra space was actually needed mof.append(u' ') else: # Adjust by the extra space that was not needed line_pos -= 1 mof.append(val_str) mof.append(';\n') return u''.join(mof)
[ "def", "tomof", "(", "self", ",", "is_instance", "=", "True", ",", "indent", "=", "0", ",", "maxline", "=", "MAX_MOF_LINE", ",", "line_pos", "=", "0", ")", ":", "mof", "=", "[", "]", "if", "is_instance", ":", "# Property value in an instance", "mof", "."...
Return a MOF string with the declaration of this CIM property for use in a CIM class, or the specification of this CIM property for use in a CIM instance. *New in pywbem 0.9.* Even though pywbem supports qualifiers on :class:`~pywbem.CIMProperty` objects that are used as property values within an instance, the returned MOF string for property values in instances does not contain any qualifier values. The order of qualifiers is preserved. Parameters: is_instance (bool): If `True`, return MOF for a property value in a CIM instance. Else, return MOF for a property definition in a CIM class. indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the property name. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "declaration", "of", "this", "CIM", "property", "for", "use", "in", "a", "CIM", "class", "or", "the", "specification", "of", "this", "CIM", "property", "for", "use", "in", "a", "CIM", "instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L4998-L5096
train
28,382
pywbem/pywbem
pywbem/cim_obj.py
CIMMethod.tomof
def tomof(self, indent=0, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM method for use in a CIM class declaration. The order of parameters and qualifiers is preserved. Parameters: indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the method name. Returns: :term:`unicode string`: MOF string. """ mof = [] if self.qualifiers: mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT, maxline)) mof.append(_indent_str(indent)) # return_type is ensured not to be None or reference mof.append(moftype(self.return_type, None)) mof.append(u' ') mof.append(self.name) if self.parameters.values(): mof.append(u'(\n') mof_parms = [] for p in self.parameters.itervalues(): mof_parms.append(p.tomof(indent + MOF_INDENT, maxline)) mof.append(u',\n'.join(mof_parms)) mof.append(u');\n') else: mof.append(u'();\n') return u''.join(mof)
python
def tomof(self, indent=0, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM method for use in a CIM class declaration. The order of parameters and qualifiers is preserved. Parameters: indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the method name. Returns: :term:`unicode string`: MOF string. """ mof = [] if self.qualifiers: mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT, maxline)) mof.append(_indent_str(indent)) # return_type is ensured not to be None or reference mof.append(moftype(self.return_type, None)) mof.append(u' ') mof.append(self.name) if self.parameters.values(): mof.append(u'(\n') mof_parms = [] for p in self.parameters.itervalues(): mof_parms.append(p.tomof(indent + MOF_INDENT, maxline)) mof.append(u',\n'.join(mof_parms)) mof.append(u');\n') else: mof.append(u'();\n') return u''.join(mof)
[ "def", "tomof", "(", "self", ",", "indent", "=", "0", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "mof", "=", "[", "]", "if", "self", ".", "qualifiers", ":", "mof", ".", "append", "(", "_qualifiers_tomof", "(", "self", ".", "qualifiers", ",", "ind...
Return a MOF string with the declaration of this CIM method for use in a CIM class declaration. The order of parameters and qualifiers is preserved. Parameters: indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the method name. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "declaration", "of", "this", "CIM", "method", "for", "use", "in", "a", "CIM", "class", "declaration", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L5647-L5688
train
28,383
pywbem/pywbem
pywbem/cim_obj.py
CIMParameter.tomof
def tomof(self, indent=0, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM parameter for use in a CIM method declaration. The object is always interpreted as a parameter declaration; so the :attr:`~pywbem.CIMParameter.value` and :attr:`~pywbem.CIMParameter.embedded_object` attributes are ignored. The order of qualifiers is preserved. Parameters: indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the parameter name. Returns: :term:`unicode string`: MOF string. """ mof = [] if self.qualifiers: mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT, maxline)) mof.append(_indent_str(indent)) mof.append(moftype(self.type, self.reference_class)) mof.append(u' ') mof.append(self.name) if self.is_array: mof.append(u'[') if self.array_size is not None: mof.append(six.text_type(self.array_size)) mof.append(u']') return u''.join(mof)
python
def tomof(self, indent=0, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM parameter for use in a CIM method declaration. The object is always interpreted as a parameter declaration; so the :attr:`~pywbem.CIMParameter.value` and :attr:`~pywbem.CIMParameter.embedded_object` attributes are ignored. The order of qualifiers is preserved. Parameters: indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the parameter name. Returns: :term:`unicode string`: MOF string. """ mof = [] if self.qualifiers: mof.append(_qualifiers_tomof(self.qualifiers, indent + MOF_INDENT, maxline)) mof.append(_indent_str(indent)) mof.append(moftype(self.type, self.reference_class)) mof.append(u' ') mof.append(self.name) if self.is_array: mof.append(u'[') if self.array_size is not None: mof.append(six.text_type(self.array_size)) mof.append(u']') return u''.join(mof)
[ "def", "tomof", "(", "self", ",", "indent", "=", "0", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "mof", "=", "[", "]", "if", "self", ".", "qualifiers", ":", "mof", ".", "append", "(", "_qualifiers_tomof", "(", "self", ".", "qualifiers", ",", "ind...
Return a MOF string with the declaration of this CIM parameter for use in a CIM method declaration. The object is always interpreted as a parameter declaration; so the :attr:`~pywbem.CIMParameter.value` and :attr:`~pywbem.CIMParameter.embedded_object` attributes are ignored. The order of qualifiers is preserved. Parameters: indent (:term:`integer`): Number of spaces to indent each line of the returned string, counted in the line with the parameter name. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "declaration", "of", "this", "CIM", "parameter", "for", "use", "in", "a", "CIM", "method", "declaration", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L6349-L6387
train
28,384
pywbem/pywbem
pywbem/cim_obj.py
CIMQualifier.tomof
def tomof(self, indent=MOF_INDENT, maxline=MAX_MOF_LINE, line_pos=0): """ Return a MOF string with the specification of this CIM qualifier as a qualifier value. The items of array values are tried to keep on the same line. If the generated line would exceed the maximum MOF line length, the value is split into multiple lines, on array item boundaries, and/or within long strings on word boundaries. If a string value (of a scalar value, or of an array item) is split into multiple lines, the first line of the value is put onto a line on its own. Parameters: indent (:term:`integer`): For a multi-line result, the number of spaces to indent each line except the first line (on which the qualifier name appears). For a single-line result, ignored. Returns: :term:`unicode string`: MOF string. """ mof = [] mof.append(self.name) mof.append(u' ') if isinstance(self.value, list): mof.append(u'{') else: mof.append(u'(') line_pos += len(u''.join(mof)) # Assume in line_pos that the extra space would be needed val_str, line_pos = _value_tomof( self.value, self.type, indent, maxline, line_pos + 1, 3, True) # Empty arrays are represented as val_str='' if val_str and val_str[0] != '\n': # The extra space was actually needed mof.append(u' ') else: # Adjust by the extra space that was not needed line_pos -= 1 mof.append(val_str) if isinstance(self.value, list): mof.append(u' }') else: mof.append(u' )') mof_str = u''.join(mof) return mof_str
python
def tomof(self, indent=MOF_INDENT, maxline=MAX_MOF_LINE, line_pos=0): """ Return a MOF string with the specification of this CIM qualifier as a qualifier value. The items of array values are tried to keep on the same line. If the generated line would exceed the maximum MOF line length, the value is split into multiple lines, on array item boundaries, and/or within long strings on word boundaries. If a string value (of a scalar value, or of an array item) is split into multiple lines, the first line of the value is put onto a line on its own. Parameters: indent (:term:`integer`): For a multi-line result, the number of spaces to indent each line except the first line (on which the qualifier name appears). For a single-line result, ignored. Returns: :term:`unicode string`: MOF string. """ mof = [] mof.append(self.name) mof.append(u' ') if isinstance(self.value, list): mof.append(u'{') else: mof.append(u'(') line_pos += len(u''.join(mof)) # Assume in line_pos that the extra space would be needed val_str, line_pos = _value_tomof( self.value, self.type, indent, maxline, line_pos + 1, 3, True) # Empty arrays are represented as val_str='' if val_str and val_str[0] != '\n': # The extra space was actually needed mof.append(u' ') else: # Adjust by the extra space that was not needed line_pos -= 1 mof.append(val_str) if isinstance(self.value, list): mof.append(u' }') else: mof.append(u' )') mof_str = u''.join(mof) return mof_str
[ "def", "tomof", "(", "self", ",", "indent", "=", "MOF_INDENT", ",", "maxline", "=", "MAX_MOF_LINE", ",", "line_pos", "=", "0", ")", ":", "mof", "=", "[", "]", "mof", ".", "append", "(", "self", ".", "name", ")", "mof", ".", "append", "(", "u' '", ...
Return a MOF string with the specification of this CIM qualifier as a qualifier value. The items of array values are tried to keep on the same line. If the generated line would exceed the maximum MOF line length, the value is split into multiple lines, on array item boundaries, and/or within long strings on word boundaries. If a string value (of a scalar value, or of an array item) is split into multiple lines, the first line of the value is put onto a line on its own. Parameters: indent (:term:`integer`): For a multi-line result, the number of spaces to indent each line except the first line (on which the qualifier name appears). For a single-line result, ignored. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "specification", "of", "this", "CIM", "qualifier", "as", "a", "qualifier", "value", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L6936-L6990
train
28,385
pywbem/pywbem
pywbem/cim_obj.py
CIMQualifierDeclaration.tomof
def tomof(self, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM qualifier type. The returned MOF string conforms to the ``qualifierDeclaration`` ABNF rule defined in :term:`DSP0004`. Qualifier flavors are included in the returned MOF string only when the information is available (i.e. the value of the corresponding attribute is not `None`). Because :term:`DSP0004` does not support instance qualifiers, and thus does not define a flavor keyword for the :attr:`~pywbem.CIMQualifierDeclaration.toinstance` attribute, that flavor is not included in the returned MOF string. Returns: :term:`unicode string`: MOF string. """ mof = [] mof.append(u'Qualifier ') mof.append(self.name) mof.append(u' : ') mof.append(self.type) if self.is_array: mof.append(u'[') if self.array_size is not None: mof.append(six.text_type(self.array_size)) mof.append(u']') if self.value is not None: mof.append(u' = ') if isinstance(self.value, list): mof.append(u'{ ') mof_str = u''.join(mof) line_pos = len(mof_str) - mof_str.rfind('\n') - 1 val_str, line_pos = _value_tomof( self.value, self.type, MOF_INDENT, maxline, line_pos, 3, False) mof.append(val_str) if isinstance(self.value, list): mof.append(u' }') mof.append(u',\n') mof.append(_indent_str(MOF_INDENT + 1)) mof.append(u'Scope(') mof_scopes = [] for scope in self._ordered_scopes: if self.scopes.get(scope, False): mof_scopes.append(scope.lower()) mof.append(u', '.join(mof_scopes)) mof.append(u')') # toinstance flavor not included here because not part of DSP0004 mof_flavors = [] if self.overridable is True: mof_flavors.append('EnableOverride') elif self.overridable is False: mof_flavors.append('DisableOverride') if self.tosubclass is True: mof_flavors.append('ToSubclass') elif self.tosubclass is False: mof_flavors.append('Restricted') if self.translatable: mof_flavors.append('Translatable') if mof_flavors: mof.append(u',\n') mof.append(_indent_str(MOF_INDENT + 1)) mof.append(u'Flavor(') mof.append(u', '.join(mof_flavors)) mof.append(u')') mof.append(u';\n') return u''.join(mof)
python
def tomof(self, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM qualifier type. The returned MOF string conforms to the ``qualifierDeclaration`` ABNF rule defined in :term:`DSP0004`. Qualifier flavors are included in the returned MOF string only when the information is available (i.e. the value of the corresponding attribute is not `None`). Because :term:`DSP0004` does not support instance qualifiers, and thus does not define a flavor keyword for the :attr:`~pywbem.CIMQualifierDeclaration.toinstance` attribute, that flavor is not included in the returned MOF string. Returns: :term:`unicode string`: MOF string. """ mof = [] mof.append(u'Qualifier ') mof.append(self.name) mof.append(u' : ') mof.append(self.type) if self.is_array: mof.append(u'[') if self.array_size is not None: mof.append(six.text_type(self.array_size)) mof.append(u']') if self.value is not None: mof.append(u' = ') if isinstance(self.value, list): mof.append(u'{ ') mof_str = u''.join(mof) line_pos = len(mof_str) - mof_str.rfind('\n') - 1 val_str, line_pos = _value_tomof( self.value, self.type, MOF_INDENT, maxline, line_pos, 3, False) mof.append(val_str) if isinstance(self.value, list): mof.append(u' }') mof.append(u',\n') mof.append(_indent_str(MOF_INDENT + 1)) mof.append(u'Scope(') mof_scopes = [] for scope in self._ordered_scopes: if self.scopes.get(scope, False): mof_scopes.append(scope.lower()) mof.append(u', '.join(mof_scopes)) mof.append(u')') # toinstance flavor not included here because not part of DSP0004 mof_flavors = [] if self.overridable is True: mof_flavors.append('EnableOverride') elif self.overridable is False: mof_flavors.append('DisableOverride') if self.tosubclass is True: mof_flavors.append('ToSubclass') elif self.tosubclass is False: mof_flavors.append('Restricted') if self.translatable: mof_flavors.append('Translatable') if mof_flavors: mof.append(u',\n') mof.append(_indent_str(MOF_INDENT + 1)) mof.append(u'Flavor(') mof.append(u', '.join(mof_flavors)) mof.append(u')') mof.append(u';\n') return u''.join(mof)
[ "def", "tomof", "(", "self", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "mof", "=", "[", "]", "mof", ".", "append", "(", "u'Qualifier '", ")", "mof", ".", "append", "(", "self", ".", "name", ")", "mof", ".", "append", "(", "u' : '", ")", "mof",...
Return a MOF string with the declaration of this CIM qualifier type. The returned MOF string conforms to the ``qualifierDeclaration`` ABNF rule defined in :term:`DSP0004`. Qualifier flavors are included in the returned MOF string only when the information is available (i.e. the value of the corresponding attribute is not `None`). Because :term:`DSP0004` does not support instance qualifiers, and thus does not define a flavor keyword for the :attr:`~pywbem.CIMQualifierDeclaration.toinstance` attribute, that flavor is not included in the returned MOF string. Returns: :term:`unicode string`: MOF string.
[ "Return", "a", "MOF", "string", "with", "the", "declaration", "of", "this", "CIM", "qualifier", "type", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L7616-L7701
train
28,386
pywbem/pywbem
try/compat_args.py
main
def main(): """Main function calls the test functs""" print("Python version %s" % sys.version) print("Testing compatibility for function defined with *args") test_func_args(func_old_args) test_func_args(func_new) print("Testing compatibility for function defined with **kwargs") test_func_kwargs(func_old_kwargs) test_func_kwargs(func_new) print("All tests successful - we can change *args and **kwargs to' \ ' named args.") return 0
python
def main(): """Main function calls the test functs""" print("Python version %s" % sys.version) print("Testing compatibility for function defined with *args") test_func_args(func_old_args) test_func_args(func_new) print("Testing compatibility for function defined with **kwargs") test_func_kwargs(func_old_kwargs) test_func_kwargs(func_new) print("All tests successful - we can change *args and **kwargs to' \ ' named args.") return 0
[ "def", "main", "(", ")", ":", "print", "(", "\"Python version %s\"", "%", "sys", ".", "version", ")", "print", "(", "\"Testing compatibility for function defined with *args\"", ")", "test_func_args", "(", "func_old_args", ")", "test_func_args", "(", "func_new", ")", ...
Main function calls the test functs
[ "Main", "function", "calls", "the", "test", "functs" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/compat_args.py#L93-L108
train
28,387
pywbem/pywbem
pywbem_mock/_resolvermixin.py
ResolverMixin._validate_qualifiers
def _validate_qualifiers(qualifier_list, qual_repo, new_class, scope): """ Validate a list of qualifiers against the Qualifier decl in the repository. 1. Whether it is declared (can be obtained from the declContext). 2. Whether it has the same type as the declaration. 3. Whether the qualifier is valid for the given scope. 4. Whether the qualifier can be overridden. 5. Whether the qualifier should be propagated to the subclass. """ for qname, qvalue in qualifier_list.items(): if qname not in qual_repo: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Qualifier {0|A} in new_class {1|A} in " "CreateClass not in repository.", (qname, new_class.classnam))) q_decl = qual_repo[qname] if qvalue.type != q_decl.type: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Qualifier {0|A} in new_class {1|A} override type " "mismatch {2|A} with qualifier declaration {3|A}.", (qname, new_class.classname, qvalue.type, q_decl.type))) if scope not in q_decl.scopes: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Qualifier {0|A} in new class {1|A} scope {2|A} " "invalid. Not in qualifier decl scopes {3}", (qname, new_class.classname, scope, q_decl.scopes)))
python
def _validate_qualifiers(qualifier_list, qual_repo, new_class, scope): """ Validate a list of qualifiers against the Qualifier decl in the repository. 1. Whether it is declared (can be obtained from the declContext). 2. Whether it has the same type as the declaration. 3. Whether the qualifier is valid for the given scope. 4. Whether the qualifier can be overridden. 5. Whether the qualifier should be propagated to the subclass. """ for qname, qvalue in qualifier_list.items(): if qname not in qual_repo: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Qualifier {0|A} in new_class {1|A} in " "CreateClass not in repository.", (qname, new_class.classnam))) q_decl = qual_repo[qname] if qvalue.type != q_decl.type: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Qualifier {0|A} in new_class {1|A} override type " "mismatch {2|A} with qualifier declaration {3|A}.", (qname, new_class.classname, qvalue.type, q_decl.type))) if scope not in q_decl.scopes: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Qualifier {0|A} in new class {1|A} scope {2|A} " "invalid. Not in qualifier decl scopes {3}", (qname, new_class.classname, scope, q_decl.scopes)))
[ "def", "_validate_qualifiers", "(", "qualifier_list", ",", "qual_repo", ",", "new_class", ",", "scope", ")", ":", "for", "qname", ",", "qvalue", "in", "qualifier_list", ".", "items", "(", ")", ":", "if", "qname", "not", "in", "qual_repo", ":", "raise", "CI...
Validate a list of qualifiers against the Qualifier decl in the repository. 1. Whether it is declared (can be obtained from the declContext). 2. Whether it has the same type as the declaration. 3. Whether the qualifier is valid for the given scope. 4. Whether the qualifier can be overridden. 5. Whether the qualifier should be propagated to the subclass.
[ "Validate", "a", "list", "of", "qualifiers", "against", "the", "Qualifier", "decl", "in", "the", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_resolvermixin.py#L95-L126
train
28,388
pywbem/pywbem
pywbem_mock/_resolvermixin.py
ResolverMixin._init_qualifier
def _init_qualifier(qualifier, qual_repo): """ Initialize the flavors of a qualifier from the qualifier repo and initialize propagated. """ qual_dict_entry = qual_repo[qualifier.name] qualifier.propagated = False if qualifier.tosubclass is None: if qual_dict_entry.tosubclass is None: qualifier.tosubclass = True else: qualifier.tosubclass = qual_dict_entry.tosubclass if qualifier.overridable is None: if qual_dict_entry.overridable is None: qualifier.overridable = True else: qualifier.overridable = qual_dict_entry.overridable if qualifier.translatable is None: qualifier.translatable = qual_dict_entry.translatable
python
def _init_qualifier(qualifier, qual_repo): """ Initialize the flavors of a qualifier from the qualifier repo and initialize propagated. """ qual_dict_entry = qual_repo[qualifier.name] qualifier.propagated = False if qualifier.tosubclass is None: if qual_dict_entry.tosubclass is None: qualifier.tosubclass = True else: qualifier.tosubclass = qual_dict_entry.tosubclass if qualifier.overridable is None: if qual_dict_entry.overridable is None: qualifier.overridable = True else: qualifier.overridable = qual_dict_entry.overridable if qualifier.translatable is None: qualifier.translatable = qual_dict_entry.translatable
[ "def", "_init_qualifier", "(", "qualifier", ",", "qual_repo", ")", ":", "qual_dict_entry", "=", "qual_repo", "[", "qualifier", ".", "name", "]", "qualifier", ".", "propagated", "=", "False", "if", "qualifier", ".", "tosubclass", "is", "None", ":", "if", "qua...
Initialize the flavors of a qualifier from the qualifier repo and initialize propagated.
[ "Initialize", "the", "flavors", "of", "a", "qualifier", "from", "the", "qualifier", "repo", "and", "initialize", "propagated", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_resolvermixin.py#L129-L147
train
28,389
pywbem/pywbem
pywbem_mock/_resolvermixin.py
ResolverMixin._init_qualifier_decl
def _init_qualifier_decl(qualifier_decl, qual_repo): """ Initialize the flavors of a qualifier declaration if they are not already set. """ assert qualifier_decl.name not in qual_repo if qualifier_decl.tosubclass is None: qualifier_decl.tosubclass = True if qualifier_decl.overridable is None: qualifier_decl.overridable = True if qualifier_decl.translatable is None: qualifier_decl.translatable = False
python
def _init_qualifier_decl(qualifier_decl, qual_repo): """ Initialize the flavors of a qualifier declaration if they are not already set. """ assert qualifier_decl.name not in qual_repo if qualifier_decl.tosubclass is None: qualifier_decl.tosubclass = True if qualifier_decl.overridable is None: qualifier_decl.overridable = True if qualifier_decl.translatable is None: qualifier_decl.translatable = False
[ "def", "_init_qualifier_decl", "(", "qualifier_decl", ",", "qual_repo", ")", ":", "assert", "qualifier_decl", ".", "name", "not", "in", "qual_repo", "if", "qualifier_decl", ".", "tosubclass", "is", "None", ":", "qualifier_decl", ".", "tosubclass", "=", "True", "...
Initialize the flavors of a qualifier declaration if they are not already set.
[ "Initialize", "the", "flavors", "of", "a", "qualifier", "declaration", "if", "they", "are", "not", "already", "set", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_resolvermixin.py#L150-L161
train
28,390
pywbem/pywbem
pywbem_mock/_resolvermixin.py
ResolverMixin._set_new_object
def _set_new_object(self, new_obj, inherited_obj, new_class, superclass, qualifier_repo, propagated, type_str): """ Set the object attributes for a single object and resolve the qualifiers. This sets attributes for Properties, Methods, and Parameters. """ assert isinstance(new_obj, (CIMMethod, CIMProperty, CIMParameter)) if inherited_obj: inherited_obj_qual = inherited_obj.qualifiers else: inherited_obj_qual = None if propagated: assert superclass is not None new_obj.propagated = propagated if propagated: assert inherited_obj is not None new_obj.class_origin = inherited_obj.class_origin else: assert inherited_obj is None new_obj.class_origin = new_class.classname self._resolve_qualifiers(new_obj.qualifiers, inherited_obj_qual, new_class, superclass, new_obj.name, type_str, qualifier_repo, propagate=propagated)
python
def _set_new_object(self, new_obj, inherited_obj, new_class, superclass, qualifier_repo, propagated, type_str): """ Set the object attributes for a single object and resolve the qualifiers. This sets attributes for Properties, Methods, and Parameters. """ assert isinstance(new_obj, (CIMMethod, CIMProperty, CIMParameter)) if inherited_obj: inherited_obj_qual = inherited_obj.qualifiers else: inherited_obj_qual = None if propagated: assert superclass is not None new_obj.propagated = propagated if propagated: assert inherited_obj is not None new_obj.class_origin = inherited_obj.class_origin else: assert inherited_obj is None new_obj.class_origin = new_class.classname self._resolve_qualifiers(new_obj.qualifiers, inherited_obj_qual, new_class, superclass, new_obj.name, type_str, qualifier_repo, propagate=propagated)
[ "def", "_set_new_object", "(", "self", ",", "new_obj", ",", "inherited_obj", ",", "new_class", ",", "superclass", ",", "qualifier_repo", ",", "propagated", ",", "type_str", ")", ":", "assert", "isinstance", "(", "new_obj", ",", "(", "CIMMethod", ",", "CIMPrope...
Set the object attributes for a single object and resolve the qualifiers. This sets attributes for Properties, Methods, and Parameters.
[ "Set", "the", "object", "attributes", "for", "a", "single", "object", "and", "resolve", "the", "qualifiers", ".", "This", "sets", "attributes", "for", "Properties", "Methods", "and", "Parameters", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_resolvermixin.py#L297-L326
train
28,391
pywbem/pywbem
pywbem_mock/_resolvermixin.py
ResolverMixin._resolve_qualifiers
def _resolve_qualifiers(self, new_quals, inherited_quals, new_class, super_class, obj_name, obj_type, qualifier_repo, propagate=False, verbose=False): """ Process the override of qualifiers from the inherited_quals dictionary to the new_quals dict following the override rules in DSP0004. """ superclassname = super_class.classname if super_class else None # TODO Diagnostic we will keep until really sure of this code if verbose: print("\nRESOLVE sc_name=%s nc_name=%s, obj_name=%s obj_type=%s " " propagate=%s" % (superclassname, new_class.classname, obj_name, obj_type, propagate)) print('\nNEW QUAL') for q, qv in new_quals.items(): print(' %s: %r' % (q, qv)) print('INHERITEDQ:') if inherited_quals: for q, qv in inherited_quals.items(): print(' %s: %r' % (q, qv)) # If propagate flag not set, initialize the qualfiers # by setting flavor defaults and propagated False if not propagate: for qname, qvalue in new_quals.items(): self._init_qualifier(qvalue, qualifier_repo) return # resolve qualifiers not in inherited object for qname, qvalue in new_quals.items(): if not inherited_quals or qname not in inherited_quals: self._init_qualifier(qvalue, qualifier_repo) # resolve qualifiers from inherited object for inh_qname, inh_qvalue in inherited_quals.items(): if inh_qvalue.tosubclass: if inh_qvalue.overridable: # if not in new quals, copy it to the new quals, else ignore if inh_qname not in new_quals: new_quals[inh_qname] = inherited_quals[inh_qname].copy() new_quals[inh_qname].propagated = True else: new_quals[inh_qname].propagated = False self._init_qualifier(new_quals[inh_qname], qualifier_repo) else: # not overridable if inh_qname in new_quals: # allow for same qualifier def in subclass # TODO should more than value match here.?? if new_quals[inh_qname].value != \ inherited_quals[inh_qname].value: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Invalid new_class {0!A}:{1!A} " "qualifier {2!A}. " "in class {3!A}. Not overridable ", obj_type, obj_name, inh_qname, new_class.classname)) else: new_quals[inh_qname].propagated = True else: # not in new class, add it new_quals[inh_qname] = inherited_quals[inh_qname].copy() new_quals[inh_qname].propagated = True else: # not tosubclass, i.e. restricted. if inh_qname in new_quals: if inh_qvalue.overridable or inh_qvalue.overridable is None: new_quals[inh_qname].propagated = True else: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Invalid qualifier object {0!A} qualifier " "{1!A} . Restricted in super class {2!A}", obj_name, inh_qname, superclassname))
python
def _resolve_qualifiers(self, new_quals, inherited_quals, new_class, super_class, obj_name, obj_type, qualifier_repo, propagate=False, verbose=False): """ Process the override of qualifiers from the inherited_quals dictionary to the new_quals dict following the override rules in DSP0004. """ superclassname = super_class.classname if super_class else None # TODO Diagnostic we will keep until really sure of this code if verbose: print("\nRESOLVE sc_name=%s nc_name=%s, obj_name=%s obj_type=%s " " propagate=%s" % (superclassname, new_class.classname, obj_name, obj_type, propagate)) print('\nNEW QUAL') for q, qv in new_quals.items(): print(' %s: %r' % (q, qv)) print('INHERITEDQ:') if inherited_quals: for q, qv in inherited_quals.items(): print(' %s: %r' % (q, qv)) # If propagate flag not set, initialize the qualfiers # by setting flavor defaults and propagated False if not propagate: for qname, qvalue in new_quals.items(): self._init_qualifier(qvalue, qualifier_repo) return # resolve qualifiers not in inherited object for qname, qvalue in new_quals.items(): if not inherited_quals or qname not in inherited_quals: self._init_qualifier(qvalue, qualifier_repo) # resolve qualifiers from inherited object for inh_qname, inh_qvalue in inherited_quals.items(): if inh_qvalue.tosubclass: if inh_qvalue.overridable: # if not in new quals, copy it to the new quals, else ignore if inh_qname not in new_quals: new_quals[inh_qname] = inherited_quals[inh_qname].copy() new_quals[inh_qname].propagated = True else: new_quals[inh_qname].propagated = False self._init_qualifier(new_quals[inh_qname], qualifier_repo) else: # not overridable if inh_qname in new_quals: # allow for same qualifier def in subclass # TODO should more than value match here.?? if new_quals[inh_qname].value != \ inherited_quals[inh_qname].value: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Invalid new_class {0!A}:{1!A} " "qualifier {2!A}. " "in class {3!A}. Not overridable ", obj_type, obj_name, inh_qname, new_class.classname)) else: new_quals[inh_qname].propagated = True else: # not in new class, add it new_quals[inh_qname] = inherited_quals[inh_qname].copy() new_quals[inh_qname].propagated = True else: # not tosubclass, i.e. restricted. if inh_qname in new_quals: if inh_qvalue.overridable or inh_qvalue.overridable is None: new_quals[inh_qname].propagated = True else: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format("Invalid qualifier object {0!A} qualifier " "{1!A} . Restricted in super class {2!A}", obj_name, inh_qname, superclassname))
[ "def", "_resolve_qualifiers", "(", "self", ",", "new_quals", ",", "inherited_quals", ",", "new_class", ",", "super_class", ",", "obj_name", ",", "obj_type", ",", "qualifier_repo", ",", "propagate", "=", "False", ",", "verbose", "=", "False", ")", ":", "supercl...
Process the override of qualifiers from the inherited_quals dictionary to the new_quals dict following the override rules in DSP0004.
[ "Process", "the", "override", "of", "qualifiers", "from", "the", "inherited_quals", "dictionary", "to", "the", "new_quals", "dict", "following", "the", "override", "rules", "in", "DSP0004", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_resolvermixin.py#L328-L406
train
28,392
pywbem/pywbem
pywbem/cim_operations.py
_validateIterCommonParams
def _validateIterCommonParams(MaxObjectCount, OperationTimeout): """ Validate common parameters for an iter... operation. MaxObjectCount must be a positive non-zero integer or None. OperationTimeout must be positive integer or zero Raises: ValueError: if these parameters are invalid """ if MaxObjectCount is None or MaxObjectCount <= 0: raise ValueError( _format("MaxObjectCount must be > 0 but is {0}", MaxObjectCount)) if OperationTimeout is not None and OperationTimeout < 0: raise ValueError( _format("OperationTimeout must be >= 0 but is {0}", OperationTimeout))
python
def _validateIterCommonParams(MaxObjectCount, OperationTimeout): """ Validate common parameters for an iter... operation. MaxObjectCount must be a positive non-zero integer or None. OperationTimeout must be positive integer or zero Raises: ValueError: if these parameters are invalid """ if MaxObjectCount is None or MaxObjectCount <= 0: raise ValueError( _format("MaxObjectCount must be > 0 but is {0}", MaxObjectCount)) if OperationTimeout is not None and OperationTimeout < 0: raise ValueError( _format("OperationTimeout must be >= 0 but is {0}", OperationTimeout))
[ "def", "_validateIterCommonParams", "(", "MaxObjectCount", ",", "OperationTimeout", ")", ":", "if", "MaxObjectCount", "is", "None", "or", "MaxObjectCount", "<=", "0", ":", "raise", "ValueError", "(", "_format", "(", "\"MaxObjectCount must be > 0 but is {0}\"", ",", "M...
Validate common parameters for an iter... operation. MaxObjectCount must be a positive non-zero integer or None. OperationTimeout must be positive integer or zero Raises: ValueError: if these parameters are invalid
[ "Validate", "common", "parameters", "for", "an", "iter", "...", "operation", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L225-L244
train
28,393
pywbem/pywbem
pywbem/cim_operations.py
_validatePullParams
def _validatePullParams(MaxObjectCount, context): """ Validate the input paramaters for the PullInstances, PullInstancesWithPath, and PullInstancePaths requests. MaxObjectCount: Must be integer type and ge 0 context: Must be not None and length ge 2 """ if (not isinstance(MaxObjectCount, six.integer_types) or MaxObjectCount < 0): raise ValueError( _format("MaxObjectCount parameter must be integer >= 0 but is " "{0!A}", MaxObjectCount)) if context is None or len(context) < 2: raise ValueError( _format("Pull... Context parameter must be valid tuple {0!A}", context))
python
def _validatePullParams(MaxObjectCount, context): """ Validate the input paramaters for the PullInstances, PullInstancesWithPath, and PullInstancePaths requests. MaxObjectCount: Must be integer type and ge 0 context: Must be not None and length ge 2 """ if (not isinstance(MaxObjectCount, six.integer_types) or MaxObjectCount < 0): raise ValueError( _format("MaxObjectCount parameter must be integer >= 0 but is " "{0!A}", MaxObjectCount)) if context is None or len(context) < 2: raise ValueError( _format("Pull... Context parameter must be valid tuple {0!A}", context))
[ "def", "_validatePullParams", "(", "MaxObjectCount", ",", "context", ")", ":", "if", "(", "not", "isinstance", "(", "MaxObjectCount", ",", "six", ".", "integer_types", ")", "or", "MaxObjectCount", "<", "0", ")", ":", "raise", "ValueError", "(", "_format", "(...
Validate the input paramaters for the PullInstances, PullInstancesWithPath, and PullInstancePaths requests. MaxObjectCount: Must be integer type and ge 0 context: Must be not None and length ge 2
[ "Validate", "the", "input", "paramaters", "for", "the", "PullInstances", "PullInstancesWithPath", "and", "PullInstancePaths", "requests", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L247-L264
train
28,394
pywbem/pywbem
pywbem/cim_operations.py
is_subclass
def is_subclass(ch, ns, super_class, sub): """Determine if one class is a subclass of another class. Parameters: ch: A CIMOMHandle. Either a pycimmb.CIMOMHandle or a :class:`~pywbem.WBEMConnection` object. ns (:term:`string`): Namespace (case independent). super_class (:term:`string`): Super class name (case independent). sub: The subclass. This can either be a string or a :class:`~pywbem.CIMClass` object. Returns: :class:`py:bool`: Boolean True if the assertion is True (sub is a subclass of super_class) or False if it is not a subclass. Raises: CIMError if the the sub is not a valid class in the repo """ lsuper = super_class.lower() if isinstance(sub, CIMClass): subname = sub.classname subclass = sub else: subname = sub subclass = None if subname.lower() == lsuper: return True if subclass is None: subclass = ch.GetClass(subname, ns, LocalOnly=True, IncludeQualifiers=False, PropertyList=[], IncludeClassOrigin=False) while subclass.superclass is not None: if subclass.superclass.lower() == lsuper: return True subclass = ch.GetClass(subclass.superclass, ns, LocalOnly=True, IncludeQualifiers=False, PropertyList=[], IncludeClassOrigin=False) return False
python
def is_subclass(ch, ns, super_class, sub): """Determine if one class is a subclass of another class. Parameters: ch: A CIMOMHandle. Either a pycimmb.CIMOMHandle or a :class:`~pywbem.WBEMConnection` object. ns (:term:`string`): Namespace (case independent). super_class (:term:`string`): Super class name (case independent). sub: The subclass. This can either be a string or a :class:`~pywbem.CIMClass` object. Returns: :class:`py:bool`: Boolean True if the assertion is True (sub is a subclass of super_class) or False if it is not a subclass. Raises: CIMError if the the sub is not a valid class in the repo """ lsuper = super_class.lower() if isinstance(sub, CIMClass): subname = sub.classname subclass = sub else: subname = sub subclass = None if subname.lower() == lsuper: return True if subclass is None: subclass = ch.GetClass(subname, ns, LocalOnly=True, IncludeQualifiers=False, PropertyList=[], IncludeClassOrigin=False) while subclass.superclass is not None: if subclass.superclass.lower() == lsuper: return True subclass = ch.GetClass(subclass.superclass, ns, LocalOnly=True, IncludeQualifiers=False, PropertyList=[], IncludeClassOrigin=False) return False
[ "def", "is_subclass", "(", "ch", ",", "ns", ",", "super_class", ",", "sub", ")", ":", "lsuper", "=", "super_class", ".", "lower", "(", ")", "if", "isinstance", "(", "sub", ",", "CIMClass", ")", ":", "subname", "=", "sub", ".", "classname", "subclass", ...
Determine if one class is a subclass of another class. Parameters: ch: A CIMOMHandle. Either a pycimmb.CIMOMHandle or a :class:`~pywbem.WBEMConnection` object. ns (:term:`string`): Namespace (case independent). super_class (:term:`string`): Super class name (case independent). sub: The subclass. This can either be a string or a :class:`~pywbem.CIMClass` object. Returns: :class:`py:bool`: Boolean True if the assertion is True (sub is a subclass of super_class) or False if it is not a subclass. Raises: CIMError if the the sub is not a valid class in the repo
[ "Determine", "if", "one", "class", "is", "a", "subclass", "of", "another", "class", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L9740-L9791
train
28,395
pywbem/pywbem
pywbem/cim_operations.py
WBEMConnection._set_default_namespace
def _set_default_namespace(self, default_namespace): """Internal setter function.""" if default_namespace is not None: default_namespace = default_namespace.strip('/') else: default_namespace = DEFAULT_NAMESPACE self._default_namespace = _ensure_unicode(default_namespace)
python
def _set_default_namespace(self, default_namespace): """Internal setter function.""" if default_namespace is not None: default_namespace = default_namespace.strip('/') else: default_namespace = DEFAULT_NAMESPACE self._default_namespace = _ensure_unicode(default_namespace)
[ "def", "_set_default_namespace", "(", "self", ",", "default_namespace", ")", ":", "if", "default_namespace", "is", "not", "None", ":", "default_namespace", "=", "default_namespace", ".", "strip", "(", "'/'", ")", "else", ":", "default_namespace", "=", "DEFAULT_NAM...
Internal setter function.
[ "Internal", "setter", "function", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L760-L766
train
28,396
pywbem/pywbem
pywbem/cim_operations.py
WBEMConnection._configure_detail_level
def _configure_detail_level(cls, detail_level): """ Validate the `detail_level` parameter and return it. This accepts a string or integer for `detail_level`. """ # process detail_level if isinstance(detail_level, six.string_types): if detail_level not in LOG_DETAIL_LEVELS: raise ValueError( _format("Invalid log detail level string: {0!A}; must be " "one of: {1!A}", detail_level, LOG_DETAIL_LEVELS)) elif isinstance(detail_level, int): if detail_level < 0: raise ValueError( _format("Invalid log detail level integer: {0}; must be a " "positive integer.", detail_level)) elif detail_level is None: detail_level = DEFAULT_LOG_DETAIL_LEVEL else: raise ValueError( _format("Invalid log detail level: {0!A}; must be one of: " "{1!A}, or a positive integer", detail_level, LOG_DETAIL_LEVELS)) return detail_level
python
def _configure_detail_level(cls, detail_level): """ Validate the `detail_level` parameter and return it. This accepts a string or integer for `detail_level`. """ # process detail_level if isinstance(detail_level, six.string_types): if detail_level not in LOG_DETAIL_LEVELS: raise ValueError( _format("Invalid log detail level string: {0!A}; must be " "one of: {1!A}", detail_level, LOG_DETAIL_LEVELS)) elif isinstance(detail_level, int): if detail_level < 0: raise ValueError( _format("Invalid log detail level integer: {0}; must be a " "positive integer.", detail_level)) elif detail_level is None: detail_level = DEFAULT_LOG_DETAIL_LEVEL else: raise ValueError( _format("Invalid log detail level: {0!A}; must be one of: " "{1!A}, or a positive integer", detail_level, LOG_DETAIL_LEVELS)) return detail_level
[ "def", "_configure_detail_level", "(", "cls", ",", "detail_level", ")", ":", "# process detail_level", "if", "isinstance", "(", "detail_level", ",", "six", ".", "string_types", ")", ":", "if", "detail_level", "not", "in", "LOG_DETAIL_LEVELS", ":", "raise", "ValueE...
Validate the `detail_level` parameter and return it. This accepts a string or integer for `detail_level`.
[ "Validate", "the", "detail_level", "parameter", "and", "return", "it", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L1397-L1422
train
28,397
pywbem/pywbem
pywbem/cim_operations.py
WBEMConnection._configure_logger_handler
def _configure_logger_handler(cls, log_dest, log_filename): """ Return a logging handler for the specified `log_dest`, or `None` if `log_dest` is `None`. """ if log_dest is None: return None msg_format = '%(asctime)s-%(name)s-%(message)s' if log_dest == 'stderr': # Note: sys.stderr is the default stream for StreamHandler handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(msg_format)) elif log_dest == 'file': if not log_filename: raise ValueError("Log filename is required if log destination " "is 'file'") handler = logging.FileHandler(log_filename, encoding="UTF-8") handler.setFormatter(logging.Formatter(msg_format)) else: raise ValueError( _format("Invalid log destination: {0!A}; Must be one of: " "{1!A}", log_dest, LOG_DESTINATIONS)) return handler
python
def _configure_logger_handler(cls, log_dest, log_filename): """ Return a logging handler for the specified `log_dest`, or `None` if `log_dest` is `None`. """ if log_dest is None: return None msg_format = '%(asctime)s-%(name)s-%(message)s' if log_dest == 'stderr': # Note: sys.stderr is the default stream for StreamHandler handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(msg_format)) elif log_dest == 'file': if not log_filename: raise ValueError("Log filename is required if log destination " "is 'file'") handler = logging.FileHandler(log_filename, encoding="UTF-8") handler.setFormatter(logging.Formatter(msg_format)) else: raise ValueError( _format("Invalid log destination: {0!A}; Must be one of: " "{1!A}", log_dest, LOG_DESTINATIONS)) return handler
[ "def", "_configure_logger_handler", "(", "cls", ",", "log_dest", ",", "log_filename", ")", ":", "if", "log_dest", "is", "None", ":", "return", "None", "msg_format", "=", "'%(asctime)s-%(name)s-%(message)s'", "if", "log_dest", "==", "'stderr'", ":", "# Note: sys.stde...
Return a logging handler for the specified `log_dest`, or `None` if `log_dest` is `None`.
[ "Return", "a", "logging", "handler", "for", "the", "specified", "log_dest", "or", "None", "if", "log_dest", "is", "None", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L1425-L1451
train
28,398
pywbem/pywbem
pywbem/cim_operations.py
WBEMConnection._activate_logger
def _activate_logger(cls, logger_name, simple_name, detail_level, handler, connection, propagate): """ Configure the specified logger, and activate logging and set detail level for connections. The specified logger is always a single pywbem logger; the simple logger name 'all' has already been resolved by the caller into multiple calls to this method. The 'handler' parameter controls logger configuration: * If None, nothing is done. * If a Handler object, the specified logger gets its handlers replaced with the new handler, and logging level DEBUG is set, and the `propagate` attribute of the logger is set according to the `propagate` parameter. The 'connection' paraneter controls activation and setting of the detail level: * If None, nothing is done. * If bool=True, log activation and log detail information is stored for use by future connections in class variables of WBEMConnection. * If bool=False, log activation and log detail information is reset. * If a WBEMConnection object, logging is activated and detail level is set immediately for that connection. """ if handler is not None: assert isinstance(handler, logging.Handler) # Replace existing handlers of the specified logger (e.g. from # previous calls) by the specified handler logger = logging.getLogger(logger_name) for hdlr in logger.handlers: logger.removeHandler(hdlr) logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.propagate = propagate if connection is not None: if isinstance(connection, bool): if connection: # Store the activation and detail level information for # future connections. This information is used in the init # method of WBEMConnection to activate logging at that # point. cls._activate_logging = True cls._log_detail_levels[simple_name] = detail_level else: cls._reset_logging_config() else: assert isinstance(connection, WBEMConnection) # Activate logging for this existing connection by ensuring # the connection has a log recorder recorder_found = False # pylint: disable=protected-access for recorder in connection._operation_recorders: if isinstance(recorder, LogOperationRecorder): recorder_found = True break if not recorder_found: recorder = LogOperationRecorder(conn_id=connection.conn_id) # Add the log detail level for this logger to the log recorder # of this connection detail_levels = recorder.detail_levels.copy() detail_levels[simple_name] = detail_level recorder.set_detail_level(detail_levels) if not recorder_found: # This call must be made after the detail levels of the # recorder have been set, because that data is used # for recording the WBEM connection information. connection.add_operation_recorder(recorder)
python
def _activate_logger(cls, logger_name, simple_name, detail_level, handler, connection, propagate): """ Configure the specified logger, and activate logging and set detail level for connections. The specified logger is always a single pywbem logger; the simple logger name 'all' has already been resolved by the caller into multiple calls to this method. The 'handler' parameter controls logger configuration: * If None, nothing is done. * If a Handler object, the specified logger gets its handlers replaced with the new handler, and logging level DEBUG is set, and the `propagate` attribute of the logger is set according to the `propagate` parameter. The 'connection' paraneter controls activation and setting of the detail level: * If None, nothing is done. * If bool=True, log activation and log detail information is stored for use by future connections in class variables of WBEMConnection. * If bool=False, log activation and log detail information is reset. * If a WBEMConnection object, logging is activated and detail level is set immediately for that connection. """ if handler is not None: assert isinstance(handler, logging.Handler) # Replace existing handlers of the specified logger (e.g. from # previous calls) by the specified handler logger = logging.getLogger(logger_name) for hdlr in logger.handlers: logger.removeHandler(hdlr) logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.propagate = propagate if connection is not None: if isinstance(connection, bool): if connection: # Store the activation and detail level information for # future connections. This information is used in the init # method of WBEMConnection to activate logging at that # point. cls._activate_logging = True cls._log_detail_levels[simple_name] = detail_level else: cls._reset_logging_config() else: assert isinstance(connection, WBEMConnection) # Activate logging for this existing connection by ensuring # the connection has a log recorder recorder_found = False # pylint: disable=protected-access for recorder in connection._operation_recorders: if isinstance(recorder, LogOperationRecorder): recorder_found = True break if not recorder_found: recorder = LogOperationRecorder(conn_id=connection.conn_id) # Add the log detail level for this logger to the log recorder # of this connection detail_levels = recorder.detail_levels.copy() detail_levels[simple_name] = detail_level recorder.set_detail_level(detail_levels) if not recorder_found: # This call must be made after the detail levels of the # recorder have been set, because that data is used # for recording the WBEM connection information. connection.add_operation_recorder(recorder)
[ "def", "_activate_logger", "(", "cls", ",", "logger_name", ",", "simple_name", ",", "detail_level", ",", "handler", ",", "connection", ",", "propagate", ")", ":", "if", "handler", "is", "not", "None", ":", "assert", "isinstance", "(", "handler", ",", "loggin...
Configure the specified logger, and activate logging and set detail level for connections. The specified logger is always a single pywbem logger; the simple logger name 'all' has already been resolved by the caller into multiple calls to this method. The 'handler' parameter controls logger configuration: * If None, nothing is done. * If a Handler object, the specified logger gets its handlers replaced with the new handler, and logging level DEBUG is set, and the `propagate` attribute of the logger is set according to the `propagate` parameter. The 'connection' paraneter controls activation and setting of the detail level: * If None, nothing is done. * If bool=True, log activation and log detail information is stored for use by future connections in class variables of WBEMConnection. * If bool=False, log activation and log detail information is reset. * If a WBEMConnection object, logging is activated and detail level is set immediately for that connection.
[ "Configure", "the", "specified", "logger", "and", "activate", "logging", "and", "set", "detail", "level", "for", "connections", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L1454-L1533
train
28,399