id
int32
0
252k
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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
237,300
F5Networks/f5-common-python
f5/bigip/tm/security/firewall.py
Rule.load
def load(self, **kwargs): """Custom load method to address issue in 11.6.0 Final, where non existing objects would be True. """ if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'): return self._load_11_6(**kwargs) else: return super(Rule, self)._load(**kwargs)
python
def load(self, **kwargs): """Custom load method to address issue in 11.6.0 Final, where non existing objects would be True. """ if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'): return self._load_11_6(**kwargs) else: return super(Rule, self)._load(**kwargs)
[ "def", "load", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "LooseVersion", "(", "self", ".", "tmos_ver", ")", "==", "LooseVersion", "(", "'11.6.0'", ")", ":", "return", "self", ".", "_load_11_6", "(", "*", "*", "kwargs", ")", "else", ":", "return", "super", "(", "Rule", ",", "self", ")", ".", "_load", "(", "*", "*", "kwargs", ")" ]
Custom load method to address issue in 11.6.0 Final, where non existing objects would be True.
[ "Custom", "load", "method", "to", "address", "issue", "in", "11", ".", "6", ".", "0", "Final" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/security/firewall.py#L169-L177
237,301
F5Networks/f5-common-python
f5/utils/decorators.py
poll_for_exceptionless_callable
def poll_for_exceptionless_callable(callable, attempts, interval): '''Poll with a given callable for a specified number of times. :param callable: callable to invoke in loop -- if no exception is raised the call is considered succeeded :param attempts: number of iterations to attempt :param interval: seconds to wait before next attempt ''' @wraps(callable) def poll(*args, **kwargs): for attempt in range(attempts): try: return callable(*args, **kwargs) except Exception as ex: if attempt == attempts-1: raise MaximumAttemptsReached(ex) time.sleep(interval) continue return poll
python
def poll_for_exceptionless_callable(callable, attempts, interval): '''Poll with a given callable for a specified number of times. :param callable: callable to invoke in loop -- if no exception is raised the call is considered succeeded :param attempts: number of iterations to attempt :param interval: seconds to wait before next attempt ''' @wraps(callable) def poll(*args, **kwargs): for attempt in range(attempts): try: return callable(*args, **kwargs) except Exception as ex: if attempt == attempts-1: raise MaximumAttemptsReached(ex) time.sleep(interval) continue return poll
[ "def", "poll_for_exceptionless_callable", "(", "callable", ",", "attempts", ",", "interval", ")", ":", "@", "wraps", "(", "callable", ")", "def", "poll", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "attempt", "in", "range", "(", "attempts", ")", ":", "try", ":", "return", "callable", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "ex", ":", "if", "attempt", "==", "attempts", "-", "1", ":", "raise", "MaximumAttemptsReached", "(", "ex", ")", "time", ".", "sleep", "(", "interval", ")", "continue", "return", "poll" ]
Poll with a given callable for a specified number of times. :param callable: callable to invoke in loop -- if no exception is raised the call is considered succeeded :param attempts: number of iterations to attempt :param interval: seconds to wait before next attempt
[ "Poll", "with", "a", "given", "callable", "for", "a", "specified", "number", "of", "times", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/decorators.py#L28-L47
237,302
F5Networks/f5-common-python
f5/bigip/tm/security/log.py
Network.exists
def exists(self, **kwargs): """Some objects when deleted still return when called by their direct URI, this is a known issue in 11.6.0. """ if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'): return self._exists_11_6(**kwargs) else: return super(Network, self)._exists(**kwargs)
python
def exists(self, **kwargs): """Some objects when deleted still return when called by their direct URI, this is a known issue in 11.6.0. """ if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'): return self._exists_11_6(**kwargs) else: return super(Network, self)._exists(**kwargs)
[ "def", "exists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "LooseVersion", "(", "self", ".", "tmos_ver", ")", "==", "LooseVersion", "(", "'11.6.0'", ")", ":", "return", "self", ".", "_exists_11_6", "(", "*", "*", "kwargs", ")", "else", ":", "return", "super", "(", "Network", ",", "self", ")", ".", "_exists", "(", "*", "*", "kwargs", ")" ]
Some objects when deleted still return when called by their direct URI, this is a known issue in 11.6.0.
[ "Some", "objects", "when", "deleted", "still", "return", "when", "called", "by", "their" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/security/log.py#L168-L177
237,303
F5Networks/f5-common-python
f5/bigip/mixins.py
CommandExecutionMixin._is_allowed_command
def _is_allowed_command(self, command): """Checking if the given command is allowed on a given endpoint.""" cmds = self._meta_data['allowed_commands'] if command not in self._meta_data['allowed_commands']: error_message = "The command value {0} does not exist. " \ "Valid commands are {1}".format(command, cmds) raise InvalidCommand(error_message)
python
def _is_allowed_command(self, command): """Checking if the given command is allowed on a given endpoint.""" cmds = self._meta_data['allowed_commands'] if command not in self._meta_data['allowed_commands']: error_message = "The command value {0} does not exist. " \ "Valid commands are {1}".format(command, cmds) raise InvalidCommand(error_message)
[ "def", "_is_allowed_command", "(", "self", ",", "command", ")", ":", "cmds", "=", "self", ".", "_meta_data", "[", "'allowed_commands'", "]", "if", "command", "not", "in", "self", ".", "_meta_data", "[", "'allowed_commands'", "]", ":", "error_message", "=", "\"The command value {0} does not exist. \"", "\"Valid commands are {1}\"", ".", "format", "(", "command", ",", "cmds", ")", "raise", "InvalidCommand", "(", "error_message", ")" ]
Checking if the given command is allowed on a given endpoint.
[ "Checking", "if", "the", "given", "command", "is", "allowed", "on", "a", "given", "endpoint", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L212-L218
237,304
F5Networks/f5-common-python
f5/bigip/mixins.py
CommandExecutionMixin._check_command_result
def _check_command_result(self): """If command result exists run these checks.""" if self.commandResult.startswith('/bin/bash'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/mv'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/ls'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/rm'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if 'invalid option' in self.commandResult: raise UtilError('%s' % self.commandResult) if 'Invalid option' in self.commandResult: raise UtilError('%s' % self.commandResult) if 'usage: /usr/bin/get_dossier' in self.commandResult: raise UtilError('%s' % self.commandResult)
python
def _check_command_result(self): """If command result exists run these checks.""" if self.commandResult.startswith('/bin/bash'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/mv'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/ls'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/rm'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if 'invalid option' in self.commandResult: raise UtilError('%s' % self.commandResult) if 'Invalid option' in self.commandResult: raise UtilError('%s' % self.commandResult) if 'usage: /usr/bin/get_dossier' in self.commandResult: raise UtilError('%s' % self.commandResult)
[ "def", "_check_command_result", "(", "self", ")", ":", "if", "self", ".", "commandResult", ".", "startswith", "(", "'/bin/bash'", ")", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ".", "split", "(", "' '", ",", "1", ")", "[", "1", "]", ")", "if", "self", ".", "commandResult", ".", "startswith", "(", "'/bin/mv'", ")", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ".", "split", "(", "' '", ",", "1", ")", "[", "1", "]", ")", "if", "self", ".", "commandResult", ".", "startswith", "(", "'/bin/ls'", ")", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ".", "split", "(", "' '", ",", "1", ")", "[", "1", "]", ")", "if", "self", ".", "commandResult", ".", "startswith", "(", "'/bin/rm'", ")", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ".", "split", "(", "' '", ",", "1", ")", "[", "1", "]", ")", "if", "'invalid option'", "in", "self", ".", "commandResult", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ")", "if", "'Invalid option'", "in", "self", ".", "commandResult", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ")", "if", "'usage: /usr/bin/get_dossier'", "in", "self", ".", "commandResult", ":", "raise", "UtilError", "(", "'%s'", "%", "self", ".", "commandResult", ")" ]
If command result exists run these checks.
[ "If", "command", "result", "exists", "run", "these", "checks", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L220-L235
237,305
F5Networks/f5-common-python
f5/bigip/mixins.py
CommandExecutionMixin.exec_cmd
def exec_cmd(self, command, **kwargs): """Wrapper method that can be changed in the inheriting classes.""" self._is_allowed_command(command) self._check_command_parameters(**kwargs) return self._exec_cmd(command, **kwargs)
python
def exec_cmd(self, command, **kwargs): """Wrapper method that can be changed in the inheriting classes.""" self._is_allowed_command(command) self._check_command_parameters(**kwargs) return self._exec_cmd(command, **kwargs)
[ "def", "exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_is_allowed_command", "(", "command", ")", "self", ".", "_check_command_parameters", "(", "*", "*", "kwargs", ")", "return", "self", ".", "_exec_cmd", "(", "command", ",", "*", "*", "kwargs", ")" ]
Wrapper method that can be changed in the inheriting classes.
[ "Wrapper", "method", "that", "can", "be", "changed", "in", "the", "inheriting", "classes", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L237-L241
237,306
F5Networks/f5-common-python
f5/bigip/mixins.py
CommandExecutionMixin._exec_cmd
def _exec_cmd(self, command, **kwargs): """Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand """ kwargs['command'] = command self._check_exclusive_parameters(**kwargs) requests_params = self._handle_requests_params(kwargs) session = self._meta_data['bigip']._meta_data['icr_session'] response = session.post( self._meta_data['uri'], json=kwargs, **requests_params) new_instance = self._stamp_out_core() new_instance._local_update(response.json()) if 'commandResult' in new_instance.__dict__: new_instance._check_command_result() return new_instance
python
def _exec_cmd(self, command, **kwargs): """Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand """ kwargs['command'] = command self._check_exclusive_parameters(**kwargs) requests_params = self._handle_requests_params(kwargs) session = self._meta_data['bigip']._meta_data['icr_session'] response = session.post( self._meta_data['uri'], json=kwargs, **requests_params) new_instance = self._stamp_out_core() new_instance._local_update(response.json()) if 'commandResult' in new_instance.__dict__: new_instance._check_command_result() return new_instance
[ "def", "_exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'command'", "]", "=", "command", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "response", "=", "session", ".", "post", "(", "self", ".", "_meta_data", "[", "'uri'", "]", ",", "json", "=", "kwargs", ",", "*", "*", "requests_params", ")", "new_instance", "=", "self", ".", "_stamp_out_core", "(", ")", "new_instance", ".", "_local_update", "(", "response", ".", "json", "(", ")", ")", "if", "'commandResult'", "in", "new_instance", ".", "__dict__", ":", "new_instance", ".", "_check_command_result", "(", ")", "return", "new_instance" ]
Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand
[ "Create", "a", "new", "method", "as", "command", "has", "specific", "requirements", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L243-L263
237,307
F5Networks/f5-common-python
f5/bigip/mixins.py
DeviceMixin.get_device_info
def get_device_info(self, bigip): '''Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object ''' coll = bigip.tm.cm.devices.get_collection() device = [device for device in coll if device.selfDevice == 'true'] assert len(device) == 1 return device[0]
python
def get_device_info(self, bigip): '''Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object ''' coll = bigip.tm.cm.devices.get_collection() device = [device for device in coll if device.selfDevice == 'true'] assert len(device) == 1 return device[0]
[ "def", "get_device_info", "(", "self", ",", "bigip", ")", ":", "coll", "=", "bigip", ".", "tm", ".", "cm", ".", "devices", ".", "get_collection", "(", ")", "device", "=", "[", "device", "for", "device", "in", "coll", "if", "device", ".", "selfDevice", "==", "'true'", "]", "assert", "len", "(", "device", ")", "==", "1", "return", "device", "[", "0", "]" ]
Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object
[ "Get", "device", "information", "about", "a", "specific", "BigIP", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L434-L444
237,308
F5Networks/f5-common-python
f5/bigip/mixins.py
CheckExistenceMixin._check_existence_by_collection
def _check_existence_by_collection(self, container, item_name): '''Check existnce of item based on get collection call. :param collection: container object -- capable of get_collection() :param item_name: str -- name of item to search for in collection ''' coll = container.get_collection() for item in coll: if item.name == item_name: return True return False
python
def _check_existence_by_collection(self, container, item_name): '''Check existnce of item based on get collection call. :param collection: container object -- capable of get_collection() :param item_name: str -- name of item to search for in collection ''' coll = container.get_collection() for item in coll: if item.name == item_name: return True return False
[ "def", "_check_existence_by_collection", "(", "self", ",", "container", ",", "item_name", ")", ":", "coll", "=", "container", ".", "get_collection", "(", ")", "for", "item", "in", "coll", ":", "if", "item", ".", "name", "==", "item_name", ":", "return", "True", "return", "False" ]
Check existnce of item based on get collection call. :param collection: container object -- capable of get_collection() :param item_name: str -- name of item to search for in collection
[ "Check", "existnce", "of", "item", "based", "on", "get", "collection", "call", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L450-L461
237,309
F5Networks/f5-common-python
f5/bigip/mixins.py
CheckExistenceMixin._return_object
def _return_object(self, container, item_name): """Helper method to retrieve the object""" coll = container.get_collection() for item in coll: if item.name == item_name: return item
python
def _return_object(self, container, item_name): """Helper method to retrieve the object""" coll = container.get_collection() for item in coll: if item.name == item_name: return item
[ "def", "_return_object", "(", "self", ",", "container", ",", "item_name", ")", ":", "coll", "=", "container", ".", "get_collection", "(", ")", "for", "item", "in", "coll", ":", "if", "item", ".", "name", "==", "item_name", ":", "return", "item" ]
Helper method to retrieve the object
[ "Helper", "method", "to", "retrieve", "the", "object" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L463-L468
237,310
F5Networks/f5-common-python
f5/bigip/tm/sys/config.py
Config.exec_cmd
def exec_cmd(self, command, **kwargs): """Normal save and load only need the command. To merge, just supply the merge and file arguments as kwargs like so: exec_cmd('load', merge=True, file='/path/to/file.txt') """ if command == 'load': if kwargs: kwargs = dict(options=[kwargs]) return self._exec_cmd(command, **kwargs)
python
def exec_cmd(self, command, **kwargs): """Normal save and load only need the command. To merge, just supply the merge and file arguments as kwargs like so: exec_cmd('load', merge=True, file='/path/to/file.txt') """ if command == 'load': if kwargs: kwargs = dict(options=[kwargs]) return self._exec_cmd(command, **kwargs)
[ "def", "exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "if", "command", "==", "'load'", ":", "if", "kwargs", ":", "kwargs", "=", "dict", "(", "options", "=", "[", "kwargs", "]", ")", "return", "self", ".", "_exec_cmd", "(", "command", ",", "*", "*", "kwargs", ")" ]
Normal save and load only need the command. To merge, just supply the merge and file arguments as kwargs like so: exec_cmd('load', merge=True, file='/path/to/file.txt')
[ "Normal", "save", "and", "load", "only", "need", "the", "command", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/config.py#L52-L62
237,311
F5Networks/f5-common-python
f5/bigip/tm/sys/snmp.py
User.update
def update(self, **kwargs): """Due to a password decryption bug we will disable update() method for 12.1.0 and up """ tmos_version = self._meta_data['bigip'].tmos_version if LooseVersion(tmos_version) > LooseVersion('12.0.0'): msg = "Update() is unsupported for User on version %s. " \ "Utilize Modify() method instead" % tmos_version raise UnsupportedOperation(msg) else: self._update(**kwargs)
python
def update(self, **kwargs): """Due to a password decryption bug we will disable update() method for 12.1.0 and up """ tmos_version = self._meta_data['bigip'].tmos_version if LooseVersion(tmos_version) > LooseVersion('12.0.0'): msg = "Update() is unsupported for User on version %s. " \ "Utilize Modify() method instead" % tmos_version raise UnsupportedOperation(msg) else: self._update(**kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "tmos_version", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "tmos_version", "if", "LooseVersion", "(", "tmos_version", ")", ">", "LooseVersion", "(", "'12.0.0'", ")", ":", "msg", "=", "\"Update() is unsupported for User on version %s. \"", "\"Utilize Modify() method instead\"", "%", "tmos_version", "raise", "UnsupportedOperation", "(", "msg", ")", "else", ":", "self", ".", "_update", "(", "*", "*", "kwargs", ")" ]
Due to a password decryption bug we will disable update() method for 12.1.0 and up
[ "Due", "to", "a", "password", "decryption", "bug" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/snmp.py#L128-L140
237,312
F5Networks/f5-common-python
devtools/template_engine.py
TemplateEngine._process_config_with_kind
def _process_config_with_kind(self, raw_conf): '''Use this to decide which format is called for by the kind. NOTE, order matters since subsequent conditions are not evaluated is an earlier condition is met. In the some cases, e.g. a kind contains both "stats" and "state", this will become an issue. ''' kind = raw_conf[u"kind"] org_match = re.match(self.OC_pattern, kind) if org_match: return self._format_org_collection(org_match, kind, raw_conf) elif 'collectionstate' in kind: return self._format_collection(kind, raw_conf) elif kind.endswith('stats'): return self._format_stats(kind, raw_conf) elif kind.endswith('state'): return self._format_resource(kind, raw_conf)
python
def _process_config_with_kind(self, raw_conf): '''Use this to decide which format is called for by the kind. NOTE, order matters since subsequent conditions are not evaluated is an earlier condition is met. In the some cases, e.g. a kind contains both "stats" and "state", this will become an issue. ''' kind = raw_conf[u"kind"] org_match = re.match(self.OC_pattern, kind) if org_match: return self._format_org_collection(org_match, kind, raw_conf) elif 'collectionstate' in kind: return self._format_collection(kind, raw_conf) elif kind.endswith('stats'): return self._format_stats(kind, raw_conf) elif kind.endswith('state'): return self._format_resource(kind, raw_conf)
[ "def", "_process_config_with_kind", "(", "self", ",", "raw_conf", ")", ":", "kind", "=", "raw_conf", "[", "u\"kind\"", "]", "org_match", "=", "re", ".", "match", "(", "self", ".", "OC_pattern", ",", "kind", ")", "if", "org_match", ":", "return", "self", ".", "_format_org_collection", "(", "org_match", ",", "kind", ",", "raw_conf", ")", "elif", "'collectionstate'", "in", "kind", ":", "return", "self", ".", "_format_collection", "(", "kind", ",", "raw_conf", ")", "elif", "kind", ".", "endswith", "(", "'stats'", ")", ":", "return", "self", ".", "_format_stats", "(", "kind", ",", "raw_conf", ")", "elif", "kind", ".", "endswith", "(", "'state'", ")", ":", "return", "self", ".", "_format_resource", "(", "kind", ",", "raw_conf", ")" ]
Use this to decide which format is called for by the kind. NOTE, order matters since subsequent conditions are not evaluated is an earlier condition is met. In the some cases, e.g. a kind contains both "stats" and "state", this will become an issue.
[ "Use", "this", "to", "decide", "which", "format", "is", "called", "for", "by", "the", "kind", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/devtools/template_engine.py#L204-L220
237,313
F5Networks/f5-common-python
f5/bigip/resource.py
_missing_required_parameters
def _missing_required_parameters(rqset, **kwargs): """Helper function to do operation on sets. Checks for any missing required parameters. Returns non-empty or empty list. With empty list being False. ::returns list """ key_set = set(list(iterkeys(kwargs))) required_minus_received = rqset - key_set if required_minus_received != set(): return list(required_minus_received)
python
def _missing_required_parameters(rqset, **kwargs): """Helper function to do operation on sets. Checks for any missing required parameters. Returns non-empty or empty list. With empty list being False. ::returns list """ key_set = set(list(iterkeys(kwargs))) required_minus_received = rqset - key_set if required_minus_received != set(): return list(required_minus_received)
[ "def", "_missing_required_parameters", "(", "rqset", ",", "*", "*", "kwargs", ")", ":", "key_set", "=", "set", "(", "list", "(", "iterkeys", "(", "kwargs", ")", ")", ")", "required_minus_received", "=", "rqset", "-", "key_set", "if", "required_minus_received", "!=", "set", "(", ")", ":", "return", "list", "(", "required_minus_received", ")" ]
Helper function to do operation on sets. Checks for any missing required parameters. Returns non-empty or empty list. With empty list being False. ::returns list
[ "Helper", "function", "to", "do", "operation", "on", "sets", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L137-L149
237,314
F5Networks/f5-common-python
f5/bigip/resource.py
PathElement._format_collection_name
def _format_collection_name(self): """Formats a name from Collection format Collections are of two name formats based on their actual URI representation in the REST service. 1. For cases where the actual URI of a collection is singular, for example, /mgmt/tm/ltm/node The name of the collection, as exposed to the user, will be made plural. For example, mgmt.tm.ltm.nodes 2. For cases where the actual URI of a collection is plural, for example, /mgmt/cm/shared/licensing/pools/ The name of the collection, as exposed to the user, will remain plural, but will have an `_s` appended to it. For example, mgmt.cm.shared.licensing.pools_s This method is responsible for undoing the user provided plurality. It ensures that the URI that is being sent to the REST service is correctly plural, or plural plus. Returns: A string representation of the user formatted Collection with its plurality identifier removed appropriately. """ base_uri = self._format_resource_name() if base_uri[-2:] == '_s': endind = 2 else: endind = 1 return base_uri[:-endind]
python
def _format_collection_name(self): """Formats a name from Collection format Collections are of two name formats based on their actual URI representation in the REST service. 1. For cases where the actual URI of a collection is singular, for example, /mgmt/tm/ltm/node The name of the collection, as exposed to the user, will be made plural. For example, mgmt.tm.ltm.nodes 2. For cases where the actual URI of a collection is plural, for example, /mgmt/cm/shared/licensing/pools/ The name of the collection, as exposed to the user, will remain plural, but will have an `_s` appended to it. For example, mgmt.cm.shared.licensing.pools_s This method is responsible for undoing the user provided plurality. It ensures that the URI that is being sent to the REST service is correctly plural, or plural plus. Returns: A string representation of the user formatted Collection with its plurality identifier removed appropriately. """ base_uri = self._format_resource_name() if base_uri[-2:] == '_s': endind = 2 else: endind = 1 return base_uri[:-endind]
[ "def", "_format_collection_name", "(", "self", ")", ":", "base_uri", "=", "self", ".", "_format_resource_name", "(", ")", "if", "base_uri", "[", "-", "2", ":", "]", "==", "'_s'", ":", "endind", "=", "2", "else", ":", "endind", "=", "1", "return", "base_uri", "[", ":", "-", "endind", "]" ]
Formats a name from Collection format Collections are of two name formats based on their actual URI representation in the REST service. 1. For cases where the actual URI of a collection is singular, for example, /mgmt/tm/ltm/node The name of the collection, as exposed to the user, will be made plural. For example, mgmt.tm.ltm.nodes 2. For cases where the actual URI of a collection is plural, for example, /mgmt/cm/shared/licensing/pools/ The name of the collection, as exposed to the user, will remain plural, but will have an `_s` appended to it. For example, mgmt.cm.shared.licensing.pools_s This method is responsible for undoing the user provided plurality. It ensures that the URI that is being sent to the REST service is correctly plural, or plural plus. Returns: A string representation of the user formatted Collection with its plurality identifier removed appropriately.
[ "Formats", "a", "name", "from", "Collection", "format" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L199-L238
237,315
F5Networks/f5-common-python
f5/bigip/resource.py
PathElement._check_command_parameters
def _check_command_parameters(self, **kwargs): """Params given to exec_cmd should satisfy required params. :params: kwargs :raises: MissingRequiredCommandParameter """ rset = self._meta_data['required_command_parameters'] check = _missing_required_parameters(rset, **kwargs) if check: error_message = 'Missing required params: %s' % check raise MissingRequiredCommandParameter(error_message)
python
def _check_command_parameters(self, **kwargs): """Params given to exec_cmd should satisfy required params. :params: kwargs :raises: MissingRequiredCommandParameter """ rset = self._meta_data['required_command_parameters'] check = _missing_required_parameters(rset, **kwargs) if check: error_message = 'Missing required params: %s' % check raise MissingRequiredCommandParameter(error_message)
[ "def", "_check_command_parameters", "(", "self", ",", "*", "*", "kwargs", ")", ":", "rset", "=", "self", ".", "_meta_data", "[", "'required_command_parameters'", "]", "check", "=", "_missing_required_parameters", "(", "rset", ",", "*", "*", "kwargs", ")", "if", "check", ":", "error_message", "=", "'Missing required params: %s'", "%", "check", "raise", "MissingRequiredCommandParameter", "(", "error_message", ")" ]
Params given to exec_cmd should satisfy required params. :params: kwargs :raises: MissingRequiredCommandParameter
[ "Params", "given", "to", "exec_cmd", "should", "satisfy", "required", "params", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L264-L274
237,316
F5Networks/f5-common-python
f5/bigip/resource.py
PathElement._handle_requests_params
def _handle_requests_params(self, kwargs): """Validate parameters that will be passed to the requests verbs. This method validates that there is no conflict in the names of the requests_params passed to the function and the other kwargs. It also ensures that the required request parameters for the object are added to the request params that are passed into the verbs. An example of the latter is ensuring that a certain version of the API is always called to add 'ver=11.6.0' to the url. """ requests_params = kwargs.pop('requests_params', {}) for param in requests_params: if param in kwargs: error_message = 'Requests Parameter %r collides with a load'\ ' parameter of the same name.' % param raise RequestParamKwargCollision(error_message) # If we have an icontrol version we need to add 'ver' to params if self._meta_data['icontrol_version']: params = requests_params.pop('params', {}) params.update({'ver': self._meta_data['icontrol_version']}) requests_params.update({'params': params}) return requests_params
python
def _handle_requests_params(self, kwargs): """Validate parameters that will be passed to the requests verbs. This method validates that there is no conflict in the names of the requests_params passed to the function and the other kwargs. It also ensures that the required request parameters for the object are added to the request params that are passed into the verbs. An example of the latter is ensuring that a certain version of the API is always called to add 'ver=11.6.0' to the url. """ requests_params = kwargs.pop('requests_params', {}) for param in requests_params: if param in kwargs: error_message = 'Requests Parameter %r collides with a load'\ ' parameter of the same name.' % param raise RequestParamKwargCollision(error_message) # If we have an icontrol version we need to add 'ver' to params if self._meta_data['icontrol_version']: params = requests_params.pop('params', {}) params.update({'ver': self._meta_data['icontrol_version']}) requests_params.update({'params': params}) return requests_params
[ "def", "_handle_requests_params", "(", "self", ",", "kwargs", ")", ":", "requests_params", "=", "kwargs", ".", "pop", "(", "'requests_params'", ",", "{", "}", ")", "for", "param", "in", "requests_params", ":", "if", "param", "in", "kwargs", ":", "error_message", "=", "'Requests Parameter %r collides with a load'", "' parameter of the same name.'", "%", "param", "raise", "RequestParamKwargCollision", "(", "error_message", ")", "# If we have an icontrol version we need to add 'ver' to params", "if", "self", ".", "_meta_data", "[", "'icontrol_version'", "]", ":", "params", "=", "requests_params", ".", "pop", "(", "'params'", ",", "{", "}", ")", "params", ".", "update", "(", "{", "'ver'", ":", "self", ".", "_meta_data", "[", "'icontrol_version'", "]", "}", ")", "requests_params", ".", "update", "(", "{", "'params'", ":", "params", "}", ")", "return", "requests_params" ]
Validate parameters that will be passed to the requests verbs. This method validates that there is no conflict in the names of the requests_params passed to the function and the other kwargs. It also ensures that the required request parameters for the object are added to the request params that are passed into the verbs. An example of the latter is ensuring that a certain version of the API is always called to add 'ver=11.6.0' to the url.
[ "Validate", "parameters", "that", "will", "be", "passed", "to", "the", "requests", "verbs", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L298-L319
237,317
F5Networks/f5-common-python
f5/bigip/resource.py
PathElement._check_exclusive_parameters
def _check_exclusive_parameters(self, **kwargs): """Check for mutually exclusive attributes in kwargs. :raises ExclusiveAttributesPresent """ if len(self._meta_data['exclusive_attributes']) > 0: attr_set = set(list(iterkeys(kwargs))) ex_set = set(self._meta_data['exclusive_attributes'][0]) common_set = sorted(attr_set.intersection(ex_set)) if len(common_set) > 1: cset = ', '.join(common_set) error = 'Mutually exclusive arguments submitted. ' \ 'The following arguments cannot be set ' \ 'together: "%s".' % cset raise ExclusiveAttributesPresent(error)
python
def _check_exclusive_parameters(self, **kwargs): """Check for mutually exclusive attributes in kwargs. :raises ExclusiveAttributesPresent """ if len(self._meta_data['exclusive_attributes']) > 0: attr_set = set(list(iterkeys(kwargs))) ex_set = set(self._meta_data['exclusive_attributes'][0]) common_set = sorted(attr_set.intersection(ex_set)) if len(common_set) > 1: cset = ', '.join(common_set) error = 'Mutually exclusive arguments submitted. ' \ 'The following arguments cannot be set ' \ 'together: "%s".' % cset raise ExclusiveAttributesPresent(error)
[ "def", "_check_exclusive_parameters", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "self", ".", "_meta_data", "[", "'exclusive_attributes'", "]", ")", ">", "0", ":", "attr_set", "=", "set", "(", "list", "(", "iterkeys", "(", "kwargs", ")", ")", ")", "ex_set", "=", "set", "(", "self", ".", "_meta_data", "[", "'exclusive_attributes'", "]", "[", "0", "]", ")", "common_set", "=", "sorted", "(", "attr_set", ".", "intersection", "(", "ex_set", ")", ")", "if", "len", "(", "common_set", ")", ">", "1", ":", "cset", "=", "', '", ".", "join", "(", "common_set", ")", "error", "=", "'Mutually exclusive arguments submitted. '", "'The following arguments cannot be set '", "'together: \"%s\".'", "%", "cset", "raise", "ExclusiveAttributesPresent", "(", "error", ")" ]
Check for mutually exclusive attributes in kwargs. :raises ExclusiveAttributesPresent
[ "Check", "for", "mutually", "exclusive", "attributes", "in", "kwargs", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L321-L335
237,318
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._modify
def _modify(self, **patch): """Wrapped with modify, override in a subclass to customize.""" requests_params, patch_uri, session, read_only = \ self._prepare_put_or_patch(patch) self._check_for_boolean_pair_reduction(patch) read_only_mutations = [] for attr in read_only: if attr in patch: read_only_mutations.append(attr) if read_only_mutations: msg = 'Attempted to mutate read-only attribute(s): %s' \ % read_only_mutations raise AttemptedMutationOfReadOnly(msg) patch = self._prepare_request_json(patch) response = session.patch(patch_uri, json=patch, **requests_params) self._local_update(response.json())
python
def _modify(self, **patch): """Wrapped with modify, override in a subclass to customize.""" requests_params, patch_uri, session, read_only = \ self._prepare_put_or_patch(patch) self._check_for_boolean_pair_reduction(patch) read_only_mutations = [] for attr in read_only: if attr in patch: read_only_mutations.append(attr) if read_only_mutations: msg = 'Attempted to mutate read-only attribute(s): %s' \ % read_only_mutations raise AttemptedMutationOfReadOnly(msg) patch = self._prepare_request_json(patch) response = session.patch(patch_uri, json=patch, **requests_params) self._local_update(response.json())
[ "def", "_modify", "(", "self", ",", "*", "*", "patch", ")", ":", "requests_params", ",", "patch_uri", ",", "session", ",", "read_only", "=", "self", ".", "_prepare_put_or_patch", "(", "patch", ")", "self", ".", "_check_for_boolean_pair_reduction", "(", "patch", ")", "read_only_mutations", "=", "[", "]", "for", "attr", "in", "read_only", ":", "if", "attr", "in", "patch", ":", "read_only_mutations", ".", "append", "(", "attr", ")", "if", "read_only_mutations", ":", "msg", "=", "'Attempted to mutate read-only attribute(s): %s'", "%", "read_only_mutations", "raise", "AttemptedMutationOfReadOnly", "(", "msg", ")", "patch", "=", "self", ".", "_prepare_request_json", "(", "patch", ")", "response", "=", "session", ".", "patch", "(", "patch_uri", ",", "json", "=", "patch", ",", "*", "*", "requests_params", ")", "self", ".", "_local_update", "(", "response", ".", "json", "(", ")", ")" ]
Wrapped with modify, override in a subclass to customize.
[ "Wrapped", "with", "modify", "override", "in", "a", "subclass", "to", "customize", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L388-L405
237,319
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._check_for_boolean_pair_reduction
def _check_for_boolean_pair_reduction(self, kwargs): """Check if boolean pairs should be reduced in this resource.""" if 'reduction_forcing_pairs' in self._meta_data: for key1, key2 in self._meta_data['reduction_forcing_pairs']: kwargs = self._reduce_boolean_pair(kwargs, key1, key2) return kwargs
python
def _check_for_boolean_pair_reduction(self, kwargs): """Check if boolean pairs should be reduced in this resource.""" if 'reduction_forcing_pairs' in self._meta_data: for key1, key2 in self._meta_data['reduction_forcing_pairs']: kwargs = self._reduce_boolean_pair(kwargs, key1, key2) return kwargs
[ "def", "_check_for_boolean_pair_reduction", "(", "self", ",", "kwargs", ")", ":", "if", "'reduction_forcing_pairs'", "in", "self", ".", "_meta_data", ":", "for", "key1", ",", "key2", "in", "self", ".", "_meta_data", "[", "'reduction_forcing_pairs'", "]", ":", "kwargs", "=", "self", ".", "_reduce_boolean_pair", "(", "kwargs", ",", "key1", ",", "key2", ")", "return", "kwargs" ]
Check if boolean pairs should be reduced in this resource.
[ "Check", "if", "boolean", "pairs", "should", "be", "reduced", "in", "this", "resource", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L413-L419
237,320
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._prepare_put_or_patch
def _prepare_put_or_patch(self, kwargs): """Retrieve the appropriate request items for put or patch calls.""" requests_params = self._handle_requests_params(kwargs) update_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] read_only = self._meta_data.get('read_only_attributes', []) return requests_params, update_uri, session, read_only
python
def _prepare_put_or_patch(self, kwargs): """Retrieve the appropriate request items for put or patch calls.""" requests_params = self._handle_requests_params(kwargs) update_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] read_only = self._meta_data.get('read_only_attributes', []) return requests_params, update_uri, session, read_only
[ "def", "_prepare_put_or_patch", "(", "self", ",", "kwargs", ")", ":", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "update_uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "read_only", "=", "self", ".", "_meta_data", ".", "get", "(", "'read_only_attributes'", ",", "[", "]", ")", "return", "requests_params", ",", "update_uri", ",", "session", ",", "read_only" ]
Retrieve the appropriate request items for put or patch calls.
[ "Retrieve", "the", "appropriate", "request", "items", "for", "put", "or", "patch", "calls", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L421-L428
237,321
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._prepare_request_json
def _prepare_request_json(self, kwargs): """Prepare request args for sending to device as JSON.""" # Check for python keywords in dict kwargs = self._check_for_python_keywords(kwargs) # Check for the key 'check' in kwargs if 'check' in kwargs: od = OrderedDict() od['check'] = kwargs['check'] kwargs.pop('check') od.update(kwargs) return od return kwargs
python
def _prepare_request_json(self, kwargs): """Prepare request args for sending to device as JSON.""" # Check for python keywords in dict kwargs = self._check_for_python_keywords(kwargs) # Check for the key 'check' in kwargs if 'check' in kwargs: od = OrderedDict() od['check'] = kwargs['check'] kwargs.pop('check') od.update(kwargs) return od return kwargs
[ "def", "_prepare_request_json", "(", "self", ",", "kwargs", ")", ":", "# Check for python keywords in dict", "kwargs", "=", "self", ".", "_check_for_python_keywords", "(", "kwargs", ")", "# Check for the key 'check' in kwargs", "if", "'check'", "in", "kwargs", ":", "od", "=", "OrderedDict", "(", ")", "od", "[", "'check'", "]", "=", "kwargs", "[", "'check'", "]", "kwargs", ".", "pop", "(", "'check'", ")", "od", ".", "update", "(", "kwargs", ")", "return", "od", "return", "kwargs" ]
Prepare request args for sending to device as JSON.
[ "Prepare", "request", "args", "for", "sending", "to", "device", "as", "JSON", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L430-L443
237,322
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._iter_list_for_dicts
def _iter_list_for_dicts(self, check_list): """Iterate over list to find dicts and check for python keywords.""" list_copy = copy.deepcopy(check_list) for index, elem in enumerate(check_list): if isinstance(elem, dict): list_copy[index] = self._check_for_python_keywords(elem) elif isinstance(elem, list): list_copy[index] = self._iter_list_for_dicts(elem) else: list_copy[index] = elem return list_copy
python
def _iter_list_for_dicts(self, check_list): """Iterate over list to find dicts and check for python keywords.""" list_copy = copy.deepcopy(check_list) for index, elem in enumerate(check_list): if isinstance(elem, dict): list_copy[index] = self._check_for_python_keywords(elem) elif isinstance(elem, list): list_copy[index] = self._iter_list_for_dicts(elem) else: list_copy[index] = elem return list_copy
[ "def", "_iter_list_for_dicts", "(", "self", ",", "check_list", ")", ":", "list_copy", "=", "copy", ".", "deepcopy", "(", "check_list", ")", "for", "index", ",", "elem", "in", "enumerate", "(", "check_list", ")", ":", "if", "isinstance", "(", "elem", ",", "dict", ")", ":", "list_copy", "[", "index", "]", "=", "self", ".", "_check_for_python_keywords", "(", "elem", ")", "elif", "isinstance", "(", "elem", ",", "list", ")", ":", "list_copy", "[", "index", "]", "=", "self", ".", "_iter_list_for_dicts", "(", "elem", ")", "else", ":", "list_copy", "[", "index", "]", "=", "elem", "return", "list_copy" ]
Iterate over list to find dicts and check for python keywords.
[ "Iterate", "over", "list", "to", "find", "dicts", "and", "check", "for", "python", "keywords", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L445-L456
237,323
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._check_for_python_keywords
def _check_for_python_keywords(self, kwargs): """When Python keywords seen, mutate to remove trailing underscore.""" kwargs_copy = copy.deepcopy(kwargs) for key, val in iteritems(kwargs): if isinstance(val, dict): kwargs_copy[key] = self._check_for_python_keywords(val) elif isinstance(val, list): kwargs_copy[key] = self._iter_list_for_dicts(val) else: if key.endswith('_'): strip_key = key.rstrip('_') if keyword.iskeyword(strip_key): kwargs_copy[strip_key] = val kwargs_copy.pop(key) return kwargs_copy
python
def _check_for_python_keywords(self, kwargs): """When Python keywords seen, mutate to remove trailing underscore.""" kwargs_copy = copy.deepcopy(kwargs) for key, val in iteritems(kwargs): if isinstance(val, dict): kwargs_copy[key] = self._check_for_python_keywords(val) elif isinstance(val, list): kwargs_copy[key] = self._iter_list_for_dicts(val) else: if key.endswith('_'): strip_key = key.rstrip('_') if keyword.iskeyword(strip_key): kwargs_copy[strip_key] = val kwargs_copy.pop(key) return kwargs_copy
[ "def", "_check_for_python_keywords", "(", "self", ",", "kwargs", ")", ":", "kwargs_copy", "=", "copy", ".", "deepcopy", "(", "kwargs", ")", "for", "key", ",", "val", "in", "iteritems", "(", "kwargs", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "kwargs_copy", "[", "key", "]", "=", "self", ".", "_check_for_python_keywords", "(", "val", ")", "elif", "isinstance", "(", "val", ",", "list", ")", ":", "kwargs_copy", "[", "key", "]", "=", "self", ".", "_iter_list_for_dicts", "(", "val", ")", "else", ":", "if", "key", ".", "endswith", "(", "'_'", ")", ":", "strip_key", "=", "key", ".", "rstrip", "(", "'_'", ")", "if", "keyword", ".", "iskeyword", "(", "strip_key", ")", ":", "kwargs_copy", "[", "strip_key", "]", "=", "val", "kwargs_copy", ".", "pop", "(", "key", ")", "return", "kwargs_copy" ]
When Python keywords seen, mutate to remove trailing underscore.
[ "When", "Python", "keywords", "seen", "mutate", "to", "remove", "trailing", "underscore", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L458-L473
237,324
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._check_keys
def _check_keys(self, rdict): """Call this from _local_update to validate response keys disallowed server-response json keys: 1. The string-literal '_meta_data' 2. strings that are not valid Python 2.7 identifiers 3. strings beginning with '__'. :param rdict: from response.json() :raises: DeviceProvidesIncompatibleKey :returns: checked response rdict """ if '_meta_data' in rdict: error_message = "Response contains key '_meta_data' which is "\ "incompatible with this API!!\n Response json: %r" % rdict raise DeviceProvidesIncompatibleKey(error_message) for x in rdict: if not re.match(tokenize.Name, x): error_message = "Device provided %r which is disallowed"\ " because it's not a valid Python 2.7 identifier." % x raise DeviceProvidesIncompatibleKey(error_message) elif keyword.iskeyword(x): # If attribute is keyword, append underscore to attribute name rdict[x + '_'] = rdict[x] rdict.pop(x) elif x.startswith('__'): error_message = "Device provided %r which is disallowed"\ ", it mangles into a Python non-public attribute." % x raise DeviceProvidesIncompatibleKey(error_message) return rdict
python
def _check_keys(self, rdict): """Call this from _local_update to validate response keys disallowed server-response json keys: 1. The string-literal '_meta_data' 2. strings that are not valid Python 2.7 identifiers 3. strings beginning with '__'. :param rdict: from response.json() :raises: DeviceProvidesIncompatibleKey :returns: checked response rdict """ if '_meta_data' in rdict: error_message = "Response contains key '_meta_data' which is "\ "incompatible with this API!!\n Response json: %r" % rdict raise DeviceProvidesIncompatibleKey(error_message) for x in rdict: if not re.match(tokenize.Name, x): error_message = "Device provided %r which is disallowed"\ " because it's not a valid Python 2.7 identifier." % x raise DeviceProvidesIncompatibleKey(error_message) elif keyword.iskeyword(x): # If attribute is keyword, append underscore to attribute name rdict[x + '_'] = rdict[x] rdict.pop(x) elif x.startswith('__'): error_message = "Device provided %r which is disallowed"\ ", it mangles into a Python non-public attribute." % x raise DeviceProvidesIncompatibleKey(error_message) return rdict
[ "def", "_check_keys", "(", "self", ",", "rdict", ")", ":", "if", "'_meta_data'", "in", "rdict", ":", "error_message", "=", "\"Response contains key '_meta_data' which is \"", "\"incompatible with this API!!\\n Response json: %r\"", "%", "rdict", "raise", "DeviceProvidesIncompatibleKey", "(", "error_message", ")", "for", "x", "in", "rdict", ":", "if", "not", "re", ".", "match", "(", "tokenize", ".", "Name", ",", "x", ")", ":", "error_message", "=", "\"Device provided %r which is disallowed\"", "\" because it's not a valid Python 2.7 identifier.\"", "%", "x", "raise", "DeviceProvidesIncompatibleKey", "(", "error_message", ")", "elif", "keyword", ".", "iskeyword", "(", "x", ")", ":", "# If attribute is keyword, append underscore to attribute name", "rdict", "[", "x", "+", "'_'", "]", "=", "rdict", "[", "x", "]", "rdict", ".", "pop", "(", "x", ")", "elif", "x", ".", "startswith", "(", "'__'", ")", ":", "error_message", "=", "\"Device provided %r which is disallowed\"", "\", it mangles into a Python non-public attribute.\"", "%", "x", "raise", "DeviceProvidesIncompatibleKey", "(", "error_message", ")", "return", "rdict" ]
Call this from _local_update to validate response keys disallowed server-response json keys: 1. The string-literal '_meta_data' 2. strings that are not valid Python 2.7 identifiers 3. strings beginning with '__'. :param rdict: from response.json() :raises: DeviceProvidesIncompatibleKey :returns: checked response rdict
[ "Call", "this", "from", "_local_update", "to", "validate", "response", "keys" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L475-L504
237,325
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._local_update
def _local_update(self, rdict): """Call this with a response dictionary to update instance attrs. If the response has only valid keys, stash meta_data, replace __dict__, and reassign meta_data. :param rdict: response attributes derived from server JSON """ sanitized = self._check_keys(rdict) temp_meta = self._meta_data self.__dict__ = sanitized self._meta_data = temp_meta
python
def _local_update(self, rdict): """Call this with a response dictionary to update instance attrs. If the response has only valid keys, stash meta_data, replace __dict__, and reassign meta_data. :param rdict: response attributes derived from server JSON """ sanitized = self._check_keys(rdict) temp_meta = self._meta_data self.__dict__ = sanitized self._meta_data = temp_meta
[ "def", "_local_update", "(", "self", ",", "rdict", ")", ":", "sanitized", "=", "self", ".", "_check_keys", "(", "rdict", ")", "temp_meta", "=", "self", ".", "_meta_data", "self", ".", "__dict__", "=", "sanitized", "self", ".", "_meta_data", "=", "temp_meta" ]
Call this with a response dictionary to update instance attrs. If the response has only valid keys, stash meta_data, replace __dict__, and reassign meta_data. :param rdict: response attributes derived from server JSON
[ "Call", "this", "with", "a", "response", "dictionary", "to", "update", "instance", "attrs", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L506-L517
237,326
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._update
def _update(self, **kwargs): """wrapped with update, override that in a subclass to customize""" requests_params, update_uri, session, read_only = \ self._prepare_put_or_patch(kwargs) read_only_mutations = [] for attr in read_only: if attr in kwargs: read_only_mutations.append(attr) if read_only_mutations: msg = 'Attempted to mutate read-only attribute(s): %s' \ % read_only_mutations raise AttemptedMutationOfReadOnly(msg) # Get the current state of the object on BIG-IP® and check the # generation Use pop here because we don't want force in the data_dict force = self._check_force_arg(kwargs.pop('force', True)) if not force: # generation has a known server-side error self._check_generation() kwargs = self._check_for_boolean_pair_reduction(kwargs) # Save the meta data so we can add it back into self after we # load the new object. temp_meta = self.__dict__.pop('_meta_data') # Need to remove any of the Collection objects from self.__dict__ # because these are subCollections and _meta_data and # other non-BIG-IP® attrs are not removed from the subCollections # See issue #146 for details tmp = dict() for key, value in iteritems(self.__dict__): # In Python2 versions we were changing a dictionary in place, # but this cannot be done with an iterator as an error is raised. # So instead we create a temporary holder for the modified dict # and then re-assign it afterwards. if isinstance(value, Collection): pass else: tmp[key] = value self.__dict__ = tmp data_dict = self.to_dict() # Remove any read-only attributes from our data_dict before we update # the data dict with the attributes. If they pass in read-only attrs # in the method call we are going to let BIG-IP® let them know about it # when it fails for attr in read_only: data_dict.pop(attr, '') data_dict.update(kwargs) data_dict = self._prepare_request_json(data_dict) # Handles ConnectionAborted errors # # @see https://github.com/F5Networks/f5-ansible/issues/317 # @see https://github.com/requests/requests/issues/2364 for _ in range(0, 30): try: response = session.put(update_uri, json=data_dict, **requests_params) self._meta_data = temp_meta self._local_update(response.json()) break except iControlUnexpectedHTTPError: response = session.get(update_uri, **requests_params) self._meta_data = temp_meta self._local_update(response.json()) raise except ConnectionError as ex: if 'Connection aborted' in str(ex): time.sleep(1) continue else: raise
python
def _update(self, **kwargs): """wrapped with update, override that in a subclass to customize""" requests_params, update_uri, session, read_only = \ self._prepare_put_or_patch(kwargs) read_only_mutations = [] for attr in read_only: if attr in kwargs: read_only_mutations.append(attr) if read_only_mutations: msg = 'Attempted to mutate read-only attribute(s): %s' \ % read_only_mutations raise AttemptedMutationOfReadOnly(msg) # Get the current state of the object on BIG-IP® and check the # generation Use pop here because we don't want force in the data_dict force = self._check_force_arg(kwargs.pop('force', True)) if not force: # generation has a known server-side error self._check_generation() kwargs = self._check_for_boolean_pair_reduction(kwargs) # Save the meta data so we can add it back into self after we # load the new object. temp_meta = self.__dict__.pop('_meta_data') # Need to remove any of the Collection objects from self.__dict__ # because these are subCollections and _meta_data and # other non-BIG-IP® attrs are not removed from the subCollections # See issue #146 for details tmp = dict() for key, value in iteritems(self.__dict__): # In Python2 versions we were changing a dictionary in place, # but this cannot be done with an iterator as an error is raised. # So instead we create a temporary holder for the modified dict # and then re-assign it afterwards. if isinstance(value, Collection): pass else: tmp[key] = value self.__dict__ = tmp data_dict = self.to_dict() # Remove any read-only attributes from our data_dict before we update # the data dict with the attributes. If they pass in read-only attrs # in the method call we are going to let BIG-IP® let them know about it # when it fails for attr in read_only: data_dict.pop(attr, '') data_dict.update(kwargs) data_dict = self._prepare_request_json(data_dict) # Handles ConnectionAborted errors # # @see https://github.com/F5Networks/f5-ansible/issues/317 # @see https://github.com/requests/requests/issues/2364 for _ in range(0, 30): try: response = session.put(update_uri, json=data_dict, **requests_params) self._meta_data = temp_meta self._local_update(response.json()) break except iControlUnexpectedHTTPError: response = session.get(update_uri, **requests_params) self._meta_data = temp_meta self._local_update(response.json()) raise except ConnectionError as ex: if 'Connection aborted' in str(ex): time.sleep(1) continue else: raise
[ "def", "_update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "requests_params", ",", "update_uri", ",", "session", ",", "read_only", "=", "self", ".", "_prepare_put_or_patch", "(", "kwargs", ")", "read_only_mutations", "=", "[", "]", "for", "attr", "in", "read_only", ":", "if", "attr", "in", "kwargs", ":", "read_only_mutations", ".", "append", "(", "attr", ")", "if", "read_only_mutations", ":", "msg", "=", "'Attempted to mutate read-only attribute(s): %s'", "%", "read_only_mutations", "raise", "AttemptedMutationOfReadOnly", "(", "msg", ")", "# Get the current state of the object on BIG-IP® and check the", "# generation Use pop here because we don't want force in the data_dict", "force", "=", "self", ".", "_check_force_arg", "(", "kwargs", ".", "pop", "(", "'force'", ",", "True", ")", ")", "if", "not", "force", ":", "# generation has a known server-side error", "self", ".", "_check_generation", "(", ")", "kwargs", "=", "self", ".", "_check_for_boolean_pair_reduction", "(", "kwargs", ")", "# Save the meta data so we can add it back into self after we", "# load the new object.", "temp_meta", "=", "self", ".", "__dict__", ".", "pop", "(", "'_meta_data'", ")", "# Need to remove any of the Collection objects from self.__dict__", "# because these are subCollections and _meta_data and", "# other non-BIG-IP® attrs are not removed from the subCollections", "# See issue #146 for details", "tmp", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "__dict__", ")", ":", "# In Python2 versions we were changing a dictionary in place,", "# but this cannot be done with an iterator as an error is raised.", "# So instead we create a temporary holder for the modified dict", "# and then re-assign it afterwards.", "if", "isinstance", "(", "value", ",", "Collection", ")", ":", "pass", "else", ":", "tmp", "[", "key", "]", "=", "value", "self", ".", "__dict__", "=", "tmp", "data_dict", "=", "self", ".", "to_dict", "(", ")", "# Remove any read-only attributes from our data_dict before we update", "# the data dict with the attributes. If they pass in read-only attrs", "# in the method call we are going to let BIG-IP® let them know about it", "# when it fails", "for", "attr", "in", "read_only", ":", "data_dict", ".", "pop", "(", "attr", ",", "''", ")", "data_dict", ".", "update", "(", "kwargs", ")", "data_dict", "=", "self", ".", "_prepare_request_json", "(", "data_dict", ")", "# Handles ConnectionAborted errors", "#", "# @see https://github.com/F5Networks/f5-ansible/issues/317", "# @see https://github.com/requests/requests/issues/2364", "for", "_", "in", "range", "(", "0", ",", "30", ")", ":", "try", ":", "response", "=", "session", ".", "put", "(", "update_uri", ",", "json", "=", "data_dict", ",", "*", "*", "requests_params", ")", "self", ".", "_meta_data", "=", "temp_meta", "self", ".", "_local_update", "(", "response", ".", "json", "(", ")", ")", "break", "except", "iControlUnexpectedHTTPError", ":", "response", "=", "session", ".", "get", "(", "update_uri", ",", "*", "*", "requests_params", ")", "self", ".", "_meta_data", "=", "temp_meta", "self", ".", "_local_update", "(", "response", ".", "json", "(", ")", ")", "raise", "except", "ConnectionError", "as", "ex", ":", "if", "'Connection aborted'", "in", "str", "(", "ex", ")", ":", "time", ".", "sleep", "(", "1", ")", "continue", "else", ":", "raise" ]
wrapped with update, override that in a subclass to customize
[ "wrapped", "with", "update", "override", "that", "in", "a", "subclass", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L519-L594
237,327
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._refresh
def _refresh(self, **kwargs): """wrapped by `refresh` override that in a subclass to customize""" requests_params = self._handle_requests_params(kwargs) refresh_session = self._meta_data['bigip']._meta_data['icr_session'] if self._meta_data['uri'].endswith('/stats/'): # Slicing off the trailing slash here for Stats enpoints because # iWorkflow doesn't consider those `stats` URLs valid if they # include the trailing slash. # # Other than that, functionality does not change uri = self._meta_data['uri'][0:-1] else: uri = self._meta_data['uri'] response = refresh_session.get(uri, **requests_params) self._local_update(response.json())
python
def _refresh(self, **kwargs): """wrapped by `refresh` override that in a subclass to customize""" requests_params = self._handle_requests_params(kwargs) refresh_session = self._meta_data['bigip']._meta_data['icr_session'] if self._meta_data['uri'].endswith('/stats/'): # Slicing off the trailing slash here for Stats enpoints because # iWorkflow doesn't consider those `stats` URLs valid if they # include the trailing slash. # # Other than that, functionality does not change uri = self._meta_data['uri'][0:-1] else: uri = self._meta_data['uri'] response = refresh_session.get(uri, **requests_params) self._local_update(response.json())
[ "def", "_refresh", "(", "self", ",", "*", "*", "kwargs", ")", ":", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "refresh_session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "if", "self", ".", "_meta_data", "[", "'uri'", "]", ".", "endswith", "(", "'/stats/'", ")", ":", "# Slicing off the trailing slash here for Stats enpoints because", "# iWorkflow doesn't consider those `stats` URLs valid if they", "# include the trailing slash.", "#", "# Other than that, functionality does not change", "uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "[", "0", ":", "-", "1", "]", "else", ":", "uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "response", "=", "refresh_session", ".", "get", "(", "uri", ",", "*", "*", "requests_params", ")", "self", ".", "_local_update", "(", "response", ".", "json", "(", ")", ")" ]
wrapped by `refresh` override that in a subclass to customize
[ "wrapped", "by", "refresh", "override", "that", "in", "a", "subclass", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L619-L635
237,328
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._produce_instance
def _produce_instance(self, response): '''Generate a new self, which is an instance of the self.''' new_instance = self._stamp_out_core() # Post-process the response new_instance._local_update(response.json()) # Allow for example files, which are KindTypeMismatches if hasattr(new_instance, 'selfLink'): if new_instance.kind != new_instance._meta_data[ 'required_json_kind'] \ and new_instance.kind != "tm:transaction:commandsstate" \ and 'example' not in new_instance.selfLink.split('/')[-1]: error_message = "For instances of type '%r' the corresponding" \ " kind must be '%r' but creation returned JSON with kind: %r" \ % (new_instance.__class__.__name__, new_instance._meta_data[ 'required_json_kind'], new_instance.kind) raise KindTypeMismatch(error_message) else: if new_instance.kind != new_instance._meta_data[ 'required_json_kind'] \ and new_instance.kind != "tm:transaction:commandsstate": error_message = "For instances of type '%r' the corresponding" \ " kind must be '%r' but creation returned JSON with kind: %r" \ % (new_instance.__class__.__name__, new_instance._meta_data[ 'required_json_kind'], new_instance.kind) raise KindTypeMismatch(error_message) # Update the object to have the correct functional uri. new_instance._activate_URI(new_instance.selfLink) return new_instance
python
def _produce_instance(self, response): '''Generate a new self, which is an instance of the self.''' new_instance = self._stamp_out_core() # Post-process the response new_instance._local_update(response.json()) # Allow for example files, which are KindTypeMismatches if hasattr(new_instance, 'selfLink'): if new_instance.kind != new_instance._meta_data[ 'required_json_kind'] \ and new_instance.kind != "tm:transaction:commandsstate" \ and 'example' not in new_instance.selfLink.split('/')[-1]: error_message = "For instances of type '%r' the corresponding" \ " kind must be '%r' but creation returned JSON with kind: %r" \ % (new_instance.__class__.__name__, new_instance._meta_data[ 'required_json_kind'], new_instance.kind) raise KindTypeMismatch(error_message) else: if new_instance.kind != new_instance._meta_data[ 'required_json_kind'] \ and new_instance.kind != "tm:transaction:commandsstate": error_message = "For instances of type '%r' the corresponding" \ " kind must be '%r' but creation returned JSON with kind: %r" \ % (new_instance.__class__.__name__, new_instance._meta_data[ 'required_json_kind'], new_instance.kind) raise KindTypeMismatch(error_message) # Update the object to have the correct functional uri. new_instance._activate_URI(new_instance.selfLink) return new_instance
[ "def", "_produce_instance", "(", "self", ",", "response", ")", ":", "new_instance", "=", "self", ".", "_stamp_out_core", "(", ")", "# Post-process the response", "new_instance", ".", "_local_update", "(", "response", ".", "json", "(", ")", ")", "# Allow for example files, which are KindTypeMismatches", "if", "hasattr", "(", "new_instance", ",", "'selfLink'", ")", ":", "if", "new_instance", ".", "kind", "!=", "new_instance", ".", "_meta_data", "[", "'required_json_kind'", "]", "and", "new_instance", ".", "kind", "!=", "\"tm:transaction:commandsstate\"", "and", "'example'", "not", "in", "new_instance", ".", "selfLink", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ":", "error_message", "=", "\"For instances of type '%r' the corresponding\"", "\" kind must be '%r' but creation returned JSON with kind: %r\"", "%", "(", "new_instance", ".", "__class__", ".", "__name__", ",", "new_instance", ".", "_meta_data", "[", "'required_json_kind'", "]", ",", "new_instance", ".", "kind", ")", "raise", "KindTypeMismatch", "(", "error_message", ")", "else", ":", "if", "new_instance", ".", "kind", "!=", "new_instance", ".", "_meta_data", "[", "'required_json_kind'", "]", "and", "new_instance", ".", "kind", "!=", "\"tm:transaction:commandsstate\"", ":", "error_message", "=", "\"For instances of type '%r' the corresponding\"", "\" kind must be '%r' but creation returned JSON with kind: %r\"", "%", "(", "new_instance", ".", "__class__", ".", "__name__", ",", "new_instance", ".", "_meta_data", "[", "'required_json_kind'", "]", ",", "new_instance", ".", "kind", ")", "raise", "KindTypeMismatch", "(", "error_message", ")", "# Update the object to have the correct functional uri.", "new_instance", ".", "_activate_URI", "(", "new_instance", ".", "selfLink", ")", "return", "new_instance" ]
Generate a new self, which is an instance of the self.
[ "Generate", "a", "new", "self", "which", "is", "an", "instance", "of", "the", "self", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L681-L714
237,329
F5Networks/f5-common-python
f5/bigip/resource.py
ResourceBase._reduce_boolean_pair
def _reduce_boolean_pair(self, config_dict, key1, key2): """Ensure only one key with a boolean value is present in dict. :param config_dict: dict -- dictionary of config or kwargs :param key1: string -- first key name :param key2: string -- second key name :raises: BooleansToReduceHaveSameValue """ if key1 in config_dict and key2 in config_dict \ and config_dict[key1] == config_dict[key2]: msg = 'Boolean pair, %s and %s, have same value: %s. If both ' \ 'are given to this method, they cannot be the same, as this ' \ 'method cannot decide which one should be True.' \ % (key1, key2, config_dict[key1]) raise BooleansToReduceHaveSameValue(msg) elif key1 in config_dict and not config_dict[key1]: config_dict[key2] = True config_dict.pop(key1) elif key2 in config_dict and not config_dict[key2]: config_dict[key1] = True config_dict.pop(key2) return config_dict
python
def _reduce_boolean_pair(self, config_dict, key1, key2): """Ensure only one key with a boolean value is present in dict. :param config_dict: dict -- dictionary of config or kwargs :param key1: string -- first key name :param key2: string -- second key name :raises: BooleansToReduceHaveSameValue """ if key1 in config_dict and key2 in config_dict \ and config_dict[key1] == config_dict[key2]: msg = 'Boolean pair, %s and %s, have same value: %s. If both ' \ 'are given to this method, they cannot be the same, as this ' \ 'method cannot decide which one should be True.' \ % (key1, key2, config_dict[key1]) raise BooleansToReduceHaveSameValue(msg) elif key1 in config_dict and not config_dict[key1]: config_dict[key2] = True config_dict.pop(key1) elif key2 in config_dict and not config_dict[key2]: config_dict[key1] = True config_dict.pop(key2) return config_dict
[ "def", "_reduce_boolean_pair", "(", "self", ",", "config_dict", ",", "key1", ",", "key2", ")", ":", "if", "key1", "in", "config_dict", "and", "key2", "in", "config_dict", "and", "config_dict", "[", "key1", "]", "==", "config_dict", "[", "key2", "]", ":", "msg", "=", "'Boolean pair, %s and %s, have same value: %s. If both '", "'are given to this method, they cannot be the same, as this '", "'method cannot decide which one should be True.'", "%", "(", "key1", ",", "key2", ",", "config_dict", "[", "key1", "]", ")", "raise", "BooleansToReduceHaveSameValue", "(", "msg", ")", "elif", "key1", "in", "config_dict", "and", "not", "config_dict", "[", "key1", "]", ":", "config_dict", "[", "key2", "]", "=", "True", "config_dict", ".", "pop", "(", "key1", ")", "elif", "key2", "in", "config_dict", "and", "not", "config_dict", "[", "key2", "]", ":", "config_dict", "[", "key1", "]", "=", "True", "config_dict", ".", "pop", "(", "key2", ")", "return", "config_dict" ]
Ensure only one key with a boolean value is present in dict. :param config_dict: dict -- dictionary of config or kwargs :param key1: string -- first key name :param key2: string -- second key name :raises: BooleansToReduceHaveSameValue
[ "Ensure", "only", "one", "key", "with", "a", "boolean", "value", "is", "present", "in", "dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L716-L738
237,330
F5Networks/f5-common-python
f5/bigip/resource.py
Collection.get_collection
def get_collection(self, **kwargs): """Get an iterator of Python ``Resource`` objects that represent URIs. The returned objects are Pythonic `Resource`s that map to the most recently `refreshed` state of uris-resources published by the device. In order to instantiate the correct types, the concrete subclass must populate its registry with acceptable types, based on the `kind` field returned by the REST server. .. note:: This method implies a single REST transaction with the Collection subclass URI. :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) return list_of_contents
python
def get_collection(self, **kwargs): """Get an iterator of Python ``Resource`` objects that represent URIs. The returned objects are Pythonic `Resource`s that map to the most recently `refreshed` state of uris-resources published by the device. In order to instantiate the correct types, the concrete subclass must populate its registry with acceptable types, based on the `kind` field returned by the REST server. .. note:: This method implies a single REST transaction with the Collection subclass URI. :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) 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", ")", "return", "list_of_contents" ]
Get an iterator of Python ``Resource`` objects that represent URIs. The returned objects are Pythonic `Resource`s that map to the most recently `refreshed` state of uris-resources published by the device. In order to instantiate the correct types, the concrete subclass must populate its registry with acceptable types, based on the `kind` field returned by the REST server. .. note:: This method implies a single REST transaction with the Collection subclass URI. :raises: UnregisteredKind :returns: list of reference dicts and Python ``Resource`` objects
[ "Get", "an", "iterator", "of", "Python", "Resource", "objects", "that", "represent", "URIs", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L783-L819
237,331
F5Networks/f5-common-python
f5/bigip/resource.py
Collection._delete_collection
def _delete_collection(self, **kwargs): """wrapped with delete_collection, override that in a sublcass to customize """ error_message = "The request must include \"requests_params\": {\"params\": \"options=<glob pattern>\"} as kwarg" try: if kwargs['requests_params']['params'].split('=')[0] != 'options': raise MissingRequiredRequestsParameter(error_message) except KeyError: raise requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] session.delete(delete_uri, **requests_params)
python
def _delete_collection(self, **kwargs): """wrapped with delete_collection, override that in a sublcass to customize """ error_message = "The request must include \"requests_params\": {\"params\": \"options=<glob pattern>\"} as kwarg" try: if kwargs['requests_params']['params'].split('=')[0] != 'options': raise MissingRequiredRequestsParameter(error_message) except KeyError: raise requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] session.delete(delete_uri, **requests_params)
[ "def", "_delete_collection", "(", "self", ",", "*", "*", "kwargs", ")", ":", "error_message", "=", "\"The request must include \\\"requests_params\\\": {\\\"params\\\": \\\"options=<glob pattern>\\\"} as kwarg\"", "try", ":", "if", "kwargs", "[", "'requests_params'", "]", "[", "'params'", "]", ".", "split", "(", "'='", ")", "[", "0", "]", "!=", "'options'", ":", "raise", "MissingRequiredRequestsParameter", "(", "error_message", ")", "except", "KeyError", ":", "raise", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "delete_uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "session", ".", "delete", "(", "delete_uri", ",", "*", "*", "requests_params", ")" ]
wrapped with delete_collection, override that in a sublcass to customize
[ "wrapped", "with", "delete_collection", "override", "that", "in", "a", "sublcass", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L821-L834
237,332
F5Networks/f5-common-python
f5/bigip/resource.py
Resource._activate_URI
def _activate_URI(self, selfLinkuri): """Call this with a selfLink, after it's returned in _create or _load. Each instance is tightly bound to a particular service URI. When that service is created by this library, or loaded from the device, the URI is set to self._meta_data['uri']. This operation can only occur once, any subsequent attempt to manipulate self._meta_data['uri'] is probably a mistake. self.selfLink references a value that is returned as a JSON value from the device. This value contains "localhost" as the domain or the uri. "localhost" is only conceivably useful if the client library is run on the device itself, so it is replaced with the domain this API used to communicate with the device. self.selfLink correctly contains a complete uri, that is only _now_ (post create or load) available to self. Now that the complete URI is available to self, it is now possible to reference subcollections, as attributes of self! e.g. a resource with a uri path like: "/mgmt/tm/ltm/pool/~Common~pool_collection1/members" The mechanism used to enable this change is to set the `allowed_lazy_attributes` _meta_data key to hold values of the `attribute_registry` _meta_data key. Finally we stash the corrected `uri`, returned hash_fragment, query args, and of course allowed_lazy_attributes in _meta_data. :param selfLinkuri: the server provided selfLink (contains localhost) :raises: URICreationCollision """ # netloc local alias uri = urlparse.urlsplit(str(self._meta_data['bigip']._meta_data['uri'])) # attrs local alias attribute_reg = self._meta_data.get('attribute_registry', {}) attrs = list(itervalues(attribute_reg)) attrs = self._assign_stats(attrs) (scheme, domain, path, qarg, frag) = urlparse.urlsplit(selfLinkuri) path_uri = urlparse.urlunsplit((scheme, uri.netloc, path, '', '')) if not path_uri.endswith('/'): path_uri = path_uri + '/' qargs = urlparse.parse_qs(qarg) self._meta_data.update({'uri': path_uri, 'creation_uri_qargs': qargs, 'creation_uri_frag': frag, 'allowed_lazy_attributes': attrs})
python
def _activate_URI(self, selfLinkuri): """Call this with a selfLink, after it's returned in _create or _load. Each instance is tightly bound to a particular service URI. When that service is created by this library, or loaded from the device, the URI is set to self._meta_data['uri']. This operation can only occur once, any subsequent attempt to manipulate self._meta_data['uri'] is probably a mistake. self.selfLink references a value that is returned as a JSON value from the device. This value contains "localhost" as the domain or the uri. "localhost" is only conceivably useful if the client library is run on the device itself, so it is replaced with the domain this API used to communicate with the device. self.selfLink correctly contains a complete uri, that is only _now_ (post create or load) available to self. Now that the complete URI is available to self, it is now possible to reference subcollections, as attributes of self! e.g. a resource with a uri path like: "/mgmt/tm/ltm/pool/~Common~pool_collection1/members" The mechanism used to enable this change is to set the `allowed_lazy_attributes` _meta_data key to hold values of the `attribute_registry` _meta_data key. Finally we stash the corrected `uri`, returned hash_fragment, query args, and of course allowed_lazy_attributes in _meta_data. :param selfLinkuri: the server provided selfLink (contains localhost) :raises: URICreationCollision """ # netloc local alias uri = urlparse.urlsplit(str(self._meta_data['bigip']._meta_data['uri'])) # attrs local alias attribute_reg = self._meta_data.get('attribute_registry', {}) attrs = list(itervalues(attribute_reg)) attrs = self._assign_stats(attrs) (scheme, domain, path, qarg, frag) = urlparse.urlsplit(selfLinkuri) path_uri = urlparse.urlunsplit((scheme, uri.netloc, path, '', '')) if not path_uri.endswith('/'): path_uri = path_uri + '/' qargs = urlparse.parse_qs(qarg) self._meta_data.update({'uri': path_uri, 'creation_uri_qargs': qargs, 'creation_uri_frag': frag, 'allowed_lazy_attributes': attrs})
[ "def", "_activate_URI", "(", "self", ",", "selfLinkuri", ")", ":", "# netloc local alias", "uri", "=", "urlparse", ".", "urlsplit", "(", "str", "(", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'uri'", "]", ")", ")", "# attrs local alias", "attribute_reg", "=", "self", ".", "_meta_data", ".", "get", "(", "'attribute_registry'", ",", "{", "}", ")", "attrs", "=", "list", "(", "itervalues", "(", "attribute_reg", ")", ")", "attrs", "=", "self", ".", "_assign_stats", "(", "attrs", ")", "(", "scheme", ",", "domain", ",", "path", ",", "qarg", ",", "frag", ")", "=", "urlparse", ".", "urlsplit", "(", "selfLinkuri", ")", "path_uri", "=", "urlparse", ".", "urlunsplit", "(", "(", "scheme", ",", "uri", ".", "netloc", ",", "path", ",", "''", ",", "''", ")", ")", "if", "not", "path_uri", ".", "endswith", "(", "'/'", ")", ":", "path_uri", "=", "path_uri", "+", "'/'", "qargs", "=", "urlparse", ".", "parse_qs", "(", "qarg", ")", "self", ".", "_meta_data", ".", "update", "(", "{", "'uri'", ":", "path_uri", ",", "'creation_uri_qargs'", ":", "qargs", ",", "'creation_uri_frag'", ":", "frag", ",", "'allowed_lazy_attributes'", ":", "attrs", "}", ")" ]
Call this with a selfLink, after it's returned in _create or _load. Each instance is tightly bound to a particular service URI. When that service is created by this library, or loaded from the device, the URI is set to self._meta_data['uri']. This operation can only occur once, any subsequent attempt to manipulate self._meta_data['uri'] is probably a mistake. self.selfLink references a value that is returned as a JSON value from the device. This value contains "localhost" as the domain or the uri. "localhost" is only conceivably useful if the client library is run on the device itself, so it is replaced with the domain this API used to communicate with the device. self.selfLink correctly contains a complete uri, that is only _now_ (post create or load) available to self. Now that the complete URI is available to self, it is now possible to reference subcollections, as attributes of self! e.g. a resource with a uri path like: "/mgmt/tm/ltm/pool/~Common~pool_collection1/members" The mechanism used to enable this change is to set the `allowed_lazy_attributes` _meta_data key to hold values of the `attribute_registry` _meta_data key. Finally we stash the corrected `uri`, returned hash_fragment, query args, and of course allowed_lazy_attributes in _meta_data. :param selfLinkuri: the server provided selfLink (contains localhost) :raises: URICreationCollision
[ "Call", "this", "with", "a", "selfLink", "after", "it", "s", "returned", "in", "_create", "or", "_load", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L900-L949
237,333
F5Networks/f5-common-python
f5/bigip/resource.py
Resource._check_create_parameters
def _check_create_parameters(self, **kwargs): """Params given to create should satisfy required params. :params: kwargs :raises: MissingRequiredCreateParameter """ rset = self._meta_data['required_creation_parameters'] check = _missing_required_parameters(rset, **kwargs) if check: error_message = 'Missing required params: %s' % check raise MissingRequiredCreationParameter(error_message)
python
def _check_create_parameters(self, **kwargs): """Params given to create should satisfy required params. :params: kwargs :raises: MissingRequiredCreateParameter """ rset = self._meta_data['required_creation_parameters'] check = _missing_required_parameters(rset, **kwargs) if check: error_message = 'Missing required params: %s' % check raise MissingRequiredCreationParameter(error_message)
[ "def", "_check_create_parameters", "(", "self", ",", "*", "*", "kwargs", ")", ":", "rset", "=", "self", ".", "_meta_data", "[", "'required_creation_parameters'", "]", "check", "=", "_missing_required_parameters", "(", "rset", ",", "*", "*", "kwargs", ")", "if", "check", ":", "error_message", "=", "'Missing required params: %s'", "%", "check", "raise", "MissingRequiredCreationParameter", "(", "error_message", ")" ]
Params given to create should satisfy required params. :params: kwargs :raises: MissingRequiredCreateParameter
[ "Params", "given", "to", "create", "should", "satisfy", "required", "params", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L956-L966
237,334
F5Networks/f5-common-python
f5/bigip/resource.py
Resource._minimum_one_is_missing
def _minimum_one_is_missing(self, **kwargs): """Helper function to do operation on sets Verify if at least one of the elements is present in **kwargs. If no items of rqset are contained in **kwargs the function raises exception. This check will only trigger if rqset is not empty. Raises: MissingRequiredCreationParameter """ rqset = self._meta_data['minimum_additional_parameters'] if rqset: kwarg_set = set(iterkeys(kwargs)) if kwarg_set.isdisjoint(rqset): args = sorted(rqset) error_message = 'This resource requires at least one of the ' \ 'mandatory additional ' \ 'parameters to be provided: %s' % ', '.join(args) raise MissingRequiredCreationParameter(error_message)
python
def _minimum_one_is_missing(self, **kwargs): """Helper function to do operation on sets Verify if at least one of the elements is present in **kwargs. If no items of rqset are contained in **kwargs the function raises exception. This check will only trigger if rqset is not empty. Raises: MissingRequiredCreationParameter """ rqset = self._meta_data['minimum_additional_parameters'] if rqset: kwarg_set = set(iterkeys(kwargs)) if kwarg_set.isdisjoint(rqset): args = sorted(rqset) error_message = 'This resource requires at least one of the ' \ 'mandatory additional ' \ 'parameters to be provided: %s' % ', '.join(args) raise MissingRequiredCreationParameter(error_message)
[ "def", "_minimum_one_is_missing", "(", "self", ",", "*", "*", "kwargs", ")", ":", "rqset", "=", "self", ".", "_meta_data", "[", "'minimum_additional_parameters'", "]", "if", "rqset", ":", "kwarg_set", "=", "set", "(", "iterkeys", "(", "kwargs", ")", ")", "if", "kwarg_set", ".", "isdisjoint", "(", "rqset", ")", ":", "args", "=", "sorted", "(", "rqset", ")", "error_message", "=", "'This resource requires at least one of the '", "'mandatory additional '", "'parameters to be provided: %s'", "%", "', '", ".", "join", "(", "args", ")", "raise", "MissingRequiredCreationParameter", "(", "error_message", ")" ]
Helper function to do operation on sets Verify if at least one of the elements is present in **kwargs. If no items of rqset are contained in **kwargs the function raises exception. This check will only trigger if rqset is not empty. Raises: MissingRequiredCreationParameter
[ "Helper", "function", "to", "do", "operation", "on", "sets" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L968-L989
237,335
F5Networks/f5-common-python
f5/bigip/resource.py
Resource._check_load_parameters
def _check_load_parameters(self, **kwargs): """Params given to load should at least satisfy required params. :params: kwargs :raises: MissingRequiredReadParameter """ rset = self._meta_data['required_load_parameters'] check = _missing_required_parameters(rset, **kwargs) if check: check.sort() error_message = 'Missing required params: %s' % check raise MissingRequiredReadParameter(error_message)
python
def _check_load_parameters(self, **kwargs): """Params given to load should at least satisfy required params. :params: kwargs :raises: MissingRequiredReadParameter """ rset = self._meta_data['required_load_parameters'] check = _missing_required_parameters(rset, **kwargs) if check: check.sort() error_message = 'Missing required params: %s' % check raise MissingRequiredReadParameter(error_message)
[ "def", "_check_load_parameters", "(", "self", ",", "*", "*", "kwargs", ")", ":", "rset", "=", "self", ".", "_meta_data", "[", "'required_load_parameters'", "]", "check", "=", "_missing_required_parameters", "(", "rset", ",", "*", "*", "kwargs", ")", "if", "check", ":", "check", ".", "sort", "(", ")", "error_message", "=", "'Missing required params: %s'", "%", "check", "raise", "MissingRequiredReadParameter", "(", "error_message", ")" ]
Params given to load should at least satisfy required params. :params: kwargs :raises: MissingRequiredReadParameter
[ "Params", "given", "to", "load", "should", "at", "least", "satisfy", "required", "params", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L1055-L1066
237,336
F5Networks/f5-common-python
f5/bigip/resource.py
Resource._load
def _load(self, **kwargs): """wrapped with load, override that in a subclass to customize""" 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) response = refresh_session.get(base_uri, **kwargs) # Make new instance of self return self._produce_instance(response)
python
def _load(self, **kwargs): """wrapped with load, override that in a subclass to customize""" 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) response = refresh_session.get(base_uri, **kwargs) # Make new instance of self return self._produce_instance(response)
[ "def", "_load", "(", "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", ")", "response", "=", "refresh_session", ".", "get", "(", "base_uri", ",", "*", "*", "kwargs", ")", "# Make new instance of self", "return", "self", ".", "_produce_instance", "(", "response", ")" ]
wrapped with load, override that in a subclass to customize
[ "wrapped", "with", "load", "override", "that", "in", "a", "subclass", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L1068-L1086
237,337
F5Networks/f5-common-python
f5/bigip/resource.py
Resource._delete
def _delete(self, **kwargs): """wrapped with delete, override that in a subclass to customize """ requests_params = self._handle_requests_params(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, **requests_params) if response.status_code == 200: self.__dict__ = {'deleted': True}
python
def _delete(self, **kwargs): """wrapped with delete, override that in a subclass to customize """ requests_params = self._handle_requests_params(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, **requests_params) if response.status_code == 200: self.__dict__ = {'deleted': True}
[ "def", "_delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "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", ",", "*", "*", "requests_params", ")", "if", "response", ".", "status_code", "==", "200", ":", "self", ".", "__dict__", "=", "{", "'deleted'", ":", "True", "}" ]
wrapped with delete, override that in a subclass to customize
[ "wrapped", "with", "delete", "override", "that", "in", "a", "subclass", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L1112-L1126
237,338
F5Networks/f5-common-python
f5/bigip/resource.py
AsmResource._delete
def _delete(self, **kwargs): """Wrapped with delete, override that in a subclass to customize """ requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] response = session.delete(delete_uri, **requests_params) if response.status_code == 200 or 201: self.__dict__ = {'deleted': True}
python
def _delete(self, **kwargs): """Wrapped with delete, override that in a subclass to customize """ requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] response = session.delete(delete_uri, **requests_params) if response.status_code == 200 or 201: self.__dict__ = {'deleted': True}
[ "def", "_delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "delete_uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "response", "=", "session", ".", "delete", "(", "delete_uri", ",", "*", "*", "requests_params", ")", "if", "response", ".", "status_code", "==", "200", "or", "201", ":", "self", ".", "__dict__", "=", "{", "'deleted'", ":", "True", "}" ]
Wrapped with delete, override that in a subclass to customize
[ "Wrapped", "with", "delete", "override", "that", "in", "a", "subclass", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L1322-L1330
237,339
F5Networks/f5-common-python
f5/bigip/resource.py
AsmResource.exists
def exists(self, **kwargs): r"""Check for the existence of the ASM object on the BIG-IP Sends an HTTP GET to the URI of the ASM 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 returns :obj:`True`. For any other errors are raised as-is. Args: \*\*kwargs (dict): Arbitrary number of keyword arguments. Keyword arguments required to get objects If kwargs has a ``requests_param`` key the corresponding dict will be passed to the underlying ``requests.session.get`` method where it will be handled according to that API. Returns: bool: True is the object exists: False otherwise. Raises: 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'] uri = self._meta_data['container']._meta_data['uri'] endpoint = kwargs.pop('id', '') # Popping name kwarg as it will cause the uri to be invalid kwargs.pop('name', '') base_uri = uri + endpoint + '/' kwargs.update(requests_params) try: session.get(base_uri, **kwargs) except HTTPError as err: if err.response.status_code == 404: return False else: raise return True
python
def exists(self, **kwargs): r"""Check for the existence of the ASM object on the BIG-IP Sends an HTTP GET to the URI of the ASM 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 returns :obj:`True`. For any other errors are raised as-is. Args: \*\*kwargs (dict): Arbitrary number of keyword arguments. Keyword arguments required to get objects If kwargs has a ``requests_param`` key the corresponding dict will be passed to the underlying ``requests.session.get`` method where it will be handled according to that API. Returns: bool: True is the object exists: False otherwise. Raises: 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'] uri = self._meta_data['container']._meta_data['uri'] endpoint = kwargs.pop('id', '') # Popping name kwarg as it will cause the uri to be invalid kwargs.pop('name', '') base_uri = uri + endpoint + '/' kwargs.update(requests_params) try: session.get(base_uri, **kwargs) except HTTPError as err: if err.response.status_code == 404: return False else: raise 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'", "]", "uri", "=", "self", ".", "_meta_data", "[", "'container'", "]", ".", "_meta_data", "[", "'uri'", "]", "endpoint", "=", "kwargs", ".", "pop", "(", "'id'", ",", "''", ")", "# Popping name kwarg as it will cause the uri to be invalid", "kwargs", ".", "pop", "(", "'name'", ",", "''", ")", "base_uri", "=", "uri", "+", "endpoint", "+", "'/'", "kwargs", ".", "update", "(", "requests_params", ")", "try", ":", "session", ".", "get", "(", "base_uri", ",", "*", "*", "kwargs", ")", "except", "HTTPError", "as", "err", ":", "if", "err", ".", "response", ".", "status_code", "==", "404", ":", "return", "False", "else", ":", "raise", "return", "True" ]
r"""Check for the existence of the ASM object on the BIG-IP Sends an HTTP GET to the URI of the ASM 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 returns :obj:`True`. For any other errors are raised as-is. Args: \*\*kwargs (dict): Arbitrary number of keyword arguments. Keyword arguments required to get objects If kwargs has a ``requests_param`` key the corresponding dict will be passed to the underlying ``requests.session.get`` method where it will be handled according to that API. Returns: bool: True is the object exists: False otherwise. Raises: requests.HTTPError: Any HTTP error that was not status code 404.
[ "r", "Check", "for", "the", "existence", "of", "the", "ASM", "object", "on", "the", "BIG", "-", "IP" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L1350-L1392
237,340
F5Networks/f5-common-python
f5/bigip/resource.py
AsmTaskResource._fetch
def _fetch(self): """wrapped by `fetch` override that in subclasses to customize""" 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) # 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'] # Invoke the REST operation on the device. response = session.post(_create_uri, json={}) # Make new instance of self return self._produce_instance(response)
python
def _fetch(self): """wrapped by `fetch` override that in subclasses to customize""" 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) # 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'] # Invoke the REST operation on the device. response = session.post(_create_uri, json={}) # Make new instance of self return self._produce_instance(response)
[ "def", "_fetch", "(", "self", ")", ":", "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", ")", "# 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'", "]", "# Invoke the REST operation on the device.", "response", "=", "session", ".", "post", "(", "_create_uri", ",", "json", "=", "{", "}", ")", "# Make new instance of self", "return", "self", ".", "_produce_instance", "(", "response", ")" ]
wrapped by `fetch` override that in subclasses to customize
[ "wrapped", "by", "fetch", "override", "that", "in", "subclasses", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L1423-L1436
237,341
F5Networks/f5-common-python
f5/multi_device/cluster/__init__.py
ClusterManager._check_device_number
def _check_device_number(self, devices): '''Check if number of devices is between 2 and 4 :param kwargs: dict -- keyword args in dict ''' if len(devices) < 2 or len(devices) > 4: msg = 'The number of devices to cluster is not supported.' raise ClusterNotSupported(msg)
python
def _check_device_number(self, devices): '''Check if number of devices is between 2 and 4 :param kwargs: dict -- keyword args in dict ''' if len(devices) < 2 or len(devices) > 4: msg = 'The number of devices to cluster is not supported.' raise ClusterNotSupported(msg)
[ "def", "_check_device_number", "(", "self", ",", "devices", ")", ":", "if", "len", "(", "devices", ")", "<", "2", "or", "len", "(", "devices", ")", ">", "4", ":", "msg", "=", "'The number of devices to cluster is not supported.'", "raise", "ClusterNotSupported", "(", "msg", ")" ]
Check if number of devices is between 2 and 4 :param kwargs: dict -- keyword args in dict
[ "Check", "if", "number", "of", "devices", "is", "between", "2", "and", "4" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/cluster/__init__.py#L126-L134
237,342
F5Networks/f5-common-python
f5/multi_device/cluster/__init__.py
ClusterManager.manage_extant
def manage_extant(self, **kwargs): '''Manage an existing cluster :param kwargs: dict -- keyword args in dict ''' self._check_device_number(kwargs['devices']) self.trust_domain = TrustDomain( devices=kwargs['devices'], partition=kwargs['device_group_partition'] ) self.device_group = DeviceGroup(**kwargs) self.cluster = Cluster(**kwargs)
python
def manage_extant(self, **kwargs): '''Manage an existing cluster :param kwargs: dict -- keyword args in dict ''' self._check_device_number(kwargs['devices']) self.trust_domain = TrustDomain( devices=kwargs['devices'], partition=kwargs['device_group_partition'] ) self.device_group = DeviceGroup(**kwargs) self.cluster = Cluster(**kwargs)
[ "def", "manage_extant", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_device_number", "(", "kwargs", "[", "'devices'", "]", ")", "self", ".", "trust_domain", "=", "TrustDomain", "(", "devices", "=", "kwargs", "[", "'devices'", "]", ",", "partition", "=", "kwargs", "[", "'device_group_partition'", "]", ")", "self", ".", "device_group", "=", "DeviceGroup", "(", "*", "*", "kwargs", ")", "self", ".", "cluster", "=", "Cluster", "(", "*", "*", "kwargs", ")" ]
Manage an existing cluster :param kwargs: dict -- keyword args in dict
[ "Manage", "an", "existing", "cluster" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/cluster/__init__.py#L136-L148
237,343
F5Networks/f5-common-python
f5/bigip/tm/ltm/policy.py
Policy._filter_version_specific_options
def _filter_version_specific_options(self, tmos_ver, **kwargs): '''Filter version-specific optional parameters Some optional parameters only exist in v12.1.0 and greater, filter these out for earlier versions to allow backward comatibility. ''' if LooseVersion(tmos_ver) < LooseVersion('12.1.0'): for k, parms in self._meta_data['optional_parameters'].items(): for r in kwargs.get(k, []): for parm in parms: value = r.pop(parm, None) if value is not None: logger.info( "Policy parameter %s:%s is invalid for v%s", k, parm, tmos_ver)
python
def _filter_version_specific_options(self, tmos_ver, **kwargs): '''Filter version-specific optional parameters Some optional parameters only exist in v12.1.0 and greater, filter these out for earlier versions to allow backward comatibility. ''' if LooseVersion(tmos_ver) < LooseVersion('12.1.0'): for k, parms in self._meta_data['optional_parameters'].items(): for r in kwargs.get(k, []): for parm in parms: value = r.pop(parm, None) if value is not None: logger.info( "Policy parameter %s:%s is invalid for v%s", k, parm, tmos_ver)
[ "def", "_filter_version_specific_options", "(", "self", ",", "tmos_ver", ",", "*", "*", "kwargs", ")", ":", "if", "LooseVersion", "(", "tmos_ver", ")", "<", "LooseVersion", "(", "'12.1.0'", ")", ":", "for", "k", ",", "parms", "in", "self", ".", "_meta_data", "[", "'optional_parameters'", "]", ".", "items", "(", ")", ":", "for", "r", "in", "kwargs", ".", "get", "(", "k", ",", "[", "]", ")", ":", "for", "parm", "in", "parms", ":", "value", "=", "r", ".", "pop", "(", "parm", ",", "None", ")", "if", "value", "is", "not", "None", ":", "logger", ".", "info", "(", "\"Policy parameter %s:%s is invalid for v%s\"", ",", "k", ",", "parm", ",", "tmos_ver", ")" ]
Filter version-specific optional parameters Some optional parameters only exist in v12.1.0 and greater, filter these out for earlier versions to allow backward comatibility.
[ "Filter", "version", "-", "specific", "optional", "parameters" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L64-L79
237,344
F5Networks/f5-common-python
f5/bigip/tm/ltm/policy.py
Policy._create
def _create(self, **kwargs): '''Allow creation of draft policy and ability to publish a draft Draft policies only exist in 12.1.0 and greater versions of TMOS. But there must be a method to create a draft, then publish it. :raises: MissingRequiredCreationParameter ''' tmos_ver = self._meta_data['bigip']._meta_data['tmos_version'] legacy = kwargs.pop('legacy', False) publish = kwargs.pop('publish', False) self._filter_version_specific_options(tmos_ver, **kwargs) if LooseVersion(tmos_ver) < LooseVersion('12.1.0'): return super(Policy, self)._create(**kwargs) else: if legacy: return super(Policy, self)._create(legacy=True, **kwargs) else: if 'subPath' not in kwargs: msg = "The keyword 'subPath' must be specified when " \ "creating draft policy in TMOS versions >= 12.1.0. " \ "Try and specify subPath as 'Drafts'." raise MissingRequiredCreationParameter(msg) self = super(Policy, self)._create(**kwargs) if publish: self.publish() return self
python
def _create(self, **kwargs): '''Allow creation of draft policy and ability to publish a draft Draft policies only exist in 12.1.0 and greater versions of TMOS. But there must be a method to create a draft, then publish it. :raises: MissingRequiredCreationParameter ''' tmos_ver = self._meta_data['bigip']._meta_data['tmos_version'] legacy = kwargs.pop('legacy', False) publish = kwargs.pop('publish', False) self._filter_version_specific_options(tmos_ver, **kwargs) if LooseVersion(tmos_ver) < LooseVersion('12.1.0'): return super(Policy, self)._create(**kwargs) else: if legacy: return super(Policy, self)._create(legacy=True, **kwargs) else: if 'subPath' not in kwargs: msg = "The keyword 'subPath' must be specified when " \ "creating draft policy in TMOS versions >= 12.1.0. " \ "Try and specify subPath as 'Drafts'." raise MissingRequiredCreationParameter(msg) self = super(Policy, self)._create(**kwargs) if publish: self.publish() return self
[ "def", "_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "tmos_ver", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'tmos_version'", "]", "legacy", "=", "kwargs", ".", "pop", "(", "'legacy'", ",", "False", ")", "publish", "=", "kwargs", ".", "pop", "(", "'publish'", ",", "False", ")", "self", ".", "_filter_version_specific_options", "(", "tmos_ver", ",", "*", "*", "kwargs", ")", "if", "LooseVersion", "(", "tmos_ver", ")", "<", "LooseVersion", "(", "'12.1.0'", ")", ":", "return", "super", "(", "Policy", ",", "self", ")", ".", "_create", "(", "*", "*", "kwargs", ")", "else", ":", "if", "legacy", ":", "return", "super", "(", "Policy", ",", "self", ")", ".", "_create", "(", "legacy", "=", "True", ",", "*", "*", "kwargs", ")", "else", ":", "if", "'subPath'", "not", "in", "kwargs", ":", "msg", "=", "\"The keyword 'subPath' must be specified when \"", "\"creating draft policy in TMOS versions >= 12.1.0. \"", "\"Try and specify subPath as 'Drafts'.\"", "raise", "MissingRequiredCreationParameter", "(", "msg", ")", "self", "=", "super", "(", "Policy", ",", "self", ")", ".", "_create", "(", "*", "*", "kwargs", ")", "if", "publish", ":", "self", ".", "publish", "(", ")", "return", "self" ]
Allow creation of draft policy and ability to publish a draft Draft policies only exist in 12.1.0 and greater versions of TMOS. But there must be a method to create a draft, then publish it. :raises: MissingRequiredCreationParameter
[ "Allow", "creation", "of", "draft", "policy", "and", "ability", "to", "publish", "a", "draft" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L81-L108
237,345
F5Networks/f5-common-python
f5/bigip/tm/ltm/policy.py
Policy._modify
def _modify(self, **patch): '''Modify only draft or legacy policies Published policies cannot be modified :raises: OperationNotSupportedOnPublishedPolicy ''' legacy = patch.pop('legacy', False) tmos_ver = self._meta_data['bigip']._meta_data['tmos_version'] self._filter_version_specific_options(tmos_ver, **patch) if 'Drafts' not in self._meta_data['uri'] and \ LooseVersion(tmos_ver) >= LooseVersion('12.1.0') and \ not legacy: msg = 'Modify operation not allowed on a published policy.' raise OperationNotSupportedOnPublishedPolicy(msg) super(Policy, self)._modify(**patch)
python
def _modify(self, **patch): '''Modify only draft or legacy policies Published policies cannot be modified :raises: OperationNotSupportedOnPublishedPolicy ''' legacy = patch.pop('legacy', False) tmos_ver = self._meta_data['bigip']._meta_data['tmos_version'] self._filter_version_specific_options(tmos_ver, **patch) if 'Drafts' not in self._meta_data['uri'] and \ LooseVersion(tmos_ver) >= LooseVersion('12.1.0') and \ not legacy: msg = 'Modify operation not allowed on a published policy.' raise OperationNotSupportedOnPublishedPolicy(msg) super(Policy, self)._modify(**patch)
[ "def", "_modify", "(", "self", ",", "*", "*", "patch", ")", ":", "legacy", "=", "patch", ".", "pop", "(", "'legacy'", ",", "False", ")", "tmos_ver", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'tmos_version'", "]", "self", ".", "_filter_version_specific_options", "(", "tmos_ver", ",", "*", "*", "patch", ")", "if", "'Drafts'", "not", "in", "self", ".", "_meta_data", "[", "'uri'", "]", "and", "LooseVersion", "(", "tmos_ver", ")", ">=", "LooseVersion", "(", "'12.1.0'", ")", "and", "not", "legacy", ":", "msg", "=", "'Modify operation not allowed on a published policy.'", "raise", "OperationNotSupportedOnPublishedPolicy", "(", "msg", ")", "super", "(", "Policy", ",", "self", ")", ".", "_modify", "(", "*", "*", "patch", ")" ]
Modify only draft or legacy policies Published policies cannot be modified :raises: OperationNotSupportedOnPublishedPolicy
[ "Modify", "only", "draft", "or", "legacy", "policies" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L110-L125
237,346
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
237,347
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
237,348
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
237,349
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
237,350
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
237,351
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
237,352
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
237,353
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
237,354
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
237,355
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
237,356
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
237,357
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
237,358
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
237,359
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
237,360
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
237,361
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
237,362
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
237,363
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
237,364
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
237,365
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
237,366
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
237,367
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
237,368
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
237,369
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
237,370
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
237,371
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
237,372
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
237,373
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
237,374
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
237,375
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
237,376
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
237,377
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
237,378
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
237,379
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
237,380
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
237,381
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
237,382
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
237,383
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
237,384
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
237,385
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
237,386
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
237,387
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
237,388
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
237,389
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
237,390
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
237,391
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
237,392
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
237,393
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
237,394
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
237,395
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
237,396
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
237,397
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
237,398
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
237,399
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