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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
F5Networks/f5-common-python | f5/bigip/tm/ltm/policy.py | Policy._update | def _update(self, **kwargs):
'''Update only draft or legacy policies
Published policies cannot be updated
:raises: OperationNotSupportedOnPublishedPolicy
'''
legacy = kwargs.pop('legacy', False)
tmos_ver = self._meta_data['bigip']._meta_data['tmos_version']
self._filter_version_specific_options(tmos_ver, **kwargs)
if 'Drafts' not in self._meta_data['uri'] and \
LooseVersion(tmos_ver) >= LooseVersion('12.1.0') and \
not legacy:
msg = 'Update operation not allowed on a published policy.'
raise OperationNotSupportedOnPublishedPolicy(msg)
super(Policy, self)._update(**kwargs) | python | def _update(self, **kwargs):
'''Update only draft or legacy policies
Published policies cannot be updated
:raises: OperationNotSupportedOnPublishedPolicy
'''
legacy = kwargs.pop('legacy', False)
tmos_ver = self._meta_data['bigip']._meta_data['tmos_version']
self._filter_version_specific_options(tmos_ver, **kwargs)
if 'Drafts' not in self._meta_data['uri'] and \
LooseVersion(tmos_ver) >= LooseVersion('12.1.0') and \
not legacy:
msg = 'Update operation not allowed on a published policy.'
raise OperationNotSupportedOnPublishedPolicy(msg)
super(Policy, self)._update(**kwargs) | [
"def",
"_update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"legacy",
"=",
"kwargs",
".",
"pop",
"(",
"'legacy'",
",",
"False",
")",
"tmos_ver",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"self",
".",
"_filter_version_specific_options",
"(",
"tmos_ver",
",",
"*",
"*",
"kwargs",
")",
"if",
"'Drafts'",
"not",
"in",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
"and",
"LooseVersion",
"(",
"tmos_ver",
")",
">=",
"LooseVersion",
"(",
"'12.1.0'",
")",
"and",
"not",
"legacy",
":",
"msg",
"=",
"'Update operation not allowed on a published policy.'",
"raise",
"OperationNotSupportedOnPublishedPolicy",
"(",
"msg",
")",
"super",
"(",
"Policy",
",",
"self",
")",
".",
"_update",
"(",
"*",
"*",
"kwargs",
")"
] | Update only draft or legacy policies
Published policies cannot be updated
:raises: OperationNotSupportedOnPublishedPolicy | [
"Update",
"only",
"draft",
"or",
"legacy",
"policies"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L127-L142 | train | 232,200 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/policy.py | Policy.publish | def publish(self, **kwargs):
'''Publishing a draft policy is only applicable in TMOS 12.1 and up.
This operation updates the meta_data['uri'] of the existing object
and effectively moves a draft into a published state on the device.
The self object is also updated with the response from a GET to the
device.
:raises: PolicyNotDraft
'''
assert 'Drafts' in self._meta_data['uri']
assert self.status.lower() == 'draft'
base_uri = self._meta_data['container']._meta_data['uri']
requests_params = self._handle_requests_params(kwargs)
session = self._meta_data['bigip']._meta_data['icr_session']
if 'command' not in kwargs:
kwargs['command'] = 'publish'
if 'Drafts' not in self.name:
kwargs['name'] = self.fullPath
session.post(base_uri, json=kwargs, **requests_params)
get_kwargs = {
'name': self.name, 'partition': self.partition,
'uri_as_parts': True
}
response = session.get(base_uri, **get_kwargs)
json_data = response.json()
self._local_update(json_data)
self._activate_URI(json_data['selfLink']) | python | def publish(self, **kwargs):
'''Publishing a draft policy is only applicable in TMOS 12.1 and up.
This operation updates the meta_data['uri'] of the existing object
and effectively moves a draft into a published state on the device.
The self object is also updated with the response from a GET to the
device.
:raises: PolicyNotDraft
'''
assert 'Drafts' in self._meta_data['uri']
assert self.status.lower() == 'draft'
base_uri = self._meta_data['container']._meta_data['uri']
requests_params = self._handle_requests_params(kwargs)
session = self._meta_data['bigip']._meta_data['icr_session']
if 'command' not in kwargs:
kwargs['command'] = 'publish'
if 'Drafts' not in self.name:
kwargs['name'] = self.fullPath
session.post(base_uri, json=kwargs, **requests_params)
get_kwargs = {
'name': self.name, 'partition': self.partition,
'uri_as_parts': True
}
response = session.get(base_uri, **get_kwargs)
json_data = response.json()
self._local_update(json_data)
self._activate_URI(json_data['selfLink']) | [
"def",
"publish",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"'Drafts'",
"in",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
"assert",
"self",
".",
"status",
".",
"lower",
"(",
")",
"==",
"'draft'",
"base_uri",
"=",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
".",
"_meta_data",
"[",
"'uri'",
"]",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"if",
"'command'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'command'",
"]",
"=",
"'publish'",
"if",
"'Drafts'",
"not",
"in",
"self",
".",
"name",
":",
"kwargs",
"[",
"'name'",
"]",
"=",
"self",
".",
"fullPath",
"session",
".",
"post",
"(",
"base_uri",
",",
"json",
"=",
"kwargs",
",",
"*",
"*",
"requests_params",
")",
"get_kwargs",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'partition'",
":",
"self",
".",
"partition",
",",
"'uri_as_parts'",
":",
"True",
"}",
"response",
"=",
"session",
".",
"get",
"(",
"base_uri",
",",
"*",
"*",
"get_kwargs",
")",
"json_data",
"=",
"response",
".",
"json",
"(",
")",
"self",
".",
"_local_update",
"(",
"json_data",
")",
"self",
".",
"_activate_URI",
"(",
"json_data",
"[",
"'selfLink'",
"]",
")"
] | Publishing a draft policy is only applicable in TMOS 12.1 and up.
This operation updates the meta_data['uri'] of the existing object
and effectively moves a draft into a published state on the device.
The self object is also updated with the response from a GET to the
device.
:raises: PolicyNotDraft | [
"Publishing",
"a",
"draft",
"policy",
"is",
"only",
"applicable",
"in",
"TMOS",
"12",
".",
"1",
"and",
"up",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L144-L172 | train | 232,201 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/policy.py | Policy.draft | def draft(self, **kwargs):
'''Allows for easily re-drafting a policy
After a policy has been created, it was not previously possible
to re-draft the published policy. This method makes it possible
for a user with existing, published, policies to create drafts
from them so that they are modifiable.
See https://github.com/F5Networks/f5-common-python/pull/1099
:param kwargs:
:return:
'''
tmos_ver = self._meta_data['bigip']._meta_data['tmos_version']
legacy = kwargs.pop('legacy', False)
if LooseVersion(tmos_ver) < LooseVersion('12.1.0') or legacy:
raise DraftPolicyNotSupportedInTMOSVersion(
"Drafting on this version of BIG-IP is not supported"
)
kwargs = dict(
createDraft=True
)
super(Policy, self)._modify(**kwargs)
get_kwargs = {
'name': self.name,
'partition': self.partition,
'uri_as_parts': True,
'subPath': 'Drafts'
}
base_uri = self._meta_data['container']._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
response = session.get(base_uri, **get_kwargs)
json_data = response.json()
self._local_update(json_data)
self._activate_URI(json_data['selfLink']) | python | def draft(self, **kwargs):
'''Allows for easily re-drafting a policy
After a policy has been created, it was not previously possible
to re-draft the published policy. This method makes it possible
for a user with existing, published, policies to create drafts
from them so that they are modifiable.
See https://github.com/F5Networks/f5-common-python/pull/1099
:param kwargs:
:return:
'''
tmos_ver = self._meta_data['bigip']._meta_data['tmos_version']
legacy = kwargs.pop('legacy', False)
if LooseVersion(tmos_ver) < LooseVersion('12.1.0') or legacy:
raise DraftPolicyNotSupportedInTMOSVersion(
"Drafting on this version of BIG-IP is not supported"
)
kwargs = dict(
createDraft=True
)
super(Policy, self)._modify(**kwargs)
get_kwargs = {
'name': self.name,
'partition': self.partition,
'uri_as_parts': True,
'subPath': 'Drafts'
}
base_uri = self._meta_data['container']._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
response = session.get(base_uri, **get_kwargs)
json_data = response.json()
self._local_update(json_data)
self._activate_URI(json_data['selfLink']) | [
"def",
"draft",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tmos_ver",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"legacy",
"=",
"kwargs",
".",
"pop",
"(",
"'legacy'",
",",
"False",
")",
"if",
"LooseVersion",
"(",
"tmos_ver",
")",
"<",
"LooseVersion",
"(",
"'12.1.0'",
")",
"or",
"legacy",
":",
"raise",
"DraftPolicyNotSupportedInTMOSVersion",
"(",
"\"Drafting on this version of BIG-IP is not supported\"",
")",
"kwargs",
"=",
"dict",
"(",
"createDraft",
"=",
"True",
")",
"super",
"(",
"Policy",
",",
"self",
")",
".",
"_modify",
"(",
"*",
"*",
"kwargs",
")",
"get_kwargs",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'partition'",
":",
"self",
".",
"partition",
",",
"'uri_as_parts'",
":",
"True",
",",
"'subPath'",
":",
"'Drafts'",
"}",
"base_uri",
"=",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
".",
"_meta_data",
"[",
"'uri'",
"]",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"response",
"=",
"session",
".",
"get",
"(",
"base_uri",
",",
"*",
"*",
"get_kwargs",
")",
"json_data",
"=",
"response",
".",
"json",
"(",
")",
"self",
".",
"_local_update",
"(",
"json_data",
")",
"self",
".",
"_activate_URI",
"(",
"json_data",
"[",
"'selfLink'",
"]",
")"
] | Allows for easily re-drafting a policy
After a policy has been created, it was not previously possible
to re-draft the published policy. This method makes it possible
for a user with existing, published, policies to create drafts
from them so that they are modifiable.
See https://github.com/F5Networks/f5-common-python/pull/1099
:param kwargs:
:return: | [
"Allows",
"for",
"easily",
"re",
"-",
"drafting",
"a",
"policy"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L174-L208 | train | 232,202 |
F5Networks/f5-common-python | f5/bigiq/cm/shared/licensing/pools.py | Member.delete | def delete(self, **kwargs):
"""Deletes a member from an unmanaged license pool
You need to be careful with this method. When you use it, and it
succeeds on the remote BIG-IP, the configuration of the BIG-IP
will be reloaded. During this process, you will not be able to
access the REST interface.
This method overrides the Resource class's method because it requires
that extra json kwargs be supplied. This is not a behavior that is
part of the normal Resource class's delete method.
:param kwargs:
:return:
"""
if 'uuid' not in kwargs:
kwargs['uuid'] = str(self.uuid)
requests_params = self._handle_requests_params(kwargs)
kwargs = self._check_for_python_keywords(kwargs)
kwargs = self._prepare_request_json(kwargs)
delete_uri = self._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
# Check the generation for match before delete
force = self._check_force_arg(kwargs.pop('force', True))
if not force:
self._check_generation()
response = session.delete(delete_uri, json=kwargs, **requests_params)
if response.status_code == 200:
self.__dict__ = {'deleted': True} | python | def delete(self, **kwargs):
"""Deletes a member from an unmanaged license pool
You need to be careful with this method. When you use it, and it
succeeds on the remote BIG-IP, the configuration of the BIG-IP
will be reloaded. During this process, you will not be able to
access the REST interface.
This method overrides the Resource class's method because it requires
that extra json kwargs be supplied. This is not a behavior that is
part of the normal Resource class's delete method.
:param kwargs:
:return:
"""
if 'uuid' not in kwargs:
kwargs['uuid'] = str(self.uuid)
requests_params = self._handle_requests_params(kwargs)
kwargs = self._check_for_python_keywords(kwargs)
kwargs = self._prepare_request_json(kwargs)
delete_uri = self._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
# Check the generation for match before delete
force = self._check_force_arg(kwargs.pop('force', True))
if not force:
self._check_generation()
response = session.delete(delete_uri, json=kwargs, **requests_params)
if response.status_code == 200:
self.__dict__ = {'deleted': True} | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'uuid'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'uuid'",
"]",
"=",
"str",
"(",
"self",
".",
"uuid",
")",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"kwargs",
"=",
"self",
".",
"_check_for_python_keywords",
"(",
"kwargs",
")",
"kwargs",
"=",
"self",
".",
"_prepare_request_json",
"(",
"kwargs",
")",
"delete_uri",
"=",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"# Check the generation for match before delete",
"force",
"=",
"self",
".",
"_check_force_arg",
"(",
"kwargs",
".",
"pop",
"(",
"'force'",
",",
"True",
")",
")",
"if",
"not",
"force",
":",
"self",
".",
"_check_generation",
"(",
")",
"response",
"=",
"session",
".",
"delete",
"(",
"delete_uri",
",",
"json",
"=",
"kwargs",
",",
"*",
"*",
"requests_params",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"self",
".",
"__dict__",
"=",
"{",
"'deleted'",
":",
"True",
"}"
] | Deletes a member from an unmanaged license pool
You need to be careful with this method. When you use it, and it
succeeds on the remote BIG-IP, the configuration of the BIG-IP
will be reloaded. During this process, you will not be able to
access the REST interface.
This method overrides the Resource class's method because it requires
that extra json kwargs be supplied. This is not a behavior that is
part of the normal Resource class's delete method.
:param kwargs:
:return: | [
"Deletes",
"a",
"member",
"from",
"an",
"unmanaged",
"license",
"pool"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigiq/cm/shared/licensing/pools.py#L101-L133 | train | 232,203 |
F5Networks/f5-common-python | f5/bigip/tm/sys/failover.py | Failover.exec_cmd | def exec_cmd(self, command, **kwargs):
"""Defining custom method to append 'exclusive_attributes'.
WARNING: Some parameters are hyphenated therefore the function
will need to utilize variable keyword argument syntax.
This only applies when utilCmdArgs method is not in use.
eg.
param_set ={'standby':True 'traffic-group': 'traffic-group-1'}
bigip.tm.sys.failover.exec_cmd('run', **param_set
The 'standby' attribute cannot be present with either 'offline'
or 'online' attribute, whichever is present. Additionally
we check for existence of same attribute values in
'offline' and 'online' if both present.
note:: There is also another way of using failover endpoint,
by the means of 'utilCmdArgs' attribute, here the syntax
will resemble more that of the 'tmsh run sys failover...'
command.
eg. exec_cmd('run', utilCmdArgs='standby traffic-group
traffic-group-1')
:: raises InvalidParameterValue
"""
kwargs = self._reduce_boolean_pair(kwargs, 'online', 'offline')
if 'offline' in kwargs:
self._meta_data['exclusive_attributes'].append(
('offline', 'standby'))
if 'online' in kwargs:
self._meta_data['exclusive_attributes'].append(
('online', 'standby'))
self._is_allowed_command(command)
self._check_command_parameters(**kwargs)
return self._exec_cmd(command, **kwargs) | python | def exec_cmd(self, command, **kwargs):
"""Defining custom method to append 'exclusive_attributes'.
WARNING: Some parameters are hyphenated therefore the function
will need to utilize variable keyword argument syntax.
This only applies when utilCmdArgs method is not in use.
eg.
param_set ={'standby':True 'traffic-group': 'traffic-group-1'}
bigip.tm.sys.failover.exec_cmd('run', **param_set
The 'standby' attribute cannot be present with either 'offline'
or 'online' attribute, whichever is present. Additionally
we check for existence of same attribute values in
'offline' and 'online' if both present.
note:: There is also another way of using failover endpoint,
by the means of 'utilCmdArgs' attribute, here the syntax
will resemble more that of the 'tmsh run sys failover...'
command.
eg. exec_cmd('run', utilCmdArgs='standby traffic-group
traffic-group-1')
:: raises InvalidParameterValue
"""
kwargs = self._reduce_boolean_pair(kwargs, 'online', 'offline')
if 'offline' in kwargs:
self._meta_data['exclusive_attributes'].append(
('offline', 'standby'))
if 'online' in kwargs:
self._meta_data['exclusive_attributes'].append(
('online', 'standby'))
self._is_allowed_command(command)
self._check_command_parameters(**kwargs)
return self._exec_cmd(command, **kwargs) | [
"def",
"exec_cmd",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_reduce_boolean_pair",
"(",
"kwargs",
",",
"'online'",
",",
"'offline'",
")",
"if",
"'offline'",
"in",
"kwargs",
":",
"self",
".",
"_meta_data",
"[",
"'exclusive_attributes'",
"]",
".",
"append",
"(",
"(",
"'offline'",
",",
"'standby'",
")",
")",
"if",
"'online'",
"in",
"kwargs",
":",
"self",
".",
"_meta_data",
"[",
"'exclusive_attributes'",
"]",
".",
"append",
"(",
"(",
"'online'",
",",
"'standby'",
")",
")",
"self",
".",
"_is_allowed_command",
"(",
"command",
")",
"self",
".",
"_check_command_parameters",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_exec_cmd",
"(",
"command",
",",
"*",
"*",
"kwargs",
")"
] | Defining custom method to append 'exclusive_attributes'.
WARNING: Some parameters are hyphenated therefore the function
will need to utilize variable keyword argument syntax.
This only applies when utilCmdArgs method is not in use.
eg.
param_set ={'standby':True 'traffic-group': 'traffic-group-1'}
bigip.tm.sys.failover.exec_cmd('run', **param_set
The 'standby' attribute cannot be present with either 'offline'
or 'online' attribute, whichever is present. Additionally
we check for existence of same attribute values in
'offline' and 'online' if both present.
note:: There is also another way of using failover endpoint,
by the means of 'utilCmdArgs' attribute, here the syntax
will resemble more that of the 'tmsh run sys failover...'
command.
eg. exec_cmd('run', utilCmdArgs='standby traffic-group
traffic-group-1')
:: raises InvalidParameterValue | [
"Defining",
"custom",
"method",
"to",
"append",
"exclusive_attributes",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/failover.py#L65-L103 | train | 232,204 |
F5Networks/f5-common-python | f5/bigip/tm/sys/failover.py | Failover.toggle_standby | def toggle_standby(self, **kwargs):
"""Toggle the standby status of a traffic group.
WARNING: This method which used POST obtains json keys from the device
that are not available in the response to a GET against the same URI.
NOTE: This method method is deprecated and probably will be removed,
usage of exec_cmd is encouraged.
"""
trafficgroup = kwargs.pop('trafficgroup')
state = kwargs.pop('state')
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
arguments = {'standby': state, 'traffic-group': trafficgroup}
return self.exec_cmd('run', **arguments) | python | def toggle_standby(self, **kwargs):
"""Toggle the standby status of a traffic group.
WARNING: This method which used POST obtains json keys from the device
that are not available in the response to a GET against the same URI.
NOTE: This method method is deprecated and probably will be removed,
usage of exec_cmd is encouraged.
"""
trafficgroup = kwargs.pop('trafficgroup')
state = kwargs.pop('state')
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
arguments = {'standby': state, 'traffic-group': trafficgroup}
return self.exec_cmd('run', **arguments) | [
"def",
"toggle_standby",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"trafficgroup",
"=",
"kwargs",
".",
"pop",
"(",
"'trafficgroup'",
")",
"state",
"=",
"kwargs",
".",
"pop",
"(",
"'state'",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'Unexpected **kwargs: %r'",
"%",
"kwargs",
")",
"arguments",
"=",
"{",
"'standby'",
":",
"state",
",",
"'traffic-group'",
":",
"trafficgroup",
"}",
"return",
"self",
".",
"exec_cmd",
"(",
"'run'",
",",
"*",
"*",
"arguments",
")"
] | Toggle the standby status of a traffic group.
WARNING: This method which used POST obtains json keys from the device
that are not available in the response to a GET against the same URI.
NOTE: This method method is deprecated and probably will be removed,
usage of exec_cmd is encouraged. | [
"Toggle",
"the",
"standby",
"status",
"of",
"a",
"traffic",
"group",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/failover.py#L105-L120 | train | 232,205 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/profile.py | Ocsp_Stapling_Params.update | def update(self, **kwargs):
"""When setting useProxyServer to enable we need to supply
proxyServerPool value as well
"""
if 'useProxyServer' in kwargs and kwargs['useProxyServer'] == 'enabled':
if 'proxyServerPool' not in kwargs:
error = 'Missing proxyServerPool parameter value.'
raise MissingUpdateParameter(error)
if hasattr(self, 'useProxyServer'):
if getattr(self, 'useProxyServer') == 'enabled' and 'proxyServerPool' not in self.__dict__:
error = 'Missing proxyServerPool parameter value.'
raise MissingUpdateParameter(error)
self._update(**kwargs)
return self | python | def update(self, **kwargs):
"""When setting useProxyServer to enable we need to supply
proxyServerPool value as well
"""
if 'useProxyServer' in kwargs and kwargs['useProxyServer'] == 'enabled':
if 'proxyServerPool' not in kwargs:
error = 'Missing proxyServerPool parameter value.'
raise MissingUpdateParameter(error)
if hasattr(self, 'useProxyServer'):
if getattr(self, 'useProxyServer') == 'enabled' and 'proxyServerPool' not in self.__dict__:
error = 'Missing proxyServerPool parameter value.'
raise MissingUpdateParameter(error)
self._update(**kwargs)
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'useProxyServer'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'useProxyServer'",
"]",
"==",
"'enabled'",
":",
"if",
"'proxyServerPool'",
"not",
"in",
"kwargs",
":",
"error",
"=",
"'Missing proxyServerPool parameter value.'",
"raise",
"MissingUpdateParameter",
"(",
"error",
")",
"if",
"hasattr",
"(",
"self",
",",
"'useProxyServer'",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'useProxyServer'",
")",
"==",
"'enabled'",
"and",
"'proxyServerPool'",
"not",
"in",
"self",
".",
"__dict__",
":",
"error",
"=",
"'Missing proxyServerPool parameter value.'",
"raise",
"MissingUpdateParameter",
"(",
"error",
")",
"self",
".",
"_update",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | When setting useProxyServer to enable we need to supply
proxyServerPool value as well | [
"When",
"setting",
"useProxyServer",
"to",
"enable",
"we",
"need",
"to",
"supply"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/profile.py#L678-L694 | train | 232,206 |
F5Networks/f5-common-python | f5/bigip/tm/net/vlan.py | Interfaces._check_tagmode_and_tmos_version | def _check_tagmode_and_tmos_version(self, **kwargs):
'''Raise an exception if tagMode in kwargs and tmos version < 11.6.0
:param kwargs: dict -- keyword arguments for request
:raises: TagModeDisallowedForTMOSVersion
'''
tmos_version = self._meta_data['bigip']._meta_data['tmos_version']
if LooseVersion(tmos_version) < LooseVersion('11.6.0'):
msg = "The parameter, 'tagMode', is not allowed against the " \
"following version of TMOS: %s" % (tmos_version)
if 'tagMode' in kwargs or hasattr(self, 'tagMode'):
raise TagModeDisallowedForTMOSVersion(msg) | python | def _check_tagmode_and_tmos_version(self, **kwargs):
'''Raise an exception if tagMode in kwargs and tmos version < 11.6.0
:param kwargs: dict -- keyword arguments for request
:raises: TagModeDisallowedForTMOSVersion
'''
tmos_version = self._meta_data['bigip']._meta_data['tmos_version']
if LooseVersion(tmos_version) < LooseVersion('11.6.0'):
msg = "The parameter, 'tagMode', is not allowed against the " \
"following version of TMOS: %s" % (tmos_version)
if 'tagMode' in kwargs or hasattr(self, 'tagMode'):
raise TagModeDisallowedForTMOSVersion(msg) | [
"def",
"_check_tagmode_and_tmos_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tmos_version",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"if",
"LooseVersion",
"(",
"tmos_version",
")",
"<",
"LooseVersion",
"(",
"'11.6.0'",
")",
":",
"msg",
"=",
"\"The parameter, 'tagMode', is not allowed against the \"",
"\"following version of TMOS: %s\"",
"%",
"(",
"tmos_version",
")",
"if",
"'tagMode'",
"in",
"kwargs",
"or",
"hasattr",
"(",
"self",
",",
"'tagMode'",
")",
":",
"raise",
"TagModeDisallowedForTMOSVersion",
"(",
"msg",
")"
] | Raise an exception if tagMode in kwargs and tmos version < 11.6.0
:param kwargs: dict -- keyword arguments for request
:raises: TagModeDisallowedForTMOSVersion | [
"Raise",
"an",
"exception",
"if",
"tagMode",
"in",
"kwargs",
"and",
"tmos",
"version",
"<",
"11",
".",
"6",
".",
"0"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/net/vlan.py#L97-L109 | train | 232,207 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/virtual.py | Policies.load | def load(self, **kwargs):
"""Override load to retrieve object based on exists above."""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if self._check_existence_by_collection(
self._meta_data['container'], kwargs['name']):
if LooseVersion(tmos_v) == LooseVersion('11.5.4'):
return self._load_11_5_4(**kwargs)
else:
return self._load(**kwargs)
msg = 'The Policy named, {}, does not exist on the device.'.format(
kwargs['name'])
raise NonExtantVirtualPolicy(msg) | python | def load(self, **kwargs):
"""Override load to retrieve object based on exists above."""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if self._check_existence_by_collection(
self._meta_data['container'], kwargs['name']):
if LooseVersion(tmos_v) == LooseVersion('11.5.4'):
return self._load_11_5_4(**kwargs)
else:
return self._load(**kwargs)
msg = 'The Policy named, {}, does not exist on the device.'.format(
kwargs['name'])
raise NonExtantVirtualPolicy(msg) | [
"def",
"load",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tmos_v",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"if",
"self",
".",
"_check_existence_by_collection",
"(",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
",",
"kwargs",
"[",
"'name'",
"]",
")",
":",
"if",
"LooseVersion",
"(",
"tmos_v",
")",
"==",
"LooseVersion",
"(",
"'11.5.4'",
")",
":",
"return",
"self",
".",
"_load_11_5_4",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"self",
".",
"_load",
"(",
"*",
"*",
"kwargs",
")",
"msg",
"=",
"'The Policy named, {}, does not exist on the device.'",
".",
"format",
"(",
"kwargs",
"[",
"'name'",
"]",
")",
"raise",
"NonExtantVirtualPolicy",
"(",
"msg",
")"
] | Override load to retrieve object based on exists above. | [
"Override",
"load",
"to",
"retrieve",
"object",
"based",
"on",
"exists",
"above",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/virtual.py#L127-L138 | train | 232,208 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/virtual.py | Policies._load_11_5_4 | def _load_11_5_4(self, **kwargs):
"""Custom _load method to accommodate for issue in 11.5.4,
where an existing object would return 404 HTTP response.
"""
if 'uri' in self._meta_data:
error = "There was an attempt to assign a new uri to this " \
"resource, the _meta_data['uri'] is %s and it should" \
" not be changed." % (self._meta_data['uri'])
raise URICreationCollision(error)
requests_params = self._handle_requests_params(kwargs)
self._check_load_parameters(**kwargs)
kwargs['uri_as_parts'] = True
refresh_session = self._meta_data['bigip']._meta_data[
'icr_session']
base_uri = self._meta_data['container']._meta_data['uri']
kwargs.update(requests_params)
for key1, key2 in self._meta_data['reduction_forcing_pairs']:
kwargs = self._reduce_boolean_pair(kwargs, key1, key2)
kwargs = self._check_for_python_keywords(kwargs)
try:
response = refresh_session.get(base_uri, **kwargs)
except HTTPError as err:
if err.response.status_code != 404:
raise
if err.response.status_code == 404:
return self._return_object(self._meta_data['container'],
kwargs['name'])
# Make new instance of self
return self._produce_instance(response) | python | def _load_11_5_4(self, **kwargs):
"""Custom _load method to accommodate for issue in 11.5.4,
where an existing object would return 404 HTTP response.
"""
if 'uri' in self._meta_data:
error = "There was an attempt to assign a new uri to this " \
"resource, the _meta_data['uri'] is %s and it should" \
" not be changed." % (self._meta_data['uri'])
raise URICreationCollision(error)
requests_params = self._handle_requests_params(kwargs)
self._check_load_parameters(**kwargs)
kwargs['uri_as_parts'] = True
refresh_session = self._meta_data['bigip']._meta_data[
'icr_session']
base_uri = self._meta_data['container']._meta_data['uri']
kwargs.update(requests_params)
for key1, key2 in self._meta_data['reduction_forcing_pairs']:
kwargs = self._reduce_boolean_pair(kwargs, key1, key2)
kwargs = self._check_for_python_keywords(kwargs)
try:
response = refresh_session.get(base_uri, **kwargs)
except HTTPError as err:
if err.response.status_code != 404:
raise
if err.response.status_code == 404:
return self._return_object(self._meta_data['container'],
kwargs['name'])
# Make new instance of self
return self._produce_instance(response) | [
"def",
"_load_11_5_4",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'uri'",
"in",
"self",
".",
"_meta_data",
":",
"error",
"=",
"\"There was an attempt to assign a new uri to this \"",
"\"resource, the _meta_data['uri'] is %s and it should\"",
"\" not be changed.\"",
"%",
"(",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
")",
"raise",
"URICreationCollision",
"(",
"error",
")",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"self",
".",
"_check_load_parameters",
"(",
"*",
"*",
"kwargs",
")",
"kwargs",
"[",
"'uri_as_parts'",
"]",
"=",
"True",
"refresh_session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"base_uri",
"=",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
".",
"_meta_data",
"[",
"'uri'",
"]",
"kwargs",
".",
"update",
"(",
"requests_params",
")",
"for",
"key1",
",",
"key2",
"in",
"self",
".",
"_meta_data",
"[",
"'reduction_forcing_pairs'",
"]",
":",
"kwargs",
"=",
"self",
".",
"_reduce_boolean_pair",
"(",
"kwargs",
",",
"key1",
",",
"key2",
")",
"kwargs",
"=",
"self",
".",
"_check_for_python_keywords",
"(",
"kwargs",
")",
"try",
":",
"response",
"=",
"refresh_session",
".",
"get",
"(",
"base_uri",
",",
"*",
"*",
"kwargs",
")",
"except",
"HTTPError",
"as",
"err",
":",
"if",
"err",
".",
"response",
".",
"status_code",
"!=",
"404",
":",
"raise",
"if",
"err",
".",
"response",
".",
"status_code",
"==",
"404",
":",
"return",
"self",
".",
"_return_object",
"(",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
",",
"kwargs",
"[",
"'name'",
"]",
")",
"# Make new instance of self",
"return",
"self",
".",
"_produce_instance",
"(",
"response",
")"
] | Custom _load method to accommodate for issue in 11.5.4,
where an existing object would return 404 HTTP response. | [
"Custom",
"_load",
"method",
"to",
"accommodate",
"for",
"issue",
"in",
"11",
".",
"5",
".",
"4"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/virtual.py#L140-L169 | train | 232,209 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/virtual.py | Policies.create | def create(self, **kwargs):
"""Custom _create method to accommodate for issue 11.5.4 and 12.1.1,
Where creation of an object would return 404, despite the object
being created.
"""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if LooseVersion(tmos_v) == LooseVersion('11.5.4') or LooseVersion(
tmos_v) == LooseVersion('12.1.1'):
if 'uri' in self._meta_data:
error = "There was an attempt to assign a new uri to this " \
"resource, the _meta_data['uri'] is %s and it should" \
" not be changed." % (self._meta_data['uri'])
raise URICreationCollision(error)
self._check_exclusive_parameters(**kwargs)
requests_params = self._handle_requests_params(kwargs)
self._check_create_parameters(**kwargs)
# Reduce boolean pairs as specified by the meta_data entry below
for key1, key2 in self._meta_data['reduction_forcing_pairs']:
kwargs = self._reduce_boolean_pair(kwargs, key1, key2)
# Make convenience variable with short names for this method.
_create_uri = self._meta_data['container']._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
# We using try/except just in case some HF will fix
# this in 11.5.4
try:
response = session.post(
_create_uri, json=kwargs, **requests_params)
except HTTPError as err:
if err.response.status_code != 404:
raise
if err.response.status_code == 404:
return self._return_object(self._meta_data['container'],
kwargs['name'])
# Make new instance of self
return self._produce_instance(response)
else:
return self._create(**kwargs) | python | def create(self, **kwargs):
"""Custom _create method to accommodate for issue 11.5.4 and 12.1.1,
Where creation of an object would return 404, despite the object
being created.
"""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if LooseVersion(tmos_v) == LooseVersion('11.5.4') or LooseVersion(
tmos_v) == LooseVersion('12.1.1'):
if 'uri' in self._meta_data:
error = "There was an attempt to assign a new uri to this " \
"resource, the _meta_data['uri'] is %s and it should" \
" not be changed." % (self._meta_data['uri'])
raise URICreationCollision(error)
self._check_exclusive_parameters(**kwargs)
requests_params = self._handle_requests_params(kwargs)
self._check_create_parameters(**kwargs)
# Reduce boolean pairs as specified by the meta_data entry below
for key1, key2 in self._meta_data['reduction_forcing_pairs']:
kwargs = self._reduce_boolean_pair(kwargs, key1, key2)
# Make convenience variable with short names for this method.
_create_uri = self._meta_data['container']._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
# We using try/except just in case some HF will fix
# this in 11.5.4
try:
response = session.post(
_create_uri, json=kwargs, **requests_params)
except HTTPError as err:
if err.response.status_code != 404:
raise
if err.response.status_code == 404:
return self._return_object(self._meta_data['container'],
kwargs['name'])
# Make new instance of self
return self._produce_instance(response)
else:
return self._create(**kwargs) | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tmos_v",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"if",
"LooseVersion",
"(",
"tmos_v",
")",
"==",
"LooseVersion",
"(",
"'11.5.4'",
")",
"or",
"LooseVersion",
"(",
"tmos_v",
")",
"==",
"LooseVersion",
"(",
"'12.1.1'",
")",
":",
"if",
"'uri'",
"in",
"self",
".",
"_meta_data",
":",
"error",
"=",
"\"There was an attempt to assign a new uri to this \"",
"\"resource, the _meta_data['uri'] is %s and it should\"",
"\" not be changed.\"",
"%",
"(",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
")",
"raise",
"URICreationCollision",
"(",
"error",
")",
"self",
".",
"_check_exclusive_parameters",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"self",
".",
"_check_create_parameters",
"(",
"*",
"*",
"kwargs",
")",
"# Reduce boolean pairs as specified by the meta_data entry below",
"for",
"key1",
",",
"key2",
"in",
"self",
".",
"_meta_data",
"[",
"'reduction_forcing_pairs'",
"]",
":",
"kwargs",
"=",
"self",
".",
"_reduce_boolean_pair",
"(",
"kwargs",
",",
"key1",
",",
"key2",
")",
"# Make convenience variable with short names for this method.",
"_create_uri",
"=",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
".",
"_meta_data",
"[",
"'uri'",
"]",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"# We using try/except just in case some HF will fix",
"# this in 11.5.4",
"try",
":",
"response",
"=",
"session",
".",
"post",
"(",
"_create_uri",
",",
"json",
"=",
"kwargs",
",",
"*",
"*",
"requests_params",
")",
"except",
"HTTPError",
"as",
"err",
":",
"if",
"err",
".",
"response",
".",
"status_code",
"!=",
"404",
":",
"raise",
"if",
"err",
".",
"response",
".",
"status_code",
"==",
"404",
":",
"return",
"self",
".",
"_return_object",
"(",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
",",
"kwargs",
"[",
"'name'",
"]",
")",
"# Make new instance of self",
"return",
"self",
".",
"_produce_instance",
"(",
"response",
")",
"else",
":",
"return",
"self",
".",
"_create",
"(",
"*",
"*",
"kwargs",
")"
] | Custom _create method to accommodate for issue 11.5.4 and 12.1.1,
Where creation of an object would return 404, despite the object
being created. | [
"Custom",
"_create",
"method",
"to",
"accommodate",
"for",
"issue",
"11",
".",
"5",
".",
"4",
"and",
"12",
".",
"1",
".",
"1"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/virtual.py#L171-L212 | train | 232,210 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/virtual.py | Policies_s.get_collection | def get_collection(self, **kwargs):
"""We need special get collection method to address issue in 11.5.4
In 11.5.4 collection 'items' were nested under 'policiesReference'
key. This has caused get_collection() calls to return empty list.
This fix will update the list if the policiesReference key is found
and 'items' key do not exists in __dict__.
:raises: UnregisteredKind
:returns: list of reference dicts and Python ``Resource`` objects
"""
list_of_contents = []
self.refresh(**kwargs)
if 'items' in self.__dict__:
for item in self.items:
# It's possible to have non-"kind" JSON returned. We just
# append the corresponding dict. PostProcessing is the caller's
# responsibility.
if 'kind' not in item:
list_of_contents.append(item)
continue
kind = item['kind']
if kind in self._meta_data['attribute_registry']:
# If it has a kind, it must be registered.
instance =\
self._meta_data['attribute_registry'][kind](self)
instance._local_update(item)
instance._activate_URI(instance.selfLink)
list_of_contents.append(instance)
else:
error_message = '%r is not registered!' % kind
raise UnregisteredKind(error_message)
if 'policiesReference' in self.__dict__ and 'items' not in \
self.__dict__:
for item in self.policiesReference['items']:
kind = item['kind']
if kind in self._meta_data['attribute_registry']:
# If it has a kind, it must be registered.
instance = \
self._meta_data['attribute_registry'][kind](self)
instance._local_update(item)
instance._activate_URI(instance.selfLink)
list_of_contents.append(instance)
else:
error_message = '%r is not registered!' % kind
raise UnregisteredKind(error_message)
return list_of_contents | python | def get_collection(self, **kwargs):
"""We need special get collection method to address issue in 11.5.4
In 11.5.4 collection 'items' were nested under 'policiesReference'
key. This has caused get_collection() calls to return empty list.
This fix will update the list if the policiesReference key is found
and 'items' key do not exists in __dict__.
:raises: UnregisteredKind
:returns: list of reference dicts and Python ``Resource`` objects
"""
list_of_contents = []
self.refresh(**kwargs)
if 'items' in self.__dict__:
for item in self.items:
# It's possible to have non-"kind" JSON returned. We just
# append the corresponding dict. PostProcessing is the caller's
# responsibility.
if 'kind' not in item:
list_of_contents.append(item)
continue
kind = item['kind']
if kind in self._meta_data['attribute_registry']:
# If it has a kind, it must be registered.
instance =\
self._meta_data['attribute_registry'][kind](self)
instance._local_update(item)
instance._activate_URI(instance.selfLink)
list_of_contents.append(instance)
else:
error_message = '%r is not registered!' % kind
raise UnregisteredKind(error_message)
if 'policiesReference' in self.__dict__ and 'items' not in \
self.__dict__:
for item in self.policiesReference['items']:
kind = item['kind']
if kind in self._meta_data['attribute_registry']:
# If it has a kind, it must be registered.
instance = \
self._meta_data['attribute_registry'][kind](self)
instance._local_update(item)
instance._activate_URI(instance.selfLink)
list_of_contents.append(instance)
else:
error_message = '%r is not registered!' % kind
raise UnregisteredKind(error_message)
return list_of_contents | [
"def",
"get_collection",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"list_of_contents",
"=",
"[",
"]",
"self",
".",
"refresh",
"(",
"*",
"*",
"kwargs",
")",
"if",
"'items'",
"in",
"self",
".",
"__dict__",
":",
"for",
"item",
"in",
"self",
".",
"items",
":",
"# It's possible to have non-\"kind\" JSON returned. We just",
"# append the corresponding dict. PostProcessing is the caller's",
"# responsibility.",
"if",
"'kind'",
"not",
"in",
"item",
":",
"list_of_contents",
".",
"append",
"(",
"item",
")",
"continue",
"kind",
"=",
"item",
"[",
"'kind'",
"]",
"if",
"kind",
"in",
"self",
".",
"_meta_data",
"[",
"'attribute_registry'",
"]",
":",
"# If it has a kind, it must be registered.",
"instance",
"=",
"self",
".",
"_meta_data",
"[",
"'attribute_registry'",
"]",
"[",
"kind",
"]",
"(",
"self",
")",
"instance",
".",
"_local_update",
"(",
"item",
")",
"instance",
".",
"_activate_URI",
"(",
"instance",
".",
"selfLink",
")",
"list_of_contents",
".",
"append",
"(",
"instance",
")",
"else",
":",
"error_message",
"=",
"'%r is not registered!'",
"%",
"kind",
"raise",
"UnregisteredKind",
"(",
"error_message",
")",
"if",
"'policiesReference'",
"in",
"self",
".",
"__dict__",
"and",
"'items'",
"not",
"in",
"self",
".",
"__dict__",
":",
"for",
"item",
"in",
"self",
".",
"policiesReference",
"[",
"'items'",
"]",
":",
"kind",
"=",
"item",
"[",
"'kind'",
"]",
"if",
"kind",
"in",
"self",
".",
"_meta_data",
"[",
"'attribute_registry'",
"]",
":",
"# If it has a kind, it must be registered.",
"instance",
"=",
"self",
".",
"_meta_data",
"[",
"'attribute_registry'",
"]",
"[",
"kind",
"]",
"(",
"self",
")",
"instance",
".",
"_local_update",
"(",
"item",
")",
"instance",
".",
"_activate_URI",
"(",
"instance",
".",
"selfLink",
")",
"list_of_contents",
".",
"append",
"(",
"instance",
")",
"else",
":",
"error_message",
"=",
"'%r is not registered!'",
"%",
"kind",
"raise",
"UnregisteredKind",
"(",
"error_message",
")",
"return",
"list_of_contents"
] | We need special get collection method to address issue in 11.5.4
In 11.5.4 collection 'items' were nested under 'policiesReference'
key. This has caused get_collection() calls to return empty list.
This fix will update the list if the policiesReference key is found
and 'items' key do not exists in __dict__.
:raises: UnregisteredKind
:returns: list of reference dicts and Python ``Resource`` objects | [
"We",
"need",
"special",
"get",
"collection",
"method",
"to",
"address",
"issue",
"in",
"11",
".",
"5",
".",
"4"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/virtual.py#L223-L271 | train | 232,211 |
F5Networks/f5-common-python | f5/multi_device/utils.py | get_device_names_to_objects | def get_device_names_to_objects(devices):
'''Map a list of devices to their hostnames.
:param devices: list -- list of ManagementRoot objects
:returns: dict -- mapping of hostnames to ManagementRoot objects
'''
name_to_object = {}
for device in devices:
device_name = get_device_info(device).name
name_to_object[device_name] = device
return name_to_object | python | def get_device_names_to_objects(devices):
'''Map a list of devices to their hostnames.
:param devices: list -- list of ManagementRoot objects
:returns: dict -- mapping of hostnames to ManagementRoot objects
'''
name_to_object = {}
for device in devices:
device_name = get_device_info(device).name
name_to_object[device_name] = device
return name_to_object | [
"def",
"get_device_names_to_objects",
"(",
"devices",
")",
":",
"name_to_object",
"=",
"{",
"}",
"for",
"device",
"in",
"devices",
":",
"device_name",
"=",
"get_device_info",
"(",
"device",
")",
".",
"name",
"name_to_object",
"[",
"device_name",
"]",
"=",
"device",
"return",
"name_to_object"
] | Map a list of devices to their hostnames.
:param devices: list -- list of ManagementRoot objects
:returns: dict -- mapping of hostnames to ManagementRoot objects | [
"Map",
"a",
"list",
"of",
"devices",
"to",
"their",
"hostnames",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/utils.py#L42-L53 | train | 232,212 |
F5Networks/f5-common-python | f5/bigip/tm/asm/policies/parameters.py | UrlParametersResource.create | def create(self, **kwargs):
"""Custom create method for v12.x and above.
Change of behavior in v12 where the returned selfLink is different
from target resource, requires us to append URI after object is
created. So any modify() calls will not lead to json kind
inconsistency when changing the resource attribute.
See issue #844
"""
if LooseVersion(self.tmos_v) < LooseVersion('12.0.0'):
return self._create(**kwargs)
else:
new_instance = self._create(**kwargs)
tmp_name = str(new_instance.id)
tmp_path = new_instance._meta_data['container']._meta_data['uri']
finalurl = tmp_path + tmp_name
new_instance._meta_data['uri'] = finalurl
return new_instance | python | def create(self, **kwargs):
"""Custom create method for v12.x and above.
Change of behavior in v12 where the returned selfLink is different
from target resource, requires us to append URI after object is
created. So any modify() calls will not lead to json kind
inconsistency when changing the resource attribute.
See issue #844
"""
if LooseVersion(self.tmos_v) < LooseVersion('12.0.0'):
return self._create(**kwargs)
else:
new_instance = self._create(**kwargs)
tmp_name = str(new_instance.id)
tmp_path = new_instance._meta_data['container']._meta_data['uri']
finalurl = tmp_path + tmp_name
new_instance._meta_data['uri'] = finalurl
return new_instance | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"LooseVersion",
"(",
"self",
".",
"tmos_v",
")",
"<",
"LooseVersion",
"(",
"'12.0.0'",
")",
":",
"return",
"self",
".",
"_create",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"new_instance",
"=",
"self",
".",
"_create",
"(",
"*",
"*",
"kwargs",
")",
"tmp_name",
"=",
"str",
"(",
"new_instance",
".",
"id",
")",
"tmp_path",
"=",
"new_instance",
".",
"_meta_data",
"[",
"'container'",
"]",
".",
"_meta_data",
"[",
"'uri'",
"]",
"finalurl",
"=",
"tmp_path",
"+",
"tmp_name",
"new_instance",
".",
"_meta_data",
"[",
"'uri'",
"]",
"=",
"finalurl",
"return",
"new_instance"
] | Custom create method for v12.x and above.
Change of behavior in v12 where the returned selfLink is different
from target resource, requires us to append URI after object is
created. So any modify() calls will not lead to json kind
inconsistency when changing the resource attribute.
See issue #844 | [
"Custom",
"create",
"method",
"for",
"v12",
".",
"x",
"and",
"above",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/asm/policies/parameters.py#L88-L107 | train | 232,213 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/pool.py | Pool._format_monitor_parameter | def _format_monitor_parameter(param):
"""This is a workaround for a known issue ID645289, which affects
all versions of TMOS at this time.
"""
if '{' in param and '}':
tmp = param.strip('}').split('{')
monitor = ''.join(tmp).rstrip()
return monitor
else:
return param | python | def _format_monitor_parameter(param):
"""This is a workaround for a known issue ID645289, which affects
all versions of TMOS at this time.
"""
if '{' in param and '}':
tmp = param.strip('}').split('{')
monitor = ''.join(tmp).rstrip()
return monitor
else:
return param | [
"def",
"_format_monitor_parameter",
"(",
"param",
")",
":",
"if",
"'{'",
"in",
"param",
"and",
"'}'",
":",
"tmp",
"=",
"param",
".",
"strip",
"(",
"'}'",
")",
".",
"split",
"(",
"'{'",
")",
"monitor",
"=",
"''",
".",
"join",
"(",
"tmp",
")",
".",
"rstrip",
"(",
")",
"return",
"monitor",
"else",
":",
"return",
"param"
] | This is a workaround for a known issue ID645289, which affects
all versions of TMOS at this time. | [
"This",
"is",
"a",
"workaround",
"for",
"a",
"known",
"issue",
"ID645289",
"which",
"affects"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/pool.py#L57-L67 | train | 232,214 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/pool.py | Pool.create | def create(self, **kwargs):
"""Custom create method to implement monitor parameter formatting."""
if 'monitor' in kwargs:
value = self._format_monitor_parameter(kwargs['monitor'])
kwargs['monitor'] = value
return super(Pool, self)._create(**kwargs) | python | def create(self, **kwargs):
"""Custom create method to implement monitor parameter formatting."""
if 'monitor' in kwargs:
value = self._format_monitor_parameter(kwargs['monitor'])
kwargs['monitor'] = value
return super(Pool, self)._create(**kwargs) | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'monitor'",
"in",
"kwargs",
":",
"value",
"=",
"self",
".",
"_format_monitor_parameter",
"(",
"kwargs",
"[",
"'monitor'",
"]",
")",
"kwargs",
"[",
"'monitor'",
"]",
"=",
"value",
"return",
"super",
"(",
"Pool",
",",
"self",
")",
".",
"_create",
"(",
"*",
"*",
"kwargs",
")"
] | Custom create method to implement monitor parameter formatting. | [
"Custom",
"create",
"method",
"to",
"implement",
"monitor",
"parameter",
"formatting",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/pool.py#L69-L74 | train | 232,215 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/pool.py | Pool.update | def update(self, **kwargs):
"""Custom update method to implement monitor parameter formatting."""
if 'monitor' in kwargs:
value = self._format_monitor_parameter(kwargs['monitor'])
kwargs['monitor'] = value
elif 'monitor' in self.__dict__:
value = self._format_monitor_parameter(self.__dict__['monitor'])
self.__dict__['monitor'] = value
return super(Pool, self)._update(**kwargs) | python | def update(self, **kwargs):
"""Custom update method to implement monitor parameter formatting."""
if 'monitor' in kwargs:
value = self._format_monitor_parameter(kwargs['monitor'])
kwargs['monitor'] = value
elif 'monitor' in self.__dict__:
value = self._format_monitor_parameter(self.__dict__['monitor'])
self.__dict__['monitor'] = value
return super(Pool, self)._update(**kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'monitor'",
"in",
"kwargs",
":",
"value",
"=",
"self",
".",
"_format_monitor_parameter",
"(",
"kwargs",
"[",
"'monitor'",
"]",
")",
"kwargs",
"[",
"'monitor'",
"]",
"=",
"value",
"elif",
"'monitor'",
"in",
"self",
".",
"__dict__",
":",
"value",
"=",
"self",
".",
"_format_monitor_parameter",
"(",
"self",
".",
"__dict__",
"[",
"'monitor'",
"]",
")",
"self",
".",
"__dict__",
"[",
"'monitor'",
"]",
"=",
"value",
"return",
"super",
"(",
"Pool",
",",
"self",
")",
".",
"_update",
"(",
"*",
"*",
"kwargs",
")"
] | Custom update method to implement monitor parameter formatting. | [
"Custom",
"update",
"method",
"to",
"implement",
"monitor",
"parameter",
"formatting",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/pool.py#L76-L84 | train | 232,216 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/pool.py | Pool.modify | def modify(self, **patch):
"""Custom modify method to implement monitor parameter formatting."""
if 'monitor' in patch:
value = self._format_monitor_parameter(patch['monitor'])
patch['monitor'] = value
return super(Pool, self)._modify(**patch) | python | def modify(self, **patch):
"""Custom modify method to implement monitor parameter formatting."""
if 'monitor' in patch:
value = self._format_monitor_parameter(patch['monitor'])
patch['monitor'] = value
return super(Pool, self)._modify(**patch) | [
"def",
"modify",
"(",
"self",
",",
"*",
"*",
"patch",
")",
":",
"if",
"'monitor'",
"in",
"patch",
":",
"value",
"=",
"self",
".",
"_format_monitor_parameter",
"(",
"patch",
"[",
"'monitor'",
"]",
")",
"patch",
"[",
"'monitor'",
"]",
"=",
"value",
"return",
"super",
"(",
"Pool",
",",
"self",
")",
".",
"_modify",
"(",
"*",
"*",
"patch",
")"
] | Custom modify method to implement monitor parameter formatting. | [
"Custom",
"modify",
"method",
"to",
"implement",
"monitor",
"parameter",
"formatting",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/pool.py#L86-L91 | train | 232,217 |
F5Networks/f5-common-python | f5/bigip/tm/ltm/pool.py | Members.exists | def exists(self, **kwargs):
"""Check for the existence of the named object on the BigIP
Sends an HTTP GET to the URI of the named object and if it fails with
a :exc:~requests.HTTPError` exception it checks the exception for
status code of 404 and returns :obj:`False` in that case.
If the GET is successful it must then check the contents of the json
contained in the response, this is because the "pool/... /members"
resource provided by the server returns a status code of 200 for
queries that do not correspond to an existing configuration. Therefore
this method checks for the presence of the "address" key in the
response JSON... of course, this means that exists depends on an
unexpected idiosyncrancy of the server, and might break with version
updates, edge cases, or other unpredictable changes.
:param kwargs: Keyword arguments required to get objects, "partition"
and "name" are required
NOTE: If kwargs has a 'requests_params' key the corresponding dict will
be passed to the underlying requests.session.get method where it will
be handled according to that API. THIS IS HOW TO PASS QUERY-ARGS!
:returns: bool -- The objects exists on BigIP or not.
:raises: :exc:`requests.HTTPError`, Any HTTP error that was not status
code 404.
"""
requests_params = self._handle_requests_params(kwargs)
self._check_load_parameters(**kwargs)
kwargs['uri_as_parts'] = True
session = self._meta_data['bigip']._meta_data['icr_session']
base_uri = self._meta_data['container']._meta_data['uri']
kwargs.update(requests_params)
try:
response = session.get(base_uri, **kwargs)
except HTTPError as err:
if err.response.status_code == 404:
return False
else:
raise
rdict = response.json()
if "address" not in rdict:
# We can add 'or' conditions to be more restrictive.
return False
# Only after all conditions are met...
return True | python | def exists(self, **kwargs):
"""Check for the existence of the named object on the BigIP
Sends an HTTP GET to the URI of the named object and if it fails with
a :exc:~requests.HTTPError` exception it checks the exception for
status code of 404 and returns :obj:`False` in that case.
If the GET is successful it must then check the contents of the json
contained in the response, this is because the "pool/... /members"
resource provided by the server returns a status code of 200 for
queries that do not correspond to an existing configuration. Therefore
this method checks for the presence of the "address" key in the
response JSON... of course, this means that exists depends on an
unexpected idiosyncrancy of the server, and might break with version
updates, edge cases, or other unpredictable changes.
:param kwargs: Keyword arguments required to get objects, "partition"
and "name" are required
NOTE: If kwargs has a 'requests_params' key the corresponding dict will
be passed to the underlying requests.session.get method where it will
be handled according to that API. THIS IS HOW TO PASS QUERY-ARGS!
:returns: bool -- The objects exists on BigIP or not.
:raises: :exc:`requests.HTTPError`, Any HTTP error that was not status
code 404.
"""
requests_params = self._handle_requests_params(kwargs)
self._check_load_parameters(**kwargs)
kwargs['uri_as_parts'] = True
session = self._meta_data['bigip']._meta_data['icr_session']
base_uri = self._meta_data['container']._meta_data['uri']
kwargs.update(requests_params)
try:
response = session.get(base_uri, **kwargs)
except HTTPError as err:
if err.response.status_code == 404:
return False
else:
raise
rdict = response.json()
if "address" not in rdict:
# We can add 'or' conditions to be more restrictive.
return False
# Only after all conditions are met...
return True | [
"def",
"exists",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"self",
".",
"_check_load_parameters",
"(",
"*",
"*",
"kwargs",
")",
"kwargs",
"[",
"'uri_as_parts'",
"]",
"=",
"True",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"base_uri",
"=",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
".",
"_meta_data",
"[",
"'uri'",
"]",
"kwargs",
".",
"update",
"(",
"requests_params",
")",
"try",
":",
"response",
"=",
"session",
".",
"get",
"(",
"base_uri",
",",
"*",
"*",
"kwargs",
")",
"except",
"HTTPError",
"as",
"err",
":",
"if",
"err",
".",
"response",
".",
"status_code",
"==",
"404",
":",
"return",
"False",
"else",
":",
"raise",
"rdict",
"=",
"response",
".",
"json",
"(",
")",
"if",
"\"address\"",
"not",
"in",
"rdict",
":",
"# We can add 'or' conditions to be more restrictive.",
"return",
"False",
"# Only after all conditions are met...",
"return",
"True"
] | Check for the existence of the named object on the BigIP
Sends an HTTP GET to the URI of the named object and if it fails with
a :exc:~requests.HTTPError` exception it checks the exception for
status code of 404 and returns :obj:`False` in that case.
If the GET is successful it must then check the contents of the json
contained in the response, this is because the "pool/... /members"
resource provided by the server returns a status code of 200 for
queries that do not correspond to an existing configuration. Therefore
this method checks for the presence of the "address" key in the
response JSON... of course, this means that exists depends on an
unexpected idiosyncrancy of the server, and might break with version
updates, edge cases, or other unpredictable changes.
:param kwargs: Keyword arguments required to get objects, "partition"
and "name" are required
NOTE: If kwargs has a 'requests_params' key the corresponding dict will
be passed to the underlying requests.session.get method where it will
be handled according to that API. THIS IS HOW TO PASS QUERY-ARGS!
:returns: bool -- The objects exists on BigIP or not.
:raises: :exc:`requests.HTTPError`, Any HTTP error that was not status
code 404. | [
"Check",
"for",
"the",
"existence",
"of",
"the",
"named",
"object",
"on",
"the",
"BigIP"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/pool.py#L162-L206 | train | 232,218 |
F5Networks/f5-common-python | f5/bigip/tm/sys/ucs.py | Ucs.exec_cmd | def exec_cmd(self, command, **kwargs):
"""Due to ID476518 the load command need special treatment."""
self._is_allowed_command(command)
self._check_command_parameters(**kwargs)
if command == 'load':
kwargs['command'] = command
self._check_exclusive_parameters(**kwargs)
requests_params = self._handle_requests_params(kwargs)
session = self._meta_data['bigip']._meta_data['icr_session']
try:
session.post(
self._meta_data['uri'], json=kwargs, **requests_params)
except HTTPError as err:
if err.response.status_code != 502:
raise
return
else:
return self._exec_cmd(command, **kwargs) | python | def exec_cmd(self, command, **kwargs):
"""Due to ID476518 the load command need special treatment."""
self._is_allowed_command(command)
self._check_command_parameters(**kwargs)
if command == 'load':
kwargs['command'] = command
self._check_exclusive_parameters(**kwargs)
requests_params = self._handle_requests_params(kwargs)
session = self._meta_data['bigip']._meta_data['icr_session']
try:
session.post(
self._meta_data['uri'], json=kwargs, **requests_params)
except HTTPError as err:
if err.response.status_code != 502:
raise
return
else:
return self._exec_cmd(command, **kwargs) | [
"def",
"exec_cmd",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_allowed_command",
"(",
"command",
")",
"self",
".",
"_check_command_parameters",
"(",
"*",
"*",
"kwargs",
")",
"if",
"command",
"==",
"'load'",
":",
"kwargs",
"[",
"'command'",
"]",
"=",
"command",
"self",
".",
"_check_exclusive_parameters",
"(",
"*",
"*",
"kwargs",
")",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"try",
":",
"session",
".",
"post",
"(",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
",",
"json",
"=",
"kwargs",
",",
"*",
"*",
"requests_params",
")",
"except",
"HTTPError",
"as",
"err",
":",
"if",
"err",
".",
"response",
".",
"status_code",
"!=",
"502",
":",
"raise",
"return",
"else",
":",
"return",
"self",
".",
"_exec_cmd",
"(",
"command",
",",
"*",
"*",
"kwargs",
")"
] | Due to ID476518 the load command need special treatment. | [
"Due",
"to",
"ID476518",
"the",
"load",
"command",
"need",
"special",
"treatment",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/ucs.py#L60-L81 | train | 232,219 |
F5Networks/f5-common-python | f5/bigip/tm/sys/ucs.py | Ucs.load | def load(self, **kwargs):
"""Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here
"""
# Check if we are using 12.1.0 version or above when using this method
self._is_version_supported_method('12.1.0')
newinst = self._stamp_out_core()
newinst._refresh(**kwargs)
return newinst | python | def load(self, **kwargs):
"""Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here
"""
# Check if we are using 12.1.0 version or above when using this method
self._is_version_supported_method('12.1.0')
newinst = self._stamp_out_core()
newinst._refresh(**kwargs)
return newinst | [
"def",
"load",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if we are using 12.1.0 version or above when using this method",
"self",
".",
"_is_version_supported_method",
"(",
"'12.1.0'",
")",
"newinst",
"=",
"self",
".",
"_stamp_out_core",
"(",
")",
"newinst",
".",
"_refresh",
"(",
"*",
"*",
"kwargs",
")",
"return",
"newinst"
] | Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here | [
"Method",
"to",
"list",
"the",
"UCS",
"on",
"the",
"system"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/ucs.py#L83-L95 | train | 232,220 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._set_attributes | def _set_attributes(self, **kwargs):
'''Set instance attributes based on kwargs
:param kwargs: dict -- kwargs to set as attributes
'''
try:
self.devices = kwargs['devices'][:]
self.name = kwargs['device_group_name']
self.type = kwargs['device_group_type']
self.partition = kwargs['device_group_partition']
except KeyError as ex:
raise MissingRequiredDeviceGroupParameter(ex) | python | def _set_attributes(self, **kwargs):
'''Set instance attributes based on kwargs
:param kwargs: dict -- kwargs to set as attributes
'''
try:
self.devices = kwargs['devices'][:]
self.name = kwargs['device_group_name']
self.type = kwargs['device_group_type']
self.partition = kwargs['device_group_partition']
except KeyError as ex:
raise MissingRequiredDeviceGroupParameter(ex) | [
"def",
"_set_attributes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"devices",
"=",
"kwargs",
"[",
"'devices'",
"]",
"[",
":",
"]",
"self",
".",
"name",
"=",
"kwargs",
"[",
"'device_group_name'",
"]",
"self",
".",
"type",
"=",
"kwargs",
"[",
"'device_group_type'",
"]",
"self",
".",
"partition",
"=",
"kwargs",
"[",
"'device_group_partition'",
"]",
"except",
"KeyError",
"as",
"ex",
":",
"raise",
"MissingRequiredDeviceGroupParameter",
"(",
"ex",
")"
] | Set instance attributes based on kwargs
:param kwargs: dict -- kwargs to set as attributes | [
"Set",
"instance",
"attributes",
"based",
"on",
"kwargs"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L104-L116 | train | 232,221 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup.validate | def validate(self, **kwargs):
'''Validate device group state among given devices.
:param kwargs: dict -- keyword args of device group information
:raises: UnexpectedDeviceGroupType, UnexpectedDeviceGroupDevices
'''
self._set_attributes(**kwargs)
self._check_type()
self.dev_group_uri_res = self._get_device_group(self.devices[0])
if self.dev_group_uri_res.type != self.type:
msg = 'Device group type found: %r does not match expected ' \
'device group type: %r' % (
self.dev_group_uri_res.type, self.type
)
raise UnexpectedDeviceGroupType(msg)
queried_device_names = self._get_device_names_in_group()
given_device_names = []
for device in self.devices:
device_name = get_device_info(device).name
given_device_names.append(device_name)
if sorted(queried_device_names) != sorted(given_device_names):
msg = 'Given devices does not match queried devices.'
raise UnexpectedDeviceGroupDevices(msg)
self.ensure_all_devices_in_sync() | python | def validate(self, **kwargs):
'''Validate device group state among given devices.
:param kwargs: dict -- keyword args of device group information
:raises: UnexpectedDeviceGroupType, UnexpectedDeviceGroupDevices
'''
self._set_attributes(**kwargs)
self._check_type()
self.dev_group_uri_res = self._get_device_group(self.devices[0])
if self.dev_group_uri_res.type != self.type:
msg = 'Device group type found: %r does not match expected ' \
'device group type: %r' % (
self.dev_group_uri_res.type, self.type
)
raise UnexpectedDeviceGroupType(msg)
queried_device_names = self._get_device_names_in_group()
given_device_names = []
for device in self.devices:
device_name = get_device_info(device).name
given_device_names.append(device_name)
if sorted(queried_device_names) != sorted(given_device_names):
msg = 'Given devices does not match queried devices.'
raise UnexpectedDeviceGroupDevices(msg)
self.ensure_all_devices_in_sync() | [
"def",
"validate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_set_attributes",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_check_type",
"(",
")",
"self",
".",
"dev_group_uri_res",
"=",
"self",
".",
"_get_device_group",
"(",
"self",
".",
"devices",
"[",
"0",
"]",
")",
"if",
"self",
".",
"dev_group_uri_res",
".",
"type",
"!=",
"self",
".",
"type",
":",
"msg",
"=",
"'Device group type found: %r does not match expected '",
"'device group type: %r'",
"%",
"(",
"self",
".",
"dev_group_uri_res",
".",
"type",
",",
"self",
".",
"type",
")",
"raise",
"UnexpectedDeviceGroupType",
"(",
"msg",
")",
"queried_device_names",
"=",
"self",
".",
"_get_device_names_in_group",
"(",
")",
"given_device_names",
"=",
"[",
"]",
"for",
"device",
"in",
"self",
".",
"devices",
":",
"device_name",
"=",
"get_device_info",
"(",
"device",
")",
".",
"name",
"given_device_names",
".",
"append",
"(",
"device_name",
")",
"if",
"sorted",
"(",
"queried_device_names",
")",
"!=",
"sorted",
"(",
"given_device_names",
")",
":",
"msg",
"=",
"'Given devices does not match queried devices.'",
"raise",
"UnexpectedDeviceGroupDevices",
"(",
"msg",
")",
"self",
".",
"ensure_all_devices_in_sync",
"(",
")"
] | Validate device group state among given devices.
:param kwargs: dict -- keyword args of device group information
:raises: UnexpectedDeviceGroupType, UnexpectedDeviceGroupDevices | [
"Validate",
"device",
"group",
"state",
"among",
"given",
"devices",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L118-L142 | train | 232,222 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._check_type | def _check_type(self):
'''Check that the device group type is correct.
:raises: DeviceGroupOperationNotSupported, DeviceGroupNotSupported
'''
if self.type not in self.available_types:
msg = 'Unsupported cluster type was given: %s' % self.type
raise DeviceGroupNotSupported(msg)
elif self.type == 'sync-only' and self.name != 'device_trust_group':
msg = "Management of sync-only device groups only supported for " \
"built-in device group named 'device_trust_group'"
raise DeviceGroupNotSupported(msg) | python | def _check_type(self):
'''Check that the device group type is correct.
:raises: DeviceGroupOperationNotSupported, DeviceGroupNotSupported
'''
if self.type not in self.available_types:
msg = 'Unsupported cluster type was given: %s' % self.type
raise DeviceGroupNotSupported(msg)
elif self.type == 'sync-only' and self.name != 'device_trust_group':
msg = "Management of sync-only device groups only supported for " \
"built-in device group named 'device_trust_group'"
raise DeviceGroupNotSupported(msg) | [
"def",
"_check_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"self",
".",
"available_types",
":",
"msg",
"=",
"'Unsupported cluster type was given: %s'",
"%",
"self",
".",
"type",
"raise",
"DeviceGroupNotSupported",
"(",
"msg",
")",
"elif",
"self",
".",
"type",
"==",
"'sync-only'",
"and",
"self",
".",
"name",
"!=",
"'device_trust_group'",
":",
"msg",
"=",
"\"Management of sync-only device groups only supported for \"",
"\"built-in device group named 'device_trust_group'\"",
"raise",
"DeviceGroupNotSupported",
"(",
"msg",
")"
] | Check that the device group type is correct.
:raises: DeviceGroupOperationNotSupported, DeviceGroupNotSupported | [
"Check",
"that",
"the",
"device",
"group",
"type",
"is",
"correct",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L144-L156 | train | 232,223 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup.create | def create(self, **kwargs):
'''Create the device service cluster group and add devices to it.'''
self._set_attributes(**kwargs)
self._check_type()
pollster(self._check_all_devices_in_sync)()
dg = self.devices[0].tm.cm.device_groups.device_group
dg.create(name=self.name, partition=self.partition, type=self.type)
for device in self.devices:
self._add_device_to_device_group(device)
device.tm.sys.config.exec_cmd('save')
self.ensure_all_devices_in_sync() | python | def create(self, **kwargs):
'''Create the device service cluster group and add devices to it.'''
self._set_attributes(**kwargs)
self._check_type()
pollster(self._check_all_devices_in_sync)()
dg = self.devices[0].tm.cm.device_groups.device_group
dg.create(name=self.name, partition=self.partition, type=self.type)
for device in self.devices:
self._add_device_to_device_group(device)
device.tm.sys.config.exec_cmd('save')
self.ensure_all_devices_in_sync() | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_set_attributes",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_check_type",
"(",
")",
"pollster",
"(",
"self",
".",
"_check_all_devices_in_sync",
")",
"(",
")",
"dg",
"=",
"self",
".",
"devices",
"[",
"0",
"]",
".",
"tm",
".",
"cm",
".",
"device_groups",
".",
"device_group",
"dg",
".",
"create",
"(",
"name",
"=",
"self",
".",
"name",
",",
"partition",
"=",
"self",
".",
"partition",
",",
"type",
"=",
"self",
".",
"type",
")",
"for",
"device",
"in",
"self",
".",
"devices",
":",
"self",
".",
"_add_device_to_device_group",
"(",
"device",
")",
"device",
".",
"tm",
".",
"sys",
".",
"config",
".",
"exec_cmd",
"(",
"'save'",
")",
"self",
".",
"ensure_all_devices_in_sync",
"(",
")"
] | Create the device service cluster group and add devices to it. | [
"Create",
"the",
"device",
"service",
"cluster",
"group",
"and",
"add",
"devices",
"to",
"it",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L161-L172 | train | 232,224 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup.teardown | def teardown(self):
'''Teardown device service cluster group.'''
self.ensure_all_devices_in_sync()
for device in self.devices:
self._delete_device_from_device_group(device)
self._sync_to_group(device)
pollster(self._ensure_device_active)(device)
self.ensure_all_devices_in_sync()
dg = pollster(self._get_device_group)(self.devices[0])
dg.delete()
pollster(self._check_devices_active_licensed)()
pollster(self._check_all_devices_in_sync)() | python | def teardown(self):
'''Teardown device service cluster group.'''
self.ensure_all_devices_in_sync()
for device in self.devices:
self._delete_device_from_device_group(device)
self._sync_to_group(device)
pollster(self._ensure_device_active)(device)
self.ensure_all_devices_in_sync()
dg = pollster(self._get_device_group)(self.devices[0])
dg.delete()
pollster(self._check_devices_active_licensed)()
pollster(self._check_all_devices_in_sync)() | [
"def",
"teardown",
"(",
"self",
")",
":",
"self",
".",
"ensure_all_devices_in_sync",
"(",
")",
"for",
"device",
"in",
"self",
".",
"devices",
":",
"self",
".",
"_delete_device_from_device_group",
"(",
"device",
")",
"self",
".",
"_sync_to_group",
"(",
"device",
")",
"pollster",
"(",
"self",
".",
"_ensure_device_active",
")",
"(",
"device",
")",
"self",
".",
"ensure_all_devices_in_sync",
"(",
")",
"dg",
"=",
"pollster",
"(",
"self",
".",
"_get_device_group",
")",
"(",
"self",
".",
"devices",
"[",
"0",
"]",
")",
"dg",
".",
"delete",
"(",
")",
"pollster",
"(",
"self",
".",
"_check_devices_active_licensed",
")",
"(",
")",
"pollster",
"(",
"self",
".",
"_check_all_devices_in_sync",
")",
"(",
")"
] | Teardown device service cluster group. | [
"Teardown",
"device",
"service",
"cluster",
"group",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L174-L186 | train | 232,225 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._get_device_group | def _get_device_group(self, device):
'''Get the device group through a device.
:param device: bigip object -- device
:returns: tm.cm.device_groups.device_group object
'''
return device.tm.cm.device_groups.device_group.load(
name=self.name, partition=self.partition
) | python | def _get_device_group(self, device):
'''Get the device group through a device.
:param device: bigip object -- device
:returns: tm.cm.device_groups.device_group object
'''
return device.tm.cm.device_groups.device_group.load(
name=self.name, partition=self.partition
) | [
"def",
"_get_device_group",
"(",
"self",
",",
"device",
")",
":",
"return",
"device",
".",
"tm",
".",
"cm",
".",
"device_groups",
".",
"device_group",
".",
"load",
"(",
"name",
"=",
"self",
".",
"name",
",",
"partition",
"=",
"self",
".",
"partition",
")"
] | Get the device group through a device.
:param device: bigip object -- device
:returns: tm.cm.device_groups.device_group object | [
"Get",
"the",
"device",
"group",
"through",
"a",
"device",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L202-L211 | train | 232,226 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._add_device_to_device_group | def _add_device_to_device_group(self, device):
'''Add device to device service cluster group.
:param device: bigip object -- device to add to group
'''
device_name = get_device_info(device).name
dg = pollster(self._get_device_group)(device)
dg.devices_s.devices.create(name=device_name, partition=self.partition)
pollster(self._check_device_exists_in_device_group)(device_name) | python | def _add_device_to_device_group(self, device):
'''Add device to device service cluster group.
:param device: bigip object -- device to add to group
'''
device_name = get_device_info(device).name
dg = pollster(self._get_device_group)(device)
dg.devices_s.devices.create(name=device_name, partition=self.partition)
pollster(self._check_device_exists_in_device_group)(device_name) | [
"def",
"_add_device_to_device_group",
"(",
"self",
",",
"device",
")",
":",
"device_name",
"=",
"get_device_info",
"(",
"device",
")",
".",
"name",
"dg",
"=",
"pollster",
"(",
"self",
".",
"_get_device_group",
")",
"(",
"device",
")",
"dg",
".",
"devices_s",
".",
"devices",
".",
"create",
"(",
"name",
"=",
"device_name",
",",
"partition",
"=",
"self",
".",
"partition",
")",
"pollster",
"(",
"self",
".",
"_check_device_exists_in_device_group",
")",
"(",
"device_name",
")"
] | Add device to device service cluster group.
:param device: bigip object -- device to add to group | [
"Add",
"device",
"to",
"device",
"service",
"cluster",
"group",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L224-L233 | train | 232,227 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._check_device_exists_in_device_group | def _check_device_exists_in_device_group(self, device_name):
'''Check whether a device exists in the device group
:param device: ManagementRoot object -- device to look for
'''
dg = self._get_device_group(self.devices[0])
dg.devices_s.devices.load(name=device_name, partition=self.partition) | python | def _check_device_exists_in_device_group(self, device_name):
'''Check whether a device exists in the device group
:param device: ManagementRoot object -- device to look for
'''
dg = self._get_device_group(self.devices[0])
dg.devices_s.devices.load(name=device_name, partition=self.partition) | [
"def",
"_check_device_exists_in_device_group",
"(",
"self",
",",
"device_name",
")",
":",
"dg",
"=",
"self",
".",
"_get_device_group",
"(",
"self",
".",
"devices",
"[",
"0",
"]",
")",
"dg",
".",
"devices_s",
".",
"devices",
".",
"load",
"(",
"name",
"=",
"device_name",
",",
"partition",
"=",
"self",
".",
"partition",
")"
] | Check whether a device exists in the device group
:param device: ManagementRoot object -- device to look for | [
"Check",
"whether",
"a",
"device",
"exists",
"in",
"the",
"device",
"group"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L235-L242 | train | 232,228 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._delete_device_from_device_group | def _delete_device_from_device_group(self, device):
'''Remove device from device service cluster group.
:param device: ManagementRoot object -- device to delete from group
'''
device_name = get_device_info(device).name
dg = pollster(self._get_device_group)(device)
device_to_remove = dg.devices_s.devices.load(
name=device_name, partition=self.partition
)
device_to_remove.delete() | python | def _delete_device_from_device_group(self, device):
'''Remove device from device service cluster group.
:param device: ManagementRoot object -- device to delete from group
'''
device_name = get_device_info(device).name
dg = pollster(self._get_device_group)(device)
device_to_remove = dg.devices_s.devices.load(
name=device_name, partition=self.partition
)
device_to_remove.delete() | [
"def",
"_delete_device_from_device_group",
"(",
"self",
",",
"device",
")",
":",
"device_name",
"=",
"get_device_info",
"(",
"device",
")",
".",
"name",
"dg",
"=",
"pollster",
"(",
"self",
".",
"_get_device_group",
")",
"(",
"device",
")",
"device_to_remove",
"=",
"dg",
".",
"devices_s",
".",
"devices",
".",
"load",
"(",
"name",
"=",
"device_name",
",",
"partition",
"=",
"self",
".",
"partition",
")",
"device_to_remove",
".",
"delete",
"(",
")"
] | Remove device from device service cluster group.
:param device: ManagementRoot object -- device to delete from group | [
"Remove",
"device",
"from",
"device",
"service",
"cluster",
"group",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L244-L255 | train | 232,229 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._ensure_device_active | def _ensure_device_active(self, device):
'''Ensure a single device is in an active state
:param device: ManagementRoot object -- device to inspect
:raises: UnexpectedClusterState
'''
act = device.tm.cm.devices.device.load(
name=get_device_info(device).name,
partition=self.partition
)
if act.failoverState != 'active':
msg = "A device in the cluster was not in the 'Active' state."
raise UnexpectedDeviceGroupState(msg) | python | def _ensure_device_active(self, device):
'''Ensure a single device is in an active state
:param device: ManagementRoot object -- device to inspect
:raises: UnexpectedClusterState
'''
act = device.tm.cm.devices.device.load(
name=get_device_info(device).name,
partition=self.partition
)
if act.failoverState != 'active':
msg = "A device in the cluster was not in the 'Active' state."
raise UnexpectedDeviceGroupState(msg) | [
"def",
"_ensure_device_active",
"(",
"self",
",",
"device",
")",
":",
"act",
"=",
"device",
".",
"tm",
".",
"cm",
".",
"devices",
".",
"device",
".",
"load",
"(",
"name",
"=",
"get_device_info",
"(",
"device",
")",
".",
"name",
",",
"partition",
"=",
"self",
".",
"partition",
")",
"if",
"act",
".",
"failoverState",
"!=",
"'active'",
":",
"msg",
"=",
"\"A device in the cluster was not in the 'Active' state.\"",
"raise",
"UnexpectedDeviceGroupState",
"(",
"msg",
")"
] | Ensure a single device is in an active state
:param device: ManagementRoot object -- device to inspect
:raises: UnexpectedClusterState | [
"Ensure",
"a",
"single",
"device",
"is",
"in",
"an",
"active",
"state"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L257-L270 | train | 232,230 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._sync_to_group | def _sync_to_group(self, device):
'''Sync the device to the cluster group
:param device: bigip object -- device to sync to group
'''
config_sync_cmd = 'config-sync to-group %s' % self.name
device.tm.cm.exec_cmd('run', utilCmdArgs=config_sync_cmd) | python | def _sync_to_group(self, device):
'''Sync the device to the cluster group
:param device: bigip object -- device to sync to group
'''
config_sync_cmd = 'config-sync to-group %s' % self.name
device.tm.cm.exec_cmd('run', utilCmdArgs=config_sync_cmd) | [
"def",
"_sync_to_group",
"(",
"self",
",",
"device",
")",
":",
"config_sync_cmd",
"=",
"'config-sync to-group %s'",
"%",
"self",
".",
"name",
"device",
".",
"tm",
".",
"cm",
".",
"exec_cmd",
"(",
"'run'",
",",
"utilCmdArgs",
"=",
"config_sync_cmd",
")"
] | Sync the device to the cluster group
:param device: bigip object -- device to sync to group | [
"Sync",
"the",
"device",
"to",
"the",
"cluster",
"group"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L272-L279 | train | 232,231 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._check_all_devices_in_sync | def _check_all_devices_in_sync(self):
'''Wait until all devices have failover status of 'In Sync'.
:raises: UnexpectedClusterState
'''
if len(self._get_devices_by_failover_status('In Sync')) != \
len(self.devices):
msg = "Expected all devices in group to have 'In Sync' status."
raise UnexpectedDeviceGroupState(msg) | python | def _check_all_devices_in_sync(self):
'''Wait until all devices have failover status of 'In Sync'.
:raises: UnexpectedClusterState
'''
if len(self._get_devices_by_failover_status('In Sync')) != \
len(self.devices):
msg = "Expected all devices in group to have 'In Sync' status."
raise UnexpectedDeviceGroupState(msg) | [
"def",
"_check_all_devices_in_sync",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_get_devices_by_failover_status",
"(",
"'In Sync'",
")",
")",
"!=",
"len",
"(",
"self",
".",
"devices",
")",
":",
"msg",
"=",
"\"Expected all devices in group to have 'In Sync' status.\"",
"raise",
"UnexpectedDeviceGroupState",
"(",
"msg",
")"
] | Wait until all devices have failover status of 'In Sync'.
:raises: UnexpectedClusterState | [
"Wait",
"until",
"all",
"devices",
"have",
"failover",
"status",
"of",
"In",
"Sync",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L287-L296 | train | 232,232 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._get_devices_by_failover_status | def _get_devices_by_failover_status(self, status):
'''Get a list of bigips by failover status.
:param status: str -- status to filter the returned list of devices
:returns: list -- list of devices that have the given status
'''
devices_with_status = []
for device in self.devices:
if (self._check_device_failover_status(device, status)):
devices_with_status.append(device)
return devices_with_status | python | def _get_devices_by_failover_status(self, status):
'''Get a list of bigips by failover status.
:param status: str -- status to filter the returned list of devices
:returns: list -- list of devices that have the given status
'''
devices_with_status = []
for device in self.devices:
if (self._check_device_failover_status(device, status)):
devices_with_status.append(device)
return devices_with_status | [
"def",
"_get_devices_by_failover_status",
"(",
"self",
",",
"status",
")",
":",
"devices_with_status",
"=",
"[",
"]",
"for",
"device",
"in",
"self",
".",
"devices",
":",
"if",
"(",
"self",
".",
"_check_device_failover_status",
"(",
"device",
",",
"status",
")",
")",
":",
"devices_with_status",
".",
"append",
"(",
"device",
")",
"return",
"devices_with_status"
] | Get a list of bigips by failover status.
:param status: str -- status to filter the returned list of devices
:returns: list -- list of devices that have the given status | [
"Get",
"a",
"list",
"of",
"bigips",
"by",
"failover",
"status",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L298-L309 | train | 232,233 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._check_device_failover_status | def _check_device_failover_status(self, device, status):
'''Determine if a device has a specific failover status.
:param status: str -- status to check against
:returns: bool -- True is it has status, False otherwise
'''
sync_status = device.tm.cm.sync_status
sync_status.refresh()
current_status = (sync_status.entries[self.sync_status_entry]
['nestedStats']['entries']['status']
['description'])
if status == current_status:
return True
return False | python | def _check_device_failover_status(self, device, status):
'''Determine if a device has a specific failover status.
:param status: str -- status to check against
:returns: bool -- True is it has status, False otherwise
'''
sync_status = device.tm.cm.sync_status
sync_status.refresh()
current_status = (sync_status.entries[self.sync_status_entry]
['nestedStats']['entries']['status']
['description'])
if status == current_status:
return True
return False | [
"def",
"_check_device_failover_status",
"(",
"self",
",",
"device",
",",
"status",
")",
":",
"sync_status",
"=",
"device",
".",
"tm",
".",
"cm",
".",
"sync_status",
"sync_status",
".",
"refresh",
"(",
")",
"current_status",
"=",
"(",
"sync_status",
".",
"entries",
"[",
"self",
".",
"sync_status_entry",
"]",
"[",
"'nestedStats'",
"]",
"[",
"'entries'",
"]",
"[",
"'status'",
"]",
"[",
"'description'",
"]",
")",
"if",
"status",
"==",
"current_status",
":",
"return",
"True",
"return",
"False"
] | Determine if a device has a specific failover status.
:param status: str -- status to check against
:returns: bool -- True is it has status, False otherwise | [
"Determine",
"if",
"a",
"device",
"has",
"a",
"specific",
"failover",
"status",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L311-L325 | train | 232,234 |
F5Networks/f5-common-python | f5/multi_device/device_group.py | DeviceGroup._get_devices_by_activation_state | def _get_devices_by_activation_state(self, state):
'''Get a list of bigips by activation statue.
:param state: str -- state to filter the returned list of devices
:returns: list -- list of devices that are in the given state
'''
devices_with_state = []
for device in self.devices:
act = device.tm.cm.devices.device.load(
name=get_device_info(device).name,
partition=self.partition
)
if act.failoverState == state:
devices_with_state.append(device)
return devices_with_state | python | def _get_devices_by_activation_state(self, state):
'''Get a list of bigips by activation statue.
:param state: str -- state to filter the returned list of devices
:returns: list -- list of devices that are in the given state
'''
devices_with_state = []
for device in self.devices:
act = device.tm.cm.devices.device.load(
name=get_device_info(device).name,
partition=self.partition
)
if act.failoverState == state:
devices_with_state.append(device)
return devices_with_state | [
"def",
"_get_devices_by_activation_state",
"(",
"self",
",",
"state",
")",
":",
"devices_with_state",
"=",
"[",
"]",
"for",
"device",
"in",
"self",
".",
"devices",
":",
"act",
"=",
"device",
".",
"tm",
".",
"cm",
".",
"devices",
".",
"device",
".",
"load",
"(",
"name",
"=",
"get_device_info",
"(",
"device",
")",
".",
"name",
",",
"partition",
"=",
"self",
".",
"partition",
")",
"if",
"act",
".",
"failoverState",
"==",
"state",
":",
"devices_with_state",
".",
"append",
"(",
"device",
")",
"return",
"devices_with_state"
] | Get a list of bigips by activation statue.
:param state: str -- state to filter the returned list of devices
:returns: list -- list of devices that are in the given state | [
"Get",
"a",
"list",
"of",
"bigips",
"by",
"activation",
"statue",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/device_group.py#L327-L342 | train | 232,235 |
F5Networks/f5-common-python | f5/bigip/tm/asm/policies/__init__.py | Policy._set_attr_reg | def _set_attr_reg(self):
"""Helper method.
Appends correct attribute registry, depending on TMOS version
"""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
attributes = self._meta_data['attribute_registry']
v12kind = 'tm:asm:policies:blocking-settings:blocking-settingcollectionstate'
v11kind = 'tm:asm:policies:blocking-settings'
builderv11 = 'tm:asm:policies:policy-builder:pbconfigstate'
builderv12 = 'tm:asm:policies:policy-builder:policy-builderstate'
if LooseVersion(tmos_v) < LooseVersion('12.0.0'):
attributes[v11kind] = Blocking_Settings
attributes[builderv11] = Policy_Builder
else:
attributes[v12kind] = Blocking_Settings
attributes[builderv12] = Policy_Builder | python | def _set_attr_reg(self):
"""Helper method.
Appends correct attribute registry, depending on TMOS version
"""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
attributes = self._meta_data['attribute_registry']
v12kind = 'tm:asm:policies:blocking-settings:blocking-settingcollectionstate'
v11kind = 'tm:asm:policies:blocking-settings'
builderv11 = 'tm:asm:policies:policy-builder:pbconfigstate'
builderv12 = 'tm:asm:policies:policy-builder:policy-builderstate'
if LooseVersion(tmos_v) < LooseVersion('12.0.0'):
attributes[v11kind] = Blocking_Settings
attributes[builderv11] = Policy_Builder
else:
attributes[v12kind] = Blocking_Settings
attributes[builderv12] = Policy_Builder | [
"def",
"_set_attr_reg",
"(",
"self",
")",
":",
"tmos_v",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"attributes",
"=",
"self",
".",
"_meta_data",
"[",
"'attribute_registry'",
"]",
"v12kind",
"=",
"'tm:asm:policies:blocking-settings:blocking-settingcollectionstate'",
"v11kind",
"=",
"'tm:asm:policies:blocking-settings'",
"builderv11",
"=",
"'tm:asm:policies:policy-builder:pbconfigstate'",
"builderv12",
"=",
"'tm:asm:policies:policy-builder:policy-builderstate'",
"if",
"LooseVersion",
"(",
"tmos_v",
")",
"<",
"LooseVersion",
"(",
"'12.0.0'",
")",
":",
"attributes",
"[",
"v11kind",
"]",
"=",
"Blocking_Settings",
"attributes",
"[",
"builderv11",
"]",
"=",
"Policy_Builder",
"else",
":",
"attributes",
"[",
"v12kind",
"]",
"=",
"Blocking_Settings",
"attributes",
"[",
"builderv12",
"]",
"=",
"Policy_Builder"
] | Helper method.
Appends correct attribute registry, depending on TMOS version | [
"Helper",
"method",
"."
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/asm/policies/__init__.py#L132-L149 | train | 232,236 |
F5Networks/f5-common-python | f5/bigip/tm/asm/policies/__init__.py | Policy.create | def create(self, **kwargs):
"""Custom creation logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return:
"""
for x in range(0, 30):
try:
return self._create(**kwargs)
except iControlUnexpectedHTTPError as ex:
if self._check_exception(ex):
continue
else:
raise | python | def create(self, **kwargs):
"""Custom creation logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return:
"""
for x in range(0, 30):
try:
return self._create(**kwargs)
except iControlUnexpectedHTTPError as ex:
if self._check_exception(ex):
continue
else:
raise | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"30",
")",
":",
"try",
":",
"return",
"self",
".",
"_create",
"(",
"*",
"*",
"kwargs",
")",
"except",
"iControlUnexpectedHTTPError",
"as",
"ex",
":",
"if",
"self",
".",
"_check_exception",
"(",
"ex",
")",
":",
"continue",
"else",
":",
"raise"
] | Custom creation logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return: | [
"Custom",
"creation",
"logic",
"to",
"handle",
"edge",
"cases"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/asm/policies/__init__.py#L151-L172 | train | 232,237 |
F5Networks/f5-common-python | f5/bigip/tm/asm/policies/__init__.py | Policy.delete | def delete(self, **kwargs):
"""Custom deletion logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return:
"""
for x in range(0, 30):
try:
return self._delete(**kwargs)
except iControlUnexpectedHTTPError as ex:
if self._check_exception(ex):
continue
else:
raise | python | def delete(self, **kwargs):
"""Custom deletion logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return:
"""
for x in range(0, 30):
try:
return self._delete(**kwargs)
except iControlUnexpectedHTTPError as ex:
if self._check_exception(ex):
continue
else:
raise | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"30",
")",
":",
"try",
":",
"return",
"self",
".",
"_delete",
"(",
"*",
"*",
"kwargs",
")",
"except",
"iControlUnexpectedHTTPError",
"as",
"ex",
":",
"if",
"self",
".",
"_check_exception",
"(",
"ex",
")",
":",
"continue",
"else",
":",
"raise"
] | Custom deletion logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return: | [
"Custom",
"deletion",
"logic",
"to",
"handle",
"edge",
"cases"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/asm/policies/__init__.py#L174-L195 | train | 232,238 |
laurencium/Causalinference | causalinference/causal.py | CausalModel.reset | def reset(self):
"""
Reinitializes data to original inputs, and drops any estimated
results.
"""
Y, D, X = self.old_data['Y'], self.old_data['D'], self.old_data['X']
self.raw_data = Data(Y, D, X)
self.summary_stats = Summary(self.raw_data)
self.propensity = None
self.cutoff = None
self.blocks = None
self.strata = None
self.estimates = Estimators() | python | def reset(self):
"""
Reinitializes data to original inputs, and drops any estimated
results.
"""
Y, D, X = self.old_data['Y'], self.old_data['D'], self.old_data['X']
self.raw_data = Data(Y, D, X)
self.summary_stats = Summary(self.raw_data)
self.propensity = None
self.cutoff = None
self.blocks = None
self.strata = None
self.estimates = Estimators() | [
"def",
"reset",
"(",
"self",
")",
":",
"Y",
",",
"D",
",",
"X",
"=",
"self",
".",
"old_data",
"[",
"'Y'",
"]",
",",
"self",
".",
"old_data",
"[",
"'D'",
"]",
",",
"self",
".",
"old_data",
"[",
"'X'",
"]",
"self",
".",
"raw_data",
"=",
"Data",
"(",
"Y",
",",
"D",
",",
"X",
")",
"self",
".",
"summary_stats",
"=",
"Summary",
"(",
"self",
".",
"raw_data",
")",
"self",
".",
"propensity",
"=",
"None",
"self",
".",
"cutoff",
"=",
"None",
"self",
".",
"blocks",
"=",
"None",
"self",
".",
"strata",
"=",
"None",
"self",
".",
"estimates",
"=",
"Estimators",
"(",
")"
] | Reinitializes data to original inputs, and drops any estimated
results. | [
"Reinitializes",
"data",
"to",
"original",
"inputs",
"and",
"drops",
"any",
"estimated",
"results",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L21-L35 | train | 232,239 |
laurencium/Causalinference | causalinference/causal.py | CausalModel.est_propensity | def est_propensity(self, lin='all', qua=None):
"""
Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
Parameters
----------
lin: string or list, optional
Column numbers (zero-based) of variables of
the original covariate matrix X to include
linearly. Defaults to the string 'all', which
uses whole covariate matrix.
qua: list, optional
Tuples indicating which columns of the original
covariate matrix to multiply and include. E.g.,
[(1,1), (2,3)] indicates squaring the 2nd column
and including the product of the 3rd and 4th
columns. Default is to not include any
quadratic terms.
"""
lin_terms = parse_lin_terms(self.raw_data['K'], lin)
qua_terms = parse_qua_terms(self.raw_data['K'], qua)
self.propensity = Propensity(self.raw_data, lin_terms, qua_terms)
self.raw_data._dict['pscore'] = self.propensity['fitted']
self._post_pscore_init() | python | def est_propensity(self, lin='all', qua=None):
"""
Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
Parameters
----------
lin: string or list, optional
Column numbers (zero-based) of variables of
the original covariate matrix X to include
linearly. Defaults to the string 'all', which
uses whole covariate matrix.
qua: list, optional
Tuples indicating which columns of the original
covariate matrix to multiply and include. E.g.,
[(1,1), (2,3)] indicates squaring the 2nd column
and including the product of the 3rd and 4th
columns. Default is to not include any
quadratic terms.
"""
lin_terms = parse_lin_terms(self.raw_data['K'], lin)
qua_terms = parse_qua_terms(self.raw_data['K'], qua)
self.propensity = Propensity(self.raw_data, lin_terms, qua_terms)
self.raw_data._dict['pscore'] = self.propensity['fitted']
self._post_pscore_init() | [
"def",
"est_propensity",
"(",
"self",
",",
"lin",
"=",
"'all'",
",",
"qua",
"=",
"None",
")",
":",
"lin_terms",
"=",
"parse_lin_terms",
"(",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
",",
"lin",
")",
"qua_terms",
"=",
"parse_qua_terms",
"(",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
",",
"qua",
")",
"self",
".",
"propensity",
"=",
"Propensity",
"(",
"self",
".",
"raw_data",
",",
"lin_terms",
",",
"qua_terms",
")",
"self",
".",
"raw_data",
".",
"_dict",
"[",
"'pscore'",
"]",
"=",
"self",
".",
"propensity",
"[",
"'fitted'",
"]",
"self",
".",
"_post_pscore_init",
"(",
")"
] | Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
Parameters
----------
lin: string or list, optional
Column numbers (zero-based) of variables of
the original covariate matrix X to include
linearly. Defaults to the string 'all', which
uses whole covariate matrix.
qua: list, optional
Tuples indicating which columns of the original
covariate matrix to multiply and include. E.g.,
[(1,1), (2,3)] indicates squaring the 2nd column
and including the product of the 3rd and 4th
columns. Default is to not include any
quadratic terms. | [
"Estimates",
"the",
"propensity",
"scores",
"given",
"list",
"of",
"covariates",
"to",
"include",
"linearly",
"or",
"quadratically",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L38-L69 | train | 232,240 |
laurencium/Causalinference | causalinference/causal.py | CausalModel.trim | def trim(self):
"""
Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated.
"""
if 0 < self.cutoff <= 0.5:
pscore = self.raw_data['pscore']
keep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff)
Y_trimmed = self.raw_data['Y'][keep]
D_trimmed = self.raw_data['D'][keep]
X_trimmed = self.raw_data['X'][keep]
self.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed)
self.raw_data._dict['pscore'] = pscore[keep]
self.summary_stats = Summary(self.raw_data)
self.strata = None
self.estimates = Estimators()
elif self.cutoff == 0:
pass
else:
raise ValueError('Invalid cutoff.') | python | def trim(self):
"""
Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated.
"""
if 0 < self.cutoff <= 0.5:
pscore = self.raw_data['pscore']
keep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff)
Y_trimmed = self.raw_data['Y'][keep]
D_trimmed = self.raw_data['D'][keep]
X_trimmed = self.raw_data['X'][keep]
self.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed)
self.raw_data._dict['pscore'] = pscore[keep]
self.summary_stats = Summary(self.raw_data)
self.strata = None
self.estimates = Estimators()
elif self.cutoff == 0:
pass
else:
raise ValueError('Invalid cutoff.') | [
"def",
"trim",
"(",
"self",
")",
":",
"if",
"0",
"<",
"self",
".",
"cutoff",
"<=",
"0.5",
":",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"keep",
"=",
"(",
"pscore",
">=",
"self",
".",
"cutoff",
")",
"&",
"(",
"pscore",
"<=",
"1",
"-",
"self",
".",
"cutoff",
")",
"Y_trimmed",
"=",
"self",
".",
"raw_data",
"[",
"'Y'",
"]",
"[",
"keep",
"]",
"D_trimmed",
"=",
"self",
".",
"raw_data",
"[",
"'D'",
"]",
"[",
"keep",
"]",
"X_trimmed",
"=",
"self",
".",
"raw_data",
"[",
"'X'",
"]",
"[",
"keep",
"]",
"self",
".",
"raw_data",
"=",
"Data",
"(",
"Y_trimmed",
",",
"D_trimmed",
",",
"X_trimmed",
")",
"self",
".",
"raw_data",
".",
"_dict",
"[",
"'pscore'",
"]",
"=",
"pscore",
"[",
"keep",
"]",
"self",
".",
"summary_stats",
"=",
"Summary",
"(",
"self",
".",
"raw_data",
")",
"self",
".",
"strata",
"=",
"None",
"self",
".",
"estimates",
"=",
"Estimators",
"(",
")",
"elif",
"self",
".",
"cutoff",
"==",
"0",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid cutoff.'",
")"
] | Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated. | [
"Trims",
"data",
"based",
"on",
"propensity",
"score",
"to",
"create",
"a",
"subsample",
"with",
"better",
"covariate",
"balance",
".",
"The",
"default",
"cutoff",
"value",
"is",
"set",
"to",
"0",
".",
"1",
".",
"To",
"set",
"a",
"custom",
"cutoff",
"value",
"modify",
"the",
"object",
"attribute",
"named",
"cutoff",
"directly",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L118-L145 | train | 232,241 |
laurencium/Causalinference | causalinference/causal.py | CausalModel.stratify | def stratify(self):
"""
Stratifies the sample based on propensity score.
By default the sample is divided into five equal-sized bins.
The number of bins can be set by modifying the object
attribute named blocks. Alternatively, custom-sized bins can
be created by setting blocks equal to a sorted list of numbers
between 0 and 1 indicating the bin boundaries.
This method should only be executed after the propensity score
has been estimated.
"""
Y, D, X = self.raw_data['Y'], self.raw_data['D'], self.raw_data['X']
pscore = self.raw_data['pscore']
if isinstance(self.blocks, int):
blocks = split_equal_bins(pscore, self.blocks)
else:
blocks = self.blocks[:] # make a copy; should be sorted
blocks[0] = 0 # avoids always dropping 1st unit
def subset(p_low, p_high):
return (p_low < pscore) & (pscore <= p_high)
subsets = [subset(*ps) for ps in zip(blocks, blocks[1:])]
strata = [CausalModel(Y[s], D[s], X[s]) for s in subsets]
self.strata = Strata(strata, subsets, pscore) | python | def stratify(self):
"""
Stratifies the sample based on propensity score.
By default the sample is divided into five equal-sized bins.
The number of bins can be set by modifying the object
attribute named blocks. Alternatively, custom-sized bins can
be created by setting blocks equal to a sorted list of numbers
between 0 and 1 indicating the bin boundaries.
This method should only be executed after the propensity score
has been estimated.
"""
Y, D, X = self.raw_data['Y'], self.raw_data['D'], self.raw_data['X']
pscore = self.raw_data['pscore']
if isinstance(self.blocks, int):
blocks = split_equal_bins(pscore, self.blocks)
else:
blocks = self.blocks[:] # make a copy; should be sorted
blocks[0] = 0 # avoids always dropping 1st unit
def subset(p_low, p_high):
return (p_low < pscore) & (pscore <= p_high)
subsets = [subset(*ps) for ps in zip(blocks, blocks[1:])]
strata = [CausalModel(Y[s], D[s], X[s]) for s in subsets]
self.strata = Strata(strata, subsets, pscore) | [
"def",
"stratify",
"(",
"self",
")",
":",
"Y",
",",
"D",
",",
"X",
"=",
"self",
".",
"raw_data",
"[",
"'Y'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'D'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'X'",
"]",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"if",
"isinstance",
"(",
"self",
".",
"blocks",
",",
"int",
")",
":",
"blocks",
"=",
"split_equal_bins",
"(",
"pscore",
",",
"self",
".",
"blocks",
")",
"else",
":",
"blocks",
"=",
"self",
".",
"blocks",
"[",
":",
"]",
"# make a copy; should be sorted",
"blocks",
"[",
"0",
"]",
"=",
"0",
"# avoids always dropping 1st unit",
"def",
"subset",
"(",
"p_low",
",",
"p_high",
")",
":",
"return",
"(",
"p_low",
"<",
"pscore",
")",
"&",
"(",
"pscore",
"<=",
"p_high",
")",
"subsets",
"=",
"[",
"subset",
"(",
"*",
"ps",
")",
"for",
"ps",
"in",
"zip",
"(",
"blocks",
",",
"blocks",
"[",
"1",
":",
"]",
")",
"]",
"strata",
"=",
"[",
"CausalModel",
"(",
"Y",
"[",
"s",
"]",
",",
"D",
"[",
"s",
"]",
",",
"X",
"[",
"s",
"]",
")",
"for",
"s",
"in",
"subsets",
"]",
"self",
".",
"strata",
"=",
"Strata",
"(",
"strata",
",",
"subsets",
",",
"pscore",
")"
] | Stratifies the sample based on propensity score.
By default the sample is divided into five equal-sized bins.
The number of bins can be set by modifying the object
attribute named blocks. Alternatively, custom-sized bins can
be created by setting blocks equal to a sorted list of numbers
between 0 and 1 indicating the bin boundaries.
This method should only be executed after the propensity score
has been estimated. | [
"Stratifies",
"the",
"sample",
"based",
"on",
"propensity",
"score",
".",
"By",
"default",
"the",
"sample",
"is",
"divided",
"into",
"five",
"equal",
"-",
"sized",
"bins",
".",
"The",
"number",
"of",
"bins",
"can",
"be",
"set",
"by",
"modifying",
"the",
"object",
"attribute",
"named",
"blocks",
".",
"Alternatively",
"custom",
"-",
"sized",
"bins",
"can",
"be",
"created",
"by",
"setting",
"blocks",
"equal",
"to",
"a",
"sorted",
"list",
"of",
"numbers",
"between",
"0",
"and",
"1",
"indicating",
"the",
"bin",
"boundaries",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L171-L199 | train | 232,242 |
laurencium/Causalinference | causalinference/causal.py | CausalModel.est_via_matching | def est_via_matching(self, weights='inv', matches=1, bias_adj=False):
"""
Estimates average treatment effects using nearest-
neighborhood matching.
Matching is done with replacement. Method supports multiple
matching. Correcting bias that arise due to imperfect matches
is also supported. For details on methodology, see [1]_.
Parameters
----------
weights: str or positive definite square matrix
Specifies weighting matrix used in computing
distance measures. Defaults to string 'inv',
which does inverse variance weighting. String
'maha' gives the weighting matrix used in the
Mahalanobis metric.
matches: int
Number of matches to use for each subject.
bias_adj: bool
Specifies whether bias adjustments should be
attempted.
References
----------
.. [1] Imbens, G. & Rubin, D. (2015). Causal Inference in
Statistics, Social, and Biomedical Sciences: An
Introduction.
"""
X, K = self.raw_data['X'], self.raw_data['K']
X_c, X_t = self.raw_data['X_c'], self.raw_data['X_t']
if weights == 'inv':
W = 1/X.var(0)
elif weights == 'maha':
V_c = np.cov(X_c, rowvar=False, ddof=0)
V_t = np.cov(X_t, rowvar=False, ddof=0)
if K == 1:
W = 1/np.array([[(V_c+V_t)/2]]) # matrix form
else:
W = np.linalg.inv((V_c+V_t)/2)
else:
W = weights
self.estimates['matching'] = Matching(self.raw_data, W,
matches, bias_adj) | python | def est_via_matching(self, weights='inv', matches=1, bias_adj=False):
"""
Estimates average treatment effects using nearest-
neighborhood matching.
Matching is done with replacement. Method supports multiple
matching. Correcting bias that arise due to imperfect matches
is also supported. For details on methodology, see [1]_.
Parameters
----------
weights: str or positive definite square matrix
Specifies weighting matrix used in computing
distance measures. Defaults to string 'inv',
which does inverse variance weighting. String
'maha' gives the weighting matrix used in the
Mahalanobis metric.
matches: int
Number of matches to use for each subject.
bias_adj: bool
Specifies whether bias adjustments should be
attempted.
References
----------
.. [1] Imbens, G. & Rubin, D. (2015). Causal Inference in
Statistics, Social, and Biomedical Sciences: An
Introduction.
"""
X, K = self.raw_data['X'], self.raw_data['K']
X_c, X_t = self.raw_data['X_c'], self.raw_data['X_t']
if weights == 'inv':
W = 1/X.var(0)
elif weights == 'maha':
V_c = np.cov(X_c, rowvar=False, ddof=0)
V_t = np.cov(X_t, rowvar=False, ddof=0)
if K == 1:
W = 1/np.array([[(V_c+V_t)/2]]) # matrix form
else:
W = np.linalg.inv((V_c+V_t)/2)
else:
W = weights
self.estimates['matching'] = Matching(self.raw_data, W,
matches, bias_adj) | [
"def",
"est_via_matching",
"(",
"self",
",",
"weights",
"=",
"'inv'",
",",
"matches",
"=",
"1",
",",
"bias_adj",
"=",
"False",
")",
":",
"X",
",",
"K",
"=",
"self",
".",
"raw_data",
"[",
"'X'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
"X_c",
",",
"X_t",
"=",
"self",
".",
"raw_data",
"[",
"'X_c'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'X_t'",
"]",
"if",
"weights",
"==",
"'inv'",
":",
"W",
"=",
"1",
"/",
"X",
".",
"var",
"(",
"0",
")",
"elif",
"weights",
"==",
"'maha'",
":",
"V_c",
"=",
"np",
".",
"cov",
"(",
"X_c",
",",
"rowvar",
"=",
"False",
",",
"ddof",
"=",
"0",
")",
"V_t",
"=",
"np",
".",
"cov",
"(",
"X_t",
",",
"rowvar",
"=",
"False",
",",
"ddof",
"=",
"0",
")",
"if",
"K",
"==",
"1",
":",
"W",
"=",
"1",
"/",
"np",
".",
"array",
"(",
"[",
"[",
"(",
"V_c",
"+",
"V_t",
")",
"/",
"2",
"]",
"]",
")",
"# matrix form",
"else",
":",
"W",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"(",
"V_c",
"+",
"V_t",
")",
"/",
"2",
")",
"else",
":",
"W",
"=",
"weights",
"self",
".",
"estimates",
"[",
"'matching'",
"]",
"=",
"Matching",
"(",
"self",
".",
"raw_data",
",",
"W",
",",
"matches",
",",
"bias_adj",
")"
] | Estimates average treatment effects using nearest-
neighborhood matching.
Matching is done with replacement. Method supports multiple
matching. Correcting bias that arise due to imperfect matches
is also supported. For details on methodology, see [1]_.
Parameters
----------
weights: str or positive definite square matrix
Specifies weighting matrix used in computing
distance measures. Defaults to string 'inv',
which does inverse variance weighting. String
'maha' gives the weighting matrix used in the
Mahalanobis metric.
matches: int
Number of matches to use for each subject.
bias_adj: bool
Specifies whether bias adjustments should be
attempted.
References
----------
.. [1] Imbens, G. & Rubin, D. (2015). Causal Inference in
Statistics, Social, and Biomedical Sciences: An
Introduction. | [
"Estimates",
"average",
"treatment",
"effects",
"using",
"nearest",
"-",
"neighborhood",
"matching",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L285-L332 | train | 232,243 |
laurencium/Causalinference | causalinference/utils/tools.py | random_data | def random_data(N=5000, K=3, unobservables=False, **kwargs):
"""
Function that generates data according to one of two simple models that
satisfies the unconfoundedness assumption.
The covariates and error terms are generated according to
X ~ N(mu, Sigma), epsilon ~ N(0, Gamma).
The counterfactual outcomes are generated by
Y0 = X*beta + epsilon_0,
Y1 = delta + X*(beta+theta) + epsilon_1.
Selection is done according to the following propensity score function:
P(D=1|X) = Lambda(X*beta).
Here Lambda is the standard logistic CDF.
Parameters
----------
N: int
Number of units to draw. Defaults to 5000.
K: int
Number of covariates. Defaults to 3.
unobservables: bool
Returns potential outcomes and true propensity score
in addition to observed outcome and covariates if True.
Defaults to False.
mu, Sigma, Gamma, beta, delta, theta: NumPy ndarrays, optional
Parameter values appearing in data generating process.
Returns
-------
tuple
A tuple in the form of (Y, D, X) or (Y, D, X, Y0, Y1) of
observed outcomes, treatment indicators, covariate matrix,
and potential outomces.
"""
mu = kwargs.get('mu', np.zeros(K))
beta = kwargs.get('beta', np.ones(K))
theta = kwargs.get('theta', np.ones(K))
delta = kwargs.get('delta', 3)
Sigma = kwargs.get('Sigma', np.identity(K))
Gamma = kwargs.get('Gamma', np.identity(2))
X = np.random.multivariate_normal(mean=mu, cov=Sigma, size=N)
Xbeta = X.dot(beta)
pscore = logistic.cdf(Xbeta)
D = np.array([np.random.binomial(1, p, size=1) for p in pscore]).flatten()
epsilon = np.random.multivariate_normal(mean=np.zeros(2), cov=Gamma, size=N)
Y0 = Xbeta + epsilon[:,0]
Y1 = delta + X.dot(beta+theta) + epsilon[:,1]
Y = (1-D)*Y0 + D*Y1
if unobservables:
return Y, D, X, Y0, Y1, pscore
else:
return Y, D, X | python | def random_data(N=5000, K=3, unobservables=False, **kwargs):
"""
Function that generates data according to one of two simple models that
satisfies the unconfoundedness assumption.
The covariates and error terms are generated according to
X ~ N(mu, Sigma), epsilon ~ N(0, Gamma).
The counterfactual outcomes are generated by
Y0 = X*beta + epsilon_0,
Y1 = delta + X*(beta+theta) + epsilon_1.
Selection is done according to the following propensity score function:
P(D=1|X) = Lambda(X*beta).
Here Lambda is the standard logistic CDF.
Parameters
----------
N: int
Number of units to draw. Defaults to 5000.
K: int
Number of covariates. Defaults to 3.
unobservables: bool
Returns potential outcomes and true propensity score
in addition to observed outcome and covariates if True.
Defaults to False.
mu, Sigma, Gamma, beta, delta, theta: NumPy ndarrays, optional
Parameter values appearing in data generating process.
Returns
-------
tuple
A tuple in the form of (Y, D, X) or (Y, D, X, Y0, Y1) of
observed outcomes, treatment indicators, covariate matrix,
and potential outomces.
"""
mu = kwargs.get('mu', np.zeros(K))
beta = kwargs.get('beta', np.ones(K))
theta = kwargs.get('theta', np.ones(K))
delta = kwargs.get('delta', 3)
Sigma = kwargs.get('Sigma', np.identity(K))
Gamma = kwargs.get('Gamma', np.identity(2))
X = np.random.multivariate_normal(mean=mu, cov=Sigma, size=N)
Xbeta = X.dot(beta)
pscore = logistic.cdf(Xbeta)
D = np.array([np.random.binomial(1, p, size=1) for p in pscore]).flatten()
epsilon = np.random.multivariate_normal(mean=np.zeros(2), cov=Gamma, size=N)
Y0 = Xbeta + epsilon[:,0]
Y1 = delta + X.dot(beta+theta) + epsilon[:,1]
Y = (1-D)*Y0 + D*Y1
if unobservables:
return Y, D, X, Y0, Y1, pscore
else:
return Y, D, X | [
"def",
"random_data",
"(",
"N",
"=",
"5000",
",",
"K",
"=",
"3",
",",
"unobservables",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"mu",
"=",
"kwargs",
".",
"get",
"(",
"'mu'",
",",
"np",
".",
"zeros",
"(",
"K",
")",
")",
"beta",
"=",
"kwargs",
".",
"get",
"(",
"'beta'",
",",
"np",
".",
"ones",
"(",
"K",
")",
")",
"theta",
"=",
"kwargs",
".",
"get",
"(",
"'theta'",
",",
"np",
".",
"ones",
"(",
"K",
")",
")",
"delta",
"=",
"kwargs",
".",
"get",
"(",
"'delta'",
",",
"3",
")",
"Sigma",
"=",
"kwargs",
".",
"get",
"(",
"'Sigma'",
",",
"np",
".",
"identity",
"(",
"K",
")",
")",
"Gamma",
"=",
"kwargs",
".",
"get",
"(",
"'Gamma'",
",",
"np",
".",
"identity",
"(",
"2",
")",
")",
"X",
"=",
"np",
".",
"random",
".",
"multivariate_normal",
"(",
"mean",
"=",
"mu",
",",
"cov",
"=",
"Sigma",
",",
"size",
"=",
"N",
")",
"Xbeta",
"=",
"X",
".",
"dot",
"(",
"beta",
")",
"pscore",
"=",
"logistic",
".",
"cdf",
"(",
"Xbeta",
")",
"D",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"random",
".",
"binomial",
"(",
"1",
",",
"p",
",",
"size",
"=",
"1",
")",
"for",
"p",
"in",
"pscore",
"]",
")",
".",
"flatten",
"(",
")",
"epsilon",
"=",
"np",
".",
"random",
".",
"multivariate_normal",
"(",
"mean",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
",",
"cov",
"=",
"Gamma",
",",
"size",
"=",
"N",
")",
"Y0",
"=",
"Xbeta",
"+",
"epsilon",
"[",
":",
",",
"0",
"]",
"Y1",
"=",
"delta",
"+",
"X",
".",
"dot",
"(",
"beta",
"+",
"theta",
")",
"+",
"epsilon",
"[",
":",
",",
"1",
"]",
"Y",
"=",
"(",
"1",
"-",
"D",
")",
"*",
"Y0",
"+",
"D",
"*",
"Y1",
"if",
"unobservables",
":",
"return",
"Y",
",",
"D",
",",
"X",
",",
"Y0",
",",
"Y1",
",",
"pscore",
"else",
":",
"return",
"Y",
",",
"D",
",",
"X"
] | Function that generates data according to one of two simple models that
satisfies the unconfoundedness assumption.
The covariates and error terms are generated according to
X ~ N(mu, Sigma), epsilon ~ N(0, Gamma).
The counterfactual outcomes are generated by
Y0 = X*beta + epsilon_0,
Y1 = delta + X*(beta+theta) + epsilon_1.
Selection is done according to the following propensity score function:
P(D=1|X) = Lambda(X*beta).
Here Lambda is the standard logistic CDF.
Parameters
----------
N: int
Number of units to draw. Defaults to 5000.
K: int
Number of covariates. Defaults to 3.
unobservables: bool
Returns potential outcomes and true propensity score
in addition to observed outcome and covariates if True.
Defaults to False.
mu, Sigma, Gamma, beta, delta, theta: NumPy ndarrays, optional
Parameter values appearing in data generating process.
Returns
-------
tuple
A tuple in the form of (Y, D, X) or (Y, D, X, Y0, Y1) of
observed outcomes, treatment indicators, covariate matrix,
and potential outomces. | [
"Function",
"that",
"generates",
"data",
"according",
"to",
"one",
"of",
"two",
"simple",
"models",
"that",
"satisfies",
"the",
"unconfoundedness",
"assumption",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/utils/tools.py#L54-L113 | train | 232,244 |
laurencium/Causalinference | causalinference/core/summary.py | Summary._summarize_pscore | def _summarize_pscore(self, pscore_c, pscore_t):
"""
Called by Strata class during initialization.
"""
self._dict['p_min'] = min(pscore_c.min(), pscore_t.min())
self._dict['p_max'] = max(pscore_c.max(), pscore_t.max())
self._dict['p_c_mean'] = pscore_c.mean()
self._dict['p_t_mean'] = pscore_t.mean() | python | def _summarize_pscore(self, pscore_c, pscore_t):
"""
Called by Strata class during initialization.
"""
self._dict['p_min'] = min(pscore_c.min(), pscore_t.min())
self._dict['p_max'] = max(pscore_c.max(), pscore_t.max())
self._dict['p_c_mean'] = pscore_c.mean()
self._dict['p_t_mean'] = pscore_t.mean() | [
"def",
"_summarize_pscore",
"(",
"self",
",",
"pscore_c",
",",
"pscore_t",
")",
":",
"self",
".",
"_dict",
"[",
"'p_min'",
"]",
"=",
"min",
"(",
"pscore_c",
".",
"min",
"(",
")",
",",
"pscore_t",
".",
"min",
"(",
")",
")",
"self",
".",
"_dict",
"[",
"'p_max'",
"]",
"=",
"max",
"(",
"pscore_c",
".",
"max",
"(",
")",
",",
"pscore_t",
".",
"max",
"(",
")",
")",
"self",
".",
"_dict",
"[",
"'p_c_mean'",
"]",
"=",
"pscore_c",
".",
"mean",
"(",
")",
"self",
".",
"_dict",
"[",
"'p_t_mean'",
"]",
"=",
"pscore_t",
".",
"mean",
"(",
")"
] | Called by Strata class during initialization. | [
"Called",
"by",
"Strata",
"class",
"during",
"initialization",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/core/summary.py#L40-L49 | train | 232,245 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.lookup_bulk | def lookup_bulk(self, ResponseGroup="Large", **kwargs):
"""Lookup Amazon Products in bulk.
Returns all products matching requested ASINs, ignoring invalid
entries.
:return:
A list of :class:`~.AmazonProduct` instances.
"""
response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if not hasattr(root.Items, 'Item'):
return []
return list(
AmazonProduct(
item,
self.aws_associate_tag,
self,
region=self.region) for item in root.Items.Item
) | python | def lookup_bulk(self, ResponseGroup="Large", **kwargs):
"""Lookup Amazon Products in bulk.
Returns all products matching requested ASINs, ignoring invalid
entries.
:return:
A list of :class:`~.AmazonProduct` instances.
"""
response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if not hasattr(root.Items, 'Item'):
return []
return list(
AmazonProduct(
item,
self.aws_associate_tag,
self,
region=self.region) for item in root.Items.Item
) | [
"def",
"lookup_bulk",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"Large\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"ItemLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"not",
"hasattr",
"(",
"root",
".",
"Items",
",",
"'Item'",
")",
":",
"return",
"[",
"]",
"return",
"list",
"(",
"AmazonProduct",
"(",
"item",
",",
"self",
".",
"aws_associate_tag",
",",
"self",
",",
"region",
"=",
"self",
".",
"region",
")",
"for",
"item",
"in",
"root",
".",
"Items",
".",
"Item",
")"
] | Lookup Amazon Products in bulk.
Returns all products matching requested ASINs, ignoring invalid
entries.
:return:
A list of :class:`~.AmazonProduct` instances. | [
"Lookup",
"Amazon",
"Products",
"in",
"bulk",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L200-L219 | train | 232,246 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.similarity_lookup | def similarity_lookup(self, ResponseGroup="Large", **kwargs):
"""Similarty Lookup.
Returns up to ten products that are similar to all items
specified in the request.
Example:
>>> api.similarity_lookup(ItemId='B002L3XLBO,B000LQTBKI')
"""
response = self.api.SimilarityLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
raise SimilartyLookupException(
"Amazon Similarty Lookup Error: '{0}', '{1}'".format(
code, msg))
return [
AmazonProduct(
item,
self.aws_associate_tag,
self.api,
region=self.region
)
for item in getattr(root.Items, 'Item', [])
] | python | def similarity_lookup(self, ResponseGroup="Large", **kwargs):
"""Similarty Lookup.
Returns up to ten products that are similar to all items
specified in the request.
Example:
>>> api.similarity_lookup(ItemId='B002L3XLBO,B000LQTBKI')
"""
response = self.api.SimilarityLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
raise SimilartyLookupException(
"Amazon Similarty Lookup Error: '{0}', '{1}'".format(
code, msg))
return [
AmazonProduct(
item,
self.aws_associate_tag,
self.api,
region=self.region
)
for item in getattr(root.Items, 'Item', [])
] | [
"def",
"similarity_lookup",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"Large\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"SimilarityLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"root",
".",
"Items",
".",
"Request",
".",
"IsValid",
"==",
"'False'",
":",
"code",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Code",
"msg",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Message",
"raise",
"SimilartyLookupException",
"(",
"\"Amazon Similarty Lookup Error: '{0}', '{1}'\"",
".",
"format",
"(",
"code",
",",
"msg",
")",
")",
"return",
"[",
"AmazonProduct",
"(",
"item",
",",
"self",
".",
"aws_associate_tag",
",",
"self",
".",
"api",
",",
"region",
"=",
"self",
".",
"region",
")",
"for",
"item",
"in",
"getattr",
"(",
"root",
".",
"Items",
",",
"'Item'",
",",
"[",
"]",
")",
"]"
] | Similarty Lookup.
Returns up to ten products that are similar to all items
specified in the request.
Example:
>>> api.similarity_lookup(ItemId='B002L3XLBO,B000LQTBKI') | [
"Similarty",
"Lookup",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L221-L247 | train | 232,247 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.browse_node_lookup | def browse_node_lookup(self, ResponseGroup="BrowseNodeInfo", **kwargs):
"""Browse Node Lookup.
Returns the specified browse node's name, children, and ancestors.
Example:
>>> api.browse_node_lookup(BrowseNodeId='163357')
"""
response = self.api.BrowseNodeLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.BrowseNodes.Request.IsValid == 'False':
code = root.BrowseNodes.Request.Errors.Error.Code
msg = root.BrowseNodes.Request.Errors.Error.Message
raise BrowseNodeLookupException(
"Amazon BrowseNode Lookup Error: '{0}', '{1}'".format(
code, msg))
return [AmazonBrowseNode(node.BrowseNode) for node in root.BrowseNodes] | python | def browse_node_lookup(self, ResponseGroup="BrowseNodeInfo", **kwargs):
"""Browse Node Lookup.
Returns the specified browse node's name, children, and ancestors.
Example:
>>> api.browse_node_lookup(BrowseNodeId='163357')
"""
response = self.api.BrowseNodeLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.BrowseNodes.Request.IsValid == 'False':
code = root.BrowseNodes.Request.Errors.Error.Code
msg = root.BrowseNodes.Request.Errors.Error.Message
raise BrowseNodeLookupException(
"Amazon BrowseNode Lookup Error: '{0}', '{1}'".format(
code, msg))
return [AmazonBrowseNode(node.BrowseNode) for node in root.BrowseNodes] | [
"def",
"browse_node_lookup",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"BrowseNodeInfo\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"BrowseNodeLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"root",
".",
"BrowseNodes",
".",
"Request",
".",
"IsValid",
"==",
"'False'",
":",
"code",
"=",
"root",
".",
"BrowseNodes",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Code",
"msg",
"=",
"root",
".",
"BrowseNodes",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Message",
"raise",
"BrowseNodeLookupException",
"(",
"\"Amazon BrowseNode Lookup Error: '{0}', '{1}'\"",
".",
"format",
"(",
"code",
",",
"msg",
")",
")",
"return",
"[",
"AmazonBrowseNode",
"(",
"node",
".",
"BrowseNode",
")",
"for",
"node",
"in",
"root",
".",
"BrowseNodes",
"]"
] | Browse Node Lookup.
Returns the specified browse node's name, children, and ancestors.
Example:
>>> api.browse_node_lookup(BrowseNodeId='163357') | [
"Browse",
"Node",
"Lookup",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L249-L265 | train | 232,248 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.search_n | def search_n(self, n, **kwargs):
"""Search and return first N results..
:param n:
An integer specifying the number of results to return.
:return:
A list of :class:`~.AmazonProduct`.
"""
region = kwargs.get('region', self.region)
kwargs.update({'region': region})
items = AmazonSearch(self.api, self.aws_associate_tag, **kwargs)
return list(islice(items, n)) | python | def search_n(self, n, **kwargs):
"""Search and return first N results..
:param n:
An integer specifying the number of results to return.
:return:
A list of :class:`~.AmazonProduct`.
"""
region = kwargs.get('region', self.region)
kwargs.update({'region': region})
items = AmazonSearch(self.api, self.aws_associate_tag, **kwargs)
return list(islice(items, n)) | [
"def",
"search_n",
"(",
"self",
",",
"n",
",",
"*",
"*",
"kwargs",
")",
":",
"region",
"=",
"kwargs",
".",
"get",
"(",
"'region'",
",",
"self",
".",
"region",
")",
"kwargs",
".",
"update",
"(",
"{",
"'region'",
":",
"region",
"}",
")",
"items",
"=",
"AmazonSearch",
"(",
"self",
".",
"api",
",",
"self",
".",
"aws_associate_tag",
",",
"*",
"*",
"kwargs",
")",
"return",
"list",
"(",
"islice",
"(",
"items",
",",
"n",
")",
")"
] | Search and return first N results..
:param n:
An integer specifying the number of results to return.
:return:
A list of :class:`~.AmazonProduct`. | [
"Search",
"and",
"return",
"first",
"N",
"results",
".."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L277-L288 | train | 232,249 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | LXMLWrapper._safe_get_element_date | def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"""
value = self._safe_get_element_text(path=path, root=root)
if value is not None:
try:
value = dateutil.parser.parse(value)
if value:
value = value.date()
except ValueError:
value = None
return value | python | def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"""
value = self._safe_get_element_text(path=path, root=root)
if value is not None:
try:
value = dateutil.parser.parse(value)
if value:
value = value.date()
except ValueError:
value = None
return value | [
"def",
"_safe_get_element_date",
"(",
"self",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"path",
"=",
"path",
",",
"root",
"=",
"root",
")",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"value",
")",
"if",
"value",
":",
"value",
"=",
"value",
".",
"date",
"(",
")",
"except",
"ValueError",
":",
"value",
"=",
"None",
"return",
"value"
] | Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None. | [
"Safe",
"get",
"elemnent",
"date",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L490-L510 | train | 232,250 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonSearch.iterate_pages | def iterate_pages(self):
"""Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements.
"""
try:
while not self.is_last_page:
self.current_page += 1
yield self._query(ItemPage=self.current_page, **self.kwargs)
except NoMorePages:
pass | python | def iterate_pages(self):
"""Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements.
"""
try:
while not self.is_last_page:
self.current_page += 1
yield self._query(ItemPage=self.current_page, **self.kwargs)
except NoMorePages:
pass | [
"def",
"iterate_pages",
"(",
"self",
")",
":",
"try",
":",
"while",
"not",
"self",
".",
"is_last_page",
":",
"self",
".",
"current_page",
"+=",
"1",
"yield",
"self",
".",
"_query",
"(",
"ItemPage",
"=",
"self",
".",
"current_page",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"except",
"NoMorePages",
":",
"pass"
] | Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements. | [
"Iterate",
"Pages",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L549-L563 | train | 232,251 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonBrowseNode.ancestor | def ancestor(self):
"""This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None.
"""
ancestors = getattr(self.parsed_response, 'Ancestors', None)
if hasattr(ancestors, 'BrowseNode'):
return AmazonBrowseNode(ancestors['BrowseNode'])
return None | python | def ancestor(self):
"""This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None.
"""
ancestors = getattr(self.parsed_response, 'Ancestors', None)
if hasattr(ancestors, 'BrowseNode'):
return AmazonBrowseNode(ancestors['BrowseNode'])
return None | [
"def",
"ancestor",
"(",
"self",
")",
":",
"ancestors",
"=",
"getattr",
"(",
"self",
".",
"parsed_response",
",",
"'Ancestors'",
",",
"None",
")",
"if",
"hasattr",
"(",
"ancestors",
",",
"'BrowseNode'",
")",
":",
"return",
"AmazonBrowseNode",
"(",
"ancestors",
"[",
"'BrowseNode'",
"]",
")",
"return",
"None"
] | This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None. | [
"This",
"browse",
"node",
"s",
"immediate",
"ancestor",
"in",
"the",
"browse",
"node",
"tree",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L624-L633 | train | 232,252 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonBrowseNode.ancestors | def ancestors(self):
"""A list of this browse node's ancestors in the browse node tree.
:return:
List of :class:`~.AmazonBrowseNode` objects.
"""
ancestors = []
node = self.ancestor
while node is not None:
ancestors.append(node)
node = node.ancestor
return ancestors | python | def ancestors(self):
"""A list of this browse node's ancestors in the browse node tree.
:return:
List of :class:`~.AmazonBrowseNode` objects.
"""
ancestors = []
node = self.ancestor
while node is not None:
ancestors.append(node)
node = node.ancestor
return ancestors | [
"def",
"ancestors",
"(",
"self",
")",
":",
"ancestors",
"=",
"[",
"]",
"node",
"=",
"self",
".",
"ancestor",
"while",
"node",
"is",
"not",
"None",
":",
"ancestors",
".",
"append",
"(",
"node",
")",
"node",
"=",
"node",
".",
"ancestor",
"return",
"ancestors"
] | A list of this browse node's ancestors in the browse node tree.
:return:
List of :class:`~.AmazonBrowseNode` objects. | [
"A",
"list",
"of",
"this",
"browse",
"node",
"s",
"ancestors",
"in",
"the",
"browse",
"node",
"tree",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L636-L647 | train | 232,253 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonBrowseNode.children | def children(self):
"""This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree.
"""
children = []
child_nodes = getattr(self.parsed_response, 'Children')
for child in getattr(child_nodes, 'BrowseNode', []):
children.append(AmazonBrowseNode(child))
return children | python | def children(self):
"""This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree.
"""
children = []
child_nodes = getattr(self.parsed_response, 'Children')
for child in getattr(child_nodes, 'BrowseNode', []):
children.append(AmazonBrowseNode(child))
return children | [
"def",
"children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"child_nodes",
"=",
"getattr",
"(",
"self",
".",
"parsed_response",
",",
"'Children'",
")",
"for",
"child",
"in",
"getattr",
"(",
"child_nodes",
",",
"'BrowseNode'",
",",
"[",
"]",
")",
":",
"children",
".",
"append",
"(",
"AmazonBrowseNode",
"(",
"child",
")",
")",
"return",
"children"
] | This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree. | [
"This",
"browse",
"node",
"s",
"children",
"in",
"the",
"browse",
"node",
"tree",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L650-L660 | train | 232,254 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.price_and_currency | def price_and_currency(self):
"""Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
else:
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.CurrencyCode')
else:
price = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.Amount')
currency = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | python | def price_and_currency(self):
"""Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
else:
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.CurrencyCode')
else:
price = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.Amount')
currency = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | [
"def",
"price_and_currency",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.CurrencyCode'",
")",
"if",
"price",
":",
"dprice",
"=",
"Decimal",
"(",
"price",
")",
"/",
"100",
"if",
"'JP'",
"not",
"in",
"self",
".",
"region",
"else",
"Decimal",
"(",
"price",
")",
"return",
"dprice",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] | Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string). | [
"Get",
"Offer",
"Price",
"and",
"Currency",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L687-L724 | train | 232,255 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.reviews | def reviews(self):
"""Customer Reviews.
Get a iframe URL for customer reviews.
:return:
A tuple of: has_reviews (bool), reviews url (string)
"""
iframe = self._safe_get_element_text('CustomerReviews.IFrameURL')
has_reviews = self._safe_get_element_text('CustomerReviews.HasReviews')
if has_reviews is not None and has_reviews == 'true':
has_reviews = True
else:
has_reviews = False
return has_reviews, iframe | python | def reviews(self):
"""Customer Reviews.
Get a iframe URL for customer reviews.
:return:
A tuple of: has_reviews (bool), reviews url (string)
"""
iframe = self._safe_get_element_text('CustomerReviews.IFrameURL')
has_reviews = self._safe_get_element_text('CustomerReviews.HasReviews')
if has_reviews is not None and has_reviews == 'true':
has_reviews = True
else:
has_reviews = False
return has_reviews, iframe | [
"def",
"reviews",
"(",
"self",
")",
":",
"iframe",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'CustomerReviews.IFrameURL'",
")",
"has_reviews",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'CustomerReviews.HasReviews'",
")",
"if",
"has_reviews",
"is",
"not",
"None",
"and",
"has_reviews",
"==",
"'true'",
":",
"has_reviews",
"=",
"True",
"else",
":",
"has_reviews",
"=",
"False",
"return",
"has_reviews",
",",
"iframe"
] | Customer Reviews.
Get a iframe URL for customer reviews.
:return:
A tuple of: has_reviews (bool), reviews url (string) | [
"Customer",
"Reviews",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L954-L968 | train | 232,256 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.editorial_reviews | def editorial_reviews(self):
"""Editorial Review.
Returns a list of all editorial reviews.
:return:
A list containing:
Editorial Review (string)
"""
result = []
reviews_node = self._safe_get_element('EditorialReviews')
if reviews_node is not None:
for review_node in reviews_node.iterchildren():
content_node = getattr(review_node, 'Content')
if content_node is not None:
result.append(content_node.text)
return result | python | def editorial_reviews(self):
"""Editorial Review.
Returns a list of all editorial reviews.
:return:
A list containing:
Editorial Review (string)
"""
result = []
reviews_node = self._safe_get_element('EditorialReviews')
if reviews_node is not None:
for review_node in reviews_node.iterchildren():
content_node = getattr(review_node, 'Content')
if content_node is not None:
result.append(content_node.text)
return result | [
"def",
"editorial_reviews",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"reviews_node",
"=",
"self",
".",
"_safe_get_element",
"(",
"'EditorialReviews'",
")",
"if",
"reviews_node",
"is",
"not",
"None",
":",
"for",
"review_node",
"in",
"reviews_node",
".",
"iterchildren",
"(",
")",
":",
"content_node",
"=",
"getattr",
"(",
"review_node",
",",
"'Content'",
")",
"if",
"content_node",
"is",
"not",
"None",
":",
"result",
".",
"append",
"(",
"content_node",
".",
"text",
")",
"return",
"result"
] | Editorial Review.
Returns a list of all editorial reviews.
:return:
A list containing:
Editorial Review (string) | [
"Editorial",
"Review",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1069-L1087 | train | 232,257 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.list_price | def list_price(self):
"""List Price.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
currency = self._safe_get_element_text(
'ItemAttributes.ListPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | python | def list_price(self):
"""List Price.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
currency = self._safe_get_element_text(
'ItemAttributes.ListPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | [
"def",
"list_price",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'ItemAttributes.ListPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'ItemAttributes.ListPrice.CurrencyCode'",
")",
"if",
"price",
":",
"dprice",
"=",
"Decimal",
"(",
"price",
")",
"/",
"100",
"if",
"'JP'",
"not",
"in",
"self",
".",
"region",
"else",
"Decimal",
"(",
"price",
")",
"return",
"dprice",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] | List Price.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string). | [
"List",
"Price",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1124-L1141 | train | 232,258 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.get_parent | def get_parent(self):
"""Get Parent.
Fetch parent product if it exists.
Use `parent_asin` to check if a parent exist before fetching.
:return:
An instance of :class:`~.AmazonProduct` representing the
parent product.
"""
if not self.parent:
parent = self._safe_get_element('ParentASIN')
if parent:
self.parent = self.api.lookup(ItemId=parent)
return self.parent | python | def get_parent(self):
"""Get Parent.
Fetch parent product if it exists.
Use `parent_asin` to check if a parent exist before fetching.
:return:
An instance of :class:`~.AmazonProduct` representing the
parent product.
"""
if not self.parent:
parent = self._safe_get_element('ParentASIN')
if parent:
self.parent = self.api.lookup(ItemId=parent)
return self.parent | [
"def",
"get_parent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"parent",
"=",
"self",
".",
"_safe_get_element",
"(",
"'ParentASIN'",
")",
"if",
"parent",
":",
"self",
".",
"parent",
"=",
"self",
".",
"api",
".",
"lookup",
"(",
"ItemId",
"=",
"parent",
")",
"return",
"self",
".",
"parent"
] | Get Parent.
Fetch parent product if it exists.
Use `parent_asin` to check if a parent exist before fetching.
:return:
An instance of :class:`~.AmazonProduct` representing the
parent product. | [
"Get",
"Parent",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1196-L1210 | train | 232,259 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.browse_nodes | def browse_nodes(self):
"""Browse Nodes.
:return:
A list of :class:`~.AmazonBrowseNode` objects.
"""
root = self._safe_get_element('BrowseNodes')
if root is None:
return []
return [AmazonBrowseNode(child) for child in root.iterchildren()] | python | def browse_nodes(self):
"""Browse Nodes.
:return:
A list of :class:`~.AmazonBrowseNode` objects.
"""
root = self._safe_get_element('BrowseNodes')
if root is None:
return []
return [AmazonBrowseNode(child) for child in root.iterchildren()] | [
"def",
"browse_nodes",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"_safe_get_element",
"(",
"'BrowseNodes'",
")",
"if",
"root",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"AmazonBrowseNode",
"(",
"child",
")",
"for",
"child",
"in",
"root",
".",
"iterchildren",
"(",
")",
"]"
] | Browse Nodes.
:return:
A list of :class:`~.AmazonBrowseNode` objects. | [
"Browse",
"Nodes",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1213-L1223 | train | 232,260 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.images | def images(self):
"""List of images for a response.
When using lookup with RespnoseGroup 'Images', you'll get a
list of images. Parse them so they are returned in an easily
used list format.
:return:
A list of `ObjectifiedElement` images
"""
try:
images = [image for image in self._safe_get_element(
'ImageSets.ImageSet')]
except TypeError: # No images in this ResponseGroup
images = []
return images | python | def images(self):
"""List of images for a response.
When using lookup with RespnoseGroup 'Images', you'll get a
list of images. Parse them so they are returned in an easily
used list format.
:return:
A list of `ObjectifiedElement` images
"""
try:
images = [image for image in self._safe_get_element(
'ImageSets.ImageSet')]
except TypeError: # No images in this ResponseGroup
images = []
return images | [
"def",
"images",
"(",
"self",
")",
":",
"try",
":",
"images",
"=",
"[",
"image",
"for",
"image",
"in",
"self",
".",
"_safe_get_element",
"(",
"'ImageSets.ImageSet'",
")",
"]",
"except",
"TypeError",
":",
"# No images in this ResponseGroup",
"images",
"=",
"[",
"]",
"return",
"images"
] | List of images for a response.
When using lookup with RespnoseGroup 'Images', you'll get a
list of images. Parse them so they are returned in an easily
used list format.
:return:
A list of `ObjectifiedElement` images | [
"List",
"of",
"images",
"for",
"a",
"response",
".",
"When",
"using",
"lookup",
"with",
"RespnoseGroup",
"Images",
"you",
"ll",
"get",
"a",
"list",
"of",
"images",
".",
"Parse",
"them",
"so",
"they",
"are",
"returned",
"in",
"an",
"easily",
"used",
"list",
"format",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1226-L1240 | train | 232,261 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.actors | def actors(self):
"""Movie Actors.
:return:
A list of actors names.
"""
result = []
actors = self._safe_get_element('ItemAttributes.Actor') or []
for actor in actors:
result.append(actor.text)
return result | python | def actors(self):
"""Movie Actors.
:return:
A list of actors names.
"""
result = []
actors = self._safe_get_element('ItemAttributes.Actor') or []
for actor in actors:
result.append(actor.text)
return result | [
"def",
"actors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"actors",
"=",
"self",
".",
"_safe_get_element",
"(",
"'ItemAttributes.Actor'",
")",
"or",
"[",
"]",
"for",
"actor",
"in",
"actors",
":",
"result",
".",
"append",
"(",
"actor",
".",
"text",
")",
"return",
"result"
] | Movie Actors.
:return:
A list of actors names. | [
"Movie",
"Actors",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1252-L1262 | train | 232,262 |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.directors | def directors(self):
"""Movie Directors.
:return:
A list of directors for a movie.
"""
result = []
directors = self._safe_get_element('ItemAttributes.Director') or []
for director in directors:
result.append(director.text)
return result | python | def directors(self):
"""Movie Directors.
:return:
A list of directors for a movie.
"""
result = []
directors = self._safe_get_element('ItemAttributes.Director') or []
for director in directors:
result.append(director.text)
return result | [
"def",
"directors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"directors",
"=",
"self",
".",
"_safe_get_element",
"(",
"'ItemAttributes.Director'",
")",
"or",
"[",
"]",
"for",
"director",
"in",
"directors",
":",
"result",
".",
"append",
"(",
"director",
".",
"text",
")",
"return",
"result"
] | Movie Directors.
:return:
A list of directors for a movie. | [
"Movie",
"Directors",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1265-L1275 | train | 232,263 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.getMibSymbol | def getMibSymbol(self):
"""Returns MIB variable symbolic identification.
Returns
-------
str
MIB module name
str
MIB variable symbolic name
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
class instance representing MIB variable instance index.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
>>>
"""
if self._state & self.ST_CLEAN:
return self._modName, self._symName, self._indices
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | python | def getMibSymbol(self):
"""Returns MIB variable symbolic identification.
Returns
-------
str
MIB module name
str
MIB variable symbolic name
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
class instance representing MIB variable instance index.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
>>>
"""
if self._state & self.ST_CLEAN:
return self._modName, self._symName, self._indices
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | [
"def",
"getMibSymbol",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_modName",
",",
"self",
".",
"_symName",
",",
"self",
".",
"_indices",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Returns MIB variable symbolic identification.
Returns
-------
str
MIB module name
str
MIB variable symbolic name
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
class instance representing MIB variable instance index.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
>>> | [
"Returns",
"MIB",
"variable",
"symbolic",
"identification",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L98-L128 | train | 232,264 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.getOid | def getOid(self):
"""Returns OID identifying MIB variable.
Returns
-------
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
full OID identifying MIB variable including possible index part.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
ObjectName('1.3.6.1.2.1.1.1.0')
>>>
"""
if self._state & self.ST_CLEAN:
return self._oid
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | python | def getOid(self):
"""Returns OID identifying MIB variable.
Returns
-------
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
full OID identifying MIB variable including possible index part.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
ObjectName('1.3.6.1.2.1.1.1.0')
>>>
"""
if self._state & self.ST_CLEAN:
return self._oid
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | [
"def",
"getOid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_oid",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Returns OID identifying MIB variable.
Returns
-------
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
full OID identifying MIB variable including possible index part.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
ObjectName('1.3.6.1.2.1.1.1.0')
>>> | [
"Returns",
"OID",
"identifying",
"MIB",
"variable",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L130-L156 | train | 232,265 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.getLabel | def getLabel(self):
"""Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
towards this MIB variable.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Notes
-----
Returned sequence may not contain full path to this MIB variable
if some symbols are now known at the moment of MIB look up.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>>
"""
if self._state & self.ST_CLEAN:
return self._label
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | python | def getLabel(self):
"""Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
towards this MIB variable.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Notes
-----
Returned sequence may not contain full path to this MIB variable
if some symbols are now known at the moment of MIB look up.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>>
"""
if self._state & self.ST_CLEAN:
return self._label
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | [
"def",
"getLabel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_label",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
towards this MIB variable.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Notes
-----
Returned sequence may not contain full path to this MIB variable
if some symbols are now known at the moment of MIB look up.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>> | [
"Returns",
"symbolic",
"path",
"to",
"this",
"MIB",
"variable",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L158-L193 | train | 232,266 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.addMibSource | def addMibSource(self, *mibSources):
"""Adds path to repository to search PySNMP MIB files.
Parameters
----------
*mibSources :
one or more paths to search or Python package names to import
and search for PySNMP MIB modules.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Notes
-----
Normally, ASN.1-to-Python MIB modules conversion is performed
automatically through PySNMP/PySMI interaction. ASN1 MIB modules
could also be manually compiled into Python via the
`mibdump.py <http://snmplabs.com/pysmi/mibdump.html>`_
tool.
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
"""
if self._mibSourcesToAdd is None:
self._mibSourcesToAdd = mibSources
else:
self._mibSourcesToAdd += mibSources
return self | python | def addMibSource(self, *mibSources):
"""Adds path to repository to search PySNMP MIB files.
Parameters
----------
*mibSources :
one or more paths to search or Python package names to import
and search for PySNMP MIB modules.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Notes
-----
Normally, ASN.1-to-Python MIB modules conversion is performed
automatically through PySNMP/PySMI interaction. ASN1 MIB modules
could also be manually compiled into Python via the
`mibdump.py <http://snmplabs.com/pysmi/mibdump.html>`_
tool.
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
"""
if self._mibSourcesToAdd is None:
self._mibSourcesToAdd = mibSources
else:
self._mibSourcesToAdd += mibSources
return self | [
"def",
"addMibSource",
"(",
"self",
",",
"*",
"mibSources",
")",
":",
"if",
"self",
".",
"_mibSourcesToAdd",
"is",
"None",
":",
"self",
".",
"_mibSourcesToAdd",
"=",
"mibSources",
"else",
":",
"self",
".",
"_mibSourcesToAdd",
"+=",
"mibSources",
"return",
"self"
] | Adds path to repository to search PySNMP MIB files.
Parameters
----------
*mibSources :
one or more paths to search or Python package names to import
and search for PySNMP MIB modules.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Notes
-----
Normally, ASN.1-to-Python MIB modules conversion is performed
automatically through PySNMP/PySMI interaction. ASN1 MIB modules
could also be manually compiled into Python via the
`mibdump.py <http://snmplabs.com/pysmi/mibdump.html>`_
tool.
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>> | [
"Adds",
"path",
"to",
"repository",
"to",
"search",
"PySNMP",
"MIB",
"files",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L253-L287 | train | 232,267 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.loadMibs | def loadMibs(self, *modNames):
"""Schedules search and load of given MIB modules.
Parameters
----------
*modNames:
one or more MIB module names to load up and use for MIB
variables resolution purposes.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
"""
if self._modNamesToLoad is None:
self._modNamesToLoad = modNames
else:
self._modNamesToLoad += modNames
return self | python | def loadMibs(self, *modNames):
"""Schedules search and load of given MIB modules.
Parameters
----------
*modNames:
one or more MIB module names to load up and use for MIB
variables resolution purposes.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
"""
if self._modNamesToLoad is None:
self._modNamesToLoad = modNames
else:
self._modNamesToLoad += modNames
return self | [
"def",
"loadMibs",
"(",
"self",
",",
"*",
"modNames",
")",
":",
"if",
"self",
".",
"_modNamesToLoad",
"is",
"None",
":",
"self",
".",
"_modNamesToLoad",
"=",
"modNames",
"else",
":",
"self",
".",
"_modNamesToLoad",
"+=",
"modNames",
"return",
"self"
] | Schedules search and load of given MIB modules.
Parameters
----------
*modNames:
one or more MIB module names to load up and use for MIB
variables resolution purposes.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>> | [
"Schedules",
"search",
"and",
"load",
"of",
"given",
"MIB",
"modules",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L290-L316 | train | 232,268 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectType.resolveWithMib | def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method involves
:py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
method invocation.
Examples
--------
>>> from pysmi.hlapi import varbinds
>>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
>>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
>>> objectType.resolveWithMib(mibViewController)
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
>>> str(objectType)
'SNMPv2-MIB::sysDescr."0" = Linux i386'
>>>
"""
if self._state & self.ST_CLEAM:
return self
self._args[0].resolveWithMib(mibViewController)
MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'MibScalar', 'MibTableColumn')
if not isinstance(self._args[0].getMibNode(),
(MibScalar, MibTableColumn)):
if not isinstance(self._args[1], AbstractSimpleAsn1Item):
raise SmiError('MIB object %r is not OBJECT-TYPE '
'(MIB not loaded?)' % (self._args[0],))
self._state |= self.ST_CLEAM
return self
if isinstance(self._args[1], (rfc1905.UnSpecified,
rfc1905.NoSuchObject,
rfc1905.NoSuchInstance,
rfc1905.EndOfMibView)):
self._state |= self.ST_CLEAM
return self
syntax = self._args[0].getMibNode().getSyntax()
try:
self._args[1] = syntax.clone(self._args[1])
except PyAsn1Error as exc:
raise SmiError(
'MIB object %r having type %r failed to cast value '
'%r: %s' % (self._args[0].prettyPrint(),
syntax.__class__.__name__, self._args[1], exc))
if rfc1902.ObjectIdentifier().isSuperTypeOf(
self._args[1], matchConstraints=False):
self._args[1] = ObjectIdentity(
self._args[1]).resolveWithMib(mibViewController)
self._state |= self.ST_CLEAM
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r syntax is %r' % (self._args[0], self._args[1]))
return self | python | def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method involves
:py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
method invocation.
Examples
--------
>>> from pysmi.hlapi import varbinds
>>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
>>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
>>> objectType.resolveWithMib(mibViewController)
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
>>> str(objectType)
'SNMPv2-MIB::sysDescr."0" = Linux i386'
>>>
"""
if self._state & self.ST_CLEAM:
return self
self._args[0].resolveWithMib(mibViewController)
MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'MibScalar', 'MibTableColumn')
if not isinstance(self._args[0].getMibNode(),
(MibScalar, MibTableColumn)):
if not isinstance(self._args[1], AbstractSimpleAsn1Item):
raise SmiError('MIB object %r is not OBJECT-TYPE '
'(MIB not loaded?)' % (self._args[0],))
self._state |= self.ST_CLEAM
return self
if isinstance(self._args[1], (rfc1905.UnSpecified,
rfc1905.NoSuchObject,
rfc1905.NoSuchInstance,
rfc1905.EndOfMibView)):
self._state |= self.ST_CLEAM
return self
syntax = self._args[0].getMibNode().getSyntax()
try:
self._args[1] = syntax.clone(self._args[1])
except PyAsn1Error as exc:
raise SmiError(
'MIB object %r having type %r failed to cast value '
'%r: %s' % (self._args[0].prettyPrint(),
syntax.__class__.__name__, self._args[1], exc))
if rfc1902.ObjectIdentifier().isSuperTypeOf(
self._args[1], matchConstraints=False):
self._args[1] = ObjectIdentity(
self._args[1]).resolveWithMib(mibViewController)
self._state |= self.ST_CLEAM
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r syntax is %r' % (self._args[0], self._args[1]))
return self | [
"def",
"resolveWithMib",
"(",
"self",
",",
"mibViewController",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAM",
":",
"return",
"self",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"MibScalar",
",",
"MibTableColumn",
"=",
"mibViewController",
".",
"mibBuilder",
".",
"importSymbols",
"(",
"'SNMPv2-SMI'",
",",
"'MibScalar'",
",",
"'MibTableColumn'",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"getMibNode",
"(",
")",
",",
"(",
"MibScalar",
",",
"MibTableColumn",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"AbstractSimpleAsn1Item",
")",
":",
"raise",
"SmiError",
"(",
"'MIB object %r is not OBJECT-TYPE '",
"'(MIB not loaded?)'",
"%",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
",",
")",
")",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAM",
"return",
"self",
"if",
"isinstance",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"(",
"rfc1905",
".",
"UnSpecified",
",",
"rfc1905",
".",
"NoSuchObject",
",",
"rfc1905",
".",
"NoSuchInstance",
",",
"rfc1905",
".",
"EndOfMibView",
")",
")",
":",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAM",
"return",
"self",
"syntax",
"=",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"getMibNode",
"(",
")",
".",
"getSyntax",
"(",
")",
"try",
":",
"self",
".",
"_args",
"[",
"1",
"]",
"=",
"syntax",
".",
"clone",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
")",
"except",
"PyAsn1Error",
"as",
"exc",
":",
"raise",
"SmiError",
"(",
"'MIB object %r having type %r failed to cast value '",
"'%r: %s'",
"%",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"prettyPrint",
"(",
")",
",",
"syntax",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"exc",
")",
")",
"if",
"rfc1902",
".",
"ObjectIdentifier",
"(",
")",
".",
"isSuperTypeOf",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"matchConstraints",
"=",
"False",
")",
":",
"self",
".",
"_args",
"[",
"1",
"]",
"=",
"ObjectIdentity",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
")",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAM",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'resolved %r syntax is %r'",
"%",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
",",
"self",
".",
"_args",
"[",
"1",
"]",
")",
")",
"return",
"self"
] | Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method involves
:py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
method invocation.
Examples
--------
>>> from pysmi.hlapi import varbinds
>>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
>>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
>>> objectType.resolveWithMib(mibViewController)
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
>>> str(objectType)
'SNMPv2-MIB::sysDescr."0" = Linux i386'
>>> | [
"Perform",
"MIB",
"variable",
"ID",
"and",
"associated",
"value",
"conversion",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L911-L993 | train | 232,269 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | NotificationType.addVarBinds | def addVarBinds(self, *varBinds):
"""Appends variable-binding to notification.
Parameters
----------
*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Notes
-----
This method can be used to add custom variable-bindings to
notification message in addition to MIB variables specified
in NOTIFICATION-TYPE->OBJECTS clause.
Examples
--------
>>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
>>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
>>>
"""
debug.logger & debug.FLAG_MIB and debug.logger(
'additional var-binds: %r' % (varBinds,))
if self._state & self.ST_CLEAN:
raise SmiError(
'%s object is already sealed' % self.__class__.__name__)
else:
self._additionalVarBinds.extend(varBinds)
return self | python | def addVarBinds(self, *varBinds):
"""Appends variable-binding to notification.
Parameters
----------
*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Notes
-----
This method can be used to add custom variable-bindings to
notification message in addition to MIB variables specified
in NOTIFICATION-TYPE->OBJECTS clause.
Examples
--------
>>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
>>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
>>>
"""
debug.logger & debug.FLAG_MIB and debug.logger(
'additional var-binds: %r' % (varBinds,))
if self._state & self.ST_CLEAN:
raise SmiError(
'%s object is already sealed' % self.__class__.__name__)
else:
self._additionalVarBinds.extend(varBinds)
return self | [
"def",
"addVarBinds",
"(",
"self",
",",
"*",
"varBinds",
")",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'additional var-binds: %r'",
"%",
"(",
"varBinds",
",",
")",
")",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"raise",
"SmiError",
"(",
"'%s object is already sealed'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"self",
".",
"_additionalVarBinds",
".",
"extend",
"(",
"varBinds",
")",
"return",
"self"
] | Appends variable-binding to notification.
Parameters
----------
*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Notes
-----
This method can be used to add custom variable-bindings to
notification message in addition to MIB variables specified
in NOTIFICATION-TYPE->OBJECTS clause.
Examples
--------
>>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
>>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
>>> | [
"Appends",
"variable",
"-",
"binding",
"to",
"notification",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L1096-L1133 | train | 232,270 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | NotificationType.resolveWithMib | def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID conversion and notification objects expansion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method might cause the following sequence of
events (exact details depends on many factors):
* :py:meth:`pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` is called
* MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause,
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instances are created
from MIB variable OID and `indexInstance` suffix.
* `objects` dictionary is queried for each MIB variable OID,
acquired values are added to corresponding MIB variable
Examples
--------
>>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))
>>> notificationType.resolveWithMib(mibViewController)
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>
"""
if self._state & self.ST_CLEAN:
return self
self._objectIdentity.resolveWithMib(mibViewController)
self._varBinds.append(
ObjectType(ObjectIdentity(v2c.apiTrapPDU.snmpTrapOID),
self._objectIdentity).resolveWithMib(mibViewController))
SmiNotificationType, = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'NotificationType')
mibNode = self._objectIdentity.getMibNode()
varBindsLocation = {}
if isinstance(mibNode, SmiNotificationType):
for notificationObject in mibNode.getObjects():
objectIdentity = ObjectIdentity(
*notificationObject + self._instanceIndex)
objectIdentity.resolveWithMib(mibViewController)
objectType = ObjectType(
objectIdentity, self._objects.get(
notificationObject, rfc1905.unSpecified))
objectType.resolveWithMib(mibViewController)
self._varBinds.append(objectType)
varBindsLocation[objectIdentity] = len(self._varBinds) - 1
else:
debug.logger & debug.FLAG_MIB and debug.logger(
'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not '
'loaded?)' % (self._objectIdentity,))
for varBinds in self._additionalVarBinds:
if not isinstance(varBinds, ObjectType):
varBinds = ObjectType(ObjectIdentity(varBinds[0]), varBinds[1])
varBinds.resolveWithMib(mibViewController)
if varBinds[0] in varBindsLocation:
self._varBinds[varBindsLocation[varBinds[0]]] = varBinds
else:
self._varBinds.append(varBinds)
self._additionalVarBinds = []
self._state |= self.ST_CLEAN
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r into %r' % (self._objectIdentity, self._varBinds))
return self | python | def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID conversion and notification objects expansion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method might cause the following sequence of
events (exact details depends on many factors):
* :py:meth:`pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` is called
* MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause,
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instances are created
from MIB variable OID and `indexInstance` suffix.
* `objects` dictionary is queried for each MIB variable OID,
acquired values are added to corresponding MIB variable
Examples
--------
>>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))
>>> notificationType.resolveWithMib(mibViewController)
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>
"""
if self._state & self.ST_CLEAN:
return self
self._objectIdentity.resolveWithMib(mibViewController)
self._varBinds.append(
ObjectType(ObjectIdentity(v2c.apiTrapPDU.snmpTrapOID),
self._objectIdentity).resolveWithMib(mibViewController))
SmiNotificationType, = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'NotificationType')
mibNode = self._objectIdentity.getMibNode()
varBindsLocation = {}
if isinstance(mibNode, SmiNotificationType):
for notificationObject in mibNode.getObjects():
objectIdentity = ObjectIdentity(
*notificationObject + self._instanceIndex)
objectIdentity.resolveWithMib(mibViewController)
objectType = ObjectType(
objectIdentity, self._objects.get(
notificationObject, rfc1905.unSpecified))
objectType.resolveWithMib(mibViewController)
self._varBinds.append(objectType)
varBindsLocation[objectIdentity] = len(self._varBinds) - 1
else:
debug.logger & debug.FLAG_MIB and debug.logger(
'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not '
'loaded?)' % (self._objectIdentity,))
for varBinds in self._additionalVarBinds:
if not isinstance(varBinds, ObjectType):
varBinds = ObjectType(ObjectIdentity(varBinds[0]), varBinds[1])
varBinds.resolveWithMib(mibViewController)
if varBinds[0] in varBindsLocation:
self._varBinds[varBindsLocation[varBinds[0]]] = varBinds
else:
self._varBinds.append(varBinds)
self._additionalVarBinds = []
self._state |= self.ST_CLEAN
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r into %r' % (self._objectIdentity, self._varBinds))
return self | [
"def",
"resolveWithMib",
"(",
"self",
",",
"mibViewController",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
"self",
".",
"_objectIdentity",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"self",
".",
"_varBinds",
".",
"append",
"(",
"ObjectType",
"(",
"ObjectIdentity",
"(",
"v2c",
".",
"apiTrapPDU",
".",
"snmpTrapOID",
")",
",",
"self",
".",
"_objectIdentity",
")",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
")",
"SmiNotificationType",
",",
"=",
"mibViewController",
".",
"mibBuilder",
".",
"importSymbols",
"(",
"'SNMPv2-SMI'",
",",
"'NotificationType'",
")",
"mibNode",
"=",
"self",
".",
"_objectIdentity",
".",
"getMibNode",
"(",
")",
"varBindsLocation",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"mibNode",
",",
"SmiNotificationType",
")",
":",
"for",
"notificationObject",
"in",
"mibNode",
".",
"getObjects",
"(",
")",
":",
"objectIdentity",
"=",
"ObjectIdentity",
"(",
"*",
"notificationObject",
"+",
"self",
".",
"_instanceIndex",
")",
"objectIdentity",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"objectType",
"=",
"ObjectType",
"(",
"objectIdentity",
",",
"self",
".",
"_objects",
".",
"get",
"(",
"notificationObject",
",",
"rfc1905",
".",
"unSpecified",
")",
")",
"objectType",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"self",
".",
"_varBinds",
".",
"append",
"(",
"objectType",
")",
"varBindsLocation",
"[",
"objectIdentity",
"]",
"=",
"len",
"(",
"self",
".",
"_varBinds",
")",
"-",
"1",
"else",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not '",
"'loaded?)'",
"%",
"(",
"self",
".",
"_objectIdentity",
",",
")",
")",
"for",
"varBinds",
"in",
"self",
".",
"_additionalVarBinds",
":",
"if",
"not",
"isinstance",
"(",
"varBinds",
",",
"ObjectType",
")",
":",
"varBinds",
"=",
"ObjectType",
"(",
"ObjectIdentity",
"(",
"varBinds",
"[",
"0",
"]",
")",
",",
"varBinds",
"[",
"1",
"]",
")",
"varBinds",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"if",
"varBinds",
"[",
"0",
"]",
"in",
"varBindsLocation",
":",
"self",
".",
"_varBinds",
"[",
"varBindsLocation",
"[",
"varBinds",
"[",
"0",
"]",
"]",
"]",
"=",
"varBinds",
"else",
":",
"self",
".",
"_varBinds",
".",
"append",
"(",
"varBinds",
")",
"self",
".",
"_additionalVarBinds",
"=",
"[",
"]",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAN",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'resolved %r into %r'",
"%",
"(",
"self",
".",
"_objectIdentity",
",",
"self",
".",
"_varBinds",
")",
")",
"return",
"self"
] | Perform MIB variable ID conversion and notification objects expansion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method might cause the following sequence of
events (exact details depends on many factors):
* :py:meth:`pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` is called
* MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause,
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instances are created
from MIB variable OID and `indexInstance` suffix.
* `objects` dictionary is queried for each MIB variable OID,
acquired values are added to corresponding MIB variable
Examples
--------
>>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))
>>> notificationType.resolveWithMib(mibViewController)
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>> | [
"Perform",
"MIB",
"variable",
"ID",
"conversion",
"and",
"notification",
"objects",
"expansion",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L1224-L1319 | train | 232,271 |
etingof/pysnmp | pysnmp/proto/rfc1902.py | Integer32.withValues | def withValues(cls, *values):
"""Creates a subclass with discreet values constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values)
X.__name__ = cls.__name__
return X | python | def withValues(cls, *values):
"""Creates a subclass with discreet values constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values)
X.__name__ = cls.__name__
return X | [
"def",
"withValues",
"(",
"cls",
",",
"*",
"values",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"SingleValueConstraint",
"(",
"*",
"values",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with discreet values constraint. | [
"Creates",
"a",
"subclass",
"with",
"discreet",
"values",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L93-L102 | train | 232,272 |
etingof/pysnmp | pysnmp/proto/rfc1902.py | Integer32.withRange | def withRange(cls, minimum, maximum):
"""Creates a subclass with value range constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | python | def withRange(cls, minimum, maximum):
"""Creates a subclass with value range constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | [
"def",
"withRange",
"(",
"cls",
",",
"minimum",
",",
"maximum",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"ValueRangeConstraint",
"(",
"minimum",
",",
"maximum",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with value range constraint. | [
"Creates",
"a",
"subclass",
"with",
"value",
"range",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L105-L114 | train | 232,273 |
etingof/pysnmp | pysnmp/proto/rfc1902.py | Integer.withNamedValues | def withNamedValues(cls, **values):
"""Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values.values())
X.__name__ = cls.__name__
return X | python | def withNamedValues(cls, **values):
"""Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values.values())
X.__name__ = cls.__name__
return X | [
"def",
"withNamedValues",
"(",
"cls",
",",
"*",
"*",
"values",
")",
":",
"enums",
"=",
"set",
"(",
"cls",
".",
"namedValues",
".",
"items",
"(",
")",
")",
"enums",
".",
"update",
"(",
"values",
".",
"items",
"(",
")",
")",
"class",
"X",
"(",
"cls",
")",
":",
"namedValues",
"=",
"namedval",
".",
"NamedValues",
"(",
"*",
"enums",
")",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"SingleValueConstraint",
"(",
"*",
"values",
".",
"values",
"(",
")",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way. | [
"Create",
"a",
"subclass",
"with",
"discreet",
"named",
"values",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L162-L177 | train | 232,274 |
etingof/pysnmp | pysnmp/proto/rfc1902.py | OctetString.withSize | def withSize(cls, minimum, maximum):
"""Creates a subclass with value size constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | python | def withSize(cls, minimum, maximum):
"""Creates a subclass with value size constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | [
"def",
"withSize",
"(",
"cls",
",",
"minimum",
",",
"maximum",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"ValueSizeConstraint",
"(",
"minimum",
",",
"maximum",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with value size constraint. | [
"Creates",
"a",
"subclass",
"with",
"value",
"size",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L248-L257 | train | 232,275 |
etingof/pysnmp | pysnmp/proto/rfc1902.py | Bits.withNamedBits | def withNamedBits(cls, **values):
"""Creates a subclass with discreet named bits constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
X.__name__ = cls.__name__
return X | python | def withNamedBits(cls, **values):
"""Creates a subclass with discreet named bits constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
X.__name__ = cls.__name__
return X | [
"def",
"withNamedBits",
"(",
"cls",
",",
"*",
"*",
"values",
")",
":",
"enums",
"=",
"set",
"(",
"cls",
".",
"namedValues",
".",
"items",
"(",
")",
")",
"enums",
".",
"update",
"(",
"values",
".",
"items",
"(",
")",
")",
"class",
"X",
"(",
"cls",
")",
":",
"namedValues",
"=",
"namedval",
".",
"NamedValues",
"(",
"*",
"enums",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with discreet named bits constraint.
Reduce fully duplicate enumerations along the way. | [
"Creates",
"a",
"subclass",
"with",
"discreet",
"named",
"bits",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L698-L710 | train | 232,276 |
etingof/pysnmp | pysnmp/smi/builder.py | MibBuilder.loadModule | def loadModule(self, modName, **userCtx):
"""Load and execute MIB modules as Python code"""
for mibSource in self._mibSources:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: trying %s at %s' % (modName, mibSource))
try:
codeObj, sfx = mibSource.read(modName)
except IOError as exc:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: read %s from %s failed: '
'%s' % (modName, mibSource, exc))
continue
modPath = mibSource.fullPath(modName, sfx)
if modPath in self._modPathsSeen:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: seen %s' % modPath)
break
else:
self._modPathsSeen.add(modPath)
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: evaluating %s' % modPath)
g = {'mibBuilder': self,
'userCtx': userCtx}
try:
exec(codeObj, g)
except Exception:
self._modPathsSeen.remove(modPath)
raise error.MibLoadError(
'MIB module "%s" load error: '
'%s' % (modPath, traceback.format_exception(*sys.exc_info())))
self._modSeen[modName] = modPath
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: loaded %s' % modPath)
break
if modName not in self._modSeen:
raise error.MibNotFoundError(
'MIB file "%s" not found in search path '
'(%s)' % (modName and modName + ".py[co]", ', '.join(
[str(x) for x in self._mibSources])))
return self | python | def loadModule(self, modName, **userCtx):
"""Load and execute MIB modules as Python code"""
for mibSource in self._mibSources:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: trying %s at %s' % (modName, mibSource))
try:
codeObj, sfx = mibSource.read(modName)
except IOError as exc:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: read %s from %s failed: '
'%s' % (modName, mibSource, exc))
continue
modPath = mibSource.fullPath(modName, sfx)
if modPath in self._modPathsSeen:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: seen %s' % modPath)
break
else:
self._modPathsSeen.add(modPath)
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: evaluating %s' % modPath)
g = {'mibBuilder': self,
'userCtx': userCtx}
try:
exec(codeObj, g)
except Exception:
self._modPathsSeen.remove(modPath)
raise error.MibLoadError(
'MIB module "%s" load error: '
'%s' % (modPath, traceback.format_exception(*sys.exc_info())))
self._modSeen[modName] = modPath
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: loaded %s' % modPath)
break
if modName not in self._modSeen:
raise error.MibNotFoundError(
'MIB file "%s" not found in search path '
'(%s)' % (modName and modName + ".py[co]", ', '.join(
[str(x) for x in self._mibSources])))
return self | [
"def",
"loadModule",
"(",
"self",
",",
"modName",
",",
"*",
"*",
"userCtx",
")",
":",
"for",
"mibSource",
"in",
"self",
".",
"_mibSources",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: trying %s at %s'",
"%",
"(",
"modName",
",",
"mibSource",
")",
")",
"try",
":",
"codeObj",
",",
"sfx",
"=",
"mibSource",
".",
"read",
"(",
"modName",
")",
"except",
"IOError",
"as",
"exc",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: read %s from %s failed: '",
"'%s'",
"%",
"(",
"modName",
",",
"mibSource",
",",
"exc",
")",
")",
"continue",
"modPath",
"=",
"mibSource",
".",
"fullPath",
"(",
"modName",
",",
"sfx",
")",
"if",
"modPath",
"in",
"self",
".",
"_modPathsSeen",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: seen %s'",
"%",
"modPath",
")",
"break",
"else",
":",
"self",
".",
"_modPathsSeen",
".",
"add",
"(",
"modPath",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: evaluating %s'",
"%",
"modPath",
")",
"g",
"=",
"{",
"'mibBuilder'",
":",
"self",
",",
"'userCtx'",
":",
"userCtx",
"}",
"try",
":",
"exec",
"(",
"codeObj",
",",
"g",
")",
"except",
"Exception",
":",
"self",
".",
"_modPathsSeen",
".",
"remove",
"(",
"modPath",
")",
"raise",
"error",
".",
"MibLoadError",
"(",
"'MIB module \"%s\" load error: '",
"'%s'",
"%",
"(",
"modPath",
",",
"traceback",
".",
"format_exception",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
")",
")",
"self",
".",
"_modSeen",
"[",
"modName",
"]",
"=",
"modPath",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: loaded %s'",
"%",
"modPath",
")",
"break",
"if",
"modName",
"not",
"in",
"self",
".",
"_modSeen",
":",
"raise",
"error",
".",
"MibNotFoundError",
"(",
"'MIB file \"%s\" not found in search path '",
"'(%s)'",
"%",
"(",
"modName",
"and",
"modName",
"+",
"\".py[co]\"",
",",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_mibSources",
"]",
")",
")",
")",
"return",
"self"
] | Load and execute MIB modules as Python code | [
"Load",
"and",
"execute",
"MIB",
"modules",
"as",
"Python",
"code"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/builder.py#L354-L407 | train | 232,277 |
etingof/pysnmp | pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py | nextCmd | def nextCmd(snmpDispatcher, authData, transportTarget,
*varBinds, **options):
"""Create a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication: str
True value indicates SNMP engine error.
errorStatus: str
True value indicates SNMP PDU error.
errorIndex: int
Non-zero value refers to `varBinds[errorIndex-1]`
varBindTable: tuple
A 2-dimensional array of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing a table of MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = nextCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
"""
def cbFun(*args, **kwargs):
response[:] = args + (kwargs.get('nextVarBinds', ()),)
options['cbFun'] = cbFun
lexicographicMode = options.pop('lexicographicMode', True)
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
totalRows = totalCalls = 0
errorIndication, errorStatus, errorIndex, varBindTable = None, 0, 0, ()
response = []
while True:
if not varBinds:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
cmdgen.nextCmd(snmpDispatcher, authData, transportTarget,
*[(x[0], Null('')) for x in varBinds], **options)
snmpDispatcher.transportDispatcher.runDispatcher()
errorIndication, errorStatus, errorIndex, varBindTable, varBinds = response
if errorIndication:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
else:
varBindRow = varBindTable and varBindTable[-1]
if not lexicographicMode:
for idx, varBind in enumerate(varBindRow):
name, val = varBind
if not isinstance(val, Null):
if initialVarBinds[idx][0].isPrefixOf(name):
break
else:
return
for varBindRow in varBindTable:
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
totalRows += 1
totalCalls += 1
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | python | def nextCmd(snmpDispatcher, authData, transportTarget,
*varBinds, **options):
"""Create a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication: str
True value indicates SNMP engine error.
errorStatus: str
True value indicates SNMP PDU error.
errorIndex: int
Non-zero value refers to `varBinds[errorIndex-1]`
varBindTable: tuple
A 2-dimensional array of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing a table of MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = nextCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
"""
def cbFun(*args, **kwargs):
response[:] = args + (kwargs.get('nextVarBinds', ()),)
options['cbFun'] = cbFun
lexicographicMode = options.pop('lexicographicMode', True)
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
totalRows = totalCalls = 0
errorIndication, errorStatus, errorIndex, varBindTable = None, 0, 0, ()
response = []
while True:
if not varBinds:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
cmdgen.nextCmd(snmpDispatcher, authData, transportTarget,
*[(x[0], Null('')) for x in varBinds], **options)
snmpDispatcher.transportDispatcher.runDispatcher()
errorIndication, errorStatus, errorIndex, varBindTable, varBinds = response
if errorIndication:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
else:
varBindRow = varBindTable and varBindTable[-1]
if not lexicographicMode:
for idx, varBind in enumerate(varBindRow):
name, val = varBind
if not isinstance(val, Null):
if initialVarBinds[idx][0].isPrefixOf(name):
break
else:
return
for varBindRow in varBindTable:
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
totalRows += 1
totalCalls += 1
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | [
"def",
"nextCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"cbFun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"[",
":",
"]",
"=",
"args",
"+",
"(",
"kwargs",
".",
"get",
"(",
"'nextVarBinds'",
",",
"(",
")",
")",
",",
")",
"options",
"[",
"'cbFun'",
"]",
"=",
"cbFun",
"lexicographicMode",
"=",
"options",
".",
"pop",
"(",
"'lexicographicMode'",
",",
"True",
")",
"maxRows",
"=",
"options",
".",
"pop",
"(",
"'maxRows'",
",",
"0",
")",
"maxCalls",
"=",
"options",
".",
"pop",
"(",
"'maxCalls'",
",",
"0",
")",
"initialVarBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"varBinds",
")",
"totalRows",
"=",
"totalCalls",
"=",
"0",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"=",
"None",
",",
"0",
",",
"0",
",",
"(",
")",
"response",
"=",
"[",
"]",
"while",
"True",
":",
"if",
"not",
"varBinds",
":",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"and",
"varBindTable",
"[",
"0",
"]",
"or",
"[",
"]",
")",
"return",
"cmdgen",
".",
"nextCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"*",
"[",
"(",
"x",
"[",
"0",
"]",
",",
"Null",
"(",
"''",
")",
")",
"for",
"x",
"in",
"varBinds",
"]",
",",
"*",
"*",
"options",
")",
"snmpDispatcher",
".",
"transportDispatcher",
".",
"runDispatcher",
"(",
")",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"varBinds",
"=",
"response",
"if",
"errorIndication",
":",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"and",
"varBindTable",
"[",
"0",
"]",
"or",
"[",
"]",
")",
"return",
"elif",
"errorStatus",
":",
"if",
"errorStatus",
"==",
"2",
":",
"# Hide SNMPv1 noSuchName error which leaks in here",
"# from SNMPv1 Agent through internal pysnmp proxy.",
"errorStatus",
"=",
"errorStatus",
".",
"clone",
"(",
"0",
")",
"errorIndex",
"=",
"errorIndex",
".",
"clone",
"(",
"0",
")",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"and",
"varBindTable",
"[",
"0",
"]",
"or",
"[",
"]",
")",
"return",
"else",
":",
"varBindRow",
"=",
"varBindTable",
"and",
"varBindTable",
"[",
"-",
"1",
"]",
"if",
"not",
"lexicographicMode",
":",
"for",
"idx",
",",
"varBind",
"in",
"enumerate",
"(",
"varBindRow",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"if",
"not",
"isinstance",
"(",
"val",
",",
"Null",
")",
":",
"if",
"initialVarBinds",
"[",
"idx",
"]",
"[",
"0",
"]",
".",
"isPrefixOf",
"(",
"name",
")",
":",
"break",
"else",
":",
"return",
"for",
"varBindRow",
"in",
"varBindTable",
":",
"nextVarBinds",
"=",
"(",
"yield",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindRow",
")",
"if",
"nextVarBinds",
":",
"initialVarBinds",
"=",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"nextVarBinds",
")",
"totalRows",
"+=",
"1",
"totalCalls",
"+=",
"1",
"if",
"maxRows",
"and",
"totalRows",
">=",
"maxRows",
":",
"return",
"if",
"maxCalls",
"and",
"totalCalls",
">=",
"maxCalls",
":",
"return"
] | Create a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication: str
True value indicates SNMP engine error.
errorStatus: str
True value indicates SNMP PDU error.
errorIndex: int
Non-zero value refers to `varBinds[errorIndex-1]`
varBindTable: tuple
A 2-dimensional array of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing a table of MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = nextCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) | [
"Create",
"a",
"generator",
"to",
"perform",
"one",
"or",
"more",
"SNMP",
"GETNEXT",
"queries",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py#L201-L363 | train | 232,278 |
etingof/pysnmp | pysnmp/proto/rfc3412.py | MsgAndPduDispatcher.registerContextEngineId | def registerContextEngineId(self, contextEngineId, pduTypes, processPdu):
"""Register application with dispatcher"""
# 4.3.2 -> no-op
# 4.3.3
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
raise error.ProtocolError(
'Duplicate registration %r/%s' % (contextEngineId, pduType))
# 4.3.4
self._appsRegistration[k] = processPdu
debug.logger & debug.FLAG_DSP and debug.logger(
'registerContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | python | def registerContextEngineId(self, contextEngineId, pduTypes, processPdu):
"""Register application with dispatcher"""
# 4.3.2 -> no-op
# 4.3.3
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
raise error.ProtocolError(
'Duplicate registration %r/%s' % (contextEngineId, pduType))
# 4.3.4
self._appsRegistration[k] = processPdu
debug.logger & debug.FLAG_DSP and debug.logger(
'registerContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | [
"def",
"registerContextEngineId",
"(",
"self",
",",
"contextEngineId",
",",
"pduTypes",
",",
"processPdu",
")",
":",
"# 4.3.2 -> no-op",
"# 4.3.3",
"for",
"pduType",
"in",
"pduTypes",
":",
"k",
"=",
"contextEngineId",
",",
"pduType",
"if",
"k",
"in",
"self",
".",
"_appsRegistration",
":",
"raise",
"error",
".",
"ProtocolError",
"(",
"'Duplicate registration %r/%s'",
"%",
"(",
"contextEngineId",
",",
"pduType",
")",
")",
"# 4.3.4",
"self",
".",
"_appsRegistration",
"[",
"k",
"]",
"=",
"processPdu",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_DSP",
"and",
"debug",
".",
"logger",
"(",
"'registerContextEngineId: contextEngineId %r pduTypes '",
"'%s'",
"%",
"(",
"contextEngineId",
",",
"pduTypes",
")",
")"
] | Register application with dispatcher | [
"Register",
"application",
"with",
"dispatcher"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc3412.py#L64-L80 | train | 232,279 |
etingof/pysnmp | pysnmp/proto/rfc3412.py | MsgAndPduDispatcher.unregisterContextEngineId | def unregisterContextEngineId(self, contextEngineId, pduTypes):
"""Unregister application with dispatcher"""
# 4.3.4
if contextEngineId is None:
# Default to local snmpEngineId
contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols(
'__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
del self._appsRegistration[k]
debug.logger & debug.FLAG_DSP and debug.logger(
'unregisterContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | python | def unregisterContextEngineId(self, contextEngineId, pduTypes):
"""Unregister application with dispatcher"""
# 4.3.4
if contextEngineId is None:
# Default to local snmpEngineId
contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols(
'__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
del self._appsRegistration[k]
debug.logger & debug.FLAG_DSP and debug.logger(
'unregisterContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | [
"def",
"unregisterContextEngineId",
"(",
"self",
",",
"contextEngineId",
",",
"pduTypes",
")",
":",
"# 4.3.4",
"if",
"contextEngineId",
"is",
"None",
":",
"# Default to local snmpEngineId",
"contextEngineId",
",",
"=",
"self",
".",
"mibInstrumController",
".",
"mibBuilder",
".",
"importSymbols",
"(",
"'__SNMP-FRAMEWORK-MIB'",
",",
"'snmpEngineID'",
")",
"for",
"pduType",
"in",
"pduTypes",
":",
"k",
"=",
"contextEngineId",
",",
"pduType",
"if",
"k",
"in",
"self",
".",
"_appsRegistration",
":",
"del",
"self",
".",
"_appsRegistration",
"[",
"k",
"]",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_DSP",
"and",
"debug",
".",
"logger",
"(",
"'unregisterContextEngineId: contextEngineId %r pduTypes '",
"'%s'",
"%",
"(",
"contextEngineId",
",",
"pduTypes",
")",
")"
] | Unregister application with dispatcher | [
"Unregister",
"application",
"with",
"dispatcher"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc3412.py#L83-L99 | train | 232,280 |
etingof/pysnmp | pysnmp/hlapi/v3arch/twisted/ntforg.py | sendNotification | def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
"""Sends SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM message
(:RFC:`1905#section-4.2.6`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine: :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData: :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData: :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
notifyType: str
Indicates type of notification to be sent. Recognized literal
values are *trap* or *inform*.
\*varBinds: :class:`tuple` of OID-value pairs or :py:class:`~pysnmp.smi.rfc1902.ObjectType` or :py:class:`~pysnmp.smi.rfc1902.NotificationType`
One or more objects representing MIB variables to place
into SNMP notification. It could be tuples of OID-values
or :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
of :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects.
SNMP Notification PDU includes some housekeeping items that
are required for SNMP to function.
Agent information:
* SNMPv2-MIB::sysUpTime.0 = <agent uptime>
* SNMPv2-SMI::snmpTrapOID.0 = {SNMPv2-MIB::coldStart, ...}
Applicable to SNMP v1 TRAP:
* SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = <agent-IP>
* SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = <snmp-community-name>
* SNMP-COMMUNITY-MIB::snmpTrapEnterprise.0 = <enterprise-OID>
.. note::
Unless user passes some of these variable-bindings, `.sendNotification()`
call will fill in the missing items.
User variable-bindings:
* SNMPv2-SMI::NOTIFICATION-TYPE
* SNMPv2-SMI::OBJECT-TYPE
.. note::
The :py:class:`~pysnmp.smi.rfc1902.NotificationType` object ensures
properly formed SNMP notification (to comply MIB definition). If you
build notification PDU out of :py:class:`~pysnmp.smi.rfc1902.ObjectType`
objects or simple tuples of OID-value objects, it is your responsibility
to provide well-formed notification payload.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) : A sequence of
:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing
MIB variables returned in SNMP response.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBinds) = args
... print(errorStatus, errorIndex, varBind)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = sendNotification(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [])
"""
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
lookupMib, deferred = cbCtx
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBinds = VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib)
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBinds))
notifyName = LCD.configure(snmpEngine, authData, transportTarget,
notifyType, contextData.contextName)
def __trapFun(deferred):
deferred.callback((0, 0, []))
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
ntforg.NotificationOriginator().sendVarBinds(
snmpEngine, notifyName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred)
)
if notifyType == 'trap':
reactor.callLater(0, __trapFun, deferred)
return deferred | python | def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
"""Sends SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM message
(:RFC:`1905#section-4.2.6`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine: :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData: :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData: :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
notifyType: str
Indicates type of notification to be sent. Recognized literal
values are *trap* or *inform*.
\*varBinds: :class:`tuple` of OID-value pairs or :py:class:`~pysnmp.smi.rfc1902.ObjectType` or :py:class:`~pysnmp.smi.rfc1902.NotificationType`
One or more objects representing MIB variables to place
into SNMP notification. It could be tuples of OID-values
or :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
of :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects.
SNMP Notification PDU includes some housekeeping items that
are required for SNMP to function.
Agent information:
* SNMPv2-MIB::sysUpTime.0 = <agent uptime>
* SNMPv2-SMI::snmpTrapOID.0 = {SNMPv2-MIB::coldStart, ...}
Applicable to SNMP v1 TRAP:
* SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = <agent-IP>
* SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = <snmp-community-name>
* SNMP-COMMUNITY-MIB::snmpTrapEnterprise.0 = <enterprise-OID>
.. note::
Unless user passes some of these variable-bindings, `.sendNotification()`
call will fill in the missing items.
User variable-bindings:
* SNMPv2-SMI::NOTIFICATION-TYPE
* SNMPv2-SMI::OBJECT-TYPE
.. note::
The :py:class:`~pysnmp.smi.rfc1902.NotificationType` object ensures
properly formed SNMP notification (to comply MIB definition). If you
build notification PDU out of :py:class:`~pysnmp.smi.rfc1902.ObjectType`
objects or simple tuples of OID-value objects, it is your responsibility
to provide well-formed notification payload.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) : A sequence of
:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing
MIB variables returned in SNMP response.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBinds) = args
... print(errorStatus, errorIndex, varBind)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = sendNotification(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [])
"""
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
lookupMib, deferred = cbCtx
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBinds = VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib)
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBinds))
notifyName = LCD.configure(snmpEngine, authData, transportTarget,
notifyType, contextData.contextName)
def __trapFun(deferred):
deferred.callback((0, 0, []))
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
ntforg.NotificationOriginator().sendVarBinds(
snmpEngine, notifyName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred)
)
if notifyType == 'trap':
reactor.callLater(0, __trapFun, deferred)
return deferred | [
"def",
"sendNotification",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"notifyType",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"__cbFun",
"(",
"snmpEngine",
",",
"sendRequestHandle",
",",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
",",
"cbCtx",
")",
":",
"lookupMib",
",",
"deferred",
"=",
"cbCtx",
"if",
"errorIndication",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"errorIndication",
")",
")",
"else",
":",
"try",
":",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"unmakeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
",",
"lookupMib",
")",
"except",
"Exception",
"as",
"e",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"e",
")",
")",
"else",
":",
"deferred",
".",
"callback",
"(",
"(",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
")",
"notifyName",
"=",
"LCD",
".",
"configure",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"notifyType",
",",
"contextData",
".",
"contextName",
")",
"def",
"__trapFun",
"(",
"deferred",
")",
":",
"deferred",
".",
"callback",
"(",
"(",
"0",
",",
"0",
",",
"[",
"]",
")",
")",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"deferred",
"=",
"Deferred",
"(",
")",
"ntforg",
".",
"NotificationOriginator",
"(",
")",
".",
"sendVarBinds",
"(",
"snmpEngine",
",",
"notifyName",
",",
"contextData",
".",
"contextEngineId",
",",
"contextData",
".",
"contextName",
",",
"varBinds",
",",
"__cbFun",
",",
"(",
"options",
".",
"get",
"(",
"'lookupMib'",
",",
"True",
")",
",",
"deferred",
")",
")",
"if",
"notifyType",
"==",
"'trap'",
":",
"reactor",
".",
"callLater",
"(",
"0",
",",
"__trapFun",
",",
"deferred",
")",
"return",
"deferred"
] | Sends SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM message
(:RFC:`1905#section-4.2.6`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine: :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData: :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData: :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
notifyType: str
Indicates type of notification to be sent. Recognized literal
values are *trap* or *inform*.
\*varBinds: :class:`tuple` of OID-value pairs or :py:class:`~pysnmp.smi.rfc1902.ObjectType` or :py:class:`~pysnmp.smi.rfc1902.NotificationType`
One or more objects representing MIB variables to place
into SNMP notification. It could be tuples of OID-values
or :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
of :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects.
SNMP Notification PDU includes some housekeeping items that
are required for SNMP to function.
Agent information:
* SNMPv2-MIB::sysUpTime.0 = <agent uptime>
* SNMPv2-SMI::snmpTrapOID.0 = {SNMPv2-MIB::coldStart, ...}
Applicable to SNMP v1 TRAP:
* SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = <agent-IP>
* SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = <snmp-community-name>
* SNMP-COMMUNITY-MIB::snmpTrapEnterprise.0 = <enterprise-OID>
.. note::
Unless user passes some of these variable-bindings, `.sendNotification()`
call will fill in the missing items.
User variable-bindings:
* SNMPv2-SMI::NOTIFICATION-TYPE
* SNMPv2-SMI::OBJECT-TYPE
.. note::
The :py:class:`~pysnmp.smi.rfc1902.NotificationType` object ensures
properly formed SNMP notification (to comply MIB definition). If you
build notification PDU out of :py:class:`~pysnmp.smi.rfc1902.ObjectType`
objects or simple tuples of OID-value objects, it is your responsibility
to provide well-formed notification payload.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) : A sequence of
:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing
MIB variables returned in SNMP response.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBinds) = args
... print(errorStatus, errorIndex, varBind)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = sendNotification(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, []) | [
"Sends",
"SNMP",
"notification",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/twisted/ntforg.py#L25-L189 | train | 232,281 |
etingof/pysnmp | pysnmp/hlapi/v3arch/twisted/cmdgen.py | nextCmd | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Performs SNMP GETNEXT query.
Based on passed parameters, prepares SNMP GETNEXT packet
(:RFC:`1905#section-4.2.2`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) :
A sequence of sequences (e.g. 2-D array) of
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response.
Inner sequences represent table rows and ordered exactly the same
as `varBinds` in request. Response to GETNEXT always contain
a single row.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBindTable) = args
... print(errorStatus, errorIndex, varBindTable)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
"""
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
lookupMib, deferred = cbCtx
if (options.get('ignoreNonIncreasingOid', False) and errorIndication
and isinstance(errorIndication, errind.OidNotIncreasing)):
errorIndication = None
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
varBindTableRow, lookupMib)
for varBindTableRow in varBindTable
]
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBindTable))
addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred))
return deferred | python | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Performs SNMP GETNEXT query.
Based on passed parameters, prepares SNMP GETNEXT packet
(:RFC:`1905#section-4.2.2`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) :
A sequence of sequences (e.g. 2-D array) of
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response.
Inner sequences represent table rows and ordered exactly the same
as `varBinds` in request. Response to GETNEXT always contain
a single row.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBindTable) = args
... print(errorStatus, errorIndex, varBindTable)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
"""
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
lookupMib, deferred = cbCtx
if (options.get('ignoreNonIncreasingOid', False) and errorIndication
and isinstance(errorIndication, errind.OidNotIncreasing)):
errorIndication = None
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
varBindTableRow, lookupMib)
for varBindTableRow in varBindTable
]
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBindTable))
addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred))
return deferred | [
"def",
"nextCmd",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"__cbFun",
"(",
"snmpEngine",
",",
"sendRequestHandle",
",",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"cbCtx",
")",
":",
"lookupMib",
",",
"deferred",
"=",
"cbCtx",
"if",
"(",
"options",
".",
"get",
"(",
"'ignoreNonIncreasingOid'",
",",
"False",
")",
"and",
"errorIndication",
"and",
"isinstance",
"(",
"errorIndication",
",",
"errind",
".",
"OidNotIncreasing",
")",
")",
":",
"errorIndication",
"=",
"None",
"if",
"errorIndication",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"errorIndication",
")",
")",
"else",
":",
"try",
":",
"varBindTable",
"=",
"[",
"VB_PROCESSOR",
".",
"unmakeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBindTableRow",
",",
"lookupMib",
")",
"for",
"varBindTableRow",
"in",
"varBindTable",
"]",
"except",
"Exception",
"as",
"e",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"e",
")",
")",
"else",
":",
"deferred",
".",
"callback",
"(",
"(",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
")",
")",
"addrName",
",",
"paramsName",
"=",
"LCD",
".",
"configure",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
".",
"contextName",
")",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"deferred",
"=",
"Deferred",
"(",
")",
"cmdgen",
".",
"NextCommandGenerator",
"(",
")",
".",
"sendVarBinds",
"(",
"snmpEngine",
",",
"addrName",
",",
"contextData",
".",
"contextEngineId",
",",
"contextData",
".",
"contextName",
",",
"varBinds",
",",
"__cbFun",
",",
"(",
"options",
".",
"get",
"(",
"'lookupMib'",
",",
"True",
")",
",",
"deferred",
")",
")",
"return",
"deferred"
] | Performs SNMP GETNEXT query.
Based on passed parameters, prepares SNMP GETNEXT packet
(:RFC:`1905#section-4.2.2`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) :
A sequence of sequences (e.g. 2-D array) of
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response.
Inner sequences represent table rows and ordered exactly the same
as `varBinds` in request. Response to GETNEXT always contain
a single row.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBindTable) = args
... print(errorStatus, errorIndex, varBindTable)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]]) | [
"Performs",
"SNMP",
"GETNEXT",
"query",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/twisted/cmdgen.py#L268-L401 | train | 232,282 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.getBranch | def getBranch(self, name, **context):
"""Return a branch of this tree where the 'name' OID may reside"""
for keyLen in self._vars.getKeysLens():
subName = name[:keyLen]
if subName in self._vars:
return self._vars[subName]
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | python | def getBranch(self, name, **context):
"""Return a branch of this tree where the 'name' OID may reside"""
for keyLen in self._vars.getKeysLens():
subName = name[:keyLen]
if subName in self._vars:
return self._vars[subName]
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | [
"def",
"getBranch",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"for",
"keyLen",
"in",
"self",
".",
"_vars",
".",
"getKeysLens",
"(",
")",
":",
"subName",
"=",
"name",
"[",
":",
"keyLen",
"]",
"if",
"subName",
"in",
"self",
".",
"_vars",
":",
"return",
"self",
".",
"_vars",
"[",
"subName",
"]",
"raise",
"error",
".",
"NoSuchObjectError",
"(",
"name",
"=",
"name",
",",
"idx",
"=",
"context",
".",
"get",
"(",
"'idx'",
")",
")"
] | Return a branch of this tree where the 'name' OID may reside | [
"Return",
"a",
"branch",
"of",
"this",
"tree",
"where",
"the",
"name",
"OID",
"may",
"reside"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L455-L462 | train | 232,283 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.getNode | def getNode(self, name, **context):
"""Return tree node found by name"""
if name == self.name:
return self
else:
return self.getBranch(name, **context).getNode(name, **context) | python | def getNode(self, name, **context):
"""Return tree node found by name"""
if name == self.name:
return self
else:
return self.getBranch(name, **context).getNode(name, **context) | [
"def",
"getNode",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"if",
"name",
"==",
"self",
".",
"name",
":",
"return",
"self",
"else",
":",
"return",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
".",
"getNode",
"(",
"name",
",",
"*",
"*",
"context",
")"
] | Return tree node found by name | [
"Return",
"tree",
"node",
"found",
"by",
"name"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L478-L483 | train | 232,284 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.getNextNode | def getNextNode(self, name, **context):
"""Return tree node next to name"""
try:
nextNode = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
return self.getNextBranch(name, **context)
else:
try:
return nextNode.getNextNode(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
try:
return self._vars[self._vars.nextKey(nextNode.name)]
except KeyError:
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | python | def getNextNode(self, name, **context):
"""Return tree node next to name"""
try:
nextNode = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
return self.getNextBranch(name, **context)
else:
try:
return nextNode.getNextNode(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
try:
return self._vars[self._vars.nextKey(nextNode.name)]
except KeyError:
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | [
"def",
"getNextNode",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"try",
":",
"nextNode",
"=",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
"except",
"(",
"error",
".",
"NoSuchInstanceError",
",",
"error",
".",
"NoSuchObjectError",
")",
":",
"return",
"self",
".",
"getNextBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
"else",
":",
"try",
":",
"return",
"nextNode",
".",
"getNextNode",
"(",
"name",
",",
"*",
"*",
"context",
")",
"except",
"(",
"error",
".",
"NoSuchInstanceError",
",",
"error",
".",
"NoSuchObjectError",
")",
":",
"try",
":",
"return",
"self",
".",
"_vars",
"[",
"self",
".",
"_vars",
".",
"nextKey",
"(",
"nextNode",
".",
"name",
")",
"]",
"except",
"KeyError",
":",
"raise",
"error",
".",
"NoSuchObjectError",
"(",
"name",
"=",
"name",
",",
"idx",
"=",
"context",
".",
"get",
"(",
"'idx'",
")",
")"
] | Return tree node next to name | [
"Return",
"tree",
"node",
"next",
"to",
"name"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L485-L498 | train | 232,285 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.writeCommit | def writeCommit(self, varBind, **context):
"""Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Instances are modified at
once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to set
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if idx in instances[self.ST_CREATE]:
self.createCommit(varBind, **context)
return
if idx in instances[self.ST_DESTROY]:
self.destroyCommit(varBind, **context)
return
try:
node = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc:
cbFun(varBind, **dict(context, error=exc))
else:
node.writeCommit(varBind, **context) | python | def writeCommit(self, varBind, **context):
"""Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Instances are modified at
once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to set
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if idx in instances[self.ST_CREATE]:
self.createCommit(varBind, **context)
return
if idx in instances[self.ST_DESTROY]:
self.destroyCommit(varBind, **context)
return
try:
node = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc:
cbFun(varBind, **dict(context, error=exc))
else:
node.writeCommit(varBind, **context) | [
"def",
"writeCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeCommit(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"if",
"idx",
"in",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
":",
"self",
".",
"createCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"if",
"idx",
"in",
"instances",
"[",
"self",
".",
"ST_DESTROY",
"]",
":",
"self",
".",
"destroyCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"try",
":",
"node",
"=",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
"except",
"(",
"error",
".",
"NoSuchInstanceError",
",",
"error",
".",
"NoSuchObjectError",
")",
"as",
"exc",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"error",
"=",
"exc",
")",
")",
"else",
":",
"node",
".",
"writeCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Instances are modified at
once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to set
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Commit",
"new",
"value",
"of",
"the",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L860-L925 | train | 232,286 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.readGet | def readGet(self, varBind, **context):
"""Read Managed Object Instance.
Implements the second of the two phases of the SNMP GET command
processing (:RFC:`1905#section-4.2.1`).
The goal of the second phase is to actually read the requested Managed
Object Instance. When multiple Managed Objects Instances are read at
once (likely coming all in one SNMP PDU), each of them has to run through
the first (*test*) and second (*read) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) has the same signature as
this method where `varBind` contains read Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
if name == self.name:
cbFun((name, exval.noSuchInstance), **context)
return
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
cbFun((name, exval.noSuchInstance), **context)
return
ManagedMibObject.readGet(self, varBind, **context) | python | def readGet(self, varBind, **context):
"""Read Managed Object Instance.
Implements the second of the two phases of the SNMP GET command
processing (:RFC:`1905#section-4.2.1`).
The goal of the second phase is to actually read the requested Managed
Object Instance. When multiple Managed Objects Instances are read at
once (likely coming all in one SNMP PDU), each of them has to run through
the first (*test*) and second (*read) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) has the same signature as
this method where `varBind` contains read Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
if name == self.name:
cbFun((name, exval.noSuchInstance), **context)
return
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
cbFun((name, exval.noSuchInstance), **context)
return
ManagedMibObject.readGet(self, varBind, **context) | [
"def",
"readGet",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: readGet(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"if",
"name",
"==",
"self",
".",
"name",
":",
"cbFun",
"(",
"(",
"name",
",",
"exval",
".",
"noSuchInstance",
")",
",",
"*",
"*",
"context",
")",
"return",
"acFun",
"=",
"context",
".",
"get",
"(",
"'acFun'",
")",
"if",
"acFun",
":",
"if",
"(",
"self",
".",
"maxAccess",
"not",
"in",
"(",
"'readonly'",
",",
"'readwrite'",
",",
"'readcreate'",
")",
"or",
"acFun",
"(",
"'read'",
",",
"(",
"name",
",",
"self",
".",
"syntax",
")",
",",
"*",
"*",
"context",
")",
")",
":",
"cbFun",
"(",
"(",
"name",
",",
"exval",
".",
"noSuchInstance",
")",
",",
"*",
"*",
"context",
")",
"return",
"ManagedMibObject",
".",
"readGet",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")"
] | Read Managed Object Instance.
Implements the second of the two phases of the SNMP GET command
processing (:RFC:`1905#section-4.2.1`).
The goal of the second phase is to actually read the requested Managed
Object Instance. When multiple Managed Objects Instances are read at
once (likely coming all in one SNMP PDU), each of them has to run through
the first (*test*) and second (*read) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) has the same signature as
this method where `varBind` contains read Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Read",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1139-L1203 | train | 232,287 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.readGetNext | def readGetNext(self, varBind, **context):
"""Read the next Managed Object Instance.
Implements the second of the two phases of the SNMP GETNEXT command
processing (:RFC:`1905#section-4.2.2`).
The goal of the second phase is to actually read the Managed Object
Instance which is next in the MIB tree to the one being requested.
When multiple Managed Objects Instances are read at once (likely coming
all in one SNMP PDU), each of them has to run through the first
(*testnext*) and second (*getnext*) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance (the *next* one in the MIB tree
relative to the one being requested) or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the Managed Object Instance which is *next*
to the one being requested. If not supplied, no access control
will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) have the same signature
as this method where `varBind` contains read Managed Object Instance
value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
nextName = context.get('nextName')
if nextName:
varBind = nextName, exval.noSuchInstance
else:
varBind = name, exval.endOfMibView
cbFun = context['cbFun']
cbFun(varBind, **context)
return
ManagedMibObject.readGetNext(self, varBind, **context) | python | def readGetNext(self, varBind, **context):
"""Read the next Managed Object Instance.
Implements the second of the two phases of the SNMP GETNEXT command
processing (:RFC:`1905#section-4.2.2`).
The goal of the second phase is to actually read the Managed Object
Instance which is next in the MIB tree to the one being requested.
When multiple Managed Objects Instances are read at once (likely coming
all in one SNMP PDU), each of them has to run through the first
(*testnext*) and second (*getnext*) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance (the *next* one in the MIB tree
relative to the one being requested) or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the Managed Object Instance which is *next*
to the one being requested. If not supplied, no access control
will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) have the same signature
as this method where `varBind` contains read Managed Object Instance
value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
nextName = context.get('nextName')
if nextName:
varBind = nextName, exval.noSuchInstance
else:
varBind = name, exval.endOfMibView
cbFun = context['cbFun']
cbFun(varBind, **context)
return
ManagedMibObject.readGetNext(self, varBind, **context) | [
"def",
"readGetNext",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: readGetNext(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"acFun",
"=",
"context",
".",
"get",
"(",
"'acFun'",
")",
"if",
"acFun",
":",
"if",
"(",
"self",
".",
"maxAccess",
"not",
"in",
"(",
"'readonly'",
",",
"'readwrite'",
",",
"'readcreate'",
")",
"or",
"acFun",
"(",
"'read'",
",",
"(",
"name",
",",
"self",
".",
"syntax",
")",
",",
"*",
"*",
"context",
")",
")",
":",
"nextName",
"=",
"context",
".",
"get",
"(",
"'nextName'",
")",
"if",
"nextName",
":",
"varBind",
"=",
"nextName",
",",
"exval",
".",
"noSuchInstance",
"else",
":",
"varBind",
"=",
"name",
",",
"exval",
".",
"endOfMibView",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"ManagedMibObject",
".",
"readGetNext",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")"
] | Read the next Managed Object Instance.
Implements the second of the two phases of the SNMP GETNEXT command
processing (:RFC:`1905#section-4.2.2`).
The goal of the second phase is to actually read the Managed Object
Instance which is next in the MIB tree to the one being requested.
When multiple Managed Objects Instances are read at once (likely coming
all in one SNMP PDU), each of them has to run through the first
(*testnext*) and second (*getnext*) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance (the *next* one in the MIB tree
relative to the one being requested) or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the Managed Object Instance which is *next*
to the one being requested. If not supplied, no access control
will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) have the same signature
as this method where `varBind` contains read Managed Object Instance
value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Read",
"the",
"next",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1205-L1274 | train | 232,288 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.createCommit | def createCommit(self, varBind, **context):
"""Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object Instance. When multiple Managed Objects Instances are created/modified
at once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if name in self._vars:
cbFun(varBind, **context)
return
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
self._vars[name], instances[self.ST_CREATE][-idx - 1] = instances[self.ST_CREATE][idx], self._vars.get(name)
instances[self.ST_CREATE][idx].writeCommit(varBind, **context) | python | def createCommit(self, varBind, **context):
"""Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object Instance. When multiple Managed Objects Instances are created/modified
at once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if name in self._vars:
cbFun(varBind, **context)
return
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
self._vars[name], instances[self.ST_CREATE][-idx - 1] = instances[self.ST_CREATE][idx], self._vars.get(name)
instances[self.ST_CREATE][idx].writeCommit(varBind, **context) | [
"def",
"createCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeCommit(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"if",
"name",
"in",
"self",
".",
"_vars",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"# NOTE: multiple names are possible in a single PDU, that could collide",
"# Therefore let's keep old object indexed by (negative) var-bind index",
"self",
".",
"_vars",
"[",
"name",
"]",
",",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
"[",
"-",
"idx",
"-",
"1",
"]",
"=",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
"[",
"idx",
"]",
",",
"self",
".",
"_vars",
".",
"get",
"(",
"name",
")",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
"[",
"idx",
"]",
".",
"writeCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object Instance. When multiple Managed Objects Instances are created/modified
at once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Create",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1420-L1481 | train | 232,289 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.createCleanup | def createCleanup(self, varBind, **context):
"""Finalize Managed Object Instance creation.
Implements the successful third step of the multi-step workflow similar to
the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new Managed Object
Instance. Once the system transitions into the *cleanup* state, no roll back
to the previous Managed Object Instance state is possible.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
self.branchVersionId += 1
instances[self.ST_CREATE].pop(-idx - 1, None)
self._vars[name].writeCleanup(varBind, **context) | python | def createCleanup(self, varBind, **context):
"""Finalize Managed Object Instance creation.
Implements the successful third step of the multi-step workflow similar to
the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new Managed Object
Instance. Once the system transitions into the *cleanup* state, no roll back
to the previous Managed Object Instance state is possible.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
self.branchVersionId += 1
instances[self.ST_CREATE].pop(-idx - 1, None)
self._vars[name].writeCleanup(varBind, **context) | [
"def",
"createCleanup",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: createCleanup(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"self",
".",
"branchVersionId",
"+=",
"1",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
".",
"pop",
"(",
"-",
"idx",
"-",
"1",
",",
"None",
")",
"self",
".",
"_vars",
"[",
"name",
"]",
".",
"writeCleanup",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Finalize Managed Object Instance creation.
Implements the successful third step of the multi-step workflow similar to
the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new Managed Object
Instance. Once the system transitions into the *cleanup* state, no roll back
to the previous Managed Object Instance state is possible.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Finalize",
"Managed",
"Object",
"Instance",
"creation",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1483-L1534 | train | 232,290 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableColumn.destroyCommit | def destroyCommit(self, varBind, **context):
"""Destroy Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually remove requested Managed
Object Instance from the MIB tree. When multiple Managed Objects Instances
are destroyed/modified at once (likely coming all in one SNMP PDU), each
of them has to run through the second (*commit*) phase successfully for
the system to transition to the third (*cleanup*) phase. If any single
*commit* step fails, the system transitions into the *undo* state for
each of Managed Objects Instances being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to destroy
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being destroyed.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyCommit(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
try:
instances[self.ST_DESTROY][-idx - 1] = self._vars.pop(name)
except KeyError:
pass
cbFun = context['cbFun']
cbFun(varBind, **context) | python | def destroyCommit(self, varBind, **context):
"""Destroy Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually remove requested Managed
Object Instance from the MIB tree. When multiple Managed Objects Instances
are destroyed/modified at once (likely coming all in one SNMP PDU), each
of them has to run through the second (*commit*) phase successfully for
the system to transition to the third (*cleanup*) phase. If any single
*commit* step fails, the system transitions into the *undo* state for
each of Managed Objects Instances being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to destroy
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being destroyed.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyCommit(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
try:
instances[self.ST_DESTROY][-idx - 1] = self._vars.pop(name)
except KeyError:
pass
cbFun = context['cbFun']
cbFun(varBind, **context) | [
"def",
"destroyCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: destroyCommit(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"# NOTE: multiple names are possible in a single PDU, that could collide",
"# Therefore let's keep old object indexed by (negative) var-bind index",
"try",
":",
"instances",
"[",
"self",
".",
"ST_DESTROY",
"]",
"[",
"-",
"idx",
"-",
"1",
"]",
"=",
"self",
".",
"_vars",
".",
"pop",
"(",
"name",
")",
"except",
"KeyError",
":",
"pass",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Destroy Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually remove requested Managed
Object Instance from the MIB tree. When multiple Managed Objects Instances
are destroyed/modified at once (likely coming all in one SNMP PDU), each
of them has to run through the second (*commit*) phase successfully for
the system to transition to the third (*cleanup*) phase. If any single
*commit* step fails, the system transitions into the *undo* state for
each of Managed Objects Instances being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to destroy
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being destroyed.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Destroy",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2267-L2327 | train | 232,291 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.oidToValue | def oidToValue(self, syntax, identifier, impliedFlag=False, parentIndices=None):
"""Turn SMI table instance identifier into a value object.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes sequence of integers, representing the tail piece
of a tabular object identifier, and turns it into a value object.
Parameters
----------
syntax: :py:class:`Integer`, :py:class:`OctetString`, :py:class:`ObjectIdentifier`, :py:class:`IpAddress` or :py:class:`Bits` -
one of the SNMP data types that can be used in SMI table indices.
identifier: :py:class:`tuple` - tuple of integers representing the tail
piece of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is expected to be present as the first integer of
the sequence. Otherwise the length is not included (which is
frequently the case for the last index in the series or a
fixed-length value).
Returns
-------
:py:class:`object` - Initialized instance of `syntax`
"""
if not identifier:
raise error.SmiError('Short OID for index %r' % (syntax,))
if hasattr(syntax, 'cloneFromName'):
return syntax.cloneFromName(
identifier, impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = syntax.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return syntax.clone(identifier[0]), identifier[1:]
elif IpAddress.tagSet.isSuperTagSetOf(syntax.getTagSet()):
return syntax.clone(
'.'.join([str(x) for x in identifier[:4]])), identifier[4:]
elif baseTag == OctetString.tagSet.getBaseTag():
# rfc1902, 7.7
if impliedFlag:
return syntax.clone(tuple(identifier)), ()
elif syntax.isFixedLength():
l = syntax.getFixedLength()
return syntax.clone(tuple(identifier[:l])), identifier[l:]
else:
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return syntax.clone(identifier), ()
else:
return syntax.clone(
identifier[1:identifier[0] + 1]), identifier[identifier[0] + 1:]
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
else:
raise error.SmiError('Unknown value type for index %r' % (syntax,)) | python | def oidToValue(self, syntax, identifier, impliedFlag=False, parentIndices=None):
"""Turn SMI table instance identifier into a value object.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes sequence of integers, representing the tail piece
of a tabular object identifier, and turns it into a value object.
Parameters
----------
syntax: :py:class:`Integer`, :py:class:`OctetString`, :py:class:`ObjectIdentifier`, :py:class:`IpAddress` or :py:class:`Bits` -
one of the SNMP data types that can be used in SMI table indices.
identifier: :py:class:`tuple` - tuple of integers representing the tail
piece of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is expected to be present as the first integer of
the sequence. Otherwise the length is not included (which is
frequently the case for the last index in the series or a
fixed-length value).
Returns
-------
:py:class:`object` - Initialized instance of `syntax`
"""
if not identifier:
raise error.SmiError('Short OID for index %r' % (syntax,))
if hasattr(syntax, 'cloneFromName'):
return syntax.cloneFromName(
identifier, impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = syntax.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return syntax.clone(identifier[0]), identifier[1:]
elif IpAddress.tagSet.isSuperTagSetOf(syntax.getTagSet()):
return syntax.clone(
'.'.join([str(x) for x in identifier[:4]])), identifier[4:]
elif baseTag == OctetString.tagSet.getBaseTag():
# rfc1902, 7.7
if impliedFlag:
return syntax.clone(tuple(identifier)), ()
elif syntax.isFixedLength():
l = syntax.getFixedLength()
return syntax.clone(tuple(identifier[:l])), identifier[l:]
else:
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return syntax.clone(identifier), ()
else:
return syntax.clone(
identifier[1:identifier[0] + 1]), identifier[identifier[0] + 1:]
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
else:
raise error.SmiError('Unknown value type for index %r' % (syntax,)) | [
"def",
"oidToValue",
"(",
"self",
",",
"syntax",
",",
"identifier",
",",
"impliedFlag",
"=",
"False",
",",
"parentIndices",
"=",
"None",
")",
":",
"if",
"not",
"identifier",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Short OID for index %r'",
"%",
"(",
"syntax",
",",
")",
")",
"if",
"hasattr",
"(",
"syntax",
",",
"'cloneFromName'",
")",
":",
"return",
"syntax",
".",
"cloneFromName",
"(",
"identifier",
",",
"impliedFlag",
",",
"parentRow",
"=",
"self",
",",
"parentIndices",
"=",
"parentIndices",
")",
"baseTag",
"=",
"syntax",
".",
"getTagSet",
"(",
")",
".",
"getBaseTag",
"(",
")",
"if",
"baseTag",
"==",
"Integer",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"syntax",
".",
"clone",
"(",
"identifier",
"[",
"0",
"]",
")",
",",
"identifier",
"[",
"1",
":",
"]",
"elif",
"IpAddress",
".",
"tagSet",
".",
"isSuperTagSetOf",
"(",
"syntax",
".",
"getTagSet",
"(",
")",
")",
":",
"return",
"syntax",
".",
"clone",
"(",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"identifier",
"[",
":",
"4",
"]",
"]",
")",
")",
",",
"identifier",
"[",
"4",
":",
"]",
"elif",
"baseTag",
"==",
"OctetString",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"# rfc1902, 7.7",
"if",
"impliedFlag",
":",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
")",
")",
",",
"(",
")",
"elif",
"syntax",
".",
"isFixedLength",
"(",
")",
":",
"l",
"=",
"syntax",
".",
"getFixedLength",
"(",
")",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
"[",
":",
"l",
"]",
")",
")",
",",
"identifier",
"[",
"l",
":",
"]",
"else",
":",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
"[",
"1",
":",
"identifier",
"[",
"0",
"]",
"+",
"1",
"]",
")",
")",
",",
"identifier",
"[",
"identifier",
"[",
"0",
"]",
"+",
"1",
":",
"]",
"elif",
"baseTag",
"==",
"ObjectIdentifier",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"if",
"impliedFlag",
":",
"return",
"syntax",
".",
"clone",
"(",
"identifier",
")",
",",
"(",
")",
"else",
":",
"return",
"syntax",
".",
"clone",
"(",
"identifier",
"[",
"1",
":",
"identifier",
"[",
"0",
"]",
"+",
"1",
"]",
")",
",",
"identifier",
"[",
"identifier",
"[",
"0",
"]",
"+",
"1",
":",
"]",
"# rfc2578, 7.1",
"elif",
"baseTag",
"==",
"Bits",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
"[",
"1",
":",
"identifier",
"[",
"0",
"]",
"+",
"1",
"]",
")",
")",
",",
"identifier",
"[",
"identifier",
"[",
"0",
"]",
"+",
"1",
":",
"]",
"else",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Unknown value type for index %r'",
"%",
"(",
"syntax",
",",
")",
")"
] | Turn SMI table instance identifier into a value object.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes sequence of integers, representing the tail piece
of a tabular object identifier, and turns it into a value object.
Parameters
----------
syntax: :py:class:`Integer`, :py:class:`OctetString`, :py:class:`ObjectIdentifier`, :py:class:`IpAddress` or :py:class:`Bits` -
one of the SNMP data types that can be used in SMI table indices.
identifier: :py:class:`tuple` - tuple of integers representing the tail
piece of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is expected to be present as the first integer of
the sequence. Otherwise the length is not included (which is
frequently the case for the last index in the series or a
fixed-length value).
Returns
-------
:py:class:`object` - Initialized instance of `syntax` | [
"Turn",
"SMI",
"table",
"instance",
"identifier",
"into",
"a",
"value",
"object",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2478-L2548 | train | 232,292 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.valueToOid | def valueToOid(self, value, impliedFlag=False, parentIndices=None):
"""Turn value object into SMI table instance identifier.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes an arbitrary value object and turns it into a
sequence of integers representing the tail piece of a tabular
object identifier.
Parameters
----------
value: one of the SNMP data types that can be used in SMI table
indices. Allowed types are: :py:class:`Integer`,
:py:class:`OctetString`, :py:class:`ObjectIdentifier`,
:py:class:`IpAddress` and :py:class:`Bits`.
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is included as the first integer of the sequence.
Otherwise the length is not included (which is frequently the
case for the last index in the series or a fixed-length value).
Returns
-------
:py:class:`tuple` - tuple of integers representing the tail piece
of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
"""
if hasattr(value, 'cloneAsName'):
return value.cloneAsName(impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = value.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return int(value),
elif IpAddress.tagSet.isSuperTagSetOf(value.getTagSet()):
return value.asNumbers()
elif baseTag == OctetString.tagSet.getBaseTag():
if impliedFlag or value.isFixedLength():
initial = ()
else:
initial = (len(value),)
return initial + value.asNumbers()
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return tuple(value)
else:
return (len(value),) + tuple(value)
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return (len(value),) + value.asNumbers()
else:
raise error.SmiError('Unknown value type for index %r' % (value,)) | python | def valueToOid(self, value, impliedFlag=False, parentIndices=None):
"""Turn value object into SMI table instance identifier.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes an arbitrary value object and turns it into a
sequence of integers representing the tail piece of a tabular
object identifier.
Parameters
----------
value: one of the SNMP data types that can be used in SMI table
indices. Allowed types are: :py:class:`Integer`,
:py:class:`OctetString`, :py:class:`ObjectIdentifier`,
:py:class:`IpAddress` and :py:class:`Bits`.
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is included as the first integer of the sequence.
Otherwise the length is not included (which is frequently the
case for the last index in the series or a fixed-length value).
Returns
-------
:py:class:`tuple` - tuple of integers representing the tail piece
of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
"""
if hasattr(value, 'cloneAsName'):
return value.cloneAsName(impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = value.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return int(value),
elif IpAddress.tagSet.isSuperTagSetOf(value.getTagSet()):
return value.asNumbers()
elif baseTag == OctetString.tagSet.getBaseTag():
if impliedFlag or value.isFixedLength():
initial = ()
else:
initial = (len(value),)
return initial + value.asNumbers()
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return tuple(value)
else:
return (len(value),) + tuple(value)
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return (len(value),) + value.asNumbers()
else:
raise error.SmiError('Unknown value type for index %r' % (value,)) | [
"def",
"valueToOid",
"(",
"self",
",",
"value",
",",
"impliedFlag",
"=",
"False",
",",
"parentIndices",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'cloneAsName'",
")",
":",
"return",
"value",
".",
"cloneAsName",
"(",
"impliedFlag",
",",
"parentRow",
"=",
"self",
",",
"parentIndices",
"=",
"parentIndices",
")",
"baseTag",
"=",
"value",
".",
"getTagSet",
"(",
")",
".",
"getBaseTag",
"(",
")",
"if",
"baseTag",
"==",
"Integer",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"int",
"(",
"value",
")",
",",
"elif",
"IpAddress",
".",
"tagSet",
".",
"isSuperTagSetOf",
"(",
"value",
".",
"getTagSet",
"(",
")",
")",
":",
"return",
"value",
".",
"asNumbers",
"(",
")",
"elif",
"baseTag",
"==",
"OctetString",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"if",
"impliedFlag",
"or",
"value",
".",
"isFixedLength",
"(",
")",
":",
"initial",
"=",
"(",
")",
"else",
":",
"initial",
"=",
"(",
"len",
"(",
"value",
")",
",",
")",
"return",
"initial",
"+",
"value",
".",
"asNumbers",
"(",
")",
"elif",
"baseTag",
"==",
"ObjectIdentifier",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"if",
"impliedFlag",
":",
"return",
"tuple",
"(",
"value",
")",
"else",
":",
"return",
"(",
"len",
"(",
"value",
")",
",",
")",
"+",
"tuple",
"(",
"value",
")",
"# rfc2578, 7.1",
"elif",
"baseTag",
"==",
"Bits",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"(",
"len",
"(",
"value",
")",
",",
")",
"+",
"value",
".",
"asNumbers",
"(",
")",
"else",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Unknown value type for index %r'",
"%",
"(",
"value",
",",
")",
")"
] | Turn value object into SMI table instance identifier.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes an arbitrary value object and turns it into a
sequence of integers representing the tail piece of a tabular
object identifier.
Parameters
----------
value: one of the SNMP data types that can be used in SMI table
indices. Allowed types are: :py:class:`Integer`,
:py:class:`OctetString`, :py:class:`ObjectIdentifier`,
:py:class:`IpAddress` and :py:class:`Bits`.
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is included as the first integer of the sequence.
Otherwise the length is not included (which is frequently the
case for the last index in the series or a fixed-length value).
Returns
-------
:py:class:`tuple` - tuple of integers representing the tail piece
of an OBJECT IDENTIFIER (i.e. tabular object instance ID) | [
"Turn",
"value",
"object",
"into",
"SMI",
"table",
"instance",
"identifier",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2552-L2608 | train | 232,293 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.announceManagementEvent | def announceManagementEvent(self, action, varBind, **context):
"""Announce mass operation on parent table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on parent :py:class:`MibTableRow` whenever
row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
being applied on the parent table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all the consumers of this notifications finished with their stuff
or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
cbFun = context['cbFun']
if not self._augmentingRows:
cbFun(varBind, **context)
return
# Convert OID suffix into index values
instId = name[len(self.name) + 1:]
baseIndices = []
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId,
impliedFlag, indices)
if self.name == mibObj.name[:-1]:
baseIndices.append((mibObj.name, syntax))
indices.append(syntax)
if instId:
exc = error.SmiError('Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId))
cbFun(varBind, **dict(context, error=exc))
return
if not baseIndices:
cbFun(varBind, **context)
return
count = [len(self._augmentingRows)]
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for modName, mibSym in self._augmentingRows:
mibObj, = mibBuilder.importSymbols(modName, mibSym)
mibObj.receiveManagementEvent(action, (baseIndices, val), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) | python | def announceManagementEvent(self, action, varBind, **context):
"""Announce mass operation on parent table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on parent :py:class:`MibTableRow` whenever
row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
being applied on the parent table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all the consumers of this notifications finished with their stuff
or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
cbFun = context['cbFun']
if not self._augmentingRows:
cbFun(varBind, **context)
return
# Convert OID suffix into index values
instId = name[len(self.name) + 1:]
baseIndices = []
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId,
impliedFlag, indices)
if self.name == mibObj.name[:-1]:
baseIndices.append((mibObj.name, syntax))
indices.append(syntax)
if instId:
exc = error.SmiError('Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId))
cbFun(varBind, **dict(context, error=exc))
return
if not baseIndices:
cbFun(varBind, **context)
return
count = [len(self._augmentingRows)]
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for modName, mibSym in self._augmentingRows:
mibObj, = mibBuilder.importSymbols(modName, mibSym)
mibObj.receiveManagementEvent(action, (baseIndices, val), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) | [
"def",
"announceManagementEvent",
"(",
"self",
",",
"action",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"if",
"not",
"self",
".",
"_augmentingRows",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"# Convert OID suffix into index values",
"instId",
"=",
"name",
"[",
"len",
"(",
"self",
".",
"name",
")",
"+",
"1",
":",
"]",
"baseIndices",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"syntax",
",",
"instId",
"=",
"self",
".",
"oidToValue",
"(",
"mibObj",
".",
"syntax",
",",
"instId",
",",
"impliedFlag",
",",
"indices",
")",
"if",
"self",
".",
"name",
"==",
"mibObj",
".",
"name",
"[",
":",
"-",
"1",
"]",
":",
"baseIndices",
".",
"append",
"(",
"(",
"mibObj",
".",
"name",
",",
"syntax",
")",
")",
"indices",
".",
"append",
"(",
"syntax",
")",
"if",
"instId",
":",
"exc",
"=",
"error",
".",
"SmiError",
"(",
"'Excessive instance identifier sub-OIDs left at %s: %s'",
"%",
"(",
"self",
",",
"instId",
")",
")",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"error",
"=",
"exc",
")",
")",
"return",
"if",
"not",
"baseIndices",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"count",
"=",
"[",
"len",
"(",
"self",
".",
"_augmentingRows",
")",
"]",
"def",
"_cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"if",
"not",
"count",
"[",
"0",
"]",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"for",
"modName",
",",
"mibSym",
"in",
"self",
".",
"_augmentingRows",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"mibSym",
")",
"mibObj",
".",
"receiveManagementEvent",
"(",
"action",
",",
"(",
"baseIndices",
",",
"val",
")",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"cbFun",
"=",
"_cbFun",
")",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'announceManagementEvent %s to %s'",
"%",
"(",
"action",
",",
"mibObj",
")",
")"
] | Announce mass operation on parent table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on parent :py:class:`MibTableRow` whenever
row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
being applied on the parent table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all the consumers of this notifications finished with their stuff
or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Announce",
"mass",
"operation",
"on",
"parent",
"table",
"s",
"row",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2612-L2693 | train | 232,294 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.receiveManagementEvent | def receiveManagementEvent(self, action, varBind, **context):
"""Apply mass operation on extending table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on the extending :py:class:`MibTableRow`
object whenever row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on extending table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
the requested operation has been applied on all columns of the
extending table or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
baseIndices, val = varBind
# The default implementation supports one-to-one rows dependency
instId = ()
# Resolve indices intersection
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
parentIndices = []
for name, syntax in baseIndices:
if name == mibObj.name:
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
if instId:
debug.logger & debug.FLAG_INS and debug.logger(
'receiveManagementEvent %s for suffix %s' % (action, instId))
self._manageColumns(action, (self.name + (0,) + instId, val), **context) | python | def receiveManagementEvent(self, action, varBind, **context):
"""Apply mass operation on extending table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on the extending :py:class:`MibTableRow`
object whenever row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on extending table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
the requested operation has been applied on all columns of the
extending table or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
baseIndices, val = varBind
# The default implementation supports one-to-one rows dependency
instId = ()
# Resolve indices intersection
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
parentIndices = []
for name, syntax in baseIndices:
if name == mibObj.name:
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
if instId:
debug.logger & debug.FLAG_INS and debug.logger(
'receiveManagementEvent %s for suffix %s' % (action, instId))
self._manageColumns(action, (self.name + (0,) + instId, val), **context) | [
"def",
"receiveManagementEvent",
"(",
"self",
",",
"action",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"baseIndices",
",",
"val",
"=",
"varBind",
"# The default implementation supports one-to-one rows dependency",
"instId",
"=",
"(",
")",
"# Resolve indices intersection",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"parentIndices",
"=",
"[",
"]",
"for",
"name",
",",
"syntax",
"in",
"baseIndices",
":",
"if",
"name",
"==",
"mibObj",
".",
"name",
":",
"instId",
"+=",
"self",
".",
"valueToOid",
"(",
"syntax",
",",
"impliedFlag",
",",
"parentIndices",
")",
"parentIndices",
".",
"append",
"(",
"syntax",
")",
"if",
"instId",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'receiveManagementEvent %s for suffix %s'",
"%",
"(",
"action",
",",
"instId",
")",
")",
"self",
".",
"_manageColumns",
"(",
"action",
",",
"(",
"self",
".",
"name",
"+",
"(",
"0",
",",
")",
"+",
"instId",
",",
"val",
")",
",",
"*",
"*",
"context",
")"
] | Apply mass operation on extending table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on the extending :py:class:`MibTableRow`
object whenever row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on extending table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
the requested operation has been applied on all columns of the
extending table or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Apply",
"mass",
"operation",
"on",
"extending",
"table",
"s",
"row",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2695-L2751 | train | 232,295 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.registerAugmentation | def registerAugmentation(self, *names):
"""Register table extension.
SNMP SMI provides a way to extend already existing SMI table with
another table. This method registers dependent (extending) table
(or type :py:class:`MibTableRow`) to already existing table.
Whenever a row of the parent table is created or destroyed, the
same mass columnar operation is applied on the extending table
row.
Parameters
----------
names: :py:class:`tuple`
One or more `tuple`'s of `str` referring to the extending table by
MIB module name (first `str`) and `:py:class:`MibTableRow` object
name (second `str`).
"""
for name in names:
if name in self._augmentingRows:
raise error.SmiError(
'Row %s already augmented by %s::%s' % (self.name, name[0], name[1])
)
self._augmentingRows.add(name)
return self | python | def registerAugmentation(self, *names):
"""Register table extension.
SNMP SMI provides a way to extend already existing SMI table with
another table. This method registers dependent (extending) table
(or type :py:class:`MibTableRow`) to already existing table.
Whenever a row of the parent table is created or destroyed, the
same mass columnar operation is applied on the extending table
row.
Parameters
----------
names: :py:class:`tuple`
One or more `tuple`'s of `str` referring to the extending table by
MIB module name (first `str`) and `:py:class:`MibTableRow` object
name (second `str`).
"""
for name in names:
if name in self._augmentingRows:
raise error.SmiError(
'Row %s already augmented by %s::%s' % (self.name, name[0], name[1])
)
self._augmentingRows.add(name)
return self | [
"def",
"registerAugmentation",
"(",
"self",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"self",
".",
"_augmentingRows",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Row %s already augmented by %s::%s'",
"%",
"(",
"self",
".",
"name",
",",
"name",
"[",
"0",
"]",
",",
"name",
"[",
"1",
"]",
")",
")",
"self",
".",
"_augmentingRows",
".",
"add",
"(",
"name",
")",
"return",
"self"
] | Register table extension.
SNMP SMI provides a way to extend already existing SMI table with
another table. This method registers dependent (extending) table
(or type :py:class:`MibTableRow`) to already existing table.
Whenever a row of the parent table is created or destroyed, the
same mass columnar operation is applied on the extending table
row.
Parameters
----------
names: :py:class:`tuple`
One or more `tuple`'s of `str` referring to the extending table by
MIB module name (first `str`) and `:py:class:`MibTableRow` object
name (second `str`). | [
"Register",
"table",
"extension",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2753-L2779 | train | 232,296 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow._manageColumns | def _manageColumns(self, action, varBind, **context):
"""Apply a management action on all columns
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on all columns but the one passed in `varBind`
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all columns have been processed or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assumes that row consistency check has been triggered by RowStatus
columnar object transition into `active` state.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _manageColumns(%s, %s, %r)' % (self, action, name, val)))
cbFun = context['cbFun']
colLen = len(self.name) + 1
# Build a map of index names and values for automatic initialization
indexVals = {}
instId = name[colLen:]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
indexVals[mibObj.name] = syntax
indices.append(syntax)
count = [len(self._vars)]
if name[:colLen] in self._vars:
count[0] -= 1
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for colName, colObj in self._vars.items():
acFun = context.get('acFun')
if colName in indexVals:
colInstanceValue = indexVals[colName]
# Index column is usually read-only
acFun = None
elif name[:colLen] == colName:
# status column is following `write` path
continue
else:
colInstanceValue = None
actionFun = getattr(colObj, action)
colInstanceName = colName + name[colLen:]
actionFun((colInstanceName, colInstanceValue),
**dict(context, acFun=acFun, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'_manageColumns: action %s name %s instance %s %svalue %r' % (
action, name, instId, name in indexVals and "index " or "", indexVals.get(name, val))) | python | def _manageColumns(self, action, varBind, **context):
"""Apply a management action on all columns
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on all columns but the one passed in `varBind`
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all columns have been processed or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assumes that row consistency check has been triggered by RowStatus
columnar object transition into `active` state.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _manageColumns(%s, %s, %r)' % (self, action, name, val)))
cbFun = context['cbFun']
colLen = len(self.name) + 1
# Build a map of index names and values for automatic initialization
indexVals = {}
instId = name[colLen:]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
indexVals[mibObj.name] = syntax
indices.append(syntax)
count = [len(self._vars)]
if name[:colLen] in self._vars:
count[0] -= 1
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for colName, colObj in self._vars.items():
acFun = context.get('acFun')
if colName in indexVals:
colInstanceValue = indexVals[colName]
# Index column is usually read-only
acFun = None
elif name[:colLen] == colName:
# status column is following `write` path
continue
else:
colInstanceValue = None
actionFun = getattr(colObj, action)
colInstanceName = colName + name[colLen:]
actionFun((colInstanceName, colInstanceValue),
**dict(context, acFun=acFun, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'_manageColumns: action %s name %s instance %s %svalue %r' % (
action, name, instId, name in indexVals and "index " or "", indexVals.get(name, val))) | [
"def",
"_manageColumns",
"(",
"self",
",",
"action",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: _manageColumns(%s, %s, %r)'",
"%",
"(",
"self",
",",
"action",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"colLen",
"=",
"len",
"(",
"self",
".",
"name",
")",
"+",
"1",
"# Build a map of index names and values for automatic initialization",
"indexVals",
"=",
"{",
"}",
"instId",
"=",
"name",
"[",
"colLen",
":",
"]",
"indices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"syntax",
",",
"instId",
"=",
"self",
".",
"oidToValue",
"(",
"mibObj",
".",
"syntax",
",",
"instId",
",",
"impliedFlag",
",",
"indices",
")",
"indexVals",
"[",
"mibObj",
".",
"name",
"]",
"=",
"syntax",
"indices",
".",
"append",
"(",
"syntax",
")",
"count",
"=",
"[",
"len",
"(",
"self",
".",
"_vars",
")",
"]",
"if",
"name",
"[",
":",
"colLen",
"]",
"in",
"self",
".",
"_vars",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"def",
"_cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"if",
"not",
"count",
"[",
"0",
"]",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"for",
"colName",
",",
"colObj",
"in",
"self",
".",
"_vars",
".",
"items",
"(",
")",
":",
"acFun",
"=",
"context",
".",
"get",
"(",
"'acFun'",
")",
"if",
"colName",
"in",
"indexVals",
":",
"colInstanceValue",
"=",
"indexVals",
"[",
"colName",
"]",
"# Index column is usually read-only",
"acFun",
"=",
"None",
"elif",
"name",
"[",
":",
"colLen",
"]",
"==",
"colName",
":",
"# status column is following `write` path",
"continue",
"else",
":",
"colInstanceValue",
"=",
"None",
"actionFun",
"=",
"getattr",
"(",
"colObj",
",",
"action",
")",
"colInstanceName",
"=",
"colName",
"+",
"name",
"[",
"colLen",
":",
"]",
"actionFun",
"(",
"(",
"colInstanceName",
",",
"colInstanceValue",
")",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"acFun",
"=",
"acFun",
",",
"cbFun",
"=",
"_cbFun",
")",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'_manageColumns: action %s name %s instance %s %svalue %r'",
"%",
"(",
"action",
",",
"name",
",",
"instId",
",",
"name",
"in",
"indexVals",
"and",
"\"index \"",
"or",
"\"\"",
",",
"indexVals",
".",
"get",
"(",
"name",
",",
"val",
")",
")",
")"
] | Apply a management action on all columns
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on all columns but the one passed in `varBind`
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all columns have been processed or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assumes that row consistency check has been triggered by RowStatus
columnar object transition into `active` state. | [
"Apply",
"a",
"management",
"action",
"on",
"all",
"columns"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2791-L2879 | train | 232,297 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow._checkColumns | def _checkColumns(self, varBind, **context):
"""Check the consistency of all columns.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assume that row consistency check has been triggered by RowStatus
columnar object transition into `active` state.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _checkColumns(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
# RowStatus != active
if val != 1:
cbFun(varBind, **context)
return
count = [len(self._vars)]
def _cbFun(varBind, **context):
count[0] -= 1
name, val = varBind
if count[0] >= 0:
exc = context.get('error')
if exc or not val.hasValue():
count[0] = -1 # ignore the rest of callbacks
exc = error.InconsistentValueError(msg='Inconsistent column %s: %s' % (name, exc))
cbFun(varBind, **dict(context, error=exc))
return
if not count[0]:
cbFun(varBind, **context)
return
colLen = len(self.name) + 1
for colName, colObj in self._vars.items():
instName = colName + name[colLen:]
colObj.readGet((instName, None), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'%s: _checkColumns: checking instance %s' % (self, instName)) | python | def _checkColumns(self, varBind, **context):
"""Check the consistency of all columns.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assume that row consistency check has been triggered by RowStatus
columnar object transition into `active` state.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _checkColumns(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
# RowStatus != active
if val != 1:
cbFun(varBind, **context)
return
count = [len(self._vars)]
def _cbFun(varBind, **context):
count[0] -= 1
name, val = varBind
if count[0] >= 0:
exc = context.get('error')
if exc or not val.hasValue():
count[0] = -1 # ignore the rest of callbacks
exc = error.InconsistentValueError(msg='Inconsistent column %s: %s' % (name, exc))
cbFun(varBind, **dict(context, error=exc))
return
if not count[0]:
cbFun(varBind, **context)
return
colLen = len(self.name) + 1
for colName, colObj in self._vars.items():
instName = colName + name[colLen:]
colObj.readGet((instName, None), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'%s: _checkColumns: checking instance %s' % (self, instName)) | [
"def",
"_checkColumns",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: _checkColumns(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"# RowStatus != active",
"if",
"val",
"!=",
"1",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"count",
"=",
"[",
"len",
"(",
"self",
".",
"_vars",
")",
"]",
"def",
"_cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"name",
",",
"val",
"=",
"varBind",
"if",
"count",
"[",
"0",
"]",
">=",
"0",
":",
"exc",
"=",
"context",
".",
"get",
"(",
"'error'",
")",
"if",
"exc",
"or",
"not",
"val",
".",
"hasValue",
"(",
")",
":",
"count",
"[",
"0",
"]",
"=",
"-",
"1",
"# ignore the rest of callbacks",
"exc",
"=",
"error",
".",
"InconsistentValueError",
"(",
"msg",
"=",
"'Inconsistent column %s: %s'",
"%",
"(",
"name",
",",
"exc",
")",
")",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"error",
"=",
"exc",
")",
")",
"return",
"if",
"not",
"count",
"[",
"0",
"]",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"colLen",
"=",
"len",
"(",
"self",
".",
"name",
")",
"+",
"1",
"for",
"colName",
",",
"colObj",
"in",
"self",
".",
"_vars",
".",
"items",
"(",
")",
":",
"instName",
"=",
"colName",
"+",
"name",
"[",
"colLen",
":",
"]",
"colObj",
".",
"readGet",
"(",
"(",
"instName",
",",
"None",
")",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"cbFun",
"=",
"_cbFun",
")",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: _checkColumns: checking instance %s'",
"%",
"(",
"self",
",",
"instName",
")",
")"
] | Check the consistency of all columns.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assume that row consistency check has been triggered by RowStatus
columnar object transition into `active` state. | [
"Check",
"the",
"consistency",
"of",
"all",
"columns",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2881-L2949 | train | 232,298 |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getIndicesFromInstId | def getIndicesFromInstId(self, instId):
"""Return index values for instance identification"""
if instId in self._idToIdxCache:
return self._idToIdxCache[instId]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
try:
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
except PyAsn1Error as exc:
debug.logger & debug.FLAG_INS and debug.logger(
'error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, exc))
indices = [instId]
instId = ()
break
indices.append(syntax) # to avoid cyclic refs
if instId:
raise error.SmiError(
'Excessive instance identifier sub-OIDs left at %s: %s' %
(self, instId)
)
indices = tuple(indices)
self._idToIdxCache[instId] = indices
return indices | python | def getIndicesFromInstId(self, instId):
"""Return index values for instance identification"""
if instId in self._idToIdxCache:
return self._idToIdxCache[instId]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
try:
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
except PyAsn1Error as exc:
debug.logger & debug.FLAG_INS and debug.logger(
'error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, exc))
indices = [instId]
instId = ()
break
indices.append(syntax) # to avoid cyclic refs
if instId:
raise error.SmiError(
'Excessive instance identifier sub-OIDs left at %s: %s' %
(self, instId)
)
indices = tuple(indices)
self._idToIdxCache[instId] = indices
return indices | [
"def",
"getIndicesFromInstId",
"(",
"self",
",",
"instId",
")",
":",
"if",
"instId",
"in",
"self",
".",
"_idToIdxCache",
":",
"return",
"self",
".",
"_idToIdxCache",
"[",
"instId",
"]",
"indices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"try",
":",
"syntax",
",",
"instId",
"=",
"self",
".",
"oidToValue",
"(",
"mibObj",
".",
"syntax",
",",
"instId",
",",
"impliedFlag",
",",
"indices",
")",
"except",
"PyAsn1Error",
"as",
"exc",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'error resolving table indices at %s, %s: %s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"instId",
",",
"exc",
")",
")",
"indices",
"=",
"[",
"instId",
"]",
"instId",
"=",
"(",
")",
"break",
"indices",
".",
"append",
"(",
"syntax",
")",
"# to avoid cyclic refs",
"if",
"instId",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Excessive instance identifier sub-OIDs left at %s: %s'",
"%",
"(",
"self",
",",
"instId",
")",
")",
"indices",
"=",
"tuple",
"(",
"indices",
")",
"self",
".",
"_idToIdxCache",
"[",
"instId",
"]",
"=",
"indices",
"return",
"indices"
] | Return index values for instance identification | [
"Return",
"index",
"values",
"for",
"instance",
"identification"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3278-L3306 | train | 232,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.