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
wavefrontHQ/python-client
wavefront_api_client/models/search_query.py
SearchQuery.matching_method
def matching_method(self, matching_method): """Sets the matching_method of this SearchQuery. The method by which search matching is performed. Default: CONTAINS # noqa: E501 :param matching_method: The matching_method of this SearchQuery. # noqa: E501 :type: str """ allowed_values = ["CONTAINS", "STARTSWITH", "EXACT", "TAGPATH"] # noqa: E501 if matching_method not in allowed_values: raise ValueError( "Invalid value for `matching_method` ({0}), must be one of {1}" # noqa: E501 .format(matching_method, allowed_values) ) self._matching_method = matching_method
python
def matching_method(self, matching_method): """Sets the matching_method of this SearchQuery. The method by which search matching is performed. Default: CONTAINS # noqa: E501 :param matching_method: The matching_method of this SearchQuery. # noqa: E501 :type: str """ allowed_values = ["CONTAINS", "STARTSWITH", "EXACT", "TAGPATH"] # noqa: E501 if matching_method not in allowed_values: raise ValueError( "Invalid value for `matching_method` ({0}), must be one of {1}" # noqa: E501 .format(matching_method, allowed_values) ) self._matching_method = matching_method
[ "def", "matching_method", "(", "self", ",", "matching_method", ")", ":", "allowed_values", "=", "[", "\"CONTAINS\"", ",", "\"STARTSWITH\"", ",", "\"EXACT\"", ",", "\"TAGPATH\"", "]", "# noqa: E501", "if", "matching_method", "not", "in", "allowed_values", ":", "rai...
Sets the matching_method of this SearchQuery. The method by which search matching is performed. Default: CONTAINS # noqa: E501 :param matching_method: The matching_method of this SearchQuery. # noqa: E501 :type: str
[ "Sets", "the", "matching_method", "of", "this", "SearchQuery", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/search_query.py#L95-L110
train
28,200
wavefrontHQ/python-client
wavefront_api_client/models/alert.py
Alert.alert_type
def alert_type(self, alert_type): """Sets the alert_type of this Alert. Alert type. # noqa: E501 :param alert_type: The alert_type of this Alert. # noqa: E501 :type: str """ allowed_values = ["CLASSIC", "THRESHOLD"] # noqa: E501 if alert_type not in allowed_values: raise ValueError( "Invalid value for `alert_type` ({0}), must be one of {1}" # noqa: E501 .format(alert_type, allowed_values) ) self._alert_type = alert_type
python
def alert_type(self, alert_type): """Sets the alert_type of this Alert. Alert type. # noqa: E501 :param alert_type: The alert_type of this Alert. # noqa: E501 :type: str """ allowed_values = ["CLASSIC", "THRESHOLD"] # noqa: E501 if alert_type not in allowed_values: raise ValueError( "Invalid value for `alert_type` ({0}), must be one of {1}" # noqa: E501 .format(alert_type, allowed_values) ) self._alert_type = alert_type
[ "def", "alert_type", "(", "self", ",", "alert_type", ")", ":", "allowed_values", "=", "[", "\"CLASSIC\"", ",", "\"THRESHOLD\"", "]", "# noqa: E501", "if", "alert_type", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value for `alert_type`...
Sets the alert_type of this Alert. Alert type. # noqa: E501 :param alert_type: The alert_type of this Alert. # noqa: E501 :type: str
[ "Sets", "the", "alert_type", "of", "this", "Alert", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/alert.py#L395-L410
train
28,201
wavefrontHQ/python-client
wavefront_api_client/models/alert.py
Alert.severity_list
def severity_list(self, severity_list): """Sets the severity_list of this Alert. Alert severity list for multi-threshold type. # noqa: E501 :param severity_list: The severity_list of this Alert. # noqa: E501 :type: list[str] """ allowed_values = ["INFO", "SMOKE", "WARN", "SEVERE"] # noqa: E501 if not set(severity_list).issubset(set(allowed_values)): raise ValueError( "Invalid values for `severity_list` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(severity_list) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._severity_list = severity_list
python
def severity_list(self, severity_list): """Sets the severity_list of this Alert. Alert severity list for multi-threshold type. # noqa: E501 :param severity_list: The severity_list of this Alert. # noqa: E501 :type: list[str] """ allowed_values = ["INFO", "SMOKE", "WARN", "SEVERE"] # noqa: E501 if not set(severity_list).issubset(set(allowed_values)): raise ValueError( "Invalid values for `severity_list` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(severity_list) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._severity_list = severity_list
[ "def", "severity_list", "(", "self", ",", "severity_list", ")", ":", "allowed_values", "=", "[", "\"INFO\"", ",", "\"SMOKE\"", ",", "\"WARN\"", ",", "\"SEVERE\"", "]", "# noqa: E501", "if", "not", "set", "(", "severity_list", ")", ".", "issubset", "(", "set"...
Sets the severity_list of this Alert. Alert severity list for multi-threshold type. # noqa: E501 :param severity_list: The severity_list of this Alert. # noqa: E501 :type: list[str]
[ "Sets", "the", "severity_list", "of", "this", "Alert", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/alert.py#L1378-L1394
train
28,202
wavefrontHQ/python-client
wavefront_api_client/models/azure_activity_log_configuration.py
AzureActivityLogConfiguration.category_filter
def category_filter(self, category_filter): """Sets the category_filter of this AzureActivityLogConfiguration. A list of Azure ActivityLog categories to pull events for.Allowable values are ADMINISTRATIVE, SERVICEHEALTH, ALERT, AUTOSCALE, SECURITY # noqa: E501 :param category_filter: The category_filter of this AzureActivityLogConfiguration. # noqa: E501 :type: list[str] """ allowed_values = ["ADMINISTRATIVE", "SERVICEHEALTH", "ALERT", "AUTOSCALE", "SECURITY"] # noqa: E501 if not set(category_filter).issubset(set(allowed_values)): raise ValueError( "Invalid values for `category_filter` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(category_filter) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._category_filter = category_filter
python
def category_filter(self, category_filter): """Sets the category_filter of this AzureActivityLogConfiguration. A list of Azure ActivityLog categories to pull events for.Allowable values are ADMINISTRATIVE, SERVICEHEALTH, ALERT, AUTOSCALE, SECURITY # noqa: E501 :param category_filter: The category_filter of this AzureActivityLogConfiguration. # noqa: E501 :type: list[str] """ allowed_values = ["ADMINISTRATIVE", "SERVICEHEALTH", "ALERT", "AUTOSCALE", "SECURITY"] # noqa: E501 if not set(category_filter).issubset(set(allowed_values)): raise ValueError( "Invalid values for `category_filter` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(category_filter) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._category_filter = category_filter
[ "def", "category_filter", "(", "self", ",", "category_filter", ")", ":", "allowed_values", "=", "[", "\"ADMINISTRATIVE\"", ",", "\"SERVICEHEALTH\"", ",", "\"ALERT\"", ",", "\"AUTOSCALE\"", ",", "\"SECURITY\"", "]", "# noqa: E501", "if", "not", "set", "(", "categor...
Sets the category_filter of this AzureActivityLogConfiguration. A list of Azure ActivityLog categories to pull events for.Allowable values are ADMINISTRATIVE, SERVICEHEALTH, ALERT, AUTOSCALE, SECURITY # noqa: E501 :param category_filter: The category_filter of this AzureActivityLogConfiguration. # noqa: E501 :type: list[str]
[ "Sets", "the", "category_filter", "of", "this", "AzureActivityLogConfiguration", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/azure_activity_log_configuration.py#L90-L106
train
28,203
wavefrontHQ/python-client
wavefront_api_client/models/saved_search.py
SavedSearch.entity_type
def entity_type(self, entity_type): """Sets the entity_type of this SavedSearch. The Wavefront entity type over which to search # noqa: E501 :param entity_type: The entity_type of this SavedSearch. # noqa: E501 :type: str """ if entity_type is None: raise ValueError("Invalid value for `entity_type`, must not be `None`") # noqa: E501 allowed_values = ["DASHBOARD", "ALERT", "MAINTENANCE_WINDOW", "NOTIFICANT", "EVENT", "SOURCE", "EXTERNAL_LINK", "AGENT", "CLOUD_INTEGRATION", "APPLICATION", "REGISTERED_QUERY", "USER", "USER_GROUP"] # noqa: E501 if entity_type not in allowed_values: raise ValueError( "Invalid value for `entity_type` ({0}), must be one of {1}" # noqa: E501 .format(entity_type, allowed_values) ) self._entity_type = entity_type
python
def entity_type(self, entity_type): """Sets the entity_type of this SavedSearch. The Wavefront entity type over which to search # noqa: E501 :param entity_type: The entity_type of this SavedSearch. # noqa: E501 :type: str """ if entity_type is None: raise ValueError("Invalid value for `entity_type`, must not be `None`") # noqa: E501 allowed_values = ["DASHBOARD", "ALERT", "MAINTENANCE_WINDOW", "NOTIFICANT", "EVENT", "SOURCE", "EXTERNAL_LINK", "AGENT", "CLOUD_INTEGRATION", "APPLICATION", "REGISTERED_QUERY", "USER", "USER_GROUP"] # noqa: E501 if entity_type not in allowed_values: raise ValueError( "Invalid value for `entity_type` ({0}), must be one of {1}" # noqa: E501 .format(entity_type, allowed_values) ) self._entity_type = entity_type
[ "def", "entity_type", "(", "self", ",", "entity_type", ")", ":", "if", "entity_type", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `entity_type`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"DASHBOARD\"", ",", "\"AL...
Sets the entity_type of this SavedSearch. The Wavefront entity type over which to search # noqa: E501 :param entity_type: The entity_type of this SavedSearch. # noqa: E501 :type: str
[ "Sets", "the", "entity_type", "of", "this", "SavedSearch", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/saved_search.py#L137-L154
train
28,204
wavefrontHQ/python-client
wavefront_api_client/models/chart.py
Chart.summarization
def summarization(self, summarization): """Sets the summarization of this Chart. Summarization strategy for the chart. MEAN is default # noqa: E501 :param summarization: The summarization of this Chart. # noqa: E501 :type: str """ allowed_values = ["MEAN", "MEDIAN", "MIN", "MAX", "SUM", "COUNT", "LAST", "FIRST"] # noqa: E501 if summarization not in allowed_values: raise ValueError( "Invalid value for `summarization` ({0}), must be one of {1}" # noqa: E501 .format(summarization, allowed_values) ) self._summarization = summarization
python
def summarization(self, summarization): """Sets the summarization of this Chart. Summarization strategy for the chart. MEAN is default # noqa: E501 :param summarization: The summarization of this Chart. # noqa: E501 :type: str """ allowed_values = ["MEAN", "MEDIAN", "MIN", "MAX", "SUM", "COUNT", "LAST", "FIRST"] # noqa: E501 if summarization not in allowed_values: raise ValueError( "Invalid value for `summarization` ({0}), must be one of {1}" # noqa: E501 .format(summarization, allowed_values) ) self._summarization = summarization
[ "def", "summarization", "(", "self", ",", "summarization", ")", ":", "allowed_values", "=", "[", "\"MEAN\"", ",", "\"MEDIAN\"", ",", "\"MIN\"", ",", "\"MAX\"", ",", "\"SUM\"", ",", "\"COUNT\"", ",", "\"LAST\"", ",", "\"FIRST\"", "]", "# noqa: E501", "if", "s...
Sets the summarization of this Chart. Summarization strategy for the chart. MEAN is default # noqa: E501 :param summarization: The summarization of this Chart. # noqa: E501 :type: str
[ "Sets", "the", "summarization", "of", "this", "Chart", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart.py#L323-L338
train
28,205
wavefrontHQ/python-client
wavefront_api_client/models/gcp_configuration.py
GCPConfiguration.categories_to_fetch
def categories_to_fetch(self, categories_to_fetch): """Sets the categories_to_fetch of this GCPConfiguration. A list of Google Cloud Platform (GCP) services (such as ComputeEngine, PubSub, etc) from which to pull metrics. Allowable values are APPENGINE, BIGQUERY, BIGTABLE, CLOUDFUNCTIONS, CLOUDIOT, CLOUDSQL, CLOUDTASKS, COMPUTE, CONTAINER, DATAFLOW, DATASTORE, FIREBASEDATABASE, FIREBASEHOSTING, LOGGING, ML, PUBSUB, ROUTER, SPANNER, STORAGE, VPN # noqa: E501 :param categories_to_fetch: The categories_to_fetch of this GCPConfiguration. # noqa: E501 :type: list[str] """ allowed_values = ["APPENGINE", "BIGQUERY", "BIGTABLE", "CLOUDFUNCTIONS", "CLOUDIOT", "CLOUDSQL", "CLOUDTASKS", "COMPUTE", "CONTAINER", "DATAFLOW", "DATAPROC", "DATASTORE", "FIREBASEDATABASE", "FIREBASEHOSTING", "INTERCONNECT", "LOADBALANCING", "LOGGING", "ML", "MONITORING", "PUBSUB", "REDIS", "ROUTER", "SERVICERUNTIME", "SPANNER", "STORAGE", "TPU", "VPN"] # noqa: E501 if not set(categories_to_fetch).issubset(set(allowed_values)): raise ValueError( "Invalid values for `categories_to_fetch` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(categories_to_fetch) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._categories_to_fetch = categories_to_fetch
python
def categories_to_fetch(self, categories_to_fetch): """Sets the categories_to_fetch of this GCPConfiguration. A list of Google Cloud Platform (GCP) services (such as ComputeEngine, PubSub, etc) from which to pull metrics. Allowable values are APPENGINE, BIGQUERY, BIGTABLE, CLOUDFUNCTIONS, CLOUDIOT, CLOUDSQL, CLOUDTASKS, COMPUTE, CONTAINER, DATAFLOW, DATASTORE, FIREBASEDATABASE, FIREBASEHOSTING, LOGGING, ML, PUBSUB, ROUTER, SPANNER, STORAGE, VPN # noqa: E501 :param categories_to_fetch: The categories_to_fetch of this GCPConfiguration. # noqa: E501 :type: list[str] """ allowed_values = ["APPENGINE", "BIGQUERY", "BIGTABLE", "CLOUDFUNCTIONS", "CLOUDIOT", "CLOUDSQL", "CLOUDTASKS", "COMPUTE", "CONTAINER", "DATAFLOW", "DATAPROC", "DATASTORE", "FIREBASEDATABASE", "FIREBASEHOSTING", "INTERCONNECT", "LOADBALANCING", "LOGGING", "ML", "MONITORING", "PUBSUB", "REDIS", "ROUTER", "SERVICERUNTIME", "SPANNER", "STORAGE", "TPU", "VPN"] # noqa: E501 if not set(categories_to_fetch).issubset(set(allowed_values)): raise ValueError( "Invalid values for `categories_to_fetch` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(categories_to_fetch) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._categories_to_fetch = categories_to_fetch
[ "def", "categories_to_fetch", "(", "self", ",", "categories_to_fetch", ")", ":", "allowed_values", "=", "[", "\"APPENGINE\"", ",", "\"BIGQUERY\"", ",", "\"BIGTABLE\"", ",", "\"CLOUDFUNCTIONS\"", ",", "\"CLOUDIOT\"", ",", "\"CLOUDSQL\"", ",", "\"CLOUDTASKS\"", ",", "...
Sets the categories_to_fetch of this GCPConfiguration. A list of Google Cloud Platform (GCP) services (such as ComputeEngine, PubSub, etc) from which to pull metrics. Allowable values are APPENGINE, BIGQUERY, BIGTABLE, CLOUDFUNCTIONS, CLOUDIOT, CLOUDSQL, CLOUDTASKS, COMPUTE, CONTAINER, DATAFLOW, DATASTORE, FIREBASEDATABASE, FIREBASEHOSTING, LOGGING, ML, PUBSUB, ROUTER, SPANNER, STORAGE, VPN # noqa: E501 :param categories_to_fetch: The categories_to_fetch of this GCPConfiguration. # noqa: E501 :type: list[str]
[ "Sets", "the", "categories_to_fetch", "of", "this", "GCPConfiguration", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/gcp_configuration.py#L75-L91
train
28,206
wavefrontHQ/python-client
wavefront_api_client/models/integration_status.py
IntegrationStatus.alert_statuses
def alert_statuses(self, alert_statuses): """Sets the alert_statuses of this IntegrationStatus. A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501 :param alert_statuses: The alert_statuses of this IntegrationStatus. # noqa: E501 :type: dict(str, str) """ if alert_statuses is None: raise ValueError("Invalid value for `alert_statuses`, must not be `None`") # noqa: E501 allowed_values = ["VISIBLE", "HIDDEN", "NOT_LOADED"] # noqa: E501 if not set(alert_statuses.keys()).issubset(set(allowed_values)): raise ValueError( "Invalid keys in `alert_statuses` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(alert_statuses.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._alert_statuses = alert_statuses
python
def alert_statuses(self, alert_statuses): """Sets the alert_statuses of this IntegrationStatus. A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501 :param alert_statuses: The alert_statuses of this IntegrationStatus. # noqa: E501 :type: dict(str, str) """ if alert_statuses is None: raise ValueError("Invalid value for `alert_statuses`, must not be `None`") # noqa: E501 allowed_values = ["VISIBLE", "HIDDEN", "NOT_LOADED"] # noqa: E501 if not set(alert_statuses.keys()).issubset(set(allowed_values)): raise ValueError( "Invalid keys in `alert_statuses` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(alert_statuses.keys()) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._alert_statuses = alert_statuses
[ "def", "alert_statuses", "(", "self", ",", "alert_statuses", ")", ":", "if", "alert_statuses", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `alert_statuses`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"VISIBLE\"", ",...
Sets the alert_statuses of this IntegrationStatus. A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501 :param alert_statuses: The alert_statuses of this IntegrationStatus. # noqa: E501 :type: dict(str, str)
[ "Sets", "the", "alert_statuses", "of", "this", "IntegrationStatus", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/integration_status.py#L75-L93
train
28,207
wavefrontHQ/python-client
wavefront_api_client/models/integration_status.py
IntegrationStatus.content_status
def content_status(self, content_status): """Sets the content_status of this IntegrationStatus. Status of integration content, e.g. dashboards # noqa: E501 :param content_status: The content_status of this IntegrationStatus. # noqa: E501 :type: str """ if content_status is None: raise ValueError("Invalid value for `content_status`, must not be `None`") # noqa: E501 allowed_values = ["INVALID", "NOT_LOADED", "HIDDEN", "VISIBLE"] # noqa: E501 if content_status not in allowed_values: raise ValueError( "Invalid value for `content_status` ({0}), must be one of {1}" # noqa: E501 .format(content_status, allowed_values) ) self._content_status = content_status
python
def content_status(self, content_status): """Sets the content_status of this IntegrationStatus. Status of integration content, e.g. dashboards # noqa: E501 :param content_status: The content_status of this IntegrationStatus. # noqa: E501 :type: str """ if content_status is None: raise ValueError("Invalid value for `content_status`, must not be `None`") # noqa: E501 allowed_values = ["INVALID", "NOT_LOADED", "HIDDEN", "VISIBLE"] # noqa: E501 if content_status not in allowed_values: raise ValueError( "Invalid value for `content_status` ({0}), must be one of {1}" # noqa: E501 .format(content_status, allowed_values) ) self._content_status = content_status
[ "def", "content_status", "(", "self", ",", "content_status", ")", ":", "if", "content_status", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `content_status`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"INVALID\"", ",...
Sets the content_status of this IntegrationStatus. Status of integration content, e.g. dashboards # noqa: E501 :param content_status: The content_status of this IntegrationStatus. # noqa: E501 :type: str
[ "Sets", "the", "content_status", "of", "this", "IntegrationStatus", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/integration_status.py#L107-L124
train
28,208
wavefrontHQ/python-client
wavefront_api_client/models/integration_status.py
IntegrationStatus.install_status
def install_status(self, install_status): """Sets the install_status of this IntegrationStatus. Whether the customer or an automated process has installed the dashboards for this integration # noqa: E501 :param install_status: The install_status of this IntegrationStatus. # noqa: E501 :type: str """ if install_status is None: raise ValueError("Invalid value for `install_status`, must not be `None`") # noqa: E501 allowed_values = ["UNDECIDED", "UNINSTALLED", "INSTALLED"] # noqa: E501 if install_status not in allowed_values: raise ValueError( "Invalid value for `install_status` ({0}), must be one of {1}" # noqa: E501 .format(install_status, allowed_values) ) self._install_status = install_status
python
def install_status(self, install_status): """Sets the install_status of this IntegrationStatus. Whether the customer or an automated process has installed the dashboards for this integration # noqa: E501 :param install_status: The install_status of this IntegrationStatus. # noqa: E501 :type: str """ if install_status is None: raise ValueError("Invalid value for `install_status`, must not be `None`") # noqa: E501 allowed_values = ["UNDECIDED", "UNINSTALLED", "INSTALLED"] # noqa: E501 if install_status not in allowed_values: raise ValueError( "Invalid value for `install_status` ({0}), must be one of {1}" # noqa: E501 .format(install_status, allowed_values) ) self._install_status = install_status
[ "def", "install_status", "(", "self", ",", "install_status", ")", ":", "if", "install_status", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `install_status`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"UNDECIDED\"", ...
Sets the install_status of this IntegrationStatus. Whether the customer or an automated process has installed the dashboards for this integration # noqa: E501 :param install_status: The install_status of this IntegrationStatus. # noqa: E501 :type: str
[ "Sets", "the", "install_status", "of", "this", "IntegrationStatus", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/integration_status.py#L138-L155
train
28,209
wavefrontHQ/python-client
wavefront_api_client/models/dashboard.py
Dashboard.event_filter_type
def event_filter_type(self, event_filter_type): """Sets the event_filter_type of this Dashboard. How charts belonging to this dashboard should display events. BYCHART is default if unspecified # noqa: E501 :param event_filter_type: The event_filter_type of this Dashboard. # noqa: E501 :type: str """ allowed_values = ["BYCHART", "AUTOMATIC", "ALL", "NONE", "BYDASHBOARD", "BYCHARTANDDASHBOARD"] # noqa: E501 if event_filter_type not in allowed_values: raise ValueError( "Invalid value for `event_filter_type` ({0}), must be one of {1}" # noqa: E501 .format(event_filter_type, allowed_values) ) self._event_filter_type = event_filter_type
python
def event_filter_type(self, event_filter_type): """Sets the event_filter_type of this Dashboard. How charts belonging to this dashboard should display events. BYCHART is default if unspecified # noqa: E501 :param event_filter_type: The event_filter_type of this Dashboard. # noqa: E501 :type: str """ allowed_values = ["BYCHART", "AUTOMATIC", "ALL", "NONE", "BYDASHBOARD", "BYCHARTANDDASHBOARD"] # noqa: E501 if event_filter_type not in allowed_values: raise ValueError( "Invalid value for `event_filter_type` ({0}), must be one of {1}" # noqa: E501 .format(event_filter_type, allowed_values) ) self._event_filter_type = event_filter_type
[ "def", "event_filter_type", "(", "self", ",", "event_filter_type", ")", ":", "allowed_values", "=", "[", "\"BYCHART\"", ",", "\"AUTOMATIC\"", ",", "\"ALL\"", ",", "\"NONE\"", ",", "\"BYDASHBOARD\"", ",", "\"BYCHARTANDDASHBOARD\"", "]", "# noqa: E501", "if", "event_f...
Sets the event_filter_type of this Dashboard. How charts belonging to this dashboard should display events. BYCHART is default if unspecified # noqa: E501 :param event_filter_type: The event_filter_type of this Dashboard. # noqa: E501 :type: str
[ "Sets", "the", "event_filter_type", "of", "this", "Dashboard", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/dashboard.py#L596-L611
train
28,210
wavefrontHQ/python-client
wavefront_api_client/models/chart_source_query.py
ChartSourceQuery.scatter_plot_source
def scatter_plot_source(self, scatter_plot_source): """Sets the scatter_plot_source of this ChartSourceQuery. For scatter plots, does this query source the X-axis or the Y-axis # noqa: E501 :param scatter_plot_source: The scatter_plot_source of this ChartSourceQuery. # noqa: E501 :type: str """ allowed_values = ["X", "Y"] # noqa: E501 if scatter_plot_source not in allowed_values: raise ValueError( "Invalid value for `scatter_plot_source` ({0}), must be one of {1}" # noqa: E501 .format(scatter_plot_source, allowed_values) ) self._scatter_plot_source = scatter_plot_source
python
def scatter_plot_source(self, scatter_plot_source): """Sets the scatter_plot_source of this ChartSourceQuery. For scatter plots, does this query source the X-axis or the Y-axis # noqa: E501 :param scatter_plot_source: The scatter_plot_source of this ChartSourceQuery. # noqa: E501 :type: str """ allowed_values = ["X", "Y"] # noqa: E501 if scatter_plot_source not in allowed_values: raise ValueError( "Invalid value for `scatter_plot_source` ({0}), must be one of {1}" # noqa: E501 .format(scatter_plot_source, allowed_values) ) self._scatter_plot_source = scatter_plot_source
[ "def", "scatter_plot_source", "(", "self", ",", "scatter_plot_source", ")", ":", "allowed_values", "=", "[", "\"X\"", ",", "\"Y\"", "]", "# noqa: E501", "if", "scatter_plot_source", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value for...
Sets the scatter_plot_source of this ChartSourceQuery. For scatter plots, does this query source the X-axis or the Y-axis # noqa: E501 :param scatter_plot_source: The scatter_plot_source of this ChartSourceQuery. # noqa: E501 :type: str
[ "Sets", "the", "scatter_plot_source", "of", "this", "ChartSourceQuery", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_source_query.py#L219-L234
train
28,211
wavefrontHQ/python-client
wavefront_api_client/models/notificant.py
Notificant.content_type
def content_type(self, content_type): """Sets the content_type of this Notificant. The value of the Content-Type header of the webhook POST request. # noqa: E501 :param content_type: The content_type of this Notificant. # noqa: E501 :type: str """ allowed_values = ["application/json", "text/html", "text/plain", "application/x-www-form-urlencoded", ""] # noqa: E501 if content_type not in allowed_values: raise ValueError( "Invalid value for `content_type` ({0}), must be one of {1}" # noqa: E501 .format(content_type, allowed_values) ) self._content_type = content_type
python
def content_type(self, content_type): """Sets the content_type of this Notificant. The value of the Content-Type header of the webhook POST request. # noqa: E501 :param content_type: The content_type of this Notificant. # noqa: E501 :type: str """ allowed_values = ["application/json", "text/html", "text/plain", "application/x-www-form-urlencoded", ""] # noqa: E501 if content_type not in allowed_values: raise ValueError( "Invalid value for `content_type` ({0}), must be one of {1}" # noqa: E501 .format(content_type, allowed_values) ) self._content_type = content_type
[ "def", "content_type", "(", "self", ",", "content_type", ")", ":", "allowed_values", "=", "[", "\"application/json\"", ",", "\"text/html\"", ",", "\"text/plain\"", ",", "\"application/x-www-form-urlencoded\"", ",", "\"\"", "]", "# noqa: E501", "if", "content_type", "n...
Sets the content_type of this Notificant. The value of the Content-Type header of the webhook POST request. # noqa: E501 :param content_type: The content_type of this Notificant. # noqa: E501 :type: str
[ "Sets", "the", "content_type", "of", "this", "Notificant", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/notificant.py#L131-L146
train
28,212
wavefrontHQ/python-client
wavefront_api_client/models/notificant.py
Notificant.method
def method(self, method): """Sets the method of this Notificant. The notification method used for notification target. # noqa: E501 :param method: The method of this Notificant. # noqa: E501 :type: str """ if method is None: raise ValueError("Invalid value for `method`, must not be `None`") # noqa: E501 allowed_values = ["WEBHOOK", "EMAIL", "PAGERDUTY"] # noqa: E501 if method not in allowed_values: raise ValueError( "Invalid value for `method` ({0}), must be one of {1}" # noqa: E501 .format(method, allowed_values) ) self._method = method
python
def method(self, method): """Sets the method of this Notificant. The notification method used for notification target. # noqa: E501 :param method: The method of this Notificant. # noqa: E501 :type: str """ if method is None: raise ValueError("Invalid value for `method`, must not be `None`") # noqa: E501 allowed_values = ["WEBHOOK", "EMAIL", "PAGERDUTY"] # noqa: E501 if method not in allowed_values: raise ValueError( "Invalid value for `method` ({0}), must be one of {1}" # noqa: E501 .format(method, allowed_values) ) self._method = method
[ "def", "method", "(", "self", ",", "method", ")", ":", "if", "method", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `method`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"WEBHOOK\"", ",", "\"EMAIL\"", ",", "\"PA...
Sets the method of this Notificant. The notification method used for notification target. # noqa: E501 :param method: The method of this Notificant. # noqa: E501 :type: str
[ "Sets", "the", "method", "of", "this", "Notificant", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/notificant.py#L338-L355
train
28,213
wavefrontHQ/python-client
wavefront_api_client/models/notificant.py
Notificant.triggers
def triggers(self, triggers): """Sets the triggers of this Notificant. A list of occurrences on which this webhook will be fired. Valid values are ALERT_OPENED, ALERT_UPDATED, ALERT_RESOLVED, ALERT_MAINTENANCE, ALERT_SNOOZED # noqa: E501 :param triggers: The triggers of this Notificant. # noqa: E501 :type: list[str] """ if triggers is None: raise ValueError("Invalid value for `triggers`, must not be `None`") # noqa: E501 allowed_values = ["ALERT_OPENED", "ALERT_UPDATED", "ALERT_RESOLVED", "ALERT_MAINTENANCE", "ALERT_SNOOZED", "ALERT_INVALID", "ALERT_NO_LONGER_INVALID", "ALERT_TESTING", "ALERT_RETRIGGERED", "ALERT_NO_DATA", "ALERT_NO_DATA_RESOLVED", "ALERT_NO_DATA_MAINTENANCE", "ALERT_SERIES_SEVERITY_UPDATE", "ALERT_SEVERITY_UPDATE"] # noqa: E501 if not set(triggers).issubset(set(allowed_values)): raise ValueError( "Invalid values for `triggers` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(triggers) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._triggers = triggers
python
def triggers(self, triggers): """Sets the triggers of this Notificant. A list of occurrences on which this webhook will be fired. Valid values are ALERT_OPENED, ALERT_UPDATED, ALERT_RESOLVED, ALERT_MAINTENANCE, ALERT_SNOOZED # noqa: E501 :param triggers: The triggers of this Notificant. # noqa: E501 :type: list[str] """ if triggers is None: raise ValueError("Invalid value for `triggers`, must not be `None`") # noqa: E501 allowed_values = ["ALERT_OPENED", "ALERT_UPDATED", "ALERT_RESOLVED", "ALERT_MAINTENANCE", "ALERT_SNOOZED", "ALERT_INVALID", "ALERT_NO_LONGER_INVALID", "ALERT_TESTING", "ALERT_RETRIGGERED", "ALERT_NO_DATA", "ALERT_NO_DATA_RESOLVED", "ALERT_NO_DATA_MAINTENANCE", "ALERT_SERIES_SEVERITY_UPDATE", "ALERT_SEVERITY_UPDATE"] # noqa: E501 if not set(triggers).issubset(set(allowed_values)): raise ValueError( "Invalid values for `triggers` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(triggers) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._triggers = triggers
[ "def", "triggers", "(", "self", ",", "triggers", ")", ":", "if", "triggers", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `triggers`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"ALERT_OPENED\"", ",", "\"ALERT_UPDAT...
Sets the triggers of this Notificant. A list of occurrences on which this webhook will be fired. Valid values are ALERT_OPENED, ALERT_UPDATED, ALERT_RESOLVED, ALERT_MAINTENANCE, ALERT_SNOOZED # noqa: E501 :param triggers: The triggers of this Notificant. # noqa: E501 :type: list[str]
[ "Sets", "the", "triggers", "of", "this", "Notificant", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/notificant.py#L444-L462
train
28,214
wavefrontHQ/python-client
wavefront_api_client/models/event.py
Event.creator_type
def creator_type(self, creator_type): """Sets the creator_type of this Event. :param creator_type: The creator_type of this Event. # noqa: E501 :type: list[str] """ allowed_values = ["USER", "ALERT", "SYSTEM"] # noqa: E501 if not set(creator_type).issubset(set(allowed_values)): raise ValueError( "Invalid values for `creator_type` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(creator_type) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._creator_type = creator_type
python
def creator_type(self, creator_type): """Sets the creator_type of this Event. :param creator_type: The creator_type of this Event. # noqa: E501 :type: list[str] """ allowed_values = ["USER", "ALERT", "SYSTEM"] # noqa: E501 if not set(creator_type).issubset(set(allowed_values)): raise ValueError( "Invalid values for `creator_type` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(creator_type) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._creator_type = creator_type
[ "def", "creator_type", "(", "self", ",", "creator_type", ")", ":", "allowed_values", "=", "[", "\"USER\"", ",", "\"ALERT\"", ",", "\"SYSTEM\"", "]", "# noqa: E501", "if", "not", "set", "(", "creator_type", ")", ".", "issubset", "(", "set", "(", "allowed_valu...
Sets the creator_type of this Event. :param creator_type: The creator_type of this Event. # noqa: E501 :type: list[str]
[ "Sets", "the", "creator_type", "of", "this", "Event", "." ]
b0f1046a8f68c2c7d69e395f7167241f224c738a
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/event.py#L288-L303
train
28,215
pywbem/pywbem
pywbem/_utils.py
_integerValue_to_int
def _integerValue_to_int(value_str): """ Convert a value string that conforms to DSP0004 `integerValue`, into the corresponding integer and return it. The returned value has Python type `int`, or in Python 2, type `long` if needed. Note that DSP0207 and DSP0004 only allow US-ASCII decimal digits. However, the Python `int()` function supports all Unicode decimal digits (e.g. US-ASCII digits, ARABIC-INDIC digits, superscripts, subscripts) and raises `ValueError` for non-decimal digits (e.g. Kharoshthi digits). Therefore, the match patterns explicitly check for US-ASCII digits, and the `int()` function should never raise `ValueError`. Returns `None` if the value string does not conform to `integerValue`. """ m = BINARY_VALUE.match(value_str) if m: value = int(m.group(1), 2) elif OCTAL_VALUE.match(value_str): value = int(value_str, 8) elif DECIMAL_VALUE.match(value_str): value = int(value_str) elif HEX_VALUE.match(value_str): value = int(value_str, 16) else: value = None return value
python
def _integerValue_to_int(value_str): """ Convert a value string that conforms to DSP0004 `integerValue`, into the corresponding integer and return it. The returned value has Python type `int`, or in Python 2, type `long` if needed. Note that DSP0207 and DSP0004 only allow US-ASCII decimal digits. However, the Python `int()` function supports all Unicode decimal digits (e.g. US-ASCII digits, ARABIC-INDIC digits, superscripts, subscripts) and raises `ValueError` for non-decimal digits (e.g. Kharoshthi digits). Therefore, the match patterns explicitly check for US-ASCII digits, and the `int()` function should never raise `ValueError`. Returns `None` if the value string does not conform to `integerValue`. """ m = BINARY_VALUE.match(value_str) if m: value = int(m.group(1), 2) elif OCTAL_VALUE.match(value_str): value = int(value_str, 8) elif DECIMAL_VALUE.match(value_str): value = int(value_str) elif HEX_VALUE.match(value_str): value = int(value_str, 16) else: value = None return value
[ "def", "_integerValue_to_int", "(", "value_str", ")", ":", "m", "=", "BINARY_VALUE", ".", "match", "(", "value_str", ")", "if", "m", ":", "value", "=", "int", "(", "m", ".", "group", "(", "1", ")", ",", "2", ")", "elif", "OCTAL_VALUE", ".", "match", ...
Convert a value string that conforms to DSP0004 `integerValue`, into the corresponding integer and return it. The returned value has Python type `int`, or in Python 2, type `long` if needed. Note that DSP0207 and DSP0004 only allow US-ASCII decimal digits. However, the Python `int()` function supports all Unicode decimal digits (e.g. US-ASCII digits, ARABIC-INDIC digits, superscripts, subscripts) and raises `ValueError` for non-decimal digits (e.g. Kharoshthi digits). Therefore, the match patterns explicitly check for US-ASCII digits, and the `int()` function should never raise `ValueError`. Returns `None` if the value string does not conform to `integerValue`.
[ "Convert", "a", "value", "string", "that", "conforms", "to", "DSP0004", "integerValue", "into", "the", "corresponding", "integer", "and", "return", "it", ".", "The", "returned", "value", "has", "Python", "type", "int", "or", "in", "Python", "2", "type", "lon...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_utils.py#L316-L342
train
28,216
pywbem/pywbem
pywbem/_utils.py
_realValue_to_float
def _realValue_to_float(value_str): """ Convert a value string that conforms to DSP0004 `realValue`, into the corresponding float and return it. The special values 'INF', '-INF', and 'NAN' are supported. Note that the Python `float()` function supports a superset of input formats compared to the `realValue` definition in DSP0004. For example, "1." is allowed for `float()` but not for `realValue`. In addition, it has the same support for Unicode decimal digits as `int()`. Therefore, the match patterns explicitly check for US-ASCII digits, and the `float()` function should never raise `ValueError`. Returns None if the value string does not conform to `realValue`. """ if REAL_VALUE.match(value_str): value = float(value_str) else: value = None return value
python
def _realValue_to_float(value_str): """ Convert a value string that conforms to DSP0004 `realValue`, into the corresponding float and return it. The special values 'INF', '-INF', and 'NAN' are supported. Note that the Python `float()` function supports a superset of input formats compared to the `realValue` definition in DSP0004. For example, "1." is allowed for `float()` but not for `realValue`. In addition, it has the same support for Unicode decimal digits as `int()`. Therefore, the match patterns explicitly check for US-ASCII digits, and the `float()` function should never raise `ValueError`. Returns None if the value string does not conform to `realValue`. """ if REAL_VALUE.match(value_str): value = float(value_str) else: value = None return value
[ "def", "_realValue_to_float", "(", "value_str", ")", ":", "if", "REAL_VALUE", ".", "match", "(", "value_str", ")", ":", "value", "=", "float", "(", "value_str", ")", "else", ":", "value", "=", "None", "return", "value" ]
Convert a value string that conforms to DSP0004 `realValue`, into the corresponding float and return it. The special values 'INF', '-INF', and 'NAN' are supported. Note that the Python `float()` function supports a superset of input formats compared to the `realValue` definition in DSP0004. For example, "1." is allowed for `float()` but not for `realValue`. In addition, it has the same support for Unicode decimal digits as `int()`. Therefore, the match patterns explicitly check for US-ASCII digits, and the `float()` function should never raise `ValueError`. Returns None if the value string does not conform to `realValue`.
[ "Convert", "a", "value", "string", "that", "conforms", "to", "DSP0004", "realValue", "into", "the", "corresponding", "float", "and", "return", "it", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_utils.py#L345-L365
train
28,217
pywbem/pywbem
examples/enumerator_generator.py
parse_cmdline
def parse_cmdline(argparser_): """ Parse the command line. This tests for any required args""" opts = argparser_.parse_args() if not opts.server: argparser_.error('No WBEM server specified') return None return opts
python
def parse_cmdline(argparser_): """ Parse the command line. This tests for any required args""" opts = argparser_.parse_args() if not opts.server: argparser_.error('No WBEM server specified') return None return opts
[ "def", "parse_cmdline", "(", "argparser_", ")", ":", "opts", "=", "argparser_", ".", "parse_args", "(", ")", "if", "not", "opts", ".", "server", ":", "argparser_", ".", "error", "(", "'No WBEM server specified'", ")", "return", "None", "return", "opts" ]
Parse the command line. This tests for any required args
[ "Parse", "the", "command", "line", ".", "This", "tests", "for", "any", "required", "args" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/enumerator_generator.py#L170-L178
train
28,218
pywbem/pywbem
pywbem/cim_constants.py
_statuscode2name
def _statuscode2name(status_code): """Return the symbolic name for a CIM status code.""" try: s = _STATUSCODE2NAME[status_code] except KeyError: s = _format("Invalid status code {0}", status_code) return s
python
def _statuscode2name(status_code): """Return the symbolic name for a CIM status code.""" try: s = _STATUSCODE2NAME[status_code] except KeyError: s = _format("Invalid status code {0}", status_code) return s
[ "def", "_statuscode2name", "(", "status_code", ")", ":", "try", ":", "s", "=", "_STATUSCODE2NAME", "[", "status_code", "]", "except", "KeyError", ":", "s", "=", "_format", "(", "\"Invalid status code {0}\"", ",", "status_code", ")", "return", "s" ]
Return the symbolic name for a CIM status code.
[ "Return", "the", "symbolic", "name", "for", "a", "CIM", "status", "code", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_constants.py#L208-L214
train
28,219
pywbem/pywbem
pywbem/cim_constants.py
_statuscode2string
def _statuscode2string(status_code): """Return a short message for a CIM status code.""" try: s = _STATUSCODE2STRING[status_code] except KeyError: s = _format("Invalid status code {0}", status_code) return s
python
def _statuscode2string(status_code): """Return a short message for a CIM status code.""" try: s = _STATUSCODE2STRING[status_code] except KeyError: s = _format("Invalid status code {0}", status_code) return s
[ "def", "_statuscode2string", "(", "status_code", ")", ":", "try", ":", "s", "=", "_STATUSCODE2STRING", "[", "status_code", "]", "except", "KeyError", ":", "s", "=", "_format", "(", "\"Invalid status code {0}\"", ",", "status_code", ")", "return", "s" ]
Return a short message for a CIM status code.
[ "Return", "a", "short", "message", "for", "a", "CIM", "status", "code", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_constants.py#L246-L252
train
28,220
pywbem/pywbem
wbemcli.py
build_mock_repository
def build_mock_repository(conn_, file_path_list, verbose): """ Build the mock repository from the file_path list and fake connection instance. This allows both mof files and python files to be used to build the repository. If verbose is True, it displays the respository after it is build as mof. """ for file_path in file_path_list: ext = _os.path.splitext(file_path)[1] if not _os.path.exists(file_path): raise ValueError('File name %s does not exist' % file_path) if ext == '.mof': conn_.compile_mof_file(file_path) elif ext == '.py': try: with open(file_path) as fp: # the exec includes CONN and VERBOSE globalparams = {'CONN': conn_, 'VERBOSE': verbose} # pylint: disable=exec-used exec(fp.read(), globalparams, None) except Exception as ex: exc_type, exc_value, exc_traceback = _sys.exc_info() tb = repr(traceback.format_exception(exc_type, exc_value, exc_traceback)) raise ValueError( 'Exception failure of "--mock-server" python script %r ' 'with conn %r Exception: %r\nTraceback\n%s' % (file_path, conn, ex, tb)) else: raise ValueError('Invalid suffix %s on "--mock-server" ' 'global parameter %s. Must be "py" or "mof".' % (ext, file_path)) if verbose: conn_.display_repository()
python
def build_mock_repository(conn_, file_path_list, verbose): """ Build the mock repository from the file_path list and fake connection instance. This allows both mof files and python files to be used to build the repository. If verbose is True, it displays the respository after it is build as mof. """ for file_path in file_path_list: ext = _os.path.splitext(file_path)[1] if not _os.path.exists(file_path): raise ValueError('File name %s does not exist' % file_path) if ext == '.mof': conn_.compile_mof_file(file_path) elif ext == '.py': try: with open(file_path) as fp: # the exec includes CONN and VERBOSE globalparams = {'CONN': conn_, 'VERBOSE': verbose} # pylint: disable=exec-used exec(fp.read(), globalparams, None) except Exception as ex: exc_type, exc_value, exc_traceback = _sys.exc_info() tb = repr(traceback.format_exception(exc_type, exc_value, exc_traceback)) raise ValueError( 'Exception failure of "--mock-server" python script %r ' 'with conn %r Exception: %r\nTraceback\n%s' % (file_path, conn, ex, tb)) else: raise ValueError('Invalid suffix %s on "--mock-server" ' 'global parameter %s. Must be "py" or "mof".' % (ext, file_path)) if verbose: conn_.display_repository()
[ "def", "build_mock_repository", "(", "conn_", ",", "file_path_list", ",", "verbose", ")", ":", "for", "file_path", "in", "file_path_list", ":", "ext", "=", "_os", ".", "path", ".", "splitext", "(", "file_path", ")", "[", "1", "]", "if", "not", "_os", "."...
Build the mock repository from the file_path list and fake connection instance. This allows both mof files and python files to be used to build the repository. If verbose is True, it displays the respository after it is build as mof.
[ "Build", "the", "mock", "repository", "from", "the", "file_path", "list", "and", "fake", "connection", "instance", ".", "This", "allows", "both", "mof", "files", "and", "python", "files", "to", "be", "used", "to", "build", "the", "repository", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L132-L170
train
28,221
pywbem/pywbem
wbemcli.py
_remote_connection
def _remote_connection(server, opts, argparser_): """Initiate a remote connection, via PyWBEM. Arguments for the request are part of the command line arguments and include user name, password, namespace, etc. """ global CONN # pylint: disable=global-statement if opts.timeout is not None: if opts.timeout < 0 or opts.timeout > 300: argparser_.error('timeout option(%s) out of range' % opts.timeout) # mock only uses the namespace timeout and statistics options from the # original set of options. It ignores the url if opts.mock_server: CONN = FakedWBEMConnection( default_namespace=opts.namespace, timeout=opts.timeout, stats_enabled=opts.statistics) try: build_mock_repository(CONN, opts.mock_server, opts.verbose) except ValueError as ve: argparser_.error('Build Repository failed: %s' % ve) return CONN if server[0] == '/': url = server elif re.match(r"^https{0,1}://", server) is not None: url = server elif re.match(r"^[a-zA-Z0-9]+://", server) is not None: argparser_.error('Invalid scheme on server argument.' ' Use "http" or "https"') else: url = '%s://%s' % ('https', server) creds = None if opts.key_file is not None and opts.cert_file is None: argparser_.error('keyfile option requires certfile option') if opts.user is not None and opts.password is None: opts.password = _getpass.getpass('Enter password for %s: ' % opts.user) if opts.user is not None or opts.password is not None: creds = (opts.user, opts.password) # if client cert and key provided, create dictionary for # wbem connection x509_dict = None if opts.cert_file is not None: x509_dict = {"cert_file": opts.cert_file} if opts.key_file is not None: x509_dict.update({'key_file': opts.key_file}) CONN = WBEMConnection(url, creds, default_namespace=opts.namespace, no_verification=opts.no_verify_cert, x509=x509_dict, ca_certs=opts.ca_certs, timeout=opts.timeout, stats_enabled=opts.statistics) CONN.debug = True return CONN
python
def _remote_connection(server, opts, argparser_): """Initiate a remote connection, via PyWBEM. Arguments for the request are part of the command line arguments and include user name, password, namespace, etc. """ global CONN # pylint: disable=global-statement if opts.timeout is not None: if opts.timeout < 0 or opts.timeout > 300: argparser_.error('timeout option(%s) out of range' % opts.timeout) # mock only uses the namespace timeout and statistics options from the # original set of options. It ignores the url if opts.mock_server: CONN = FakedWBEMConnection( default_namespace=opts.namespace, timeout=opts.timeout, stats_enabled=opts.statistics) try: build_mock_repository(CONN, opts.mock_server, opts.verbose) except ValueError as ve: argparser_.error('Build Repository failed: %s' % ve) return CONN if server[0] == '/': url = server elif re.match(r"^https{0,1}://", server) is not None: url = server elif re.match(r"^[a-zA-Z0-9]+://", server) is not None: argparser_.error('Invalid scheme on server argument.' ' Use "http" or "https"') else: url = '%s://%s' % ('https', server) creds = None if opts.key_file is not None and opts.cert_file is None: argparser_.error('keyfile option requires certfile option') if opts.user is not None and opts.password is None: opts.password = _getpass.getpass('Enter password for %s: ' % opts.user) if opts.user is not None or opts.password is not None: creds = (opts.user, opts.password) # if client cert and key provided, create dictionary for # wbem connection x509_dict = None if opts.cert_file is not None: x509_dict = {"cert_file": opts.cert_file} if opts.key_file is not None: x509_dict.update({'key_file': opts.key_file}) CONN = WBEMConnection(url, creds, default_namespace=opts.namespace, no_verification=opts.no_verify_cert, x509=x509_dict, ca_certs=opts.ca_certs, timeout=opts.timeout, stats_enabled=opts.statistics) CONN.debug = True return CONN
[ "def", "_remote_connection", "(", "server", ",", "opts", ",", "argparser_", ")", ":", "global", "CONN", "# pylint: disable=global-statement", "if", "opts", ".", "timeout", "is", "not", "None", ":", "if", "opts", ".", "timeout", "<", "0", "or", "opts", ".", ...
Initiate a remote connection, via PyWBEM. Arguments for the request are part of the command line arguments and include user name, password, namespace, etc.
[ "Initiate", "a", "remote", "connection", "via", "PyWBEM", ".", "Arguments", "for", "the", "request", "are", "part", "of", "the", "command", "line", "arguments", "and", "include", "user", "name", "password", "namespace", "etc", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L173-L241
train
28,222
pywbem/pywbem
wbemcli.py
_get_connection_info
def _get_connection_info(): """Return a string with the connection info.""" info = 'Connection: %s,' % CONN.url if CONN.creds is not None: info += ' userid=%s,' % CONN.creds[0] else: info += ' no creds,' info += ' cacerts=%s,' % ('sys-default' if CONN.ca_certs is None else CONN.ca_certs) info += ' verifycert=%s,' % ('off' if CONN.no_verification else 'on') info += ' default-namespace=%s' % CONN.default_namespace if CONN.x509 is not None: info += ', client-cert=%s' % CONN.x509['cert_file'] try: kf = CONN.x509['key_file'] except KeyError: kf = "none" info += ":%s" % kf if CONN.timeout is not None: info += ', timeout=%s' % CONN.timeout # pylint: disable=protected-access info += ' stats=%s, ' % ('on' if CONN._statistics else 'off') info += 'log=%s' % ('on' if CONN._operation_recorders else 'off') if isinstance(CONN, FakedWBEMConnection): info += ', mock-server' return fill(info, 78, subsequent_indent=' ')
python
def _get_connection_info(): """Return a string with the connection info.""" info = 'Connection: %s,' % CONN.url if CONN.creds is not None: info += ' userid=%s,' % CONN.creds[0] else: info += ' no creds,' info += ' cacerts=%s,' % ('sys-default' if CONN.ca_certs is None else CONN.ca_certs) info += ' verifycert=%s,' % ('off' if CONN.no_verification else 'on') info += ' default-namespace=%s' % CONN.default_namespace if CONN.x509 is not None: info += ', client-cert=%s' % CONN.x509['cert_file'] try: kf = CONN.x509['key_file'] except KeyError: kf = "none" info += ":%s" % kf if CONN.timeout is not None: info += ', timeout=%s' % CONN.timeout # pylint: disable=protected-access info += ' stats=%s, ' % ('on' if CONN._statistics else 'off') info += 'log=%s' % ('on' if CONN._operation_recorders else 'off') if isinstance(CONN, FakedWBEMConnection): info += ', mock-server' return fill(info, 78, subsequent_indent=' ')
[ "def", "_get_connection_info", "(", ")", ":", "info", "=", "'Connection: %s,'", "%", "CONN", ".", "url", "if", "CONN", ".", "creds", "is", "not", "None", ":", "info", "+=", "' userid=%s,'", "%", "CONN", ".", "creds", "[", "0", "]", "else", ":", "info",...
Return a string with the connection info.
[ "Return", "a", "string", "with", "the", "connection", "info", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L3074-L3108
train
28,223
pywbem/pywbem
wbemcli.py
_get_banner
def _get_banner(): """Return a banner message for the interactive console.""" result = '' result += '\nPython %s' % _sys.version result += '\n\nWbemcli interactive shell' result += '\n%s' % _get_connection_info() # Give hint about exiting. Most people exit with 'quit()' which will # not return from the interact() method, and thus will not write # the history. if _sys.platform == 'win32': result += '\nEnter Ctrl-Z or quit() or exit() to exit' else: result += '\nPress Ctrl-D or enter quit() or exit() to exit' result += '\nEnter h() for help' return result
python
def _get_banner(): """Return a banner message for the interactive console.""" result = '' result += '\nPython %s' % _sys.version result += '\n\nWbemcli interactive shell' result += '\n%s' % _get_connection_info() # Give hint about exiting. Most people exit with 'quit()' which will # not return from the interact() method, and thus will not write # the history. if _sys.platform == 'win32': result += '\nEnter Ctrl-Z or quit() or exit() to exit' else: result += '\nPress Ctrl-D or enter quit() or exit() to exit' result += '\nEnter h() for help' return result
[ "def", "_get_banner", "(", ")", ":", "result", "=", "''", "result", "+=", "'\\nPython %s'", "%", "_sys", ".", "version", "result", "+=", "'\\n\\nWbemcli interactive shell'", "result", "+=", "'\\n%s'", "%", "_get_connection_info", "(", ")", "# Give hint about exiting...
Return a banner message for the interactive console.
[ "Return", "a", "banner", "message", "for", "the", "interactive", "console", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L3111-L3128
train
28,224
pywbem/pywbem
pywbem_mock/_dmtf_cim_schema.py
DMTFCIMSchema._setup_dmtf_schema
def _setup_dmtf_schema(self): """ Install the DMTF CIM schema from the DMTF web site if it is not already installed. This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by `schema_mof_dir`. Once the schema zip file is downloaded into `schema_root_dir`, it is not re-downloaded if this function is recalled since DMTF CIM Schema releases are never modified; new update versions are released for minor changes. If the `schema_zip_file` is in the `schema_root_dir` directory, but no 'schema_mof_dir' subdirectory exists, the schema is unzipped. This allows the DMTF CIM schema zip file to be downloaded once and reused and the user to chose if they want to retain the extracted MOF files or remove them with :meth:`~pywbem_mock.DMTFCIMSchema.clean` when not being used. If the schema is to be committed a source repository such as git it is logical to commit only the DMTF CIM schema zip file. Creation of the `schema_mof_dir` subdirectory will be created when the :class:`pywbem_mock.DMTFCIMSchema` object is created. Raises: ValueError: If the schema cannot be retrieved from the DMTF web site. TypeError: If the `schema_version` is not a valid tuple with 3 integer components """ def print_verbose(msg): """ Inner method prints msg if self.verbose is `True`. """ if self.verbose: print(msg) if not os.path.isdir(self.schema_root_dir): print_verbose( _format("Creating directory for CIM Schema archive: {0}", self.schema_root_dir)) os.mkdir(self.schema_root_dir) if not os.path.isfile(self.schema_zip_file): print_verbose( _format("Downloading CIM Schema archive from: {0}", self.schema_zip_url)) try: ufo = urlopen(self.schema_zip_url) except IOError as ie: os.rmdir(self.schema_root_dir) raise ValueError( _format("DMTF Schema archive not found at url {0}: {1}", self.schema_zip_url, ie)) with open(self.schema_zip_file, 'wb') as fp: for data in ufo: fp.write(data) if not os.path.isdir(self.schema_mof_dir): print_verbose( _format("Creating directory for CIM Schema MOF files: {0}", self.schema_mof_dir)) os.mkdir(self.schema_mof_dir) if not os.path.isfile(self._schema_mof_file): print_verbose( _format("Unpacking CIM Schema archive: {0}", self.schema_zip_file)) zfp = None try: zfp = ZipFile(self.schema_zip_file, 'r') nlist = zfp.namelist() for file_ in nlist: dfile = os.path.join(self.schema_mof_dir, file_) if dfile[-1] == '/': if not os.path.exists(dfile): os.mkdir(dfile) else: with open(dfile, 'w+b') as dfp: dfp.write(zfp.read(file_)) finally: if zfp: zfp.close()
python
def _setup_dmtf_schema(self): """ Install the DMTF CIM schema from the DMTF web site if it is not already installed. This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by `schema_mof_dir`. Once the schema zip file is downloaded into `schema_root_dir`, it is not re-downloaded if this function is recalled since DMTF CIM Schema releases are never modified; new update versions are released for minor changes. If the `schema_zip_file` is in the `schema_root_dir` directory, but no 'schema_mof_dir' subdirectory exists, the schema is unzipped. This allows the DMTF CIM schema zip file to be downloaded once and reused and the user to chose if they want to retain the extracted MOF files or remove them with :meth:`~pywbem_mock.DMTFCIMSchema.clean` when not being used. If the schema is to be committed a source repository such as git it is logical to commit only the DMTF CIM schema zip file. Creation of the `schema_mof_dir` subdirectory will be created when the :class:`pywbem_mock.DMTFCIMSchema` object is created. Raises: ValueError: If the schema cannot be retrieved from the DMTF web site. TypeError: If the `schema_version` is not a valid tuple with 3 integer components """ def print_verbose(msg): """ Inner method prints msg if self.verbose is `True`. """ if self.verbose: print(msg) if not os.path.isdir(self.schema_root_dir): print_verbose( _format("Creating directory for CIM Schema archive: {0}", self.schema_root_dir)) os.mkdir(self.schema_root_dir) if not os.path.isfile(self.schema_zip_file): print_verbose( _format("Downloading CIM Schema archive from: {0}", self.schema_zip_url)) try: ufo = urlopen(self.schema_zip_url) except IOError as ie: os.rmdir(self.schema_root_dir) raise ValueError( _format("DMTF Schema archive not found at url {0}: {1}", self.schema_zip_url, ie)) with open(self.schema_zip_file, 'wb') as fp: for data in ufo: fp.write(data) if not os.path.isdir(self.schema_mof_dir): print_verbose( _format("Creating directory for CIM Schema MOF files: {0}", self.schema_mof_dir)) os.mkdir(self.schema_mof_dir) if not os.path.isfile(self._schema_mof_file): print_verbose( _format("Unpacking CIM Schema archive: {0}", self.schema_zip_file)) zfp = None try: zfp = ZipFile(self.schema_zip_file, 'r') nlist = zfp.namelist() for file_ in nlist: dfile = os.path.join(self.schema_mof_dir, file_) if dfile[-1] == '/': if not os.path.exists(dfile): os.mkdir(dfile) else: with open(dfile, 'w+b') as dfp: dfp.write(zfp.read(file_)) finally: if zfp: zfp.close()
[ "def", "_setup_dmtf_schema", "(", "self", ")", ":", "def", "print_verbose", "(", "msg", ")", ":", "\"\"\"\n Inner method prints msg if self.verbose is `True`.\n \"\"\"", "if", "self", ".", "verbose", ":", "print", "(", "msg", ")", "if", "not", "o...
Install the DMTF CIM schema from the DMTF web site if it is not already installed. This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by `schema_mof_dir`. Once the schema zip file is downloaded into `schema_root_dir`, it is not re-downloaded if this function is recalled since DMTF CIM Schema releases are never modified; new update versions are released for minor changes. If the `schema_zip_file` is in the `schema_root_dir` directory, but no 'schema_mof_dir' subdirectory exists, the schema is unzipped. This allows the DMTF CIM schema zip file to be downloaded once and reused and the user to chose if they want to retain the extracted MOF files or remove them with :meth:`~pywbem_mock.DMTFCIMSchema.clean` when not being used. If the schema is to be committed a source repository such as git it is logical to commit only the DMTF CIM schema zip file. Creation of the `schema_mof_dir` subdirectory will be created when the :class:`pywbem_mock.DMTFCIMSchema` object is created. Raises: ValueError: If the schema cannot be retrieved from the DMTF web site. TypeError: If the `schema_version` is not a valid tuple with 3 integer components
[ "Install", "the", "DMTF", "CIM", "schema", "from", "the", "DMTF", "web", "site", "if", "it", "is", "not", "already", "installed", ".", "This", "includes", "downloading", "the", "DMTF", "CIM", "schema", "zip", "file", "from", "the", "DMTF", "web", "site", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_dmtf_cim_schema.py#L299-L384
train
28,225
pywbem/pywbem
pywbem_mock/_dmtf_cim_schema.py
DMTFCIMSchema.clean
def clean(self): """ Remove all of the MOF files and the `schema_mof_dir` for the defined schema. This is useful because while the downloaded schema is a single compressed zip file, it creates several thousand MOF files that take up considerable space. The next time the :class:`~pywbem_mock.DMTFCIMSchema` object for this `schema_version` and `schema_root_dir` is created, the MOF file are extracted again. """ if os.path.isdir(self.schema_mof_dir): shutil.rmtree(self.schema_mof_dir)
python
def clean(self): """ Remove all of the MOF files and the `schema_mof_dir` for the defined schema. This is useful because while the downloaded schema is a single compressed zip file, it creates several thousand MOF files that take up considerable space. The next time the :class:`~pywbem_mock.DMTFCIMSchema` object for this `schema_version` and `schema_root_dir` is created, the MOF file are extracted again. """ if os.path.isdir(self.schema_mof_dir): shutil.rmtree(self.schema_mof_dir)
[ "def", "clean", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "schema_mof_dir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "schema_mof_dir", ")" ]
Remove all of the MOF files and the `schema_mof_dir` for the defined schema. This is useful because while the downloaded schema is a single compressed zip file, it creates several thousand MOF files that take up considerable space. The next time the :class:`~pywbem_mock.DMTFCIMSchema` object for this `schema_version` and `schema_root_dir` is created, the MOF file are extracted again.
[ "Remove", "all", "of", "the", "MOF", "files", "and", "the", "schema_mof_dir", "for", "the", "defined", "schema", ".", "This", "is", "useful", "because", "while", "the", "downloaded", "schema", "is", "a", "single", "compressed", "zip", "file", "it", "creates"...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_dmtf_cim_schema.py#L445-L457
train
28,226
pywbem/pywbem
pywbem_mock/_dmtf_cim_schema.py
DMTFCIMSchema.remove
def remove(self): """ The `schema_mof_dir` directory is removed if it esists and the `schema_zip_file` is removed if it exists. If the `schema_root_dir` is empty after these removals that directory is removed. """ self.clean() if os.path.isfile(self.schema_zip_file): os.remove(self.schema_zip_file) if os.path.isdir(self.schema_root_dir) and \ os.listdir(self.schema_root_dir) == []: os.rmdir(self.schema_root_dir)
python
def remove(self): """ The `schema_mof_dir` directory is removed if it esists and the `schema_zip_file` is removed if it exists. If the `schema_root_dir` is empty after these removals that directory is removed. """ self.clean() if os.path.isfile(self.schema_zip_file): os.remove(self.schema_zip_file) if os.path.isdir(self.schema_root_dir) and \ os.listdir(self.schema_root_dir) == []: os.rmdir(self.schema_root_dir)
[ "def", "remove", "(", "self", ")", ":", "self", ".", "clean", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "schema_zip_file", ")", ":", "os", ".", "remove", "(", "self", ".", "schema_zip_file", ")", "if", "os", ".", "path", ...
The `schema_mof_dir` directory is removed if it esists and the `schema_zip_file` is removed if it exists. If the `schema_root_dir` is empty after these removals that directory is removed.
[ "The", "schema_mof_dir", "directory", "is", "removed", "if", "it", "esists", "and", "the", "schema_zip_file", "is", "removed", "if", "it", "exists", ".", "If", "the", "schema_root_dir", "is", "empty", "after", "these", "removals", "that", "directory", "is", "r...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_dmtf_cim_schema.py#L459-L470
train
28,227
pywbem/pywbem
try/run_central_instances.py
print_table
def print_table(title, headers, rows, sort_columns=None): """ Print a table of rows with headers using tabulate. Parameters: title (:term: string): String that will be output before the Table. headers (list or tuple): List of strings that defines the header for each row. Each string in this list may be multiline by inserting EOL in the string rows (iterable of iterables) The outer iterable is the rows. The inner iterables are the colums for each row args (int or list of int that defines sort) Defines the cols that will be sorted. If int, it defines the column that will be sorted. If list of int, the sort is in sort order of cols in the list (i.e. minor sorts to the left, major sorts to the right) """ if sort_columns is not None: if isinstance(sort_columns, int): rows = sorted(rows, key=itemgetter(sort_columns)) elif isinstance(sort_columns, (list, tuple)): rows = sorted(rows, key=itemgetter(*sort_columns)) else: assert False, "Sort_columns must be int or list/tuple of int" if title: print('\n%s:' % title) else: print('') print(tabulate.tabulate(rows, headers, tablefmt='simple')) print('')
python
def print_table(title, headers, rows, sort_columns=None): """ Print a table of rows with headers using tabulate. Parameters: title (:term: string): String that will be output before the Table. headers (list or tuple): List of strings that defines the header for each row. Each string in this list may be multiline by inserting EOL in the string rows (iterable of iterables) The outer iterable is the rows. The inner iterables are the colums for each row args (int or list of int that defines sort) Defines the cols that will be sorted. If int, it defines the column that will be sorted. If list of int, the sort is in sort order of cols in the list (i.e. minor sorts to the left, major sorts to the right) """ if sort_columns is not None: if isinstance(sort_columns, int): rows = sorted(rows, key=itemgetter(sort_columns)) elif isinstance(sort_columns, (list, tuple)): rows = sorted(rows, key=itemgetter(*sort_columns)) else: assert False, "Sort_columns must be int or list/tuple of int" if title: print('\n%s:' % title) else: print('') print(tabulate.tabulate(rows, headers, tablefmt='simple')) print('')
[ "def", "print_table", "(", "title", ",", "headers", ",", "rows", ",", "sort_columns", "=", "None", ")", ":", "if", "sort_columns", "is", "not", "None", ":", "if", "isinstance", "(", "sort_columns", ",", "int", ")", ":", "rows", "=", "sorted", "(", "row...
Print a table of rows with headers using tabulate. Parameters: title (:term: string): String that will be output before the Table. headers (list or tuple): List of strings that defines the header for each row. Each string in this list may be multiline by inserting EOL in the string rows (iterable of iterables) The outer iterable is the rows. The inner iterables are the colums for each row args (int or list of int that defines sort) Defines the cols that will be sorted. If int, it defines the column that will be sorted. If list of int, the sort is in sort order of cols in the list (i.e. minor sorts to the left, major sorts to the right)
[ "Print", "a", "table", "of", "rows", "with", "headers", "using", "tabulate", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L167-L204
train
28,228
pywbem/pywbem
try/run_central_instances.py
fold_list
def fold_list(input_list, max_width=None): """ Fold the entries in input_list. If max_width is not None, fold only if it is longer than max_width. Otherwise fold each entry. """ if not input_list: return "" if not isinstance(input_list[0], six.string_types): input_list = [str(item) for item in input_list] if max_width: mystr = ", ".join(input_list) return fold_string(mystr, max_width) return "\n".join(input_list)
python
def fold_list(input_list, max_width=None): """ Fold the entries in input_list. If max_width is not None, fold only if it is longer than max_width. Otherwise fold each entry. """ if not input_list: return "" if not isinstance(input_list[0], six.string_types): input_list = [str(item) for item in input_list] if max_width: mystr = ", ".join(input_list) return fold_string(mystr, max_width) return "\n".join(input_list)
[ "def", "fold_list", "(", "input_list", ",", "max_width", "=", "None", ")", ":", "if", "not", "input_list", ":", "return", "\"\"", "if", "not", "isinstance", "(", "input_list", "[", "0", "]", ",", "six", ".", "string_types", ")", ":", "input_list", "=", ...
Fold the entries in input_list. If max_width is not None, fold only if it is longer than max_width. Otherwise fold each entry.
[ "Fold", "the", "entries", "in", "input_list", ".", "If", "max_width", "is", "not", "None", "fold", "only", "if", "it", "is", "longer", "than", "max_width", ".", "Otherwise", "fold", "each", "entry", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L207-L221
train
28,229
pywbem/pywbem
try/run_central_instances.py
fold_string
def fold_string(input_string, max_width): """ Fold a string within a maximum width. Parameters: input_string: The string of data to go into the cell max_width: Maximum width of cell. Data is folded into multiple lines to fit into this width. Return: String representing the folded string """ new_string = input_string if isinstance(input_string, six.string_types): if max_width < len(input_string): # use textwrap to fold the string new_string = textwrap.fill(input_string, max_width) return new_string
python
def fold_string(input_string, max_width): """ Fold a string within a maximum width. Parameters: input_string: The string of data to go into the cell max_width: Maximum width of cell. Data is folded into multiple lines to fit into this width. Return: String representing the folded string """ new_string = input_string if isinstance(input_string, six.string_types): if max_width < len(input_string): # use textwrap to fold the string new_string = textwrap.fill(input_string, max_width) return new_string
[ "def", "fold_string", "(", "input_string", ",", "max_width", ")", ":", "new_string", "=", "input_string", "if", "isinstance", "(", "input_string", ",", "six", ".", "string_types", ")", ":", "if", "max_width", "<", "len", "(", "input_string", ")", ":", "# use...
Fold a string within a maximum width. Parameters: input_string: The string of data to go into the cell max_width: Maximum width of cell. Data is folded into multiple lines to fit into this width. Return: String representing the folded string
[ "Fold", "a", "string", "within", "a", "maximum", "width", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L224-L245
train
28,230
pywbem/pywbem
try/run_central_instances.py
path_wo_ns
def path_wo_ns(obj): """ Return path of an instance or instance path without host or namespace. Creates copy of the object so the original is not changed. """ if isinstance(obj, pywbem.CIMInstance): path = obj.path.copy() elif isinstance(obj, pywbem.CIMInstanceName): path = obj.copy() else: assert False path.host = None path.namespace = None return path
python
def path_wo_ns(obj): """ Return path of an instance or instance path without host or namespace. Creates copy of the object so the original is not changed. """ if isinstance(obj, pywbem.CIMInstance): path = obj.path.copy() elif isinstance(obj, pywbem.CIMInstanceName): path = obj.copy() else: assert False path.host = None path.namespace = None return path
[ "def", "path_wo_ns", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "pywbem", ".", "CIMInstance", ")", ":", "path", "=", "obj", ".", "path", ".", "copy", "(", ")", "elif", "isinstance", "(", "obj", ",", "pywbem", ".", "CIMInstanceName", "...
Return path of an instance or instance path without host or namespace. Creates copy of the object so the original is not changed.
[ "Return", "path", "of", "an", "instance", "or", "instance", "path", "without", "host", "or", "namespace", ".", "Creates", "copy", "of", "the", "object", "so", "the", "original", "is", "not", "changed", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L291-L305
train
28,231
pywbem/pywbem
try/run_central_instances.py
connect
def connect(nickname, server_def, debug=None, timeout=10): """ Connect and confirm server works by testing for a known class in the default namespace or if there is no default namespace defined, in all the possible interop namespaces. returns a WBEMConnection object or None if the connection fails. """ url = server_def.url conn = pywbem.WBEMConnection( url, (server_def.user, server_def.password), default_namespace=server_def.implementation_namespace, no_verification=server_def.no_verification, timeout=timeout) if debug: conn.debug = True ns = server_def.implementation_namespace if \ server_def.implementation_namespace \ else 'interop' try: conn.GetQualifier('Association', namespace=ns) return conn except pywbem.ConnectionError as exc: print("Test server {0} at {1!r} cannot be reached. {2}: {3}". format(nickname, url, exc.__class__.__name__, exc)) return None except pywbem.AuthError as exc: print("Test server {0} at {1!r} cannot be authenticated with. " "{2}: {3}". format(nickname, url, exc.__class__.__name__, exc)) return None except pywbem.CIMError as ce: if ce.status_code == pywbem.CIM_ERR_NAMESPACE_NOT_FOUND or \ ce.status.code == pywbem.CIM_ERR_NOT_FOUND: return conn else: return None except pywbem.Error as exc: print("Test server {0} at {1!r} returned exception. {2}: {3}". format(nickname, url, exc.__class__.__name__, exc)) return None
python
def connect(nickname, server_def, debug=None, timeout=10): """ Connect and confirm server works by testing for a known class in the default namespace or if there is no default namespace defined, in all the possible interop namespaces. returns a WBEMConnection object or None if the connection fails. """ url = server_def.url conn = pywbem.WBEMConnection( url, (server_def.user, server_def.password), default_namespace=server_def.implementation_namespace, no_verification=server_def.no_verification, timeout=timeout) if debug: conn.debug = True ns = server_def.implementation_namespace if \ server_def.implementation_namespace \ else 'interop' try: conn.GetQualifier('Association', namespace=ns) return conn except pywbem.ConnectionError as exc: print("Test server {0} at {1!r} cannot be reached. {2}: {3}". format(nickname, url, exc.__class__.__name__, exc)) return None except pywbem.AuthError as exc: print("Test server {0} at {1!r} cannot be authenticated with. " "{2}: {3}". format(nickname, url, exc.__class__.__name__, exc)) return None except pywbem.CIMError as ce: if ce.status_code == pywbem.CIM_ERR_NAMESPACE_NOT_FOUND or \ ce.status.code == pywbem.CIM_ERR_NOT_FOUND: return conn else: return None except pywbem.Error as exc: print("Test server {0} at {1!r} returned exception. {2}: {3}". format(nickname, url, exc.__class__.__name__, exc)) return None
[ "def", "connect", "(", "nickname", ",", "server_def", ",", "debug", "=", "None", ",", "timeout", "=", "10", ")", ":", "url", "=", "server_def", ".", "url", "conn", "=", "pywbem", ".", "WBEMConnection", "(", "url", ",", "(", "server_def", ".", "user", ...
Connect and confirm server works by testing for a known class in the default namespace or if there is no default namespace defined, in all the possible interop namespaces. returns a WBEMConnection object or None if the connection fails.
[ "Connect", "and", "confirm", "server", "works", "by", "testing", "for", "a", "known", "class", "in", "the", "default", "namespace", "or", "if", "there", "is", "no", "default", "namespace", "defined", "in", "all", "the", "possible", "interop", "namespaces", "...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L351-L393
train
28,232
pywbem/pywbem
try/run_central_instances.py
overview
def overview(name, server): """ Overview of the server as seen through the properties of the server class. """ print('%s OVERVIEW' % name) print(" Interop namespace: %s" % server.interop_ns) print(" Brand: %s" % server.brand) print(" Version: %s" % server.version) print(" Namespaces: %s" % ", ".join(server.namespaces)) print(' namespace_classname: %s' % server.namespace_classname) if VERBOSE: print('cimom_inst:\n%s' % server.cimom_inst.tomof()) print('server__str__: %s' % server) print('server__repr__: %r' % server) try: insts = server.conn.EnumerateInstances('CIM_Namespace', namespace=server.interop_ns) print('%s: Instances of CIM_Namespace' % name) for inst in insts: print('%r' % inst) except pywbem.Error as er: print('ERROR: %s: Enum CIM_Namespace failed %s' % (name, er)) try: insts = server.conn.EnumerateInstances('__Namespace', namespace=server.interop_ns) print('%s: Instances of __Namespace' % name) for inst in insts: print('%r' % inst) except pywbem.Error as er: print('ERROR: %s: Enum __Namespace failed %s' % (name, er))
python
def overview(name, server): """ Overview of the server as seen through the properties of the server class. """ print('%s OVERVIEW' % name) print(" Interop namespace: %s" % server.interop_ns) print(" Brand: %s" % server.brand) print(" Version: %s" % server.version) print(" Namespaces: %s" % ", ".join(server.namespaces)) print(' namespace_classname: %s' % server.namespace_classname) if VERBOSE: print('cimom_inst:\n%s' % server.cimom_inst.tomof()) print('server__str__: %s' % server) print('server__repr__: %r' % server) try: insts = server.conn.EnumerateInstances('CIM_Namespace', namespace=server.interop_ns) print('%s: Instances of CIM_Namespace' % name) for inst in insts: print('%r' % inst) except pywbem.Error as er: print('ERROR: %s: Enum CIM_Namespace failed %s' % (name, er)) try: insts = server.conn.EnumerateInstances('__Namespace', namespace=server.interop_ns) print('%s: Instances of __Namespace' % name) for inst in insts: print('%r' % inst) except pywbem.Error as er: print('ERROR: %s: Enum __Namespace failed %s' % (name, er))
[ "def", "overview", "(", "name", ",", "server", ")", ":", "print", "(", "'%s OVERVIEW'", "%", "name", ")", "print", "(", "\" Interop namespace: %s\"", "%", "server", ".", "interop_ns", ")", "print", "(", "\" Brand: %s\"", "%", "server", ".", "brand", ")", ...
Overview of the server as seen through the properties of the server class.
[ "Overview", "of", "the", "server", "as", "seen", "through", "the", "properties", "of", "the", "server", "class", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L454-L485
train
28,233
pywbem/pywbem
try/run_central_instances.py
get_references
def get_references(profile_path, role, profile_name, server): """ Get display and return the References for the path provided, ResultClass CIM_ReferencedProfile, and the role provided. """ references_for_profile = server.conn.References( ObjectName=profile_path, ResultClass="CIM_ReferencedProfile", Role=role) if VERBOSE: print('References for profile=%s, path=%s, ResultClass=' 'CIM_ReferencedProfile, Role=%s' % (profile_name, profile_path, role)) for ref in references_for_profile: print('Reference for %s get_role=%s cn=%s\n antecedent=%s\n ' 'dependent=%s' % (profile_name, role, ref.classname, ref['Antecedent'], ref['Dependent'])) return references_for_profile
python
def get_references(profile_path, role, profile_name, server): """ Get display and return the References for the path provided, ResultClass CIM_ReferencedProfile, and the role provided. """ references_for_profile = server.conn.References( ObjectName=profile_path, ResultClass="CIM_ReferencedProfile", Role=role) if VERBOSE: print('References for profile=%s, path=%s, ResultClass=' 'CIM_ReferencedProfile, Role=%s' % (profile_name, profile_path, role)) for ref in references_for_profile: print('Reference for %s get_role=%s cn=%s\n antecedent=%s\n ' 'dependent=%s' % (profile_name, role, ref.classname, ref['Antecedent'], ref['Dependent'])) return references_for_profile
[ "def", "get_references", "(", "profile_path", ",", "role", ",", "profile_name", ",", "server", ")", ":", "references_for_profile", "=", "server", ".", "conn", ".", "References", "(", "ObjectName", "=", "profile_path", ",", "ResultClass", "=", "\"CIM_ReferencedProf...
Get display and return the References for the path provided, ResultClass CIM_ReferencedProfile, and the role provided.
[ "Get", "display", "and", "return", "the", "References", "for", "the", "path", "provided", "ResultClass", "CIM_ReferencedProfile", "and", "the", "role", "provided", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L525-L544
train
28,234
pywbem/pywbem
try/run_central_instances.py
show_profiles
def show_profiles(name, server, org_vm): """ Create a table of info about the profiles based on getting the references, etc. both in the dependent and antecedent direction. The resulting table is printed. """ rows = [] for profile_inst in server.profiles: pn = profile_name(org_vm, profile_inst) deps = get_associated_profile_names( profile_inst.path, "dependent", org_vm, server, include_classnames=False) dep_refs = get_references(profile_inst.path, "antecedent", pn, server) ants = get_associated_profile_names( profile_inst.path, "antecedent", org_vm, server, include_classnames=False) ant_refs = get_references(profile_inst.path, "dependent", profile_name, server) # get unique class names dep_ref_clns = set([ref.classname for ref in dep_refs]) ant_ref_clns = set([ref.classname for ref in ant_refs]) row = (pn, fold_list(deps), fold_list(list(dep_ref_clns)), fold_list(ants), fold_list(list(ant_ref_clns))) rows.append(row) # append this server to the dict of servers for this profile SERVERS_FOR_PROFILE[profile_name].append(name) title = '%s: Advertised profiles showing Profiles associations' \ 'Dependencies are Associators, AssocClass=CIM_ReferencedProfile' \ 'This table shows the results for ' % name headers = ['Profile', 'Assoc CIMReferencedProfile\nResultRole\nDependent', 'Ref classes References\nRole=Dependent', 'Assoc CIMReferencedProfile\nResultRole\nAntecedent', 'Ref classesReferences\nRole=Dependent'] print_table(title, headers, rows, sort_columns=[1, 0])
python
def show_profiles(name, server, org_vm): """ Create a table of info about the profiles based on getting the references, etc. both in the dependent and antecedent direction. The resulting table is printed. """ rows = [] for profile_inst in server.profiles: pn = profile_name(org_vm, profile_inst) deps = get_associated_profile_names( profile_inst.path, "dependent", org_vm, server, include_classnames=False) dep_refs = get_references(profile_inst.path, "antecedent", pn, server) ants = get_associated_profile_names( profile_inst.path, "antecedent", org_vm, server, include_classnames=False) ant_refs = get_references(profile_inst.path, "dependent", profile_name, server) # get unique class names dep_ref_clns = set([ref.classname for ref in dep_refs]) ant_ref_clns = set([ref.classname for ref in ant_refs]) row = (pn, fold_list(deps), fold_list(list(dep_ref_clns)), fold_list(ants), fold_list(list(ant_ref_clns))) rows.append(row) # append this server to the dict of servers for this profile SERVERS_FOR_PROFILE[profile_name].append(name) title = '%s: Advertised profiles showing Profiles associations' \ 'Dependencies are Associators, AssocClass=CIM_ReferencedProfile' \ 'This table shows the results for ' % name headers = ['Profile', 'Assoc CIMReferencedProfile\nResultRole\nDependent', 'Ref classes References\nRole=Dependent', 'Assoc CIMReferencedProfile\nResultRole\nAntecedent', 'Ref classesReferences\nRole=Dependent'] print_table(title, headers, rows, sort_columns=[1, 0])
[ "def", "show_profiles", "(", "name", ",", "server", ",", "org_vm", ")", ":", "rows", "=", "[", "]", "for", "profile_inst", "in", "server", ".", "profiles", ":", "pn", "=", "profile_name", "(", "org_vm", ",", "profile_inst", ")", "deps", "=", "get_associa...
Create a table of info about the profiles based on getting the references, etc. both in the dependent and antecedent direction. The resulting table is printed.
[ "Create", "a", "table", "of", "info", "about", "the", "profiles", "based", "on", "getting", "the", "references", "etc", ".", "both", "in", "the", "dependent", "and", "antecedent", "direction", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L547-L588
train
28,235
pywbem/pywbem
try/run_central_instances.py
fold_path
def fold_path(path, width=30): """ Fold a string form of a path so that each element is on separate line """ assert isinstance(path, six.string_types) if len(path) > width: path.replace(".", ".\n ") return path
python
def fold_path(path, width=30): """ Fold a string form of a path so that each element is on separate line """ assert isinstance(path, six.string_types) if len(path) > width: path.replace(".", ".\n ") return path
[ "def", "fold_path", "(", "path", ",", "width", "=", "30", ")", ":", "assert", "isinstance", "(", "path", ",", "six", ".", "string_types", ")", "if", "len", "(", "path", ")", ">", "width", ":", "path", ".", "replace", "(", "\".\"", ",", "\".\\n \""...
Fold a string form of a path so that each element is on separate line
[ "Fold", "a", "string", "form", "of", "a", "path", "so", "that", "each", "element", "is", "on", "separate", "line" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L591-L598
train
28,236
pywbem/pywbem
try/run_central_instances.py
count_ref_associators
def count_ref_associators(nickname, server, profile_insts, org_vm): """ Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list. This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile instance in profile_insts with the result Role set to Dependent and then Antecedent to get the count of objects returned. Returns a dictionary where keys are profile name and value are a tuple of the number of associator instances for each of the AssociatorName calls. NOTE: This can take a long time because it executes 2 server requests for each profile in profile_insts. """ def get_assoc_count(server, profile_inst): """ Execute Associator names with ResultRole as 'Dependent' and then as 'Antecedent' and return the count of associations returned for each operation """ deps = server.conn.AssociatorNames( ObjectName=profile_inst.path, AssocClass="CIM_ReferencedProfile", ResultRole='Dependent') ants = server.conn.AssociatorNames( ObjectName=profile_inst.path, AssocClass="CIM_ReferencedProfile", ResultRole='Antecedent') return (len(deps), len(ants)) assoc_dict = {} for profile_inst in profile_insts: deps_count, ants_count = get_assoc_count(server, profile_inst) pn = profile_name(org_vm, profile_inst) assoc_dict[pn] = (deps_count, ants_count) title = 'Display antecedent and dependent counts for possible ' \ 'autonomous profiles using slow algorithm.\n' \ 'Displays the number of instances returned by\n' \ 'Associators request on profile for possible autonomous profiles' rows = [(key, value[0], value[1]) for key, value in assoc_dict.items()] print_table(title, ['profile', 'Dependent\nCount', 'Antecedent\nCount'], rows, sort_columns=0) # add rows to the global list for table of g_rows = [(nickname, key, value[0], value[1]) for key, value in assoc_dict.items()] ASSOC_PROPERTY_COUNTS.extend(g_rows) return assoc_dict
python
def count_ref_associators(nickname, server, profile_insts, org_vm): """ Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list. This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile instance in profile_insts with the result Role set to Dependent and then Antecedent to get the count of objects returned. Returns a dictionary where keys are profile name and value are a tuple of the number of associator instances for each of the AssociatorName calls. NOTE: This can take a long time because it executes 2 server requests for each profile in profile_insts. """ def get_assoc_count(server, profile_inst): """ Execute Associator names with ResultRole as 'Dependent' and then as 'Antecedent' and return the count of associations returned for each operation """ deps = server.conn.AssociatorNames( ObjectName=profile_inst.path, AssocClass="CIM_ReferencedProfile", ResultRole='Dependent') ants = server.conn.AssociatorNames( ObjectName=profile_inst.path, AssocClass="CIM_ReferencedProfile", ResultRole='Antecedent') return (len(deps), len(ants)) assoc_dict = {} for profile_inst in profile_insts: deps_count, ants_count = get_assoc_count(server, profile_inst) pn = profile_name(org_vm, profile_inst) assoc_dict[pn] = (deps_count, ants_count) title = 'Display antecedent and dependent counts for possible ' \ 'autonomous profiles using slow algorithm.\n' \ 'Displays the number of instances returned by\n' \ 'Associators request on profile for possible autonomous profiles' rows = [(key, value[0], value[1]) for key, value in assoc_dict.items()] print_table(title, ['profile', 'Dependent\nCount', 'Antecedent\nCount'], rows, sort_columns=0) # add rows to the global list for table of g_rows = [(nickname, key, value[0], value[1]) for key, value in assoc_dict.items()] ASSOC_PROPERTY_COUNTS.extend(g_rows) return assoc_dict
[ "def", "count_ref_associators", "(", "nickname", ",", "server", ",", "profile_insts", ",", "org_vm", ")", ":", "def", "get_assoc_count", "(", "server", ",", "profile_inst", ")", ":", "\"\"\"\n Execute Associator names with ResultRole as 'Dependent' and then as\n ...
Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list. This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile instance in profile_insts with the result Role set to Dependent and then Antecedent to get the count of objects returned. Returns a dictionary where keys are profile name and value are a tuple of the number of associator instances for each of the AssociatorName calls. NOTE: This can take a long time because it executes 2 server requests for each profile in profile_insts.
[ "Get", "dict", "of", "counts", "of", "associator", "returns", "for", "ResultRole", "==", "Dependent", "and", "ResultRole", "==", "Antecedent", "for", "profiles", "in", "list", ".", "This", "method", "counts", "by", "executing", "repeated", "AssociationName", "ca...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L601-L651
train
28,237
pywbem/pywbem
try/run_central_instances.py
fast_count_associators
def fast_count_associators(server): """ Create count of associators for CIM_ReferencedProfile using the antecedent and dependent reference properties as ResultRole for each profile defined in server.profiles and return a dictionary of the count. This code does a shortcut in executing EnumerateInstances to get CIM_ReferencedProfile and processing the association locally. Returns Dictionary where the keys are the profile names and the value for each key is a dictionary with two keys ('dep' and 'ant') and the value is the count of associator paths when the key value is used as the ResultRole """ try: ref_insts = server.conn.EnumerateInstances("CIM_ReferencedProfile", namespace=server.interop_ns) # Remove host from responses since the host causes confusion # with the enum of registered profile. Enums do not return host but # the associator properties contain host for ref_inst in ref_insts: for prop in ref_inst.values(): prop.host = None except pywbem.Error as er: print('CIM_ReferencedProfile failed for conn=%s\nexception=%s' % (server, er)) raise # Create dict with the following characteristics: # key = associator source object path # value = {'dep' : count of associations, # 'ant' : count of associations} # where: an association is a reference property that does not have same # value as the source object path but for which the source object # path is the value of one of the properties association_dict = {} # We are counting too many. Have same properties for class and subclass # but appear to count that one twice. Looks like we need one more piece. # for each. If association_dict[profile_key] not in some list for profile in server.profiles: profile_key = profile.path ant_dict = {} dep_dict = {} for ref_inst in ref_insts: # These dictionaries insure that there are no duplicates in # the result. Some servers duplicate the references in subclasses. if profile_key not in association_dict: association_dict[profile_key] = {'dep': 0, 'ant': 0} ant = ref_inst['antecedent'] dep = ref_inst['dependent'] if profile_key != ant and profile_key != dep: continue if dep != profile_key: if dep not in dep_dict: dep_dict[dep] = True association_dict[profile_key]['dep'] += 1 if ant != profile_key: if ant not in ant_dict: ant_dict[ant] = True association_dict[profile_key]['ant'] += 1 return association_dict
python
def fast_count_associators(server): """ Create count of associators for CIM_ReferencedProfile using the antecedent and dependent reference properties as ResultRole for each profile defined in server.profiles and return a dictionary of the count. This code does a shortcut in executing EnumerateInstances to get CIM_ReferencedProfile and processing the association locally. Returns Dictionary where the keys are the profile names and the value for each key is a dictionary with two keys ('dep' and 'ant') and the value is the count of associator paths when the key value is used as the ResultRole """ try: ref_insts = server.conn.EnumerateInstances("CIM_ReferencedProfile", namespace=server.interop_ns) # Remove host from responses since the host causes confusion # with the enum of registered profile. Enums do not return host but # the associator properties contain host for ref_inst in ref_insts: for prop in ref_inst.values(): prop.host = None except pywbem.Error as er: print('CIM_ReferencedProfile failed for conn=%s\nexception=%s' % (server, er)) raise # Create dict with the following characteristics: # key = associator source object path # value = {'dep' : count of associations, # 'ant' : count of associations} # where: an association is a reference property that does not have same # value as the source object path but for which the source object # path is the value of one of the properties association_dict = {} # We are counting too many. Have same properties for class and subclass # but appear to count that one twice. Looks like we need one more piece. # for each. If association_dict[profile_key] not in some list for profile in server.profiles: profile_key = profile.path ant_dict = {} dep_dict = {} for ref_inst in ref_insts: # These dictionaries insure that there are no duplicates in # the result. Some servers duplicate the references in subclasses. if profile_key not in association_dict: association_dict[profile_key] = {'dep': 0, 'ant': 0} ant = ref_inst['antecedent'] dep = ref_inst['dependent'] if profile_key != ant and profile_key != dep: continue if dep != profile_key: if dep not in dep_dict: dep_dict[dep] = True association_dict[profile_key]['dep'] += 1 if ant != profile_key: if ant not in ant_dict: ant_dict[ant] = True association_dict[profile_key]['ant'] += 1 return association_dict
[ "def", "fast_count_associators", "(", "server", ")", ":", "try", ":", "ref_insts", "=", "server", ".", "conn", ".", "EnumerateInstances", "(", "\"CIM_ReferencedProfile\"", ",", "namespace", "=", "server", ".", "interop_ns", ")", "# Remove host from responses since the...
Create count of associators for CIM_ReferencedProfile using the antecedent and dependent reference properties as ResultRole for each profile defined in server.profiles and return a dictionary of the count. This code does a shortcut in executing EnumerateInstances to get CIM_ReferencedProfile and processing the association locally. Returns Dictionary where the keys are the profile names and the value for each key is a dictionary with two keys ('dep' and 'ant') and the value is the count of associator paths when the key value is used as the ResultRole
[ "Create", "count", "of", "associators", "for", "CIM_ReferencedProfile", "using", "the", "antecedent", "and", "dependent", "reference", "properties", "as", "ResultRole", "for", "each", "profile", "defined", "in", "server", ".", "profiles", "and", "return", "a", "di...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L755-L819
train
28,238
pywbem/pywbem
try/run_central_instances.py
show_instances
def show_instances(server, cim_class): """ Display the instances of the CIM_Class defined by cim_class. If the namespace is None, use the interop namespace. Search all namespaces for instances except for CIM_RegisteredProfile """ if cim_class == 'CIM_RegisteredProfile': for inst in server.profiles: print(inst.tomof()) return for ns in server.namespaces: try: insts = server.conn.EnumerateInstances(cim_class, namespace=ns) if len(insts): print('INSTANCES OF %s ns=%s' % (cim_class, ns)) for inst in insts: print(inst.tomof()) except pywbem.Error as er: if er.status_code != pywbem.CIM_ERR_INVALID_CLASS: print('%s namespace %s Enumerate failed for conn=%s\n' 'exception=%s' % (cim_class, ns, server, er))
python
def show_instances(server, cim_class): """ Display the instances of the CIM_Class defined by cim_class. If the namespace is None, use the interop namespace. Search all namespaces for instances except for CIM_RegisteredProfile """ if cim_class == 'CIM_RegisteredProfile': for inst in server.profiles: print(inst.tomof()) return for ns in server.namespaces: try: insts = server.conn.EnumerateInstances(cim_class, namespace=ns) if len(insts): print('INSTANCES OF %s ns=%s' % (cim_class, ns)) for inst in insts: print(inst.tomof()) except pywbem.Error as er: if er.status_code != pywbem.CIM_ERR_INVALID_CLASS: print('%s namespace %s Enumerate failed for conn=%s\n' 'exception=%s' % (cim_class, ns, server, er))
[ "def", "show_instances", "(", "server", ",", "cim_class", ")", ":", "if", "cim_class", "==", "'CIM_RegisteredProfile'", ":", "for", "inst", "in", "server", ".", "profiles", ":", "print", "(", "inst", ".", "tomof", "(", ")", ")", "return", "for", "ns", "i...
Display the instances of the CIM_Class defined by cim_class. If the namespace is None, use the interop namespace. Search all namespaces for instances except for CIM_RegisteredProfile
[ "Display", "the", "instances", "of", "the", "CIM_Class", "defined", "by", "cim_class", ".", "If", "the", "namespace", "is", "None", "use", "the", "interop", "namespace", ".", "Search", "all", "namespaces", "for", "instances", "except", "for", "CIM_RegisteredProf...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L1096-L1118
train
28,239
pywbem/pywbem
try/run_central_instances.py
get_profiles_in_svr
def get_profiles_in_svr(nickname, server, all_profiles_dict, org_vm, add_error_list=False): """ Test all profiles in server.profiles to determine if profile is in the all_profiles_dict. Returns list of profiles in the profile_dict and in the defined server. If add_error_list is True, it also adds profiles not found to PROFILES_WITH_NO_DEFINITIONS. """ profiles_in_dict = [] for profile_inst in server.profiles: pn = profile_name(org_vm, profile_inst, short=True) if pn in all_profiles_dict: profiles_in_dict.append(profile_inst) else: if add_error_list: print('PROFILES_WITH_NO_DEFINITIONS svr=%s: %s' % (nickname, pn)) PROFILES_WITH_NO_DEFINITIONS[nickname] = pn return profiles_in_dict
python
def get_profiles_in_svr(nickname, server, all_profiles_dict, org_vm, add_error_list=False): """ Test all profiles in server.profiles to determine if profile is in the all_profiles_dict. Returns list of profiles in the profile_dict and in the defined server. If add_error_list is True, it also adds profiles not found to PROFILES_WITH_NO_DEFINITIONS. """ profiles_in_dict = [] for profile_inst in server.profiles: pn = profile_name(org_vm, profile_inst, short=True) if pn in all_profiles_dict: profiles_in_dict.append(profile_inst) else: if add_error_list: print('PROFILES_WITH_NO_DEFINITIONS svr=%s: %s' % (nickname, pn)) PROFILES_WITH_NO_DEFINITIONS[nickname] = pn return profiles_in_dict
[ "def", "get_profiles_in_svr", "(", "nickname", ",", "server", ",", "all_profiles_dict", ",", "org_vm", ",", "add_error_list", "=", "False", ")", ":", "profiles_in_dict", "=", "[", "]", "for", "profile_inst", "in", "server", ".", "profiles", ":", "pn", "=", "...
Test all profiles in server.profiles to determine if profile is in the all_profiles_dict. Returns list of profiles in the profile_dict and in the defined server. If add_error_list is True, it also adds profiles not found to PROFILES_WITH_NO_DEFINITIONS.
[ "Test", "all", "profiles", "in", "server", ".", "profiles", "to", "determine", "if", "profile", "is", "in", "the", "all_profiles_dict", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L1216-L1236
train
28,240
pywbem/pywbem
try/run_central_instances.py
possible_target_profiles
def possible_target_profiles(nickname, server, all_profiles_dict, org_vm, autonomous=True, output='path'): """ Get list of possible autonomous or component profiles based on the list of all profiles and the list of profiles in the defined server. Returns list of *paths or insts, or profile names depending on the value of the output parameter. """ assert output in ['path', 'name'] profiles_in_svr = get_profiles_in_svr(nickname, server, all_profiles_dict, org_vm) # list of possible autonomous profiles for testing possible_profiles = [] for profile_inst in profiles_in_svr: profile_org_name = profile_name(org_vm, profile_inst, short=True) if autonomous: if all_profiles_dict[profile_org_name].type == 'autonomous': possible_profiles.append(profile_inst) else: if not all_profiles_dict[profile_org_name].type == 'component': possible_profiles.append(profile_inst) if output == 'path': possible_profiles = [inst.path for inst in possible_profiles] elif output == 'name': possible_profiles = [profile_name(org_vm, inst) for inst in possible_profiles] return possible_profiles
python
def possible_target_profiles(nickname, server, all_profiles_dict, org_vm, autonomous=True, output='path'): """ Get list of possible autonomous or component profiles based on the list of all profiles and the list of profiles in the defined server. Returns list of *paths or insts, or profile names depending on the value of the output parameter. """ assert output in ['path', 'name'] profiles_in_svr = get_profiles_in_svr(nickname, server, all_profiles_dict, org_vm) # list of possible autonomous profiles for testing possible_profiles = [] for profile_inst in profiles_in_svr: profile_org_name = profile_name(org_vm, profile_inst, short=True) if autonomous: if all_profiles_dict[profile_org_name].type == 'autonomous': possible_profiles.append(profile_inst) else: if not all_profiles_dict[profile_org_name].type == 'component': possible_profiles.append(profile_inst) if output == 'path': possible_profiles = [inst.path for inst in possible_profiles] elif output == 'name': possible_profiles = [profile_name(org_vm, inst) for inst in possible_profiles] return possible_profiles
[ "def", "possible_target_profiles", "(", "nickname", ",", "server", ",", "all_profiles_dict", ",", "org_vm", ",", "autonomous", "=", "True", ",", "output", "=", "'path'", ")", ":", "assert", "output", "in", "[", "'path'", ",", "'name'", "]", "profiles_in_svr", ...
Get list of possible autonomous or component profiles based on the list of all profiles and the list of profiles in the defined server. Returns list of *paths or insts, or profile names depending on the value of the output parameter.
[ "Get", "list", "of", "possible", "autonomous", "or", "component", "profiles", "based", "on", "the", "list", "of", "all", "profiles", "and", "the", "list", "of", "profiles", "in", "the", "defined", "server", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L1286-L1317
train
28,241
pywbem/pywbem
try/run_central_instances.py
show_tree
def show_tree(nickname, server, org_vm, reference_direction='snia'): """ sShow a tree view of the registered profiles using the ECTP and referencedprofile associations to define the tree. Starts with SMI-S if it iexists """ scoping_result_role = "Dependent" if reference_direction == 'snia' \ else "Antecedent" profiles = server.profiles reg_profiles = {} for profile in profiles: reg_profiles[profile.path.to_wbem_uri(format="canonical")] = profile # defines element to subelement tree_dict = defaultdict(list) for profile in profiles: paths = server.conn.AssociatorNames( profile.path, AssocClass='CIM_ElementConformsToProfile', ResultClass="CIM_RegisteredProfile", ResultRole="ManagedElement") if paths: print('%s: associators ELEMENTCONFORMSTO %s' % (nickname, profile.path.to_wbem_uri(format="canonical"))) for path in paths: print(" %s" % path) profile.path.host = None profile_path_str = profile.path.to_wbem_uri(format="canonical") for path in paths: tree_dict[profile_path_str].append( path.to_wbem_uri(format="canonical")) # Go down one level on the profile side, to the scoping profile referenced_profile_paths = server.conn.AssociatorNames( ObjectName=profile.path, AssocClass="CIM_ReferencedProfile", ResultRole=scoping_result_role) if referenced_profile_paths: print('%s AssocNames CIM_ReferencedProfile %s' % (nickname, profile.path.to_wbem_uri(format="canonical"))) for path in referenced_profile_paths: print(" %s" % path.to_wbem_uri(format="canonical")) for path in referenced_profile_paths: path.host = None tree_dict[profile_path_str].append( path.to_wbem_uri(format="canonical")) for key, values in tree_dict.items(): print('%s\n %s' % (key, "\n ".join(values))) name_dict = {} for key, values in tree_dict.items(): prof = reg_profiles[key] pn = profile_name(org_vm, prof) pvalues = [] for value in values: profx = reg_profiles[value] pvalues.append(profile_name(org_vm, profx)) name_dict[pn] = pvalues for key, values in name_dict.items(): print('%s\n %s' % (key, "\n ".join(values)))
python
def show_tree(nickname, server, org_vm, reference_direction='snia'): """ sShow a tree view of the registered profiles using the ECTP and referencedprofile associations to define the tree. Starts with SMI-S if it iexists """ scoping_result_role = "Dependent" if reference_direction == 'snia' \ else "Antecedent" profiles = server.profiles reg_profiles = {} for profile in profiles: reg_profiles[profile.path.to_wbem_uri(format="canonical")] = profile # defines element to subelement tree_dict = defaultdict(list) for profile in profiles: paths = server.conn.AssociatorNames( profile.path, AssocClass='CIM_ElementConformsToProfile', ResultClass="CIM_RegisteredProfile", ResultRole="ManagedElement") if paths: print('%s: associators ELEMENTCONFORMSTO %s' % (nickname, profile.path.to_wbem_uri(format="canonical"))) for path in paths: print(" %s" % path) profile.path.host = None profile_path_str = profile.path.to_wbem_uri(format="canonical") for path in paths: tree_dict[profile_path_str].append( path.to_wbem_uri(format="canonical")) # Go down one level on the profile side, to the scoping profile referenced_profile_paths = server.conn.AssociatorNames( ObjectName=profile.path, AssocClass="CIM_ReferencedProfile", ResultRole=scoping_result_role) if referenced_profile_paths: print('%s AssocNames CIM_ReferencedProfile %s' % (nickname, profile.path.to_wbem_uri(format="canonical"))) for path in referenced_profile_paths: print(" %s" % path.to_wbem_uri(format="canonical")) for path in referenced_profile_paths: path.host = None tree_dict[profile_path_str].append( path.to_wbem_uri(format="canonical")) for key, values in tree_dict.items(): print('%s\n %s' % (key, "\n ".join(values))) name_dict = {} for key, values in tree_dict.items(): prof = reg_profiles[key] pn = profile_name(org_vm, prof) pvalues = [] for value in values: profx = reg_profiles[value] pvalues.append(profile_name(org_vm, profx)) name_dict[pn] = pvalues for key, values in name_dict.items(): print('%s\n %s' % (key, "\n ".join(values)))
[ "def", "show_tree", "(", "nickname", ",", "server", ",", "org_vm", ",", "reference_direction", "=", "'snia'", ")", ":", "scoping_result_role", "=", "\"Dependent\"", "if", "reference_direction", "==", "'snia'", "else", "\"Antecedent\"", "profiles", "=", "server", "...
sShow a tree view of the registered profiles using the ECTP and referencedprofile associations to define the tree. Starts with SMI-S if it iexists
[ "sShow", "a", "tree", "view", "of", "the", "registered", "profiles", "using", "the", "ECTP", "and", "referencedprofile", "associations", "to", "define", "the", "tree", ".", "Starts", "with", "SMI", "-", "S", "if", "it", "iexists" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L1480-L1544
train
28,242
pywbem/pywbem
try/run_central_instances.py
display_servers
def display_servers(server_definitions_filename): """ display the defined servers information as a table. """ servers = ServerDefinitionFile2(server_definitions_filename) title = 'List of all servers that can be tested' headers = ['Name', 'Url', 'Default_namespace'] rows = [] for server in servers.list_all_servers(): # specifically does not show server user and pw rows.append((server.nickname, server.url, server.default_namespace)) print_table(title, headers, rows, sort_columns=0)
python
def display_servers(server_definitions_filename): """ display the defined servers information as a table. """ servers = ServerDefinitionFile2(server_definitions_filename) title = 'List of all servers that can be tested' headers = ['Name', 'Url', 'Default_namespace'] rows = [] for server in servers.list_all_servers(): # specifically does not show server user and pw rows.append((server.nickname, server.url, server.default_namespace)) print_table(title, headers, rows, sort_columns=0)
[ "def", "display_servers", "(", "server_definitions_filename", ")", ":", "servers", "=", "ServerDefinitionFile2", "(", "server_definitions_filename", ")", "title", "=", "'List of all servers that can be tested'", "headers", "=", "[", "'Name'", ",", "'Url'", ",", "'Default_...
display the defined servers information as a table.
[ "display", "the", "defined", "servers", "information", "as", "a", "table", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L1677-L1693
train
28,243
pywbem/pywbem
try/run_central_instances.py
ElapsedTimer.elapsed_ms
def elapsed_ms(self): """ Get the elapsed time in milliseconds. returns floating point representation of elapsed time in seconds. """ dt = datetime.datetime.now() - self.start_time return ((dt.days * 24 * 3600) + dt.seconds) * 1000 \ + dt.microseconds / 1000.0
python
def elapsed_ms(self): """ Get the elapsed time in milliseconds. returns floating point representation of elapsed time in seconds. """ dt = datetime.datetime.now() - self.start_time return ((dt.days * 24 * 3600) + dt.seconds) * 1000 \ + dt.microseconds / 1000.0
[ "def", "elapsed_ms", "(", "self", ")", ":", "dt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "start_time", "return", "(", "(", "dt", ".", "days", "*", "24", "*", "3600", ")", "+", "dt", ".", "seconds", ")", "*", "...
Get the elapsed time in milliseconds. returns floating point representation of elapsed time in seconds.
[ "Get", "the", "elapsed", "time", "in", "milliseconds", ".", "returns", "floating", "point", "representation", "of", "elapsed", "time", "in", "seconds", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L141-L147
train
28,244
pywbem/pywbem
try/run_central_instances.py
ServerDefinitionFile2.list_servers
def list_servers(self, nicknames=None): """ Iterate through the servers of the server group with the specified nicknames, or the single server with the specified nickname, and yield a `ServerDefinition` object for each server. nicknames may be: None, string defining a nickname or list of nicknames """ if not nicknames: return self.list_all_servers() if isinstance(nicknames, six.string_types): nicknames = [nicknames] sd_list = [] sd_nick_list = [] for nickname in nicknames: if nickname in self._servers: sd_list.append(self.get_server(nickname)) elif nickname in self._server_groups: for item_nick in self._server_groups[nickname]: for sd in self.list_servers(item_nick): if sd.nickname not in sd_nick_list: sd_nick_list.append(sd.nickname) sd_list.append(sd) else: raise ValueError( "Server group or server nickname {0!r} not found in WBEM " "server definition file {1!r}". format(nickname, self._filepath)) return sd_list
python
def list_servers(self, nicknames=None): """ Iterate through the servers of the server group with the specified nicknames, or the single server with the specified nickname, and yield a `ServerDefinition` object for each server. nicknames may be: None, string defining a nickname or list of nicknames """ if not nicknames: return self.list_all_servers() if isinstance(nicknames, six.string_types): nicknames = [nicknames] sd_list = [] sd_nick_list = [] for nickname in nicknames: if nickname in self._servers: sd_list.append(self.get_server(nickname)) elif nickname in self._server_groups: for item_nick in self._server_groups[nickname]: for sd in self.list_servers(item_nick): if sd.nickname not in sd_nick_list: sd_nick_list.append(sd.nickname) sd_list.append(sd) else: raise ValueError( "Server group or server nickname {0!r} not found in WBEM " "server definition file {1!r}". format(nickname, self._filepath)) return sd_list
[ "def", "list_servers", "(", "self", ",", "nicknames", "=", "None", ")", ":", "if", "not", "nicknames", ":", "return", "self", ".", "list_all_servers", "(", ")", "if", "isinstance", "(", "nicknames", ",", "six", ".", "string_types", ")", ":", "nicknames", ...
Iterate through the servers of the server group with the specified nicknames, or the single server with the specified nickname, and yield a `ServerDefinition` object for each server. nicknames may be: None, string defining a nickname or list of nicknames
[ "Iterate", "through", "the", "servers", "of", "the", "server", "group", "with", "the", "specified", "nicknames", "or", "the", "single", "server", "with", "the", "specified", "nickname", "and", "yield", "a", "ServerDefinition", "object", "for", "each", "server", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L318-L348
train
28,245
pywbem/pywbem
examples/wbemcli_server.py
print_profile_info
def print_profile_info(org_vm, profile_instance): """ Print information on a profile defined by profile_instance. Parameters: org_vm: The value mapping for CIMRegisterdProfile and RegisteredOrganization so that the value and not value mapping is displayed. profile_instance: instance of a profile to be printed """ org = org_vm.tovalues(profile_instance['RegisteredOrganization']) name = profile_instance['RegisteredName'] vers = profile_instance['RegisteredVersion'] print(" %s %s Profile %s" % (org, name, vers))
python
def print_profile_info(org_vm, profile_instance): """ Print information on a profile defined by profile_instance. Parameters: org_vm: The value mapping for CIMRegisterdProfile and RegisteredOrganization so that the value and not value mapping is displayed. profile_instance: instance of a profile to be printed """ org = org_vm.tovalues(profile_instance['RegisteredOrganization']) name = profile_instance['RegisteredName'] vers = profile_instance['RegisteredVersion'] print(" %s %s Profile %s" % (org, name, vers))
[ "def", "print_profile_info", "(", "org_vm", ",", "profile_instance", ")", ":", "org", "=", "org_vm", ".", "tovalues", "(", "profile_instance", "[", "'RegisteredOrganization'", "]", ")", "name", "=", "profile_instance", "[", "'RegisteredName'", "]", "vers", "=", ...
Print information on a profile defined by profile_instance. Parameters: org_vm: The value mapping for CIMRegisterdProfile and RegisteredOrganization so that the value and not value mapping is displayed. profile_instance: instance of a profile to be printed
[ "Print", "information", "on", "a", "profile", "defined", "by", "profile_instance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/wbemcli_server.py#L12-L27
train
28,246
pywbem/pywbem
examples/send_indications.py
create_indication_data
def create_indication_data(msg_id, sequence_number, source_id, delta_time, \ protocol_ver): ''' Create a singled indication XML from the template and the included sequence_number, delta_time, and protocol_ver Returns the completed indication XML ''' data_template = """<?xml version="1.0" encoding="utf-8" ?> <CIM CIMVERSION="2.0" DTDVERSION="2.4"> <MESSAGE ID="%(msg_id)s" PROTOCOLVERSION="%(protocol_ver)s"> <SIMPLEEXPREQ> <EXPMETHODCALL NAME="ExportIndication"> <EXPPARAMVALUE NAME="NewIndication"> <INSTANCE CLASSNAME="CIM_AlertIndication"> <PROPERTY NAME="Severity" TYPE="string"> <VALUE>high</VALUE> </PROPERTY> <PROPERTY NAME="SequenceNumber" TYPE="string"> <VALUE>%(sequence_number)s</VALUE> </PROPERTY> <PROPERTY NAME="SourceId" TYPE="string"> <VALUE>%(source_id)s</VALUE> </PROPERTY> <PROPERTY NAME="DELTA_TIME" TYPE="string"> <VALUE>%(delta_time)s</VALUE> </PROPERTY> </INSTANCE> </EXPPARAMVALUE> </EXPMETHODCALL> </SIMPLEEXPREQ> </MESSAGE> </CIM>""" data = {'sequence_number' : sequence_number, 'source_id' : source_id, 'delta_time' : delta_time, 'protocol_ver' : protocol_ver, 'msg_id' : msg_id} return data_template%data
python
def create_indication_data(msg_id, sequence_number, source_id, delta_time, \ protocol_ver): ''' Create a singled indication XML from the template and the included sequence_number, delta_time, and protocol_ver Returns the completed indication XML ''' data_template = """<?xml version="1.0" encoding="utf-8" ?> <CIM CIMVERSION="2.0" DTDVERSION="2.4"> <MESSAGE ID="%(msg_id)s" PROTOCOLVERSION="%(protocol_ver)s"> <SIMPLEEXPREQ> <EXPMETHODCALL NAME="ExportIndication"> <EXPPARAMVALUE NAME="NewIndication"> <INSTANCE CLASSNAME="CIM_AlertIndication"> <PROPERTY NAME="Severity" TYPE="string"> <VALUE>high</VALUE> </PROPERTY> <PROPERTY NAME="SequenceNumber" TYPE="string"> <VALUE>%(sequence_number)s</VALUE> </PROPERTY> <PROPERTY NAME="SourceId" TYPE="string"> <VALUE>%(source_id)s</VALUE> </PROPERTY> <PROPERTY NAME="DELTA_TIME" TYPE="string"> <VALUE>%(delta_time)s</VALUE> </PROPERTY> </INSTANCE> </EXPPARAMVALUE> </EXPMETHODCALL> </SIMPLEEXPREQ> </MESSAGE> </CIM>""" data = {'sequence_number' : sequence_number, 'source_id' : source_id, 'delta_time' : delta_time, 'protocol_ver' : protocol_ver, 'msg_id' : msg_id} return data_template%data
[ "def", "create_indication_data", "(", "msg_id", ",", "sequence_number", ",", "source_id", ",", "delta_time", ",", "protocol_ver", ")", ":", "data_template", "=", "\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n <CIM CIMVERSION=\"2.0\" DTDVERSION=\"2.4\">\n <MESSAGE ID=\"%...
Create a singled indication XML from the template and the included sequence_number, delta_time, and protocol_ver Returns the completed indication XML
[ "Create", "a", "singled", "indication", "XML", "from", "the", "template", "and", "the", "included", "sequence_number", "delta_time", "and", "protocol_ver" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/send_indications.py#L53-L91
train
28,247
pywbem/pywbem
examples/send_indications.py
send_indication
def send_indication(url, headers, payload, verbose, verify=None, keyfile=None, timeout=4): ''' Send indication using requests module. Parameters: url(:term:`string): listener url including scheme, host name, port headers: All headers for the request pyload: XML payload containing the indication verbose: Flag for verbose responses verify: Either False or file of cert for verification of host. Note that this combination is unique to the requests module in place of using a no_verification flag. keyfile: None if there is no client verification or either a single file containing the cert amd private key file or a pair of files containing both (key, cert) Returns: True if response code = 200. Otherwise False ''' try: response = requests.post(url, headers=headers, data=payload, timeout=timeout, verify=verify) except Exception as ex: print('Exception %s' % ex) return False # validate response status code and xml if verbose or response.status_code != 200: print('\nResponse code=%s headers=%s data=%s' % (response.status_code, response.headers, response.text)) root = ET.fromstring(response.text) if (root.tag != 'CIM') or (root.attrib['CIMVERSION'] != '2.0') \ or (root.attrib['DTDVERSION'] != '2.4'): print('Invalid XML\nResponse code=%s headers=%s data=%s' % \ (response.status_code, response.headers, response.text)) return False for child in root: if child.tag != 'MESSAGE' or child.attrib['PROTOCOLVERSION'] != '1.4': print('Invalid child\nResponse code=%s headers=%s data=%s' % \ (response.status_code, response.headers, response.text)) return False return True if(response.status_code == 200) else False
python
def send_indication(url, headers, payload, verbose, verify=None, keyfile=None, timeout=4): ''' Send indication using requests module. Parameters: url(:term:`string): listener url including scheme, host name, port headers: All headers for the request pyload: XML payload containing the indication verbose: Flag for verbose responses verify: Either False or file of cert for verification of host. Note that this combination is unique to the requests module in place of using a no_verification flag. keyfile: None if there is no client verification or either a single file containing the cert amd private key file or a pair of files containing both (key, cert) Returns: True if response code = 200. Otherwise False ''' try: response = requests.post(url, headers=headers, data=payload, timeout=timeout, verify=verify) except Exception as ex: print('Exception %s' % ex) return False # validate response status code and xml if verbose or response.status_code != 200: print('\nResponse code=%s headers=%s data=%s' % (response.status_code, response.headers, response.text)) root = ET.fromstring(response.text) if (root.tag != 'CIM') or (root.attrib['CIMVERSION'] != '2.0') \ or (root.attrib['DTDVERSION'] != '2.4'): print('Invalid XML\nResponse code=%s headers=%s data=%s' % \ (response.status_code, response.headers, response.text)) return False for child in root: if child.tag != 'MESSAGE' or child.attrib['PROTOCOLVERSION'] != '1.4': print('Invalid child\nResponse code=%s headers=%s data=%s' % \ (response.status_code, response.headers, response.text)) return False return True if(response.status_code == 200) else False
[ "def", "send_indication", "(", "url", ",", "headers", ",", "payload", ",", "verbose", ",", "verify", "=", "None", ",", "keyfile", "=", "None", ",", "timeout", "=", "4", ")", ":", "try", ":", "response", "=", "requests", ".", "post", "(", "url", ",", ...
Send indication using requests module. Parameters: url(:term:`string): listener url including scheme, host name, port headers: All headers for the request pyload: XML payload containing the indication verbose: Flag for verbose responses verify: Either False or file of cert for verification of host. Note that this combination is unique to the requests module in place of using a no_verification flag. keyfile: None if there is no client verification or either a single file containing the cert amd private key file or a pair of files containing both (key, cert) Returns: True if response code = 200. Otherwise False
[ "Send", "indication", "using", "requests", "module", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/send_indications.py#L94-L155
train
28,248
pywbem/pywbem
attic/cimxml_parse.py
_get_required_attribute
def _get_required_attribute(node, attr): """Return an attribute by name. Raise ParseError if not present.""" if not node.hasAttribute(attr): raise ParseError( 'Expecting %s attribute in element %s' % (attr, node.tagName)) return node.getAttribute(attr)
python
def _get_required_attribute(node, attr): """Return an attribute by name. Raise ParseError if not present.""" if not node.hasAttribute(attr): raise ParseError( 'Expecting %s attribute in element %s' % (attr, node.tagName)) return node.getAttribute(attr)
[ "def", "_get_required_attribute", "(", "node", ",", "attr", ")", ":", "if", "not", "node", ".", "hasAttribute", "(", "attr", ")", ":", "raise", "ParseError", "(", "'Expecting %s attribute in element %s'", "%", "(", "attr", ",", "node", ".", "tagName", ")", "...
Return an attribute by name. Raise ParseError if not present.
[ "Return", "an", "attribute", "by", "name", ".", "Raise", "ParseError", "if", "not", "present", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L54-L61
train
28,249
pywbem/pywbem
attic/cimxml_parse.py
_get_end_event
def _get_end_event(parser, tagName): """Check that the next event is the end of a particular XML tag.""" (event, node) = six.next(parser) if event != pulldom.END_ELEMENT or node.tagName != tagName: raise ParseError( 'Expecting %s end tag, got %s %s' % (tagName, event, node.tagName))
python
def _get_end_event(parser, tagName): """Check that the next event is the end of a particular XML tag.""" (event, node) = six.next(parser) if event != pulldom.END_ELEMENT or node.tagName != tagName: raise ParseError( 'Expecting %s end tag, got %s %s' % (tagName, event, node.tagName))
[ "def", "_get_end_event", "(", "parser", ",", "tagName", ")", ":", "(", "event", ",", "node", ")", "=", "six", ".", "next", "(", "parser", ")", "if", "event", "!=", "pulldom", ".", "END_ELEMENT", "or", "node", ".", "tagName", "!=", "tagName", ":", "ra...
Check that the next event is the end of a particular XML tag.
[ "Check", "that", "the", "next", "event", "is", "the", "end", "of", "a", "particular", "XML", "tag", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L71-L78
train
28,250
pywbem/pywbem
attic/cimxml_parse.py
make_parser
def make_parser(stream_or_string): """Create a xml.dom.pulldom parser.""" if isinstance(stream_or_string, six.string_types): # XXX: the pulldom.parseString() function doesn't seem to # like operating on unicode strings! return pulldom.parseString(str(stream_or_string)) else: return pulldom.parse(stream_or_string)
python
def make_parser(stream_or_string): """Create a xml.dom.pulldom parser.""" if isinstance(stream_or_string, six.string_types): # XXX: the pulldom.parseString() function doesn't seem to # like operating on unicode strings! return pulldom.parseString(str(stream_or_string)) else: return pulldom.parse(stream_or_string)
[ "def", "make_parser", "(", "stream_or_string", ")", ":", "if", "isinstance", "(", "stream_or_string", ",", "six", ".", "string_types", ")", ":", "# XXX: the pulldom.parseString() function doesn't seem to", "# like operating on unicode strings!", "return", "pulldom", ".", "p...
Create a xml.dom.pulldom parser.
[ "Create", "a", "xml", ".", "dom", ".", "pulldom", "parser", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L999-L1011
train
28,251
pywbem/pywbem
attic/cimxml_parse.py
parse_any
def parse_any(stream_or_string): """Parse any XML string or stream. This function fabricates the names of the parser functions by prepending parse_ to the node name and then calling that function. """ parser = make_parser(stream_or_string) (event, node) = six.next(parser) if event != pulldom.START_DOCUMENT: raise ParseError('Expecting document start') (event, node) = six.next(parser) if event != pulldom.START_ELEMENT: raise ParseError('Expecting element start') fn_name = 'parse_%s' % node.tagName.lower().replace('.', '_') fn = globals().get(fn_name) if fn is None: raise ParseError('No parser for element %s' % node.tagName) return fn(parser, event, node)
python
def parse_any(stream_or_string): """Parse any XML string or stream. This function fabricates the names of the parser functions by prepending parse_ to the node name and then calling that function. """ parser = make_parser(stream_or_string) (event, node) = six.next(parser) if event != pulldom.START_DOCUMENT: raise ParseError('Expecting document start') (event, node) = six.next(parser) if event != pulldom.START_ELEMENT: raise ParseError('Expecting element start') fn_name = 'parse_%s' % node.tagName.lower().replace('.', '_') fn = globals().get(fn_name) if fn is None: raise ParseError('No parser for element %s' % node.tagName) return fn(parser, event, node)
[ "def", "parse_any", "(", "stream_or_string", ")", ":", "parser", "=", "make_parser", "(", "stream_or_string", ")", "(", "event", ",", "node", ")", "=", "six", ".", "next", "(", "parser", ")", "if", "event", "!=", "pulldom", ".", "START_DOCUMENT", ":", "r...
Parse any XML string or stream. This function fabricates the names of the parser functions by prepending parse_ to the node name and then calling that function.
[ "Parse", "any", "XML", "string", "or", "stream", ".", "This", "function", "fabricates", "the", "names", "of", "the", "parser", "functions", "by", "prepending", "parse_", "to", "the", "node", "name", "and", "then", "calling", "that", "function", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L1013-L1036
train
28,252
pywbem/pywbem
examples/listen.py
_process_indication
def _process_indication(indication, host): '''This function gets called when an indication is received.''' global RECEIVED_INDICATION_DICT COUNTER_LOCK.acquire() if host in RECEIVED_INDICATION_DICT: RECEIVED_INDICATION_DICT[host] += 1 else: RECEIVED_INDICATION_DICT[host] = 1 COUNTER_LOCK.release() listener.logger.info("Consumed CIM indication #%s: host=%s\n%s", RECEIVED_INDICATION_DICT, host, indication.tomof())
python
def _process_indication(indication, host): '''This function gets called when an indication is received.''' global RECEIVED_INDICATION_DICT COUNTER_LOCK.acquire() if host in RECEIVED_INDICATION_DICT: RECEIVED_INDICATION_DICT[host] += 1 else: RECEIVED_INDICATION_DICT[host] = 1 COUNTER_LOCK.release() listener.logger.info("Consumed CIM indication #%s: host=%s\n%s", RECEIVED_INDICATION_DICT, host, indication.tomof())
[ "def", "_process_indication", "(", "indication", ",", "host", ")", ":", "global", "RECEIVED_INDICATION_DICT", "COUNTER_LOCK", ".", "acquire", "(", ")", "if", "host", "in", "RECEIVED_INDICATION_DICT", ":", "RECEIVED_INDICATION_DICT", "[", "host", "]", "+=", "1", "e...
This function gets called when an indication is received.
[ "This", "function", "gets", "called", "when", "an", "indication", "is", "received", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/listen.py#L34-L46
train
28,253
pywbem/pywbem
examples/listen.py
_get_argv
def _get_argv(index, default=None): ''' get the argv input argument defined by index. Return the default attribute if that argument does not exist ''' return _sys.argv[index] if len(_sys.argv) > index else default
python
def _get_argv(index, default=None): ''' get the argv input argument defined by index. Return the default attribute if that argument does not exist ''' return _sys.argv[index] if len(_sys.argv) > index else default
[ "def", "_get_argv", "(", "index", ",", "default", "=", "None", ")", ":", "return", "_sys", ".", "argv", "[", "index", "]", "if", "len", "(", "_sys", ".", "argv", ")", ">", "index", "else", "default" ]
get the argv input argument defined by index. Return the default attribute if that argument does not exist
[ "get", "the", "argv", "input", "argument", "defined", "by", "index", ".", "Return", "the", "default", "attribute", "if", "that", "argument", "does", "not", "exist" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/listen.py#L48-L52
train
28,254
pywbem/pywbem
examples/listen.py
status
def status(reset=None): ''' Show status of indications received. If optional reset attribute is True, reset the counter. ''' global RECEIVED_INDICATION_DICT for host, count in six.iteritems(RECEIVED_INDICATION_DICT): print('Host %s Received %s indications' % (host, count)) if reset: for host in RECEIVED_INDICATION_DICT: RECEIVED_INDICATION_DICT[host] = 0 print('Host %s Reset: Received %s indications' % (host, RECEIVED_INDICATION_DICT[host])) print('counts reset to 0')
python
def status(reset=None): ''' Show status of indications received. If optional reset attribute is True, reset the counter. ''' global RECEIVED_INDICATION_DICT for host, count in six.iteritems(RECEIVED_INDICATION_DICT): print('Host %s Received %s indications' % (host, count)) if reset: for host in RECEIVED_INDICATION_DICT: RECEIVED_INDICATION_DICT[host] = 0 print('Host %s Reset: Received %s indications' % (host, RECEIVED_INDICATION_DICT[host])) print('counts reset to 0')
[ "def", "status", "(", "reset", "=", "None", ")", ":", "global", "RECEIVED_INDICATION_DICT", "for", "host", ",", "count", "in", "six", ".", "iteritems", "(", "RECEIVED_INDICATION_DICT", ")", ":", "print", "(", "'Host %s Received %s indications'", "%", "(", "host"...
Show status of indications received. If optional reset attribute is True, reset the counter.
[ "Show", "status", "of", "indications", "received", ".", "If", "optional", "reset", "attribute", "is", "True", "reset", "the", "counter", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/listen.py#L55-L69
train
28,255
pywbem/pywbem
docs/conf.py
AutoAutoSummary._get_members
def _get_members(self, class_obj, member_type, include_in_public=None): """ Return class members of the specified type. class_obj: Class object. member_type: Member type ('method' or 'attribute'). include_in_public: set/list/tuple with member names that should be included in public members in addition to the public names (those starting without underscore). Returns: tuple(public_members, all_members): Names of the class members of the specified member type (public / all). """ try: app = self.state.document.settings.env.app except AttributeError: app = None if not include_in_public: include_in_public = [] all_members = [] for member_name in dir(class_obj): try: documenter = get_documenter( app, safe_getattr(class_obj, member_name), class_obj) except AttributeError: continue if documenter.objtype == member_type: all_members.append(member_name) public_members = [x for x in all_members if x in include_in_public or not x.startswith('_')] return public_members, all_members
python
def _get_members(self, class_obj, member_type, include_in_public=None): """ Return class members of the specified type. class_obj: Class object. member_type: Member type ('method' or 'attribute'). include_in_public: set/list/tuple with member names that should be included in public members in addition to the public names (those starting without underscore). Returns: tuple(public_members, all_members): Names of the class members of the specified member type (public / all). """ try: app = self.state.document.settings.env.app except AttributeError: app = None if not include_in_public: include_in_public = [] all_members = [] for member_name in dir(class_obj): try: documenter = get_documenter( app, safe_getattr(class_obj, member_name), class_obj) except AttributeError: continue if documenter.objtype == member_type: all_members.append(member_name) public_members = [x for x in all_members if x in include_in_public or not x.startswith('_')] return public_members, all_members
[ "def", "_get_members", "(", "self", ",", "class_obj", ",", "member_type", ",", "include_in_public", "=", "None", ")", ":", "try", ":", "app", "=", "self", ".", "state", ".", "document", ".", "settings", ".", "env", ".", "app", "except", "AttributeError", ...
Return class members of the specified type. class_obj: Class object. member_type: Member type ('method' or 'attribute'). include_in_public: set/list/tuple with member names that should be included in public members in addition to the public names (those starting without underscore). Returns: tuple(public_members, all_members): Names of the class members of the specified member type (public / all).
[ "Return", "class", "members", "of", "the", "specified", "type", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/docs/conf.py#L560-L595
train
28,256
pywbem/pywbem
docs/conf.py
AutoAutoSummary._get_def_class
def _get_def_class(self, class_obj, member_name): """ Return the class object in MRO order that defines a member. class_obj: Class object that exposes (but not necessarily defines) the member. I.e. starting point of the search. member_name: Name of the member (method or attribute). Returns: Class object that defines the member. """ member_obj = getattr(class_obj, member_name) for def_class_obj in inspect.getmro(class_obj): if member_name in def_class_obj.__dict__: if def_class_obj.__name__ in self._excluded_classes: return class_obj # Fall back to input class return def_class_obj self._logger.warning( "%s: Definition class not found for member %s.%s, " "defaulting to class %s", self._log_prefix, class_obj.__name__, member_name, class_obj.__name__) return class_obj
python
def _get_def_class(self, class_obj, member_name): """ Return the class object in MRO order that defines a member. class_obj: Class object that exposes (but not necessarily defines) the member. I.e. starting point of the search. member_name: Name of the member (method or attribute). Returns: Class object that defines the member. """ member_obj = getattr(class_obj, member_name) for def_class_obj in inspect.getmro(class_obj): if member_name in def_class_obj.__dict__: if def_class_obj.__name__ in self._excluded_classes: return class_obj # Fall back to input class return def_class_obj self._logger.warning( "%s: Definition class not found for member %s.%s, " "defaulting to class %s", self._log_prefix, class_obj.__name__, member_name, class_obj.__name__) return class_obj
[ "def", "_get_def_class", "(", "self", ",", "class_obj", ",", "member_name", ")", ":", "member_obj", "=", "getattr", "(", "class_obj", ",", "member_name", ")", "for", "def_class_obj", "in", "inspect", ".", "getmro", "(", "class_obj", ")", ":", "if", "member_n...
Return the class object in MRO order that defines a member. class_obj: Class object that exposes (but not necessarily defines) the member. I.e. starting point of the search. member_name: Name of the member (method or attribute). Returns: Class object that defines the member.
[ "Return", "the", "class", "object", "in", "MRO", "order", "that", "defines", "a", "member", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/docs/conf.py#L597-L620
train
28,257
pywbem/pywbem
pywbem/_statistics.py
OperationStatistic.reset
def reset(self): """ Reset the statistics data for this object. """ self._count = 0 self._exception_count = 0 self._stat_start_time = None self._time_sum = float(0) self._time_min = float('inf') self._time_max = float(0) self._server_time_sum = float(0) self._server_time_min = float('inf') self._server_time_max = float(0) self._server_time_stored = False self._request_len_sum = float(0) self._request_len_min = float('inf') self._request_len_max = float(0) self._reply_len_sum = float(0) self._reply_len_min = float('inf') self._reply_len_max = float(0)
python
def reset(self): """ Reset the statistics data for this object. """ self._count = 0 self._exception_count = 0 self._stat_start_time = None self._time_sum = float(0) self._time_min = float('inf') self._time_max = float(0) self._server_time_sum = float(0) self._server_time_min = float('inf') self._server_time_max = float(0) self._server_time_stored = False self._request_len_sum = float(0) self._request_len_min = float('inf') self._request_len_max = float(0) self._reply_len_sum = float(0) self._reply_len_min = float('inf') self._reply_len_max = float(0)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_count", "=", "0", "self", ".", "_exception_count", "=", "0", "self", ".", "_stat_start_time", "=", "None", "self", ".", "_time_sum", "=", "float", "(", "0", ")", "self", ".", "_time_min", "=", "fl...
Reset the statistics data for this object.
[ "Reset", "the", "statistics", "data", "for", "this", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L359-L381
train
28,258
pywbem/pywbem
pywbem/_statistics.py
OperationStatistic.start_timer
def start_timer(self): """ This is a low-level method that is called by pywbem at the begin of an operation. It starts the measurement for that operation, if statistics is enabled for the connection. A subsequent invocation of :meth:`~pywbem.OperationStatistic.stop_timer` will complete the measurement for that operation and will update the statistics data. """ if self.container.enabled: self._start_time = time.time() if not self._stat_start_time: self._stat_start_time = self._start_time
python
def start_timer(self): """ This is a low-level method that is called by pywbem at the begin of an operation. It starts the measurement for that operation, if statistics is enabled for the connection. A subsequent invocation of :meth:`~pywbem.OperationStatistic.stop_timer` will complete the measurement for that operation and will update the statistics data. """ if self.container.enabled: self._start_time = time.time() if not self._stat_start_time: self._stat_start_time = self._start_time
[ "def", "start_timer", "(", "self", ")", ":", "if", "self", ".", "container", ".", "enabled", ":", "self", ".", "_start_time", "=", "time", ".", "time", "(", ")", "if", "not", "self", ".", "_stat_start_time", ":", "self", ".", "_stat_start_time", "=", "...
This is a low-level method that is called by pywbem at the begin of an operation. It starts the measurement for that operation, if statistics is enabled for the connection. A subsequent invocation of :meth:`~pywbem.OperationStatistic.stop_timer` will complete the measurement for that operation and will update the statistics data.
[ "This", "is", "a", "low", "-", "level", "method", "that", "is", "called", "by", "pywbem", "at", "the", "begin", "of", "an", "operation", ".", "It", "starts", "the", "measurement", "for", "that", "operation", "if", "statistics", "is", "enabled", "for", "t...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L383-L396
train
28,259
pywbem/pywbem
pywbem/_statistics.py
OperationStatistic.stop_timer
def stop_timer(self, request_len, reply_len, server_time=None, exception=False): """ This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data, if statistics is enabled for the connection. Parameters: request_len (:term:`integer`) Size of the HTTP body of the CIM-XML request message, in Bytes. reply_len (:term:`integer`) Size of the HTTP body of the CIM-XML response message, in Bytes. exception (:class:`py:bool`) Boolean that specifies whether an exception was raised while processing the operation. server_time (:class:`py:bool`) Time in seconds that the server optionally returns to the client in the HTTP response defining the time from when the server received the request to when it started sending the response. If `None`, there is no time from the server. Returns: float: The elapsed time for the operation that just ended, or `None` if the statistics container holding this object is not enabled. """ if not self.container.enabled: return None # stop the timer if self._start_time is None: raise RuntimeError('stop_timer() called without preceding ' 'start_timer()') dt = time.time() - self._start_time self._start_time = None self._count += 1 self._time_sum += dt self._request_len_sum += request_len self._reply_len_sum += reply_len if exception: self._exception_count += 1 if dt > self._time_max: self._time_max = dt if dt < self._time_min: self._time_min = dt if server_time: self._server_time_stored = True self._server_time_sum += server_time if dt > self._server_time_max: self._server_time_max = server_time if dt < self._server_time_min: self._server_time_min = server_time if request_len > self._request_len_max: self._request_len_max = request_len if request_len < self._request_len_min: self._request_len_min = request_len if reply_len > self._reply_len_max: self._reply_len_max = reply_len if reply_len < self._reply_len_min: self._reply_len_min = reply_len return dt
python
def stop_timer(self, request_len, reply_len, server_time=None, exception=False): """ This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data, if statistics is enabled for the connection. Parameters: request_len (:term:`integer`) Size of the HTTP body of the CIM-XML request message, in Bytes. reply_len (:term:`integer`) Size of the HTTP body of the CIM-XML response message, in Bytes. exception (:class:`py:bool`) Boolean that specifies whether an exception was raised while processing the operation. server_time (:class:`py:bool`) Time in seconds that the server optionally returns to the client in the HTTP response defining the time from when the server received the request to when it started sending the response. If `None`, there is no time from the server. Returns: float: The elapsed time for the operation that just ended, or `None` if the statistics container holding this object is not enabled. """ if not self.container.enabled: return None # stop the timer if self._start_time is None: raise RuntimeError('stop_timer() called without preceding ' 'start_timer()') dt = time.time() - self._start_time self._start_time = None self._count += 1 self._time_sum += dt self._request_len_sum += request_len self._reply_len_sum += reply_len if exception: self._exception_count += 1 if dt > self._time_max: self._time_max = dt if dt < self._time_min: self._time_min = dt if server_time: self._server_time_stored = True self._server_time_sum += server_time if dt > self._server_time_max: self._server_time_max = server_time if dt < self._server_time_min: self._server_time_min = server_time if request_len > self._request_len_max: self._request_len_max = request_len if request_len < self._request_len_min: self._request_len_min = request_len if reply_len > self._reply_len_max: self._reply_len_max = reply_len if reply_len < self._reply_len_min: self._reply_len_min = reply_len return dt
[ "def", "stop_timer", "(", "self", ",", "request_len", ",", "reply_len", ",", "server_time", "=", "None", ",", "exception", "=", "False", ")", ":", "if", "not", "self", ".", "container", ".", "enabled", ":", "return", "None", "# stop the timer", "if", "self...
This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data, if statistics is enabled for the connection. Parameters: request_len (:term:`integer`) Size of the HTTP body of the CIM-XML request message, in Bytes. reply_len (:term:`integer`) Size of the HTTP body of the CIM-XML response message, in Bytes. exception (:class:`py:bool`) Boolean that specifies whether an exception was raised while processing the operation. server_time (:class:`py:bool`) Time in seconds that the server optionally returns to the client in the HTTP response defining the time from when the server received the request to when it started sending the response. If `None`, there is no time from the server. Returns: float: The elapsed time for the operation that just ended, or `None` if the statistics container holding this object is not enabled.
[ "This", "is", "a", "low", "-", "level", "method", "is", "called", "by", "pywbem", "at", "the", "end", "of", "an", "operation", ".", "It", "completes", "the", "measurement", "for", "that", "operation", "by", "capturing", "the", "needed", "data", "and", "u...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L398-L470
train
28,260
pywbem/pywbem
pywbem/_statistics.py
OperationStatistic.formatted
def formatted(self, include_server_time): """ Return a formatted one-line string with the statistics values for the operation for which this statistics object maintains data. This is a low-level method that is called by :meth:`pywbem.Statistics.formatted`. """ if include_server_time: # pylint: disable=no-else-return return ('{0:5d} {1:5d} ' '{2:7.3f} {3:7.3f} {4:7.3f} ' '{5:7.3f} {6:7.3f} {7:7.3f} ' '{8:6.0f} {9:6.0f} {10:6.0f} ' '{11:8.0f} {12:8.0f} {13:8.0f} {14}\n'. format(self.count, self.exception_count, self.avg_time, self.min_time, self.max_time, self.avg_server_time, self.min_server_time, self.max_server_time, self.avg_request_len, self.min_request_len, self.max_request_len, self.avg_reply_len, self.min_reply_len, self.max_reply_len, self.name)) else: return ('{0:5d} {1:5d} ' '{2:7.3f} {3:7.3f} {4:7.3f} ' '{5:6.0f} {6:6.0f} {7:6.0f} ' '{8:6.0f} {9:8.0f} {10:8.0f} {11}\n'. format(self.count, self.exception_count, self.avg_time, self.min_time, self.max_time, self.avg_request_len, self.min_request_len, self.max_request_len, self.avg_reply_len, self.min_reply_len, self.max_reply_len, self.name))
python
def formatted(self, include_server_time): """ Return a formatted one-line string with the statistics values for the operation for which this statistics object maintains data. This is a low-level method that is called by :meth:`pywbem.Statistics.formatted`. """ if include_server_time: # pylint: disable=no-else-return return ('{0:5d} {1:5d} ' '{2:7.3f} {3:7.3f} {4:7.3f} ' '{5:7.3f} {6:7.3f} {7:7.3f} ' '{8:6.0f} {9:6.0f} {10:6.0f} ' '{11:8.0f} {12:8.0f} {13:8.0f} {14}\n'. format(self.count, self.exception_count, self.avg_time, self.min_time, self.max_time, self.avg_server_time, self.min_server_time, self.max_server_time, self.avg_request_len, self.min_request_len, self.max_request_len, self.avg_reply_len, self.min_reply_len, self.max_reply_len, self.name)) else: return ('{0:5d} {1:5d} ' '{2:7.3f} {3:7.3f} {4:7.3f} ' '{5:6.0f} {6:6.0f} {7:6.0f} ' '{8:6.0f} {9:8.0f} {10:8.0f} {11}\n'. format(self.count, self.exception_count, self.avg_time, self.min_time, self.max_time, self.avg_request_len, self.min_request_len, self.max_request_len, self.avg_reply_len, self.min_reply_len, self.max_reply_len, self.name))
[ "def", "formatted", "(", "self", ",", "include_server_time", ")", ":", "if", "include_server_time", ":", "# pylint: disable=no-else-return", "return", "(", "'{0:5d} {1:5d} '", "'{2:7.3f} {3:7.3f} {4:7.3f} '", "'{5:7.3f} {6:7.3f} {7:7.3f} '", "'{8:6.0f} {9:6.0f} {10:6.0f} '", "'{1...
Return a formatted one-line string with the statistics values for the operation for which this statistics object maintains data. This is a low-level method that is called by :meth:`pywbem.Statistics.formatted`.
[ "Return", "a", "formatted", "one", "-", "line", "string", "with", "the", "statistics", "values", "for", "the", "operation", "for", "which", "this", "statistics", "object", "maintains", "data", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L508-L543
train
28,261
pywbem/pywbem
pywbem/_statistics.py
Statistics.formatted
def formatted(self): # pylint: disable=line-too-long """ Return a human readable string with the statistics for this container. The operations are sorted by decreasing average time. The three columns for `ServerTime` are included only if the WBEM server has returned WBEM server response times. Example if statistics are enabled:: Statistics (times in seconds, lengths in Bytes): Count Excep ClientTime ServerTime RequestLen ReplyLen Operation Cnt Avg Min Max Avg Min Max Avg Min Max Avg Min Max 3 0 0.234 0.100 0.401 0.204 0.080 0.361 1233 1000 1500 26667 20000 35000 EnumerateInstances 1 0 0.100 0.100 0.100 0.080 0.080 0.080 1200 1200 1200 22000 22000 22000 EnumerateInstanceNames . . . Example if statistics are disabled:: Statistics (times in seconds, lengths in Bytes): Disabled """ # noqa: E501 # pylint: enable=line-too-long ret = "Statistics (times in seconds, lengths in Bytes):\n" if self.enabled: snapshot = sorted(self.snapshot(), key=lambda item: item[1].avg_time, reverse=True) # Test to see if any server time is non-zero include_svr = False for name, stats in snapshot: # pylint: disable=unused-variable # pylint: disable=protected-access if stats._server_time_stored: include_svr = True # pylint: disable=protected-access if include_svr: ret += OperationStatistic._formatted_header_w_svr else: ret += OperationStatistic._formatted_header for name, stats in snapshot: # pylint: disable=unused-variable ret += stats.formatted(include_svr) else: ret += "Disabled" return ret.strip()
python
def formatted(self): # pylint: disable=line-too-long """ Return a human readable string with the statistics for this container. The operations are sorted by decreasing average time. The three columns for `ServerTime` are included only if the WBEM server has returned WBEM server response times. Example if statistics are enabled:: Statistics (times in seconds, lengths in Bytes): Count Excep ClientTime ServerTime RequestLen ReplyLen Operation Cnt Avg Min Max Avg Min Max Avg Min Max Avg Min Max 3 0 0.234 0.100 0.401 0.204 0.080 0.361 1233 1000 1500 26667 20000 35000 EnumerateInstances 1 0 0.100 0.100 0.100 0.080 0.080 0.080 1200 1200 1200 22000 22000 22000 EnumerateInstanceNames . . . Example if statistics are disabled:: Statistics (times in seconds, lengths in Bytes): Disabled """ # noqa: E501 # pylint: enable=line-too-long ret = "Statistics (times in seconds, lengths in Bytes):\n" if self.enabled: snapshot = sorted(self.snapshot(), key=lambda item: item[1].avg_time, reverse=True) # Test to see if any server time is non-zero include_svr = False for name, stats in snapshot: # pylint: disable=unused-variable # pylint: disable=protected-access if stats._server_time_stored: include_svr = True # pylint: disable=protected-access if include_svr: ret += OperationStatistic._formatted_header_w_svr else: ret += OperationStatistic._formatted_header for name, stats in snapshot: # pylint: disable=unused-variable ret += stats.formatted(include_svr) else: ret += "Disabled" return ret.strip()
[ "def", "formatted", "(", "self", ")", ":", "# pylint: disable=line-too-long", "# noqa: E501", "# pylint: enable=line-too-long", "ret", "=", "\"Statistics (times in seconds, lengths in Bytes):\\n\"", "if", "self", ".", "enabled", ":", "snapshot", "=", "sorted", "(", "self", ...
Return a human readable string with the statistics for this container. The operations are sorted by decreasing average time. The three columns for `ServerTime` are included only if the WBEM server has returned WBEM server response times. Example if statistics are enabled:: Statistics (times in seconds, lengths in Bytes): Count Excep ClientTime ServerTime RequestLen ReplyLen Operation Cnt Avg Min Max Avg Min Max Avg Min Max Avg Min Max 3 0 0.234 0.100 0.401 0.204 0.080 0.361 1233 1000 1500 26667 20000 35000 EnumerateInstances 1 0 0.100 0.100 0.100 0.080 0.080 0.080 1200 1200 1200 22000 22000 22000 EnumerateInstanceNames . . . Example if statistics are disabled:: Statistics (times in seconds, lengths in Bytes): Disabled
[ "Return", "a", "human", "readable", "string", "with", "the", "statistics", "for", "this", "container", ".", "The", "operations", "are", "sorted", "by", "decreasing", "average", "time", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L676-L722
train
28,262
pywbem/pywbem
pywbem/_statistics.py
Statistics.reset
def reset(self): """ Reset all statistics and clear any statistic names. All statistics must be inactive before a reset will execute Returns: True if reset, False if not """ # Test for any stats being currently timed. for stat in six.itervalues(self._op_stats): if stat._start_time is not None: # pylint: disable=protected-access return False # clear all statistics self._op_stats = {} return True
python
def reset(self): """ Reset all statistics and clear any statistic names. All statistics must be inactive before a reset will execute Returns: True if reset, False if not """ # Test for any stats being currently timed. for stat in six.itervalues(self._op_stats): if stat._start_time is not None: # pylint: disable=protected-access return False # clear all statistics self._op_stats = {} return True
[ "def", "reset", "(", "self", ")", ":", "# Test for any stats being currently timed.", "for", "stat", "in", "six", ".", "itervalues", "(", "self", ".", "_op_stats", ")", ":", "if", "stat", ".", "_start_time", "is", "not", "None", ":", "# pylint: disable=protected...
Reset all statistics and clear any statistic names. All statistics must be inactive before a reset will execute Returns: True if reset, False if not
[ "Reset", "all", "statistics", "and", "clear", "any", "statistic", "names", ".", "All", "statistics", "must", "be", "inactive", "before", "a", "reset", "will", "execute" ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_statistics.py#L724-L738
train
28,263
pywbem/pywbem
remove_duplicate_setuptools.py
remove_duplicate_metadata_dirs
def remove_duplicate_metadata_dirs(package_name): """Remove duplicate metadata directories of a package.""" print("Removing duplicate metadata directories of package: %s" % package_name) module = importlib.import_module(package_name) py_mn = "%s.%s" % (sys.version_info[0], sys.version_info[1]) print("Current Python version: %s" % py_mn) version = module.__version__ print("Version of imported %s package: %s" % (package_name, version)) site_dir = os.path.dirname(os.path.dirname(module.__file__)) print("Site packages directory of imported package: %s" % site_dir) metadata_dirs = [] metadata_dirs.extend(glob.glob(os.path.join( site_dir, '%s-*.dist-info' % package_name))) metadata_dirs.extend(glob.glob(os.path.join( site_dir, '%s-*-py%s.egg-info' % (package_name, py_mn)))) for d in metadata_dirs: m = re.search(r'/%s-([0-9.]+)(\.di|-py)' % package_name, d) if not m: print("Warning: Could not parse metadata directory: %s" % d) continue d_version = m.group(1) if d_version == version: print("Found matching metadata directory: %s" % d) continue print("Removing duplicate metadata directory: %s" % d) shutil.rmtree(d)
python
def remove_duplicate_metadata_dirs(package_name): """Remove duplicate metadata directories of a package.""" print("Removing duplicate metadata directories of package: %s" % package_name) module = importlib.import_module(package_name) py_mn = "%s.%s" % (sys.version_info[0], sys.version_info[1]) print("Current Python version: %s" % py_mn) version = module.__version__ print("Version of imported %s package: %s" % (package_name, version)) site_dir = os.path.dirname(os.path.dirname(module.__file__)) print("Site packages directory of imported package: %s" % site_dir) metadata_dirs = [] metadata_dirs.extend(glob.glob(os.path.join( site_dir, '%s-*.dist-info' % package_name))) metadata_dirs.extend(glob.glob(os.path.join( site_dir, '%s-*-py%s.egg-info' % (package_name, py_mn)))) for d in metadata_dirs: m = re.search(r'/%s-([0-9.]+)(\.di|-py)' % package_name, d) if not m: print("Warning: Could not parse metadata directory: %s" % d) continue d_version = m.group(1) if d_version == version: print("Found matching metadata directory: %s" % d) continue print("Removing duplicate metadata directory: %s" % d) shutil.rmtree(d)
[ "def", "remove_duplicate_metadata_dirs", "(", "package_name", ")", ":", "print", "(", "\"Removing duplicate metadata directories of package: %s\"", "%", "package_name", ")", "module", "=", "importlib", ".", "import_module", "(", "package_name", ")", "py_mn", "=", "\"%s.%s...
Remove duplicate metadata directories of a package.
[ "Remove", "duplicate", "metadata", "directories", "of", "a", "package", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/remove_duplicate_setuptools.py#L18-L56
train
28,264
pywbem/pywbem
examples/wbemcli_clean_subscriptions.py
display_path_info
def display_path_info(descriptor, class_, namespace): """ Display info on the instance names of the class parameter retrieved from the interop namespace of the server defined by CONN. The descriptor is text defining the class(ex. Filter)). Returns a list of the paths """ paths = CONN.EnumerateInstanceNames(class_, namespace=interop) # noqa: F821 print('%ss: count=%s' % (descriptor, len(paths))) for path in paths: print('%s: %s' % (descriptor, path)) return paths
python
def display_path_info(descriptor, class_, namespace): """ Display info on the instance names of the class parameter retrieved from the interop namespace of the server defined by CONN. The descriptor is text defining the class(ex. Filter)). Returns a list of the paths """ paths = CONN.EnumerateInstanceNames(class_, namespace=interop) # noqa: F821 print('%ss: count=%s' % (descriptor, len(paths))) for path in paths: print('%s: %s' % (descriptor, path)) return paths
[ "def", "display_path_info", "(", "descriptor", ",", "class_", ",", "namespace", ")", ":", "paths", "=", "CONN", ".", "EnumerateInstanceNames", "(", "class_", ",", "namespace", "=", "interop", ")", "# noqa: F821", "print", "(", "'%ss: count=%s'", "%", "(", "des...
Display info on the instance names of the class parameter retrieved from the interop namespace of the server defined by CONN. The descriptor is text defining the class(ex. Filter)). Returns a list of the paths
[ "Display", "info", "on", "the", "instance", "names", "of", "the", "class", "parameter", "retrieved", "from", "the", "interop", "namespace", "of", "the", "server", "defined", "by", "CONN", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/wbemcli_clean_subscriptions.py#L9-L21
train
28,265
pywbem/pywbem
pywbem/tupleparse.py
kids
def kids(tup_tree): """ Return a list with the child elements of tup_tree. The child elements are represented as tupletree nodes. Child nodes that are not XML elements (e.g. text nodes) in tup_tree are filtered out. """ k = tup_tree[2] if k is None: return [] # pylint: disable=unidiomatic-typecheck return [x for x in k if type(x) == tuple]
python
def kids(tup_tree): """ Return a list with the child elements of tup_tree. The child elements are represented as tupletree nodes. Child nodes that are not XML elements (e.g. text nodes) in tup_tree are filtered out. """ k = tup_tree[2] if k is None: return [] # pylint: disable=unidiomatic-typecheck return [x for x in k if type(x) == tuple]
[ "def", "kids", "(", "tup_tree", ")", ":", "k", "=", "tup_tree", "[", "2", "]", "if", "k", "is", "None", ":", "return", "[", "]", "# pylint: disable=unidiomatic-typecheck", "return", "[", "x", "for", "x", "in", "k", "if", "type", "(", "x", ")", "==", ...
Return a list with the child elements of tup_tree. The child elements are represented as tupletree nodes. Child nodes that are not XML elements (e.g. text nodes) in tup_tree are filtered out.
[ "Return", "a", "list", "with", "the", "child", "elements", "of", "tup_tree", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L117-L130
train
28,266
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.pcdata
def pcdata(self, tup_tree): """ Return the concatenated character data within the child nodes of a tuple tree node, as a unicode string. Whitespace is preserved. The child nodes must be text nodes (no element nodes). """ try: data = u''.join(tup_tree[2]) except TypeError: raise CIMXMLParseError( _format("Element {0!A} has unexpected child elements: " "{1!A} (allowed is only text content)", name(tup_tree), tup_tree[2]), conn_id=self.conn_id) return data
python
def pcdata(self, tup_tree): """ Return the concatenated character data within the child nodes of a tuple tree node, as a unicode string. Whitespace is preserved. The child nodes must be text nodes (no element nodes). """ try: data = u''.join(tup_tree[2]) except TypeError: raise CIMXMLParseError( _format("Element {0!A} has unexpected child elements: " "{1!A} (allowed is only text content)", name(tup_tree), tup_tree[2]), conn_id=self.conn_id) return data
[ "def", "pcdata", "(", "self", ",", "tup_tree", ")", ":", "try", ":", "data", "=", "u''", ".", "join", "(", "tup_tree", "[", "2", "]", ")", "except", "TypeError", ":", "raise", "CIMXMLParseError", "(", "_format", "(", "\"Element {0!A} has unexpected child ele...
Return the concatenated character data within the child nodes of a tuple tree node, as a unicode string. Whitespace is preserved. The child nodes must be text nodes (no element nodes).
[ "Return", "the", "concatenated", "character", "data", "within", "the", "child", "nodes", "of", "a", "tuple", "tree", "node", "as", "a", "unicode", "string", ".", "Whitespace", "is", "preserved", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L145-L162
train
28,267
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.check_node
def check_node(self, tup_tree, nodename, required_attrs=None, optional_attrs=None, allowed_children=None, allow_pcdata=False): # pylint: disable=too-many-branches """ Check static local constraints on a tuple tree node. The node must have the given nodename. Required_attrs is a list/tuple of attribute names that must be present. None means the same as an empty list: No attributes are required. Optional_attrs is a list/tuple of attribute names that may be present. None means the same as an empty list: No attributes are optional. Present attributes is a list/tuple of attributes that are neither required nor optional, are rejected. If allowed_children is not None, it is a list/tuple where the node may have children of the given types. It can be [] for nodes that may not have any children. If it's None, no validation of the children is performed. If allow_pcdata is True, then non-whitespace text nodes are allowed as children. (Whitespace text nodes are always allowed as children.) """ if name(tup_tree) != nodename: raise CIMXMLParseError( _format("Unexpected element {0!A} (expecting element {1!A})", name(tup_tree), nodename), conn_id=self.conn_id) # Check we have all the required attributes, and no unexpected ones tt_attrs = {} if attrs(tup_tree) is not None: tt_attrs = attrs(tup_tree).copy() if required_attrs: for attr in required_attrs: if attr not in tt_attrs: raise CIMXMLParseError( _format("Element {0!A} missing required attribute " "{1!A} (only has attributes {2!A})", name(tup_tree), attr, attrs(tup_tree).keys()), conn_id=self.conn_id) del tt_attrs[attr] if optional_attrs: for attr in optional_attrs: if attr in tt_attrs: del tt_attrs[attr] if tt_attrs: raise CIMXMLParseError( _format("Element {0!A} has invalid attribute(s) {1!A}", name(tup_tree), tt_attrs.keys()), conn_id=self.conn_id) if allowed_children is not None: invalid_children = [] for child in kids(tup_tree): if name(child) not in allowed_children: invalid_children.append(name(child)) if invalid_children: if not allowed_children: allow_txt = "no child elements are allowed" else: allow_txt = _format("allowed are child elements {0!A}", allowed_children) raise CIMXMLParseError( _format("Element {0!A} has invalid child element(s) " "{1!A} ({2})", name(tup_tree), set(invalid_children), allow_txt), conn_id=self.conn_id) if not allow_pcdata: for child in tup_tree[2]: if isinstance(child, six.string_types): if child.lstrip(' \t\n') != '': raise CIMXMLParseError( _format("Element {0!A} has unexpected non-blank " "text content {1!A}", name(tup_tree), child), conn_id=self.conn_id)
python
def check_node(self, tup_tree, nodename, required_attrs=None, optional_attrs=None, allowed_children=None, allow_pcdata=False): # pylint: disable=too-many-branches """ Check static local constraints on a tuple tree node. The node must have the given nodename. Required_attrs is a list/tuple of attribute names that must be present. None means the same as an empty list: No attributes are required. Optional_attrs is a list/tuple of attribute names that may be present. None means the same as an empty list: No attributes are optional. Present attributes is a list/tuple of attributes that are neither required nor optional, are rejected. If allowed_children is not None, it is a list/tuple where the node may have children of the given types. It can be [] for nodes that may not have any children. If it's None, no validation of the children is performed. If allow_pcdata is True, then non-whitespace text nodes are allowed as children. (Whitespace text nodes are always allowed as children.) """ if name(tup_tree) != nodename: raise CIMXMLParseError( _format("Unexpected element {0!A} (expecting element {1!A})", name(tup_tree), nodename), conn_id=self.conn_id) # Check we have all the required attributes, and no unexpected ones tt_attrs = {} if attrs(tup_tree) is not None: tt_attrs = attrs(tup_tree).copy() if required_attrs: for attr in required_attrs: if attr not in tt_attrs: raise CIMXMLParseError( _format("Element {0!A} missing required attribute " "{1!A} (only has attributes {2!A})", name(tup_tree), attr, attrs(tup_tree).keys()), conn_id=self.conn_id) del tt_attrs[attr] if optional_attrs: for attr in optional_attrs: if attr in tt_attrs: del tt_attrs[attr] if tt_attrs: raise CIMXMLParseError( _format("Element {0!A} has invalid attribute(s) {1!A}", name(tup_tree), tt_attrs.keys()), conn_id=self.conn_id) if allowed_children is not None: invalid_children = [] for child in kids(tup_tree): if name(child) not in allowed_children: invalid_children.append(name(child)) if invalid_children: if not allowed_children: allow_txt = "no child elements are allowed" else: allow_txt = _format("allowed are child elements {0!A}", allowed_children) raise CIMXMLParseError( _format("Element {0!A} has invalid child element(s) " "{1!A} ({2})", name(tup_tree), set(invalid_children), allow_txt), conn_id=self.conn_id) if not allow_pcdata: for child in tup_tree[2]: if isinstance(child, six.string_types): if child.lstrip(' \t\n') != '': raise CIMXMLParseError( _format("Element {0!A} has unexpected non-blank " "text content {1!A}", name(tup_tree), child), conn_id=self.conn_id)
[ "def", "check_node", "(", "self", ",", "tup_tree", ",", "nodename", ",", "required_attrs", "=", "None", ",", "optional_attrs", "=", "None", ",", "allowed_children", "=", "None", ",", "allow_pcdata", "=", "False", ")", ":", "# pylint: disable=too-many-branches", ...
Check static local constraints on a tuple tree node. The node must have the given nodename. Required_attrs is a list/tuple of attribute names that must be present. None means the same as an empty list: No attributes are required. Optional_attrs is a list/tuple of attribute names that may be present. None means the same as an empty list: No attributes are optional. Present attributes is a list/tuple of attributes that are neither required nor optional, are rejected. If allowed_children is not None, it is a list/tuple where the node may have children of the given types. It can be [] for nodes that may not have any children. If it's None, no validation of the children is performed. If allow_pcdata is True, then non-whitespace text nodes are allowed as children. (Whitespace text nodes are always allowed as children.)
[ "Check", "static", "local", "constraints", "on", "a", "tuple", "tree", "node", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L165-L249
train
28,268
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.one_child
def one_child(self, tup_tree, acceptable): """ Parse children of a node with exactly one child node. acceptable is a list/tuple of acceptable child nodes PCData is ignored. """ k = kids(tup_tree) if not k: raise CIMXMLParseError( _format("Element {0!A} missing required child element {1!A}", name(tup_tree), acceptable), conn_id=self.conn_id) if len(k) > 1: raise CIMXMLParseError( _format("Element {0!A} has too many child elements {1!A} " "(allowed is one child element {2!A})", name(tup_tree), [name(t) for t in k], acceptable), conn_id=self.conn_id) child = k[0] if name(child) not in acceptable: raise CIMXMLParseError( _format("Element {0!A} has invalid child element {1!A} " "(allowed is one child element {2!A})", name(tup_tree), name(child), acceptable), conn_id=self.conn_id) return self.parse_any(child)
python
def one_child(self, tup_tree, acceptable): """ Parse children of a node with exactly one child node. acceptable is a list/tuple of acceptable child nodes PCData is ignored. """ k = kids(tup_tree) if not k: raise CIMXMLParseError( _format("Element {0!A} missing required child element {1!A}", name(tup_tree), acceptable), conn_id=self.conn_id) if len(k) > 1: raise CIMXMLParseError( _format("Element {0!A} has too many child elements {1!A} " "(allowed is one child element {2!A})", name(tup_tree), [name(t) for t in k], acceptable), conn_id=self.conn_id) child = k[0] if name(child) not in acceptable: raise CIMXMLParseError( _format("Element {0!A} has invalid child element {1!A} " "(allowed is one child element {2!A})", name(tup_tree), name(child), acceptable), conn_id=self.conn_id) return self.parse_any(child)
[ "def", "one_child", "(", "self", ",", "tup_tree", ",", "acceptable", ")", ":", "k", "=", "kids", "(", "tup_tree", ")", "if", "not", "k", ":", "raise", "CIMXMLParseError", "(", "_format", "(", "\"Element {0!A} missing required child element {1!A}\"", ",", "name",...
Parse children of a node with exactly one child node. acceptable is a list/tuple of acceptable child nodes PCData is ignored.
[ "Parse", "children", "of", "a", "node", "with", "exactly", "one", "child", "node", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L251-L283
train
28,269
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.notimplemented
def notimplemented(self, tup_tree): """ Raise exception for not implemented function. """ raise CIMXMLParseError( _format("Internal Error: Parsing support for element {0!A} is " "not implemented", name(tup_tree)), conn_id=self.conn_id)
python
def notimplemented(self, tup_tree): """ Raise exception for not implemented function. """ raise CIMXMLParseError( _format("Internal Error: Parsing support for element {0!A} is " "not implemented", name(tup_tree)), conn_id=self.conn_id)
[ "def", "notimplemented", "(", "self", ",", "tup_tree", ")", ":", "raise", "CIMXMLParseError", "(", "_format", "(", "\"Internal Error: Parsing support for element {0!A} is \"", "\"not implemented\"", ",", "name", "(", "tup_tree", ")", ")", ",", "conn_id", "=", "self", ...
Raise exception for not implemented function.
[ "Raise", "exception", "for", "not", "implemented", "function", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L376-L383
train
28,270
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_value
def parse_value(self, tup_tree): """ Parse a VALUE element and return its text content as a unicode string. Whitespace is preserved. The conversion of the text representation of the value to a CIM data type object requires CIM type information which is not available on the VALUE element and therefore will be done when parsing higher level elements that have that information. :: <!ELEMENT VALUE (#PCDATA)> """ self.check_node(tup_tree, 'VALUE', (), (), (), allow_pcdata=True) return self.pcdata(tup_tree)
python
def parse_value(self, tup_tree): """ Parse a VALUE element and return its text content as a unicode string. Whitespace is preserved. The conversion of the text representation of the value to a CIM data type object requires CIM type information which is not available on the VALUE element and therefore will be done when parsing higher level elements that have that information. :: <!ELEMENT VALUE (#PCDATA)> """ self.check_node(tup_tree, 'VALUE', (), (), (), allow_pcdata=True) return self.pcdata(tup_tree)
[ "def", "parse_value", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'VALUE'", ",", "(", ")", ",", "(", ")", ",", "(", ")", ",", "allow_pcdata", "=", "True", ")", "return", "self", ".", "pcdata", "(", "tup...
Parse a VALUE element and return its text content as a unicode string. Whitespace is preserved. The conversion of the text representation of the value to a CIM data type object requires CIM type information which is not available on the VALUE element and therefore will be done when parsing higher level elements that have that information. :: <!ELEMENT VALUE (#PCDATA)>
[ "Parse", "a", "VALUE", "element", "and", "return", "its", "text", "content", "as", "a", "unicode", "string", ".", "Whitespace", "is", "preserved", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L455-L472
train
28,271
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_value_array
def parse_value_array(self, tup_tree): """ Parse a VALUE.ARRAY element and return the items in the array as a list of unicode strings, or None for NULL items. Whitespace is preserved. :: <!ELEMENT VALUE.ARRAY (VALUE | VALUE.NULL)*> """ self.check_node(tup_tree, 'VALUE.ARRAY') children = self.list_of_various(tup_tree, ('VALUE', 'VALUE.NULL')) return children
python
def parse_value_array(self, tup_tree): """ Parse a VALUE.ARRAY element and return the items in the array as a list of unicode strings, or None for NULL items. Whitespace is preserved. :: <!ELEMENT VALUE.ARRAY (VALUE | VALUE.NULL)*> """ self.check_node(tup_tree, 'VALUE.ARRAY') children = self.list_of_various(tup_tree, ('VALUE', 'VALUE.NULL')) return children
[ "def", "parse_value_array", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'VALUE.ARRAY'", ")", "children", "=", "self", ".", "list_of_various", "(", "tup_tree", ",", "(", "'VALUE'", ",", "'VALUE.NULL'", ")", ")", ...
Parse a VALUE.ARRAY element and return the items in the array as a list of unicode strings, or None for NULL items. Whitespace is preserved. :: <!ELEMENT VALUE.ARRAY (VALUE | VALUE.NULL)*>
[ "Parse", "a", "VALUE", ".", "ARRAY", "element", "and", "return", "the", "items", "in", "the", "array", "as", "a", "list", "of", "unicode", "strings", "or", "None", "for", "NULL", "items", ".", "Whitespace", "is", "preserved", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L474-L488
train
28,272
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_value_reference
def parse_value_reference(self, tup_tree): """ Parse a VALUE.REFERENCE element and return the instance path or class path it represents as a CIMInstanceName or CIMClassName object, respectively. :: <!ELEMENT VALUE.REFERENCE (CLASSPATH | LOCALCLASSPATH | CLASSNAME | INSTANCEPATH | LOCALINSTANCEPATH | INSTANCENAME)> """ self.check_node(tup_tree, 'VALUE.REFERENCE') child = self.one_child(tup_tree, ('CLASSPATH', 'LOCALCLASSPATH', 'CLASSNAME', 'INSTANCEPATH', 'LOCALINSTANCEPATH', 'INSTANCENAME')) return child
python
def parse_value_reference(self, tup_tree): """ Parse a VALUE.REFERENCE element and return the instance path or class path it represents as a CIMInstanceName or CIMClassName object, respectively. :: <!ELEMENT VALUE.REFERENCE (CLASSPATH | LOCALCLASSPATH | CLASSNAME | INSTANCEPATH | LOCALINSTANCEPATH | INSTANCENAME)> """ self.check_node(tup_tree, 'VALUE.REFERENCE') child = self.one_child(tup_tree, ('CLASSPATH', 'LOCALCLASSPATH', 'CLASSNAME', 'INSTANCEPATH', 'LOCALINSTANCEPATH', 'INSTANCENAME')) return child
[ "def", "parse_value_reference", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'VALUE.REFERENCE'", ")", "child", "=", "self", ".", "one_child", "(", "tup_tree", ",", "(", "'CLASSPATH'", ",", "'LOCALCLASSPATH'", ",", ...
Parse a VALUE.REFERENCE element and return the instance path or class path it represents as a CIMInstanceName or CIMClassName object, respectively. :: <!ELEMENT VALUE.REFERENCE (CLASSPATH | LOCALCLASSPATH | CLASSNAME | INSTANCEPATH | LOCALINSTANCEPATH | INSTANCENAME)>
[ "Parse", "a", "VALUE", ".", "REFERENCE", "element", "and", "return", "the", "instance", "path", "or", "class", "path", "it", "represents", "as", "a", "CIMInstanceName", "or", "CIMClassName", "object", "respectively", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L490-L510
train
28,273
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_value_refarray
def parse_value_refarray(self, tup_tree): """ Parse a VALUE.REFARRAY element and return the array of instance paths or class paths it represents as a list of CIMInstanceName or CIMClassName objects, respectively. :: <!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE | VALUE.NULL)*> """ self.check_node(tup_tree, 'VALUE.REFARRAY') children = self.list_of_various(tup_tree, ('VALUE.REFERENCE', 'VALUE.NULL')) return children
python
def parse_value_refarray(self, tup_tree): """ Parse a VALUE.REFARRAY element and return the array of instance paths or class paths it represents as a list of CIMInstanceName or CIMClassName objects, respectively. :: <!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE | VALUE.NULL)*> """ self.check_node(tup_tree, 'VALUE.REFARRAY') children = self.list_of_various(tup_tree, ('VALUE.REFERENCE', 'VALUE.NULL')) return children
[ "def", "parse_value_refarray", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'VALUE.REFARRAY'", ")", "children", "=", "self", ".", "list_of_various", "(", "tup_tree", ",", "(", "'VALUE.REFERENCE'", ",", "'VALUE.NULL'",...
Parse a VALUE.REFARRAY element and return the array of instance paths or class paths it represents as a list of CIMInstanceName or CIMClassName objects, respectively. :: <!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE | VALUE.NULL)*>
[ "Parse", "a", "VALUE", ".", "REFARRAY", "element", "and", "return", "the", "array", "of", "instance", "paths", "or", "class", "paths", "it", "represents", "as", "a", "list", "of", "CIMInstanceName", "or", "CIMClassName", "objects", "respectively", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L512-L528
train
28,274
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_value_instancewithpath
def parse_value_instancewithpath(self, tup_tree): """ The VALUE.INSTANCEWITHPATH is used to define a value that comprises a single CIMInstance with additional information that defines the absolute path to that object. :: <!ELEMENT VALUE.INSTANCEWITHPATH (INSTANCEPATH, INSTANCE)> """ self.check_node(tup_tree, 'VALUE.INSTANCEWITHPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(INSTANCEPATH, INSTANCE))", name(tup_tree), k), conn_id=self.conn_id) inst_path = self.parse_instancepath(k[0]) instance = self.parse_instance(k[1]) instance.path = inst_path return instance
python
def parse_value_instancewithpath(self, tup_tree): """ The VALUE.INSTANCEWITHPATH is used to define a value that comprises a single CIMInstance with additional information that defines the absolute path to that object. :: <!ELEMENT VALUE.INSTANCEWITHPATH (INSTANCEPATH, INSTANCE)> """ self.check_node(tup_tree, 'VALUE.INSTANCEWITHPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(INSTANCEPATH, INSTANCE))", name(tup_tree), k), conn_id=self.conn_id) inst_path = self.parse_instancepath(k[0]) instance = self.parse_instance(k[1]) instance.path = inst_path return instance
[ "def", "parse_value_instancewithpath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'VALUE.INSTANCEWITHPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", ...
The VALUE.INSTANCEWITHPATH is used to define a value that comprises a single CIMInstance with additional information that defines the absolute path to that object. :: <!ELEMENT VALUE.INSTANCEWITHPATH (INSTANCEPATH, INSTANCE)>
[ "The", "VALUE", ".", "INSTANCEWITHPATH", "is", "used", "to", "define", "a", "value", "that", "comprises", "a", "single", "CIMInstance", "with", "additional", "information", "that", "defines", "the", "absolute", "path", "to", "that", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L570-L596
train
28,275
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_localnamespacepath
def parse_localnamespacepath(self, tup_tree): """ Parse a LOCALNAMESPACEPATH element and return the namespace it represents as a unicode string. The namespace is formed by joining the namespace components (one from each NAMESPACE child element) with a slash (e.g. to "root/cimv2"). :: <!ELEMENT LOCALNAMESPACEPATH (NAMESPACE+)> """ self.check_node(tup_tree, 'LOCALNAMESPACEPATH', (), (), ('NAMESPACE',)) if not kids(tup_tree): raise CIMXMLParseError( _format("Element {0!A} missing child elements (expecting one " "or more child elements 'NAMESPACE')", name(tup_tree)), conn_id=self.conn_id) # self.list_of_various() has the same effect as self.list_of_same() # when used with a single allowed child element, but is a little # faster. ns_list = self.list_of_various(tup_tree, ('NAMESPACE',)) return u'/'.join(ns_list)
python
def parse_localnamespacepath(self, tup_tree): """ Parse a LOCALNAMESPACEPATH element and return the namespace it represents as a unicode string. The namespace is formed by joining the namespace components (one from each NAMESPACE child element) with a slash (e.g. to "root/cimv2"). :: <!ELEMENT LOCALNAMESPACEPATH (NAMESPACE+)> """ self.check_node(tup_tree, 'LOCALNAMESPACEPATH', (), (), ('NAMESPACE',)) if not kids(tup_tree): raise CIMXMLParseError( _format("Element {0!A} missing child elements (expecting one " "or more child elements 'NAMESPACE')", name(tup_tree)), conn_id=self.conn_id) # self.list_of_various() has the same effect as self.list_of_same() # when used with a single allowed child element, but is a little # faster. ns_list = self.list_of_various(tup_tree, ('NAMESPACE',)) return u'/'.join(ns_list)
[ "def", "parse_localnamespacepath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'LOCALNAMESPACEPATH'", ",", "(", ")", ",", "(", ")", ",", "(", "'NAMESPACE'", ",", ")", ")", "if", "not", "kids", "(", "tup_tree"...
Parse a LOCALNAMESPACEPATH element and return the namespace it represents as a unicode string. The namespace is formed by joining the namespace components (one from each NAMESPACE child element) with a slash (e.g. to "root/cimv2"). :: <!ELEMENT LOCALNAMESPACEPATH (NAMESPACE+)>
[ "Parse", "a", "LOCALNAMESPACEPATH", "element", "and", "return", "the", "namespace", "it", "represents", "as", "a", "unicode", "string", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L757-L783
train
28,276
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_host
def parse_host(self, tup_tree): """ Parse a HOST element and return its text content as a unicode string. :: <!ELEMENT HOST (#PCDATA)> """ self.check_node(tup_tree, 'HOST', (), (), (), allow_pcdata=True) return self.pcdata(tup_tree)
python
def parse_host(self, tup_tree): """ Parse a HOST element and return its text content as a unicode string. :: <!ELEMENT HOST (#PCDATA)> """ self.check_node(tup_tree, 'HOST', (), (), (), allow_pcdata=True) return self.pcdata(tup_tree)
[ "def", "parse_host", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'HOST'", ",", "(", ")", ",", "(", ")", ",", "(", ")", ",", "allow_pcdata", "=", "True", ")", "return", "self", ".", "pcdata", "(", "tup_t...
Parse a HOST element and return its text content as a unicode string. :: <!ELEMENT HOST (#PCDATA)>
[ "Parse", "a", "HOST", "element", "and", "return", "its", "text", "content", "as", "a", "unicode", "string", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L785-L796
train
28,277
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_classpath
def parse_classpath(self, tup_tree): """ Parse a CLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSPATH (NAMESPACEPATH, CLASSNAME)> """ self.check_node(tup_tree, 'CLASSPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, CLASSNAME))", name(tup_tree), k), conn_id=self.conn_id) host, namespace = self.parse_namespacepath(k[0]) class_path = self.parse_classname(k[1]) class_path.host = host class_path.namespace = namespace return class_path
python
def parse_classpath(self, tup_tree): """ Parse a CLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSPATH (NAMESPACEPATH, CLASSNAME)> """ self.check_node(tup_tree, 'CLASSPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, CLASSNAME))", name(tup_tree), k), conn_id=self.conn_id) host, namespace = self.parse_namespacepath(k[0]) class_path = self.parse_classname(k[1]) class_path.host = host class_path.namespace = namespace return class_path
[ "def", "parse_classpath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'CLASSPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", "CIMXMLParseError", "(",...
Parse a CLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSPATH (NAMESPACEPATH, CLASSNAME)>
[ "Parse", "a", "CLASSPATH", "element", "and", "return", "the", "class", "path", "it", "represents", "as", "a", "CIMClassName", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L814-L840
train
28,278
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_localclasspath
def parse_localclasspath(self, tup_tree): """ Parse a LOCALCLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)> """ self.check_node(tup_tree, 'LOCALCLASSPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, CLASSNAME))", name(tup_tree), k), conn_id=self.conn_id) namespace = self.parse_localnamespacepath(k[0]) class_path = self.parse_classname(k[1]) class_path.namespace = namespace return class_path
python
def parse_localclasspath(self, tup_tree): """ Parse a LOCALCLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)> """ self.check_node(tup_tree, 'LOCALCLASSPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, CLASSNAME))", name(tup_tree), k), conn_id=self.conn_id) namespace = self.parse_localnamespacepath(k[0]) class_path = self.parse_classname(k[1]) class_path.namespace = namespace return class_path
[ "def", "parse_localclasspath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'LOCALCLASSPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", "CIMXMLParseErro...
Parse a LOCALCLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)>
[ "Parse", "a", "LOCALCLASSPATH", "element", "and", "return", "the", "class", "path", "it", "represents", "as", "a", "CIMClassName", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L842-L867
train
28,279
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_classname
def parse_classname(self, tup_tree): """ Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object (without namespace or host) """ self.check_node(tup_tree, 'CLASSNAME', ('NAME',), (), ()) classname = attrs(tup_tree)['NAME'] class_path = CIMClassName(classname) return class_path
python
def parse_classname(self, tup_tree): """ Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object (without namespace or host) """ self.check_node(tup_tree, 'CLASSNAME', ('NAME',), (), ()) classname = attrs(tup_tree)['NAME'] class_path = CIMClassName(classname) return class_path
[ "def", "parse_classname", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'CLASSNAME'", ",", "(", "'NAME'", ",", ")", ",", "(", ")", ",", "(", ")", ")", "classname", "=", "attrs", "(", "tup_tree", ")", "[", ...
Parse a CLASSNAME element and return the class path it represents as a CIMClassName object. :: <!ELEMENT CLASSNAME EMPTY> <!ATTLIST CLASSNAME %CIMName;> Returns: CIMClassName object (without namespace or host)
[ "Parse", "a", "CLASSNAME", "element", "and", "return", "the", "class", "path", "it", "represents", "as", "a", "CIMClassName", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L869-L889
train
28,280
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_instancepath
def parse_instancepath(self, tup_tree): """ Parse an INSTANCEPATH element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)> """ self.check_node(tup_tree, 'INSTANCEPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, INSTANCENAME))", name(tup_tree), k), conn_id=self.conn_id) host, namespace = self.parse_namespacepath(k[0]) inst_path = self.parse_instancename(k[1]) inst_path.host = host inst_path.namespace = namespace return inst_path
python
def parse_instancepath(self, tup_tree): """ Parse an INSTANCEPATH element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)> """ self.check_node(tup_tree, 'INSTANCEPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(NAMESPACEPATH, INSTANCENAME))", name(tup_tree), k), conn_id=self.conn_id) host, namespace = self.parse_namespacepath(k[0]) inst_path = self.parse_instancename(k[1]) inst_path.host = host inst_path.namespace = namespace return inst_path
[ "def", "parse_instancepath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'INSTANCEPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", "CIMXMLParseError", ...
Parse an INSTANCEPATH element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>
[ "Parse", "an", "INSTANCEPATH", "element", "and", "return", "the", "instance", "path", "it", "represents", "as", "a", "CIMInstanceName", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L891-L917
train
28,281
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_localinstancepath
def parse_localinstancepath(self, tup_tree): """ Parse a LOCALINSTANCEPATH element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT LOCALINSTANCEPATH (LOCALNAMESPACEPATH, INSTANCENAME)> """ self.check_node(tup_tree, 'LOCALINSTANCEPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, INSTANCENAME))", name(tup_tree), k), conn_id=self.conn_id) namespace = self.parse_localnamespacepath(k[0]) inst_path = self.parse_instancename(k[1]) inst_path.namespace = namespace return inst_path
python
def parse_localinstancepath(self, tup_tree): """ Parse a LOCALINSTANCEPATH element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT LOCALINSTANCEPATH (LOCALNAMESPACEPATH, INSTANCENAME)> """ self.check_node(tup_tree, 'LOCALINSTANCEPATH') k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, INSTANCENAME))", name(tup_tree), k), conn_id=self.conn_id) namespace = self.parse_localnamespacepath(k[0]) inst_path = self.parse_instancename(k[1]) inst_path.namespace = namespace return inst_path
[ "def", "parse_localinstancepath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'LOCALINSTANCEPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", "CIMXMLPar...
Parse a LOCALINSTANCEPATH element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT LOCALINSTANCEPATH (LOCALNAMESPACEPATH, INSTANCENAME)>
[ "Parse", "a", "LOCALINSTANCEPATH", "element", "and", "return", "the", "instance", "path", "it", "represents", "as", "a", "CIMInstanceName", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L919-L945
train
28,282
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_instancename
def parse_instancename(self, tup_tree): """ Parse an INSTANCENAME element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT INSTANCENAME (KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?)> <!ATTLIST INSTANCENAME %ClassName;> """ self.check_node(tup_tree, 'INSTANCENAME', ('CLASSNAME',)) k = kids(tup_tree) if not k: # probably not ever going to see this, but it's valid # according to the grammar return CIMInstanceName(attrs(tup_tree)['CLASSNAME'], {}) kid0 = k[0] k0_name = name(kid0) classname = attrs(tup_tree)['CLASSNAME'] if k0_name in ('KEYVALUE', 'VALUE.REFERENCE'): if len(k) != 1: raise CIMXMLParseError( _format("Element {0!A} has more than one child element " "{1!A} (expecting child elements " "(KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?))", name(tup_tree), k0_name), conn_id=self.conn_id) val = self.parse_any(kid0) return CIMInstanceName(classname, {None: val}) if k0_name == 'KEYBINDING': kbs = {} # self.list_of_various() has the same effect as self.list_of_same() # when used with a single allowed child element, but is a little # faster. for key_bind in self.list_of_various(tup_tree, ('KEYBINDING',)): kbs.update(key_bind) return CIMInstanceName(classname, kbs) raise CIMXMLParseError( _format("Element {0!A} has invalid child elements {1!A} " "(expecting child elements " "(KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?))", name(tup_tree), k), conn_id=self.conn_id)
python
def parse_instancename(self, tup_tree): """ Parse an INSTANCENAME element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT INSTANCENAME (KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?)> <!ATTLIST INSTANCENAME %ClassName;> """ self.check_node(tup_tree, 'INSTANCENAME', ('CLASSNAME',)) k = kids(tup_tree) if not k: # probably not ever going to see this, but it's valid # according to the grammar return CIMInstanceName(attrs(tup_tree)['CLASSNAME'], {}) kid0 = k[0] k0_name = name(kid0) classname = attrs(tup_tree)['CLASSNAME'] if k0_name in ('KEYVALUE', 'VALUE.REFERENCE'): if len(k) != 1: raise CIMXMLParseError( _format("Element {0!A} has more than one child element " "{1!A} (expecting child elements " "(KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?))", name(tup_tree), k0_name), conn_id=self.conn_id) val = self.parse_any(kid0) return CIMInstanceName(classname, {None: val}) if k0_name == 'KEYBINDING': kbs = {} # self.list_of_various() has the same effect as self.list_of_same() # when used with a single allowed child element, but is a little # faster. for key_bind in self.list_of_various(tup_tree, ('KEYBINDING',)): kbs.update(key_bind) return CIMInstanceName(classname, kbs) raise CIMXMLParseError( _format("Element {0!A} has invalid child elements {1!A} " "(expecting child elements " "(KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?))", name(tup_tree), k), conn_id=self.conn_id)
[ "def", "parse_instancename", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'INSTANCENAME'", ",", "(", "'CLASSNAME'", ",", ")", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "not", "k", ":", "# probably not...
Parse an INSTANCENAME element and return the instance path it represents as a CIMInstanceName object. :: <!ELEMENT INSTANCENAME (KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?)> <!ATTLIST INSTANCENAME %ClassName;>
[ "Parse", "an", "INSTANCENAME", "element", "and", "return", "the", "instance", "path", "it", "represents", "as", "a", "CIMInstanceName", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L947-L999
train
28,283
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_keybinding
def parse_keybinding(self, tup_tree): """ Parse a KEYBINDING element and return the keybinding as a one-item dictionary from name to value, where the value is a CIM data type object, based upon the type information in the child elements, if present. If no type information is present, numeric values are returned as int or float. :: <!ELEMENT KEYBINDING (KEYVALUE | VALUE.REFERENCE)> <!ATTLIST KEYBINDING %CIMName;> """ self.check_node(tup_tree, 'KEYBINDING', ('NAME',)) child = self.one_child(tup_tree, ('KEYVALUE', 'VALUE.REFERENCE')) return {attrs(tup_tree)['NAME']: child}
python
def parse_keybinding(self, tup_tree): """ Parse a KEYBINDING element and return the keybinding as a one-item dictionary from name to value, where the value is a CIM data type object, based upon the type information in the child elements, if present. If no type information is present, numeric values are returned as int or float. :: <!ELEMENT KEYBINDING (KEYVALUE | VALUE.REFERENCE)> <!ATTLIST KEYBINDING %CIMName;> """ self.check_node(tup_tree, 'KEYBINDING', ('NAME',)) child = self.one_child(tup_tree, ('KEYVALUE', 'VALUE.REFERENCE')) return {attrs(tup_tree)['NAME']: child}
[ "def", "parse_keybinding", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'KEYBINDING'", ",", "(", "'NAME'", ",", ")", ")", "child", "=", "self", ".", "one_child", "(", "tup_tree", ",", "(", "'KEYVALUE'", ",", ...
Parse a KEYBINDING element and return the keybinding as a one-item dictionary from name to value, where the value is a CIM data type object, based upon the type information in the child elements, if present. If no type information is present, numeric values are returned as int or float. :: <!ELEMENT KEYBINDING (KEYVALUE | VALUE.REFERENCE)> <!ATTLIST KEYBINDING %CIMName;>
[ "Parse", "a", "KEYBINDING", "element", "and", "return", "the", "keybinding", "as", "a", "one", "-", "item", "dictionary", "from", "name", "to", "value", "where", "the", "value", "is", "a", "CIM", "data", "type", "object", "based", "upon", "the", "type", ...
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1018-L1037
train
28,284
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_keyvalue
def parse_keyvalue(self, tup_tree): """ Parse a KEYVALUE element and return the keybinding value as a CIM data type object, based upon the type information in its VALUETYPE and TYPE attributes, if present. If TYPE is specified, its value is used to create the corresponding CIM data type object. in this case, VALUETYPE is ignored and may be omitted. Discrepancies between TYPE and VALUETYPE are not checked. Note that DSP0201 does not detail how such discrepancies should be resolved, including the precedence of the DTD-defined default for VALUETYPE over a specified TYPE value. If TYPE is not specified but VALUETYPE is specified, the CIM type is defaulted for a VALUETYPE of 'string' and 'boolean'. For a VALUETYPE of 'numeric', the CIM type remains undetermined and the numeric values are returned as Python int/long or float objects. :: <!ELEMENT KEYVALUE (#PCDATA)> <!ATTLIST KEYVALUE VALUETYPE (string | boolean | numeric) "string" %CIMType; #IMPLIED> """ self.check_node(tup_tree, 'KEYVALUE', (), ('VALUETYPE', 'TYPE'), (), allow_pcdata=True) data = self.pcdata(tup_tree) attrl = attrs(tup_tree) valuetype = attrl.get('VALUETYPE', None) cimtype = attrl.get('TYPE', None) # Tolerate that some WBEM servers return TYPE="" instead of omitting # TYPE (e.g. the WBEM Solutions server). if cimtype == '': cimtype = None # Default the CIM type from VALUETYPE if not specified in TYPE if cimtype is None: if valuetype is None or valuetype == 'string': cimtype = 'string' elif valuetype == 'boolean': cimtype = 'boolean' elif valuetype == 'numeric': pass else: raise CIMXMLParseError( _format("Element {0!A} has invalid 'VALUETYPE' attribute " "value {1!A}", name(tup_tree), valuetype), conn_id=self.conn_id) return self.unpack_single_value(data, cimtype)
python
def parse_keyvalue(self, tup_tree): """ Parse a KEYVALUE element and return the keybinding value as a CIM data type object, based upon the type information in its VALUETYPE and TYPE attributes, if present. If TYPE is specified, its value is used to create the corresponding CIM data type object. in this case, VALUETYPE is ignored and may be omitted. Discrepancies between TYPE and VALUETYPE are not checked. Note that DSP0201 does not detail how such discrepancies should be resolved, including the precedence of the DTD-defined default for VALUETYPE over a specified TYPE value. If TYPE is not specified but VALUETYPE is specified, the CIM type is defaulted for a VALUETYPE of 'string' and 'boolean'. For a VALUETYPE of 'numeric', the CIM type remains undetermined and the numeric values are returned as Python int/long or float objects. :: <!ELEMENT KEYVALUE (#PCDATA)> <!ATTLIST KEYVALUE VALUETYPE (string | boolean | numeric) "string" %CIMType; #IMPLIED> """ self.check_node(tup_tree, 'KEYVALUE', (), ('VALUETYPE', 'TYPE'), (), allow_pcdata=True) data = self.pcdata(tup_tree) attrl = attrs(tup_tree) valuetype = attrl.get('VALUETYPE', None) cimtype = attrl.get('TYPE', None) # Tolerate that some WBEM servers return TYPE="" instead of omitting # TYPE (e.g. the WBEM Solutions server). if cimtype == '': cimtype = None # Default the CIM type from VALUETYPE if not specified in TYPE if cimtype is None: if valuetype is None or valuetype == 'string': cimtype = 'string' elif valuetype == 'boolean': cimtype = 'boolean' elif valuetype == 'numeric': pass else: raise CIMXMLParseError( _format("Element {0!A} has invalid 'VALUETYPE' attribute " "value {1!A}", name(tup_tree), valuetype), conn_id=self.conn_id) return self.unpack_single_value(data, cimtype)
[ "def", "parse_keyvalue", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'KEYVALUE'", ",", "(", ")", ",", "(", "'VALUETYPE'", ",", "'TYPE'", ")", ",", "(", ")", ",", "allow_pcdata", "=", "True", ")", "data", ...
Parse a KEYVALUE element and return the keybinding value as a CIM data type object, based upon the type information in its VALUETYPE and TYPE attributes, if present. If TYPE is specified, its value is used to create the corresponding CIM data type object. in this case, VALUETYPE is ignored and may be omitted. Discrepancies between TYPE and VALUETYPE are not checked. Note that DSP0201 does not detail how such discrepancies should be resolved, including the precedence of the DTD-defined default for VALUETYPE over a specified TYPE value. If TYPE is not specified but VALUETYPE is specified, the CIM type is defaulted for a VALUETYPE of 'string' and 'boolean'. For a VALUETYPE of 'numeric', the CIM type remains undetermined and the numeric values are returned as Python int/long or float objects. :: <!ELEMENT KEYVALUE (#PCDATA)> <!ATTLIST KEYVALUE VALUETYPE (string | boolean | numeric) "string" %CIMType; #IMPLIED>
[ "Parse", "a", "KEYVALUE", "element", "and", "return", "the", "keybinding", "value", "as", "a", "CIM", "data", "type", "object", "based", "upon", "the", "type", "information", "in", "its", "VALUETYPE", "and", "TYPE", "attributes", "if", "present", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1039-L1094
train
28,285
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_class
def parse_class(self, tup_tree): """ Parse CLASS element returning a CIMClass if the parse was successful. :: <!ELEMENT CLASS (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*, METHOD*)> <!ATTLIST CLASS %CIMName; %SuperClass;> """ # Doesn't check ordering of elements, but it's not very important self.check_node(tup_tree, 'CLASS', ('NAME',), ('SUPERCLASS',), ('QUALIFIER', 'PROPERTY', 'PROPERTY.REFERENCE', 'PROPERTY.ARRAY', 'METHOD')) attrl = attrs(tup_tree) superclass = attrl.get('SUPERCLASS', None) properties = self.list_of_matching(tup_tree, ('PROPERTY', 'PROPERTY.REFERENCE', 'PROPERTY.ARRAY')) qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) methods = self.list_of_matching(tup_tree, ('METHOD',)) return CIMClass(attrl['NAME'], superclass=superclass, properties=properties, qualifiers=qualifiers, methods=methods)
python
def parse_class(self, tup_tree): """ Parse CLASS element returning a CIMClass if the parse was successful. :: <!ELEMENT CLASS (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*, METHOD*)> <!ATTLIST CLASS %CIMName; %SuperClass;> """ # Doesn't check ordering of elements, but it's not very important self.check_node(tup_tree, 'CLASS', ('NAME',), ('SUPERCLASS',), ('QUALIFIER', 'PROPERTY', 'PROPERTY.REFERENCE', 'PROPERTY.ARRAY', 'METHOD')) attrl = attrs(tup_tree) superclass = attrl.get('SUPERCLASS', None) properties = self.list_of_matching(tup_tree, ('PROPERTY', 'PROPERTY.REFERENCE', 'PROPERTY.ARRAY')) qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) methods = self.list_of_matching(tup_tree, ('METHOD',)) return CIMClass(attrl['NAME'], superclass=superclass, properties=properties, qualifiers=qualifiers, methods=methods)
[ "def", "parse_class", "(", "self", ",", "tup_tree", ")", ":", "# Doesn't check ordering of elements, but it's not very important", "self", ".", "check_node", "(", "tup_tree", ",", "'CLASS'", ",", "(", "'NAME'", ",", ")", ",", "(", "'SUPERCLASS'", ",", ")", ",", ...
Parse CLASS element returning a CIMClass if the parse was successful. :: <!ELEMENT CLASS (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*, METHOD*)> <!ATTLIST CLASS %CIMName; %SuperClass;>
[ "Parse", "CLASS", "element", "returning", "a", "CIMClass", "if", "the", "parse", "was", "successful", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1100-L1131
train
28,286
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_instance
def parse_instance(self, tup_tree): """ Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*)> <!ATTLIST INSTANCE %ClassName; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'INSTANCE', ('CLASSNAME',), ('xml:lang',), ('QUALIFIER', 'PROPERTY', 'PROPERTY.ARRAY', 'PROPERTY.REFERENCE')) # The 'xml:lang' attribute is tolerated but ignored. # Note: The check above does not enforce the ordering constraint in the # DTD that QUALIFIER elements must appear before PROPERTY* elements. qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) props = self.list_of_matching(tup_tree, ('PROPERTY.REFERENCE', 'PROPERTY', 'PROPERTY.ARRAY')) obj = CIMInstance(attrs(tup_tree)['CLASSNAME'], qualifiers=qualifiers) for prop in props: obj.__setitem__(prop.name, prop) return obj
python
def parse_instance(self, tup_tree): """ Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*)> <!ATTLIST INSTANCE %ClassName; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'INSTANCE', ('CLASSNAME',), ('xml:lang',), ('QUALIFIER', 'PROPERTY', 'PROPERTY.ARRAY', 'PROPERTY.REFERENCE')) # The 'xml:lang' attribute is tolerated but ignored. # Note: The check above does not enforce the ordering constraint in the # DTD that QUALIFIER elements must appear before PROPERTY* elements. qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) props = self.list_of_matching(tup_tree, ('PROPERTY.REFERENCE', 'PROPERTY', 'PROPERTY.ARRAY')) obj = CIMInstance(attrs(tup_tree)['CLASSNAME'], qualifiers=qualifiers) for prop in props: obj.__setitem__(prop.name, prop) return obj
[ "def", "parse_instance", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'INSTANCE'", ",", "(", "'CLASSNAME'", ",", ")", ",", "(", "'xml:lang'", ",", ")", ",", "(", "'QUALIFIER'", ",", "'PROPERTY'", ",", "'PROPER...
Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*)> <!ATTLIST INSTANCE %ClassName; xml:lang NMTOKEN #IMPLIED>
[ "Return", "a", "CIMInstance", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1133-L1169
train
28,287
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_scope
def parse_scope(self, tup_tree): """ Parse a SCOPE element and return a dictionary with an item for each specified scope attribute. The keys of the dictionary items are the scope names in upper case; the values are the Python boolean values True or False. Unspecified scope attributes are not represented in the returned dictionary; the user is expected to assume their default value of False. The returned dictionary does not preserve order of the scope attributes. :: <!ELEMENT SCOPE EMPTY> <!ATTLIST SCOPE CLASS (true | false) "false" ASSOCIATION (true | false) "false" REFERENCE (true | false) "false" PROPERTY (true | false) "false" METHOD (true | false) "false" PARAMETER (true | false) "false" INDICATION (true | false) "false" """ self.check_node(tup_tree, 'SCOPE', (), ('CLASS', 'ASSOCIATION', 'REFERENCE', 'PROPERTY', 'METHOD', 'PARAMETER', 'INDICATION'), ()) # Even though XML attributes do not preserve order, we store the # scopes in an ordered dict to avoid a warning further down the # road. scopes = NocaseDict() for k, v in attrs(tup_tree).items(): v_ = self.unpack_boolean(v) if v_ is None: raise CIMXMLParseError( _format("Element {0!A} has an invalid value {1!A} for its " "boolean attribute {2!A}", name(tup_tree), v, k), conn_id=self.conn_id) scopes[k] = v_ return scopes
python
def parse_scope(self, tup_tree): """ Parse a SCOPE element and return a dictionary with an item for each specified scope attribute. The keys of the dictionary items are the scope names in upper case; the values are the Python boolean values True or False. Unspecified scope attributes are not represented in the returned dictionary; the user is expected to assume their default value of False. The returned dictionary does not preserve order of the scope attributes. :: <!ELEMENT SCOPE EMPTY> <!ATTLIST SCOPE CLASS (true | false) "false" ASSOCIATION (true | false) "false" REFERENCE (true | false) "false" PROPERTY (true | false) "false" METHOD (true | false) "false" PARAMETER (true | false) "false" INDICATION (true | false) "false" """ self.check_node(tup_tree, 'SCOPE', (), ('CLASS', 'ASSOCIATION', 'REFERENCE', 'PROPERTY', 'METHOD', 'PARAMETER', 'INDICATION'), ()) # Even though XML attributes do not preserve order, we store the # scopes in an ordered dict to avoid a warning further down the # road. scopes = NocaseDict() for k, v in attrs(tup_tree).items(): v_ = self.unpack_boolean(v) if v_ is None: raise CIMXMLParseError( _format("Element {0!A} has an invalid value {1!A} for its " "boolean attribute {2!A}", name(tup_tree), v, k), conn_id=self.conn_id) scopes[k] = v_ return scopes
[ "def", "parse_scope", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'SCOPE'", ",", "(", ")", ",", "(", "'CLASS'", ",", "'ASSOCIATION'", ",", "'REFERENCE'", ",", "'PROPERTY'", ",", "'METHOD'", ",", "'PARAMETER'", ...
Parse a SCOPE element and return a dictionary with an item for each specified scope attribute. The keys of the dictionary items are the scope names in upper case; the values are the Python boolean values True or False. Unspecified scope attributes are not represented in the returned dictionary; the user is expected to assume their default value of False. The returned dictionary does not preserve order of the scope attributes. :: <!ELEMENT SCOPE EMPTY> <!ATTLIST SCOPE CLASS (true | false) "false" ASSOCIATION (true | false) "false" REFERENCE (true | false) "false" PROPERTY (true | false) "false" METHOD (true | false) "false" PARAMETER (true | false) "false" INDICATION (true | false) "false"
[ "Parse", "a", "SCOPE", "element", "and", "return", "a", "dictionary", "with", "an", "item", "for", "each", "specified", "scope", "attribute", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1171-L1215
train
28,288
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_qualifier_declaration
def parse_qualifier_declaration(self, tup_tree): """ Parse QUALIFIER.DECLARATION element. :: <!ELEMENT QUALIFIER.DECLARATION (SCOPE?, (VALUE | VALUE.ARRAY)?)> <!ATTLIST QUALIFIER.DECLARATION %CIMName; %CIMType; #REQUIRED ISARRAY (true|false) #IMPLIED %ArraySize; %QualifierFlavor;> """ self.check_node(tup_tree, 'QUALIFIER.DECLARATION', ('NAME', 'TYPE'), ('ISARRAY', 'ARRAYSIZE', 'OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE', 'TRANSLATABLE'), ('SCOPE', 'VALUE', 'VALUE.ARRAY')) attrl = attrs(tup_tree) qname = attrl['NAME'] _type = attrl['TYPE'] is_array = self.unpack_boolean(attrl.get('ISARRAY', 'false')) array_size = attrl.get('ARRAYSIZE', None) if array_size is not None: # Issue #1044: Clarify if hex support is needed. array_size = int(array_size) scopes = None value = None for child in kids(tup_tree): if name(child) == 'SCOPE': if scopes is not None: raise CIMXMLParseError( _format("Element {0!A} has more than one child " "element {1!A} (allowed is only one)", name(tup_tree), name(child)), conn_id=self.conn_id) scopes = self.parse_any(child) else: # name is 'VALUE' or 'VALUE.ARRAY' if value is not None: raise CIMXMLParseError( _format("Element {0!A} has more than one child " "element {1!A} (allowed is only one)", name(tup_tree), name(child)), conn_id=self.conn_id) value = self.unpack_value(tup_tree) overridable = self.unpack_boolean(attrl.get('OVERRIDABLE', 'true')) tosubclass = self.unpack_boolean(attrl.get('TOSUBCLASS', 'true')) toinstance = self.unpack_boolean(attrl.get('TOINSTANCE', 'false')) translatable = self.unpack_boolean(attrl.get('TRANSLATABLE', 'false')) qual_decl = CIMQualifierDeclaration( qname, _type, value, is_array, array_size, scopes, overridable=overridable, tosubclass=tosubclass, toinstance=toinstance, translatable=translatable) return qual_decl
python
def parse_qualifier_declaration(self, tup_tree): """ Parse QUALIFIER.DECLARATION element. :: <!ELEMENT QUALIFIER.DECLARATION (SCOPE?, (VALUE | VALUE.ARRAY)?)> <!ATTLIST QUALIFIER.DECLARATION %CIMName; %CIMType; #REQUIRED ISARRAY (true|false) #IMPLIED %ArraySize; %QualifierFlavor;> """ self.check_node(tup_tree, 'QUALIFIER.DECLARATION', ('NAME', 'TYPE'), ('ISARRAY', 'ARRAYSIZE', 'OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE', 'TRANSLATABLE'), ('SCOPE', 'VALUE', 'VALUE.ARRAY')) attrl = attrs(tup_tree) qname = attrl['NAME'] _type = attrl['TYPE'] is_array = self.unpack_boolean(attrl.get('ISARRAY', 'false')) array_size = attrl.get('ARRAYSIZE', None) if array_size is not None: # Issue #1044: Clarify if hex support is needed. array_size = int(array_size) scopes = None value = None for child in kids(tup_tree): if name(child) == 'SCOPE': if scopes is not None: raise CIMXMLParseError( _format("Element {0!A} has more than one child " "element {1!A} (allowed is only one)", name(tup_tree), name(child)), conn_id=self.conn_id) scopes = self.parse_any(child) else: # name is 'VALUE' or 'VALUE.ARRAY' if value is not None: raise CIMXMLParseError( _format("Element {0!A} has more than one child " "element {1!A} (allowed is only one)", name(tup_tree), name(child)), conn_id=self.conn_id) value = self.unpack_value(tup_tree) overridable = self.unpack_boolean(attrl.get('OVERRIDABLE', 'true')) tosubclass = self.unpack_boolean(attrl.get('TOSUBCLASS', 'true')) toinstance = self.unpack_boolean(attrl.get('TOINSTANCE', 'false')) translatable = self.unpack_boolean(attrl.get('TRANSLATABLE', 'false')) qual_decl = CIMQualifierDeclaration( qname, _type, value, is_array, array_size, scopes, overridable=overridable, tosubclass=tosubclass, toinstance=toinstance, translatable=translatable) return qual_decl
[ "def", "parse_qualifier_declaration", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'QUALIFIER.DECLARATION'", ",", "(", "'NAME'", ",", "'TYPE'", ")", ",", "(", "'ISARRAY'", ",", "'ARRAYSIZE'", ",", "'OVERRIDABLE'", "...
Parse QUALIFIER.DECLARATION element. :: <!ELEMENT QUALIFIER.DECLARATION (SCOPE?, (VALUE | VALUE.ARRAY)?)> <!ATTLIST QUALIFIER.DECLARATION %CIMName; %CIMType; #REQUIRED ISARRAY (true|false) #IMPLIED %ArraySize; %QualifierFlavor;>
[ "Parse", "QUALIFIER", ".", "DECLARATION", "element", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1217-L1280
train
28,289
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_qualifier
def parse_qualifier(self, tup_tree): """ Parse QUALIFIER element returning CIMQualifier. :: <!ELEMENT QUALIFIER (VALUE | VALUE.ARRAY)> <!ATTLIST QUALIFIER %CIMName; %CIMType; #REQUIRED %Propagated; %QualifierFlavor; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'QUALIFIER', ('NAME', 'TYPE'), ('OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE', 'TRANSLATABLE', 'PROPAGATED', 'xml:lang'), ('VALUE', 'VALUE.ARRAY')) # The 'xml:lang' attribute is tolerated but ignored. attrl = attrs(tup_tree) qname = attrl['NAME'] _type = attrl['TYPE'] value = self.unpack_value(tup_tree) propagated = self.unpack_boolean(attrl.get('PROPAGATED', 'false')) overridable = self.unpack_boolean(attrl.get('OVERRIDABLE', 'true')) tosubclass = self.unpack_boolean(attrl.get('TOSUBCLASS', 'true')) toinstance = self.unpack_boolean(attrl.get('TOINSTANCE', 'false')) translatable = self.unpack_boolean(attrl.get('TRANSLATABLE', 'false')) qual = CIMQualifier(qname, value, _type, propagated=propagated, overridable=overridable, tosubclass=tosubclass, toinstance=toinstance, translatable=translatable) return qual
python
def parse_qualifier(self, tup_tree): """ Parse QUALIFIER element returning CIMQualifier. :: <!ELEMENT QUALIFIER (VALUE | VALUE.ARRAY)> <!ATTLIST QUALIFIER %CIMName; %CIMType; #REQUIRED %Propagated; %QualifierFlavor; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'QUALIFIER', ('NAME', 'TYPE'), ('OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE', 'TRANSLATABLE', 'PROPAGATED', 'xml:lang'), ('VALUE', 'VALUE.ARRAY')) # The 'xml:lang' attribute is tolerated but ignored. attrl = attrs(tup_tree) qname = attrl['NAME'] _type = attrl['TYPE'] value = self.unpack_value(tup_tree) propagated = self.unpack_boolean(attrl.get('PROPAGATED', 'false')) overridable = self.unpack_boolean(attrl.get('OVERRIDABLE', 'true')) tosubclass = self.unpack_boolean(attrl.get('TOSUBCLASS', 'true')) toinstance = self.unpack_boolean(attrl.get('TOINSTANCE', 'false')) translatable = self.unpack_boolean(attrl.get('TRANSLATABLE', 'false')) qual = CIMQualifier(qname, value, _type, propagated=propagated, overridable=overridable, tosubclass=tosubclass, toinstance=toinstance, translatable=translatable) return qual
[ "def", "parse_qualifier", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'QUALIFIER'", ",", "(", "'NAME'", ",", "'TYPE'", ")", ",", "(", "'OVERRIDABLE'", ",", "'TOSUBCLASS'", ",", "'TOINSTANCE'", ",", "'TRANSLATABLE...
Parse QUALIFIER element returning CIMQualifier. :: <!ELEMENT QUALIFIER (VALUE | VALUE.ARRAY)> <!ATTLIST QUALIFIER %CIMName; %CIMType; #REQUIRED %Propagated; %QualifierFlavor; xml:lang NMTOKEN #IMPLIED>
[ "Parse", "QUALIFIER", "element", "returning", "CIMQualifier", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1282-L1321
train
28,290
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_property
def parse_property(self, tup_tree): """ Parse PROPERTY into a CIMProperty object. VAL is just the pcdata of the enclosed VALUE node. :: <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)> <!ATTLIST PROPERTY %CIMName; %CIMType; #REQUIRED %ClassOrigin; %Propagated; %EmbeddedObject; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'PROPERTY', ('TYPE', 'NAME'), ('CLASSORIGIN', 'PROPAGATED', 'EmbeddedObject', 'EMBEDDEDOBJECT', 'xml:lang'), ('QUALIFIER', 'VALUE')) # The 'xml:lang' attribute is tolerated but ignored. attrl = attrs(tup_tree) try: val = self.unpack_value(tup_tree) except ValueError as exc: msg = str(exc) raise CIMXMLParseError( _format("Cannot parse content of 'VALUE' child element of " "'PROPERTY' element with name {0!A}: {1}", attrl['NAME'], msg), conn_id=self.conn_id) qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) embedded_object = False if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: try: embedded_object = attrl['EmbeddedObject'] except KeyError: embedded_object = attrl['EMBEDDEDOBJECT'] if embedded_object: val = self.parse_embeddedObject(val) return CIMProperty(attrl['NAME'], val, type=attrl['TYPE'], is_array=False, class_origin=attrl.get('CLASSORIGIN', None), propagated=self.unpack_boolean( attrl.get('PROPAGATED', 'false')), qualifiers=qualifiers, embedded_object=embedded_object)
python
def parse_property(self, tup_tree): """ Parse PROPERTY into a CIMProperty object. VAL is just the pcdata of the enclosed VALUE node. :: <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)> <!ATTLIST PROPERTY %CIMName; %CIMType; #REQUIRED %ClassOrigin; %Propagated; %EmbeddedObject; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'PROPERTY', ('TYPE', 'NAME'), ('CLASSORIGIN', 'PROPAGATED', 'EmbeddedObject', 'EMBEDDEDOBJECT', 'xml:lang'), ('QUALIFIER', 'VALUE')) # The 'xml:lang' attribute is tolerated but ignored. attrl = attrs(tup_tree) try: val = self.unpack_value(tup_tree) except ValueError as exc: msg = str(exc) raise CIMXMLParseError( _format("Cannot parse content of 'VALUE' child element of " "'PROPERTY' element with name {0!A}: {1}", attrl['NAME'], msg), conn_id=self.conn_id) qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) embedded_object = False if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: try: embedded_object = attrl['EmbeddedObject'] except KeyError: embedded_object = attrl['EMBEDDEDOBJECT'] if embedded_object: val = self.parse_embeddedObject(val) return CIMProperty(attrl['NAME'], val, type=attrl['TYPE'], is_array=False, class_origin=attrl.get('CLASSORIGIN', None), propagated=self.unpack_boolean( attrl.get('PROPAGATED', 'false')), qualifiers=qualifiers, embedded_object=embedded_object)
[ "def", "parse_property", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'PROPERTY'", ",", "(", "'TYPE'", ",", "'NAME'", ")", ",", "(", "'CLASSORIGIN'", ",", "'PROPAGATED'", ",", "'EmbeddedObject'", ",", "'EMBEDDEDOB...
Parse PROPERTY into a CIMProperty object. VAL is just the pcdata of the enclosed VALUE node. :: <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)> <!ATTLIST PROPERTY %CIMName; %CIMType; #REQUIRED %ClassOrigin; %Propagated; %EmbeddedObject; xml:lang NMTOKEN #IMPLIED>
[ "Parse", "PROPERTY", "into", "a", "CIMProperty", "object", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1323-L1378
train
28,291
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_paramvalue
def parse_paramvalue(self, tup_tree): """ Parse PARAMVALUE element. :: <!ELEMENT PARAMVALUE (VALUE | VALUE.REFERENCE | VALUE.ARRAY | VALUE.REFARRAY | CLASSNAME | INSTANCENAME | CLASS | INSTANCE | VALUE.NAMEDINSTANCE)?> <!ATTLIST PARAMVALUE %CIMName; %ParamType; #IMPLIED %EmbeddedObject;> """ # Version 2.4 of DSP0201 added CLASSNAME, INSTANCENAME, CLASS, # INSTANCE, and VALUE.NAMEDINSTANCE. # Version 2.1.1 of DSP0201 lacks the %ParamType entity but it is # present as optional (for backwards compatibility) in version 2.2. # VMAX returns TYPE instead of PARAMTYPE, toleration support added to # use TYPE when present if PARAMTYPE is not present. self.check_node(tup_tree, 'PARAMVALUE', ('NAME',), ('TYPE', 'PARAMTYPE', 'EmbeddedObject', 'EMBEDDEDOBJECT')) child = self.optional_child(tup_tree, ('VALUE', 'VALUE.REFERENCE', 'VALUE.ARRAY', 'VALUE.REFARRAY', 'CLASSNAME', 'INSTANCENAME', 'CLASS', 'INSTANCE', 'VALUE.NAMEDINSTANCE')) attrl = attrs(tup_tree) if 'PARAMTYPE' in attrl: paramtype = attrl['PARAMTYPE'] elif 'TYPE' in attrl: paramtype = attrl['TYPE'] else: paramtype = None if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: child = self.parse_embeddedObject(child) return attrl['NAME'], paramtype, child
python
def parse_paramvalue(self, tup_tree): """ Parse PARAMVALUE element. :: <!ELEMENT PARAMVALUE (VALUE | VALUE.REFERENCE | VALUE.ARRAY | VALUE.REFARRAY | CLASSNAME | INSTANCENAME | CLASS | INSTANCE | VALUE.NAMEDINSTANCE)?> <!ATTLIST PARAMVALUE %CIMName; %ParamType; #IMPLIED %EmbeddedObject;> """ # Version 2.4 of DSP0201 added CLASSNAME, INSTANCENAME, CLASS, # INSTANCE, and VALUE.NAMEDINSTANCE. # Version 2.1.1 of DSP0201 lacks the %ParamType entity but it is # present as optional (for backwards compatibility) in version 2.2. # VMAX returns TYPE instead of PARAMTYPE, toleration support added to # use TYPE when present if PARAMTYPE is not present. self.check_node(tup_tree, 'PARAMVALUE', ('NAME',), ('TYPE', 'PARAMTYPE', 'EmbeddedObject', 'EMBEDDEDOBJECT')) child = self.optional_child(tup_tree, ('VALUE', 'VALUE.REFERENCE', 'VALUE.ARRAY', 'VALUE.REFARRAY', 'CLASSNAME', 'INSTANCENAME', 'CLASS', 'INSTANCE', 'VALUE.NAMEDINSTANCE')) attrl = attrs(tup_tree) if 'PARAMTYPE' in attrl: paramtype = attrl['PARAMTYPE'] elif 'TYPE' in attrl: paramtype = attrl['TYPE'] else: paramtype = None if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: child = self.parse_embeddedObject(child) return attrl['NAME'], paramtype, child
[ "def", "parse_paramvalue", "(", "self", ",", "tup_tree", ")", ":", "# Version 2.4 of DSP0201 added CLASSNAME, INSTANCENAME, CLASS,", "# INSTANCE, and VALUE.NAMEDINSTANCE.", "# Version 2.1.1 of DSP0201 lacks the %ParamType entity but it is", "# present as optional (for backwards compatibility) ...
Parse PARAMVALUE element. :: <!ELEMENT PARAMVALUE (VALUE | VALUE.REFERENCE | VALUE.ARRAY | VALUE.REFARRAY | CLASSNAME | INSTANCENAME | CLASS | INSTANCE | VALUE.NAMEDINSTANCE)?> <!ATTLIST PARAMVALUE %CIMName; %ParamType; #IMPLIED %EmbeddedObject;>
[ "Parse", "PARAMVALUE", "element", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1707-L1752
train
28,292
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_expparamvalue
def parse_expparamvalue(self, tup_tree): """ Parse for EXPPARMVALUE Element. I.e. :: <!ELEMENT EXPPARAMVALUE (INSTANCE?)> <!ATTLIST EXPPARAMVALUE %CIMName;> """ self.check_node(tup_tree, 'EXPPARAMVALUE', ('NAME',), (), ('INSTANCE',)) child = self.optional_child(tup_tree, ('INSTANCE',)) _name = attrs(tup_tree)['NAME'] return _name, child
python
def parse_expparamvalue(self, tup_tree): """ Parse for EXPPARMVALUE Element. I.e. :: <!ELEMENT EXPPARAMVALUE (INSTANCE?)> <!ATTLIST EXPPARAMVALUE %CIMName;> """ self.check_node(tup_tree, 'EXPPARAMVALUE', ('NAME',), (), ('INSTANCE',)) child = self.optional_child(tup_tree, ('INSTANCE',)) _name = attrs(tup_tree)['NAME'] return _name, child
[ "def", "parse_expparamvalue", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'EXPPARAMVALUE'", ",", "(", "'NAME'", ",", ")", ",", "(", ")", ",", "(", "'INSTANCE'", ",", ")", ")", "child", "=", "self", ".", "...
Parse for EXPPARMVALUE Element. I.e. :: <!ELEMENT EXPPARAMVALUE (INSTANCE?)> <!ATTLIST EXPPARAMVALUE %CIMName;>
[ "Parse", "for", "EXPPARMVALUE", "Element", ".", "I", ".", "e", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1754-L1770
train
28,293
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_simplersp
def parse_simplersp(self, tup_tree): """ Parse for SIMPLERSP Element. :: <!ELEMENT SIMPLERSP (METHODRESPONSE | IMETHODRESPONSE)> """ self.check_node(tup_tree, 'SIMPLERSP') child = self.one_child(tup_tree, ('METHODRESPONSE', 'IMETHODRESPONSE')) return name(tup_tree), attrs(tup_tree), child
python
def parse_simplersp(self, tup_tree): """ Parse for SIMPLERSP Element. :: <!ELEMENT SIMPLERSP (METHODRESPONSE | IMETHODRESPONSE)> """ self.check_node(tup_tree, 'SIMPLERSP') child = self.one_child(tup_tree, ('METHODRESPONSE', 'IMETHODRESPONSE')) return name(tup_tree), attrs(tup_tree), child
[ "def", "parse_simplersp", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'SIMPLERSP'", ")", "child", "=", "self", ".", "one_child", "(", "tup_tree", ",", "(", "'METHODRESPONSE'", ",", "'IMETHODRESPONSE'", ")", ")", ...
Parse for SIMPLERSP Element. :: <!ELEMENT SIMPLERSP (METHODRESPONSE | IMETHODRESPONSE)>
[ "Parse", "for", "SIMPLERSP", "Element", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1794-L1807
train
28,294
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_methodresponse
def parse_methodresponse(self, tup_tree): """ Parse expected METHODRESPONSE ELEMENT. I.e. :: <!ELEMENT METHODRESPONSE (ERROR | (RETURNVALUE?, PARAMVALUE*))> <!ATTLIST METHODRESPONSE %CIMName;> """ self.check_node(tup_tree, 'METHODRESPONSE', ('NAME',)) return (name(tup_tree), attrs(tup_tree), self.list_of_various(tup_tree, ('ERROR', 'RETURNVALUE', 'PARAMVALUE')))
python
def parse_methodresponse(self, tup_tree): """ Parse expected METHODRESPONSE ELEMENT. I.e. :: <!ELEMENT METHODRESPONSE (ERROR | (RETURNVALUE?, PARAMVALUE*))> <!ATTLIST METHODRESPONSE %CIMName;> """ self.check_node(tup_tree, 'METHODRESPONSE', ('NAME',)) return (name(tup_tree), attrs(tup_tree), self.list_of_various(tup_tree, ('ERROR', 'RETURNVALUE', 'PARAMVALUE')))
[ "def", "parse_methodresponse", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'METHODRESPONSE'", ",", "(", "'NAME'", ",", ")", ")", "return", "(", "name", "(", "tup_tree", ")", ",", "attrs", "(", "tup_tree", ")"...
Parse expected METHODRESPONSE ELEMENT. I.e. :: <!ELEMENT METHODRESPONSE (ERROR | (RETURNVALUE?, PARAMVALUE*))> <!ATTLIST METHODRESPONSE %CIMName;>
[ "Parse", "expected", "METHODRESPONSE", "ELEMENT", ".", "I", ".", "e", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1821-L1837
train
28,295
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_expmethodresponse
def parse_expmethodresponse(self, tup_tree): # pylint: disable=unused-argument """ This function not implemented. """ raise CIMXMLParseError( _format("Internal Error: Parsing support for element {0!A} is not " "implemented", name(tup_tree)), conn_id=self.conn_id)
python
def parse_expmethodresponse(self, tup_tree): # pylint: disable=unused-argument """ This function not implemented. """ raise CIMXMLParseError( _format("Internal Error: Parsing support for element {0!A} is not " "implemented", name(tup_tree)), conn_id=self.conn_id)
[ "def", "parse_expmethodresponse", "(", "self", ",", "tup_tree", ")", ":", "# pylint: disable=unused-argument", "raise", "CIMXMLParseError", "(", "_format", "(", "\"Internal Error: Parsing support for element {0!A} is not \"", "\"implemented\"", ",", "name", "(", "tup_tree", "...
This function not implemented.
[ "This", "function", "not", "implemented", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1839-L1847
train
28,296
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_imethodresponse
def parse_imethodresponse(self, tup_tree): """ Parse the tuple for an IMETHODRESPONE Element. I.e. :: <!ELEMENT IMETHODRESPONSE (ERROR | (IRETURNVALUE?, PARAMVALUE*))> <!ATTLIST IMETHODRESPONSE %CIMName;> """ self.check_node(tup_tree, 'IMETHODRESPONSE', ('NAME',)) return (name(tup_tree), attrs(tup_tree), self.list_of_various(tup_tree, ('ERROR', 'IRETURNVALUE', 'PARAMVALUE')))
python
def parse_imethodresponse(self, tup_tree): """ Parse the tuple for an IMETHODRESPONE Element. I.e. :: <!ELEMENT IMETHODRESPONSE (ERROR | (IRETURNVALUE?, PARAMVALUE*))> <!ATTLIST IMETHODRESPONSE %CIMName;> """ self.check_node(tup_tree, 'IMETHODRESPONSE', ('NAME',)) return (name(tup_tree), attrs(tup_tree), self.list_of_various(tup_tree, ('ERROR', 'IRETURNVALUE', 'PARAMVALUE')))
[ "def", "parse_imethodresponse", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'IMETHODRESPONSE'", ",", "(", "'NAME'", ",", ")", ")", "return", "(", "name", "(", "tup_tree", ")", ",", "attrs", "(", "tup_tree", "...
Parse the tuple for an IMETHODRESPONE Element. I.e. :: <!ELEMENT IMETHODRESPONSE (ERROR | (IRETURNVALUE?, PARAMVALUE*))> <!ATTLIST IMETHODRESPONSE %CIMName;>
[ "Parse", "the", "tuple", "for", "an", "IMETHODRESPONE", "Element", ".", "I", ".", "e", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1849-L1864
train
28,297
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_returnvalue
def parse_returnvalue(self, tup_tree): """ Parse the RETURNVALUE element. Returns name, attributes, and one child as a tuple. :: <!ELEMENT RETURNVALUE (VALUE | VALUE.REFERENCE)?> <!ATTLIST RETURNVALUE %EmbeddedObject; %ParamType; #IMPLIED> """ # Version 2.1.1 of the DTD lacks the %ParamType attribute but it # is present in version 2.2. Make it optional to be backwards # compatible. self.check_node(tup_tree, 'RETURNVALUE', (), ('PARAMTYPE', 'EmbeddedObject', 'EMBEDDEDOBJECT')) child = self.optional_child(tup_tree, ('VALUE', 'VALUE.REFERENCE')) attrl = attrs(tup_tree) if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: child = self.parse_embeddedObject(child) return name(tup_tree), attrl, child
python
def parse_returnvalue(self, tup_tree): """ Parse the RETURNVALUE element. Returns name, attributes, and one child as a tuple. :: <!ELEMENT RETURNVALUE (VALUE | VALUE.REFERENCE)?> <!ATTLIST RETURNVALUE %EmbeddedObject; %ParamType; #IMPLIED> """ # Version 2.1.1 of the DTD lacks the %ParamType attribute but it # is present in version 2.2. Make it optional to be backwards # compatible. self.check_node(tup_tree, 'RETURNVALUE', (), ('PARAMTYPE', 'EmbeddedObject', 'EMBEDDEDOBJECT')) child = self.optional_child(tup_tree, ('VALUE', 'VALUE.REFERENCE')) attrl = attrs(tup_tree) if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: child = self.parse_embeddedObject(child) return name(tup_tree), attrl, child
[ "def", "parse_returnvalue", "(", "self", ",", "tup_tree", ")", ":", "# Version 2.1.1 of the DTD lacks the %ParamType attribute but it", "# is present in version 2.2. Make it optional to be backwards", "# compatible.", "self", ".", "check_node", "(", "tup_tree", ",", "'RETURNVALUE'...
Parse the RETURNVALUE element. Returns name, attributes, and one child as a tuple. :: <!ELEMENT RETURNVALUE (VALUE | VALUE.REFERENCE)?> <!ATTLIST RETURNVALUE %EmbeddedObject; %ParamType; #IMPLIED>
[ "Parse", "the", "RETURNVALUE", "element", ".", "Returns", "name", "attributes", "and", "one", "child", "as", "a", "tuple", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1888-L1914
train
28,298
pywbem/pywbem
pywbem/tupleparse.py
TupleParser.parse_ireturnvalue
def parse_ireturnvalue(self, tup_tree): """ Parse IRETURNVALUE element. Returns name, attributes and values of the tup_tree. :: <!ELEMENT IRETURNVALUE (CLASSNAME* | INSTANCENAME* | VALUE* | VALUE.OBJECTWITHPATH* | VALUE.OBJECTWITHLOCALPATH* | VALUE.OBJECT* | OBJECTPATH* | QUALIFIER.DECLARATION* | VALUE.ARRAY? | VALUE.REFERENCE? | CLASS* | INSTANCE* | INSTANCEPATH* | VALUE.NAMEDINSTANCE* | VALUE.INSTANCEWITHPATH*)> """ # Note: The self.check_node() below does not enforce any child elements # from the DTD, and the processing further down does not enforce that # VALUE.ARRAY and VALUE.REFERENCE may appear at most once. # Checking that at this level is not reasonable because the better # checks can be done in context of the intrinsic operation receiving # its return value. The DTD is so broad simply because it needs to # cover the possible return values of all intrinsic operations. self.check_node(tup_tree, 'IRETURNVALUE') values = self.list_of_same(tup_tree, ('CLASSNAME', 'INSTANCENAME', 'VALUE', 'VALUE.OBJECTWITHPATH', 'VALUE.OBJECTWITHLOCALPATH', 'VALUE.OBJECT', 'OBJECTPATH', 'QUALIFIER.DECLARATION', 'VALUE.ARRAY', 'VALUE.REFERENCE', 'CLASS', 'INSTANCE', 'INSTANCEPATH', 'VALUE.NAMEDINSTANCE', 'VALUE.INSTANCEWITHPATH')) # Note: The caller needs to unpack the value. return name(tup_tree), attrs(tup_tree), values
python
def parse_ireturnvalue(self, tup_tree): """ Parse IRETURNVALUE element. Returns name, attributes and values of the tup_tree. :: <!ELEMENT IRETURNVALUE (CLASSNAME* | INSTANCENAME* | VALUE* | VALUE.OBJECTWITHPATH* | VALUE.OBJECTWITHLOCALPATH* | VALUE.OBJECT* | OBJECTPATH* | QUALIFIER.DECLARATION* | VALUE.ARRAY? | VALUE.REFERENCE? | CLASS* | INSTANCE* | INSTANCEPATH* | VALUE.NAMEDINSTANCE* | VALUE.INSTANCEWITHPATH*)> """ # Note: The self.check_node() below does not enforce any child elements # from the DTD, and the processing further down does not enforce that # VALUE.ARRAY and VALUE.REFERENCE may appear at most once. # Checking that at this level is not reasonable because the better # checks can be done in context of the intrinsic operation receiving # its return value. The DTD is so broad simply because it needs to # cover the possible return values of all intrinsic operations. self.check_node(tup_tree, 'IRETURNVALUE') values = self.list_of_same(tup_tree, ('CLASSNAME', 'INSTANCENAME', 'VALUE', 'VALUE.OBJECTWITHPATH', 'VALUE.OBJECTWITHLOCALPATH', 'VALUE.OBJECT', 'OBJECTPATH', 'QUALIFIER.DECLARATION', 'VALUE.ARRAY', 'VALUE.REFERENCE', 'CLASS', 'INSTANCE', 'INSTANCEPATH', 'VALUE.NAMEDINSTANCE', 'VALUE.INSTANCEWITHPATH')) # Note: The caller needs to unpack the value. return name(tup_tree), attrs(tup_tree), values
[ "def", "parse_ireturnvalue", "(", "self", ",", "tup_tree", ")", ":", "# Note: The self.check_node() below does not enforce any child elements", "# from the DTD, and the processing further down does not enforce that", "# VALUE.ARRAY and VALUE.REFERENCE may appear at most once.", "# Checking tha...
Parse IRETURNVALUE element. Returns name, attributes and values of the tup_tree. :: <!ELEMENT IRETURNVALUE (CLASSNAME* | INSTANCENAME* | VALUE* | VALUE.OBJECTWITHPATH* | VALUE.OBJECTWITHLOCALPATH* | VALUE.OBJECT* | OBJECTPATH* | QUALIFIER.DECLARATION* | VALUE.ARRAY? | VALUE.REFERENCE? | CLASS* | INSTANCE* | INSTANCEPATH* | VALUE.NAMEDINSTANCE* | VALUE.INSTANCEWITHPATH*)>
[ "Parse", "IRETURNVALUE", "element", ".", "Returns", "name", "attributes", "and", "values", "of", "the", "tup_tree", "." ]
e54ecb82c2211e289a268567443d60fdd489f1e4
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1916-L1953
train
28,299