repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ANTsX/ANTsPy
ants/core/ants_metric.py
ANTsImageToImageMetric.set_moving_image
def set_moving_image(self, image): """ Set Moving ANTsImage for metric """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setMovingImage(image.pointer, False) self.moving_image = image
python
def set_moving_image(self, image): """ Set Moving ANTsImage for metric """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setMovingImage(image.pointer, False) self.moving_image = image
[ "def", "set_moving_image", "(", "self", ",", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "iio", ".", "ANTsImage", ")", ":", "raise", "ValueError", "(", "'image must be ANTsImage type'", ")", "if", "image", ".", "dimension", "!=", "self", ".", "dimension", ":", "raise", "ValueError", "(", "'image dim (%i) does not match metric dim (%i)'", "%", "(", "image", ".", "dimension", ",", "self", ".", "dimension", ")", ")", "self", ".", "_metric", ".", "setMovingImage", "(", "image", ".", "pointer", ",", "False", ")", "self", ".", "moving_image", "=", "image" ]
Set Moving ANTsImage for metric
[ "Set", "Moving", "ANTsImage", "for", "metric" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_metric.py#L74-L85
train
232,100
ANTsX/ANTsPy
ants/utils/image_to_cluster_images.py
image_to_cluster_images
def image_to_cluster_images(image, min_cluster_size=50, min_thresh=1e-06, max_thresh=1): """ Converts an image to several independent images. Produces a unique image for each connected component 1 through N of size > min_cluster_size ANTsR function: `image2ClusterImages` Arguments --------- image : ANTsImage input image min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image = ants.threshold_image(image, 1, 1e15) >>> image_cluster_list = ants.image_to_cluster_images(image) """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') clust = label_clusters(image, min_cluster_size, min_thresh, max_thresh) labs = np.unique(clust[clust > 0]) clustlist = [] for i in range(len(labs)): labimage = image.clone() labimage[clust != labs[i]] = 0 clustlist.append(labimage) return clustlist
python
def image_to_cluster_images(image, min_cluster_size=50, min_thresh=1e-06, max_thresh=1): """ Converts an image to several independent images. Produces a unique image for each connected component 1 through N of size > min_cluster_size ANTsR function: `image2ClusterImages` Arguments --------- image : ANTsImage input image min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image = ants.threshold_image(image, 1, 1e15) >>> image_cluster_list = ants.image_to_cluster_images(image) """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') clust = label_clusters(image, min_cluster_size, min_thresh, max_thresh) labs = np.unique(clust[clust > 0]) clustlist = [] for i in range(len(labs)): labimage = image.clone() labimage[clust != labs[i]] = 0 clustlist.append(labimage) return clustlist
[ "def", "image_to_cluster_images", "(", "image", ",", "min_cluster_size", "=", "50", ",", "min_thresh", "=", "1e-06", ",", "max_thresh", "=", "1", ")", ":", "if", "not", "isinstance", "(", "image", ",", "iio", ".", "ANTsImage", ")", ":", "raise", "ValueError", "(", "'image must be ANTsImage type'", ")", "clust", "=", "label_clusters", "(", "image", ",", "min_cluster_size", ",", "min_thresh", ",", "max_thresh", ")", "labs", "=", "np", ".", "unique", "(", "clust", "[", "clust", ">", "0", "]", ")", "clustlist", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "labs", ")", ")", ":", "labimage", "=", "image", ".", "clone", "(", ")", "labimage", "[", "clust", "!=", "labs", "[", "i", "]", "]", "=", "0", "clustlist", ".", "append", "(", "labimage", ")", "return", "clustlist" ]
Converts an image to several independent images. Produces a unique image for each connected component 1 through N of size > min_cluster_size ANTsR function: `image2ClusterImages` Arguments --------- image : ANTsImage input image min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image = ants.threshold_image(image, 1, 1e15) >>> image_cluster_list = ants.image_to_cluster_images(image)
[ "Converts", "an", "image", "to", "several", "independent", "images", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/image_to_cluster_images.py#L9-L51
train
232,101
ANTsX/ANTsPy
ants/utils/threshold_image.py
threshold_image
def threshold_image(image, low_thresh=None, high_thresh=None, inval=1, outval=0, binary=True): """ Converts a scalar image into a binary image by thresholding operations ANTsR function: `thresholdImage` Arguments --------- image : ANTsImage Input image to operate on low_thresh : scalar (optional) Lower edge of threshold window hight_thresh : scalar (optional) Higher edge of threshold window inval : scalar Output value for image voxels in between lothresh and hithresh outval : scalar Output value for image voxels lower than lothresh or higher than hithresh binary : boolean if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15) """ if high_thresh is None: high_thresh = image.max() + 0.01 if low_thresh is None: low_thresh = image.min() - 0.01 dim = image.dimension outimage = image.clone() args = [dim, image, outimage, low_thresh, high_thresh, inval, outval] processed_args = _int_antsProcessArguments(args) libfn = utils.get_lib_fn('ThresholdImage') libfn(processed_args) if binary: return outimage else: return outimage*image
python
def threshold_image(image, low_thresh=None, high_thresh=None, inval=1, outval=0, binary=True): """ Converts a scalar image into a binary image by thresholding operations ANTsR function: `thresholdImage` Arguments --------- image : ANTsImage Input image to operate on low_thresh : scalar (optional) Lower edge of threshold window hight_thresh : scalar (optional) Higher edge of threshold window inval : scalar Output value for image voxels in between lothresh and hithresh outval : scalar Output value for image voxels lower than lothresh or higher than hithresh binary : boolean if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15) """ if high_thresh is None: high_thresh = image.max() + 0.01 if low_thresh is None: low_thresh = image.min() - 0.01 dim = image.dimension outimage = image.clone() args = [dim, image, outimage, low_thresh, high_thresh, inval, outval] processed_args = _int_antsProcessArguments(args) libfn = utils.get_lib_fn('ThresholdImage') libfn(processed_args) if binary: return outimage else: return outimage*image
[ "def", "threshold_image", "(", "image", ",", "low_thresh", "=", "None", ",", "high_thresh", "=", "None", ",", "inval", "=", "1", ",", "outval", "=", "0", ",", "binary", "=", "True", ")", ":", "if", "high_thresh", "is", "None", ":", "high_thresh", "=", "image", ".", "max", "(", ")", "+", "0.01", "if", "low_thresh", "is", "None", ":", "low_thresh", "=", "image", ".", "min", "(", ")", "-", "0.01", "dim", "=", "image", ".", "dimension", "outimage", "=", "image", ".", "clone", "(", ")", "args", "=", "[", "dim", ",", "image", ",", "outimage", ",", "low_thresh", ",", "high_thresh", ",", "inval", ",", "outval", "]", "processed_args", "=", "_int_antsProcessArguments", "(", "args", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'ThresholdImage'", ")", "libfn", "(", "processed_args", ")", "if", "binary", ":", "return", "outimage", "else", ":", "return", "outimage", "*", "image" ]
Converts a scalar image into a binary image by thresholding operations ANTsR function: `thresholdImage` Arguments --------- image : ANTsImage Input image to operate on low_thresh : scalar (optional) Lower edge of threshold window hight_thresh : scalar (optional) Higher edge of threshold window inval : scalar Output value for image voxels in between lothresh and hithresh outval : scalar Output value for image voxels lower than lothresh or higher than hithresh binary : boolean if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15)
[ "Converts", "a", "scalar", "image", "into", "a", "binary", "image", "by", "thresholding", "operations" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/threshold_image.py#L10-L60
train
232,102
ANTsX/ANTsPy
ants/registration/symmetrize_image.py
symmetrize_image
def symmetrize_image(image): """ Use registration and reflection to make an image symmetric ANTsR function: N/A Arguments --------- image : ANTsImage image to make symmetric Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simage = ants.symimage(image) """ imager = reflect_image(image, axis=0) imageavg = imager * 0.5 + image for i in range(5): w1 = registration(imageavg, image, type_of_transform='SyN') w2 = registration(imageavg, imager, type_of_transform='SyN') xavg = w1['warpedmovout']*0.5 + w2['warpedmovout']*0.5 nada1 = apply_transforms(image, image, w1['fwdtransforms'], compose=w1['fwdtransforms'][0]) nada2 = apply_transforms(image, image, w2['fwdtransforms'], compose=w2['fwdtransforms'][0]) wavg = (iio.image_read(nada1) + iio.image_read(nada2)) * (-0.5) wavgfn = mktemp(suffix='.nii.gz') iio.image_write(wavg, wavgfn) xavg = apply_transforms(image, imageavg, wavgfn) return xavg
python
def symmetrize_image(image): """ Use registration and reflection to make an image symmetric ANTsR function: N/A Arguments --------- image : ANTsImage image to make symmetric Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simage = ants.symimage(image) """ imager = reflect_image(image, axis=0) imageavg = imager * 0.5 + image for i in range(5): w1 = registration(imageavg, image, type_of_transform='SyN') w2 = registration(imageavg, imager, type_of_transform='SyN') xavg = w1['warpedmovout']*0.5 + w2['warpedmovout']*0.5 nada1 = apply_transforms(image, image, w1['fwdtransforms'], compose=w1['fwdtransforms'][0]) nada2 = apply_transforms(image, image, w2['fwdtransforms'], compose=w2['fwdtransforms'][0]) wavg = (iio.image_read(nada1) + iio.image_read(nada2)) * (-0.5) wavgfn = mktemp(suffix='.nii.gz') iio.image_write(wavg, wavgfn) xavg = apply_transforms(image, imageavg, wavgfn) return xavg
[ "def", "symmetrize_image", "(", "image", ")", ":", "imager", "=", "reflect_image", "(", "image", ",", "axis", "=", "0", ")", "imageavg", "=", "imager", "*", "0.5", "+", "image", "for", "i", "in", "range", "(", "5", ")", ":", "w1", "=", "registration", "(", "imageavg", ",", "image", ",", "type_of_transform", "=", "'SyN'", ")", "w2", "=", "registration", "(", "imageavg", ",", "imager", ",", "type_of_transform", "=", "'SyN'", ")", "xavg", "=", "w1", "[", "'warpedmovout'", "]", "*", "0.5", "+", "w2", "[", "'warpedmovout'", "]", "*", "0.5", "nada1", "=", "apply_transforms", "(", "image", ",", "image", ",", "w1", "[", "'fwdtransforms'", "]", ",", "compose", "=", "w1", "[", "'fwdtransforms'", "]", "[", "0", "]", ")", "nada2", "=", "apply_transforms", "(", "image", ",", "image", ",", "w2", "[", "'fwdtransforms'", "]", ",", "compose", "=", "w2", "[", "'fwdtransforms'", "]", "[", "0", "]", ")", "wavg", "=", "(", "iio", ".", "image_read", "(", "nada1", ")", "+", "iio", ".", "image_read", "(", "nada2", ")", ")", "*", "(", "-", "0.5", ")", "wavgfn", "=", "mktemp", "(", "suffix", "=", "'.nii.gz'", ")", "iio", ".", "image_write", "(", "wavg", ",", "wavgfn", ")", "xavg", "=", "apply_transforms", "(", "image", ",", "imageavg", ",", "wavgfn", ")", "return", "xavg" ]
Use registration and reflection to make an image symmetric ANTsR function: N/A Arguments --------- image : ANTsImage image to make symmetric Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simage = ants.symimage(image)
[ "Use", "registration", "and", "reflection", "to", "make", "an", "image", "symmetric" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/symmetrize_image.py#L13-L49
train
232,103
freakboy3742/pyxero
xero/basemanager.py
BaseManager._get_attachments
def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False
python
def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False
[ "def", "_get_attachments", "(", "self", ",", "id", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "id", ",", "'Attachments'", "]", ")", "+", "'/'", "return", "uri", ",", "{", "}", ",", "'get'", ",", "None", ",", "None", ",", "False" ]
Retrieve a list of attachments associated with this Xero object.
[ "Retrieve", "a", "list", "of", "attachments", "associated", "with", "this", "Xero", "object", "." ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L240-L243
train
232,104
freakboy3742/pyxero
xero/basemanager.py
BaseManager._put_attachment_data
def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False
python
def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False
[ "def", "_put_attachment_data", "(", "self", ",", "id", ",", "filename", ",", "data", ",", "content_type", ",", "include_online", "=", "False", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "id", ",", "'Attachments'", ",", "filename", "]", ")", "params", "=", "{", "'IncludeOnline'", ":", "'true'", "}", "if", "include_online", "else", "{", "}", "headers", "=", "{", "'Content-Type'", ":", "content_type", ",", "'Content-Length'", ":", "str", "(", "len", "(", "data", ")", ")", "}", "return", "uri", ",", "params", ",", "'put'", ",", "data", ",", "headers", ",", "False" ]
Upload an attachment to the Xero object.
[ "Upload", "an", "attachment", "to", "the", "Xero", "object", "." ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L280-L285
train
232,105
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.page_response
def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close()
python
def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close()
[ "def", "page_response", "(", "self", ",", "title", "=", "''", ",", "body", "=", "''", ")", ":", "f", "=", "StringIO", "(", ")", "f", ".", "write", "(", "'<!DOCTYPE html>\\n'", ")", "f", ".", "write", "(", "'<html>\\n'", ")", "f", ".", "write", "(", "'<head><title>{}</title><head>\\n'", ".", "format", "(", "title", ")", ")", "f", ".", "write", "(", "'<body>\\n<h2>{}</h2>\\n'", ".", "format", "(", "title", ")", ")", "f", ".", "write", "(", "'<div class=\"content\">{}</div>\\n'", ".", "format", "(", "body", ")", ")", "f", ".", "write", "(", "'</body>\\n</html>\\n'", ")", "length", "=", "f", ".", "tell", "(", ")", "f", ".", "seek", "(", "0", ")", "self", ".", "send_response", "(", "200", ")", "encoding", "=", "sys", ".", "getfilesystemencoding", "(", ")", "self", ".", "send_header", "(", "\"Content-type\"", ",", "\"text/html; charset=%s\"", "%", "encoding", ")", "self", ".", "send_header", "(", "\"Content-Length\"", ",", "str", "(", "length", ")", ")", "self", ".", "end_headers", "(", ")", "self", ".", "copyfile", "(", "f", ",", "self", ".", "wfile", ")", "f", ".", "close", "(", ")" ]
Helper to render an html page with dynamic content
[ "Helper", "to", "render", "an", "html", "page", "with", "dynamic", "content" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L22-L41
train
232,106
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.redirect_response
def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers()
python
def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers()
[ "def", "redirect_response", "(", "self", ",", "url", ",", "permanent", "=", "False", ")", ":", "if", "permanent", ":", "self", ".", "send_response", "(", "301", ")", "else", ":", "self", ".", "send_response", "(", "302", ")", "self", ".", "send_header", "(", "\"Location\"", ",", "url", ")", "self", ".", "end_headers", "(", ")" ]
Generate redirect response
[ "Generate", "redirect", "response" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L43-L52
train
232,107
freakboy3742/pyxero
xero/auth.py
PublicCredentials._init_credentials
def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response)
python
def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response)
[ "def", "_init_credentials", "(", "self", ",", "oauth_token", ",", "oauth_token_secret", ")", ":", "if", "oauth_token", "and", "oauth_token_secret", ":", "if", "self", ".", "verified", ":", "# If provided, this is a fully verified set of", "# credentials. Store the oauth_token and secret", "# and initialize OAuth around those", "self", ".", "_init_oauth", "(", "oauth_token", ",", "oauth_token_secret", ")", "else", ":", "# If provided, we are reconstructing an initalized", "# (but non-verified) set of public credentials.", "self", ".", "oauth_token", "=", "oauth_token", "self", ".", "oauth_token_secret", "=", "oauth_token_secret", "else", ":", "# This is a brand new set of credentials - we need to generate", "# an oauth token so it's available for the url property.", "oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "callback_uri", "=", "self", ".", "callback_uri", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")", "url", "=", "self", ".", "base_url", "+", "REQUEST_TOKEN_URL", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "response", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "headers", ",", "auth", "=", "oauth", ")", "self", ".", "_process_oauth_response", "(", "response", ")" ]
Depending on the state passed in, get self._oauth up and running
[ "Depending", "on", "the", "state", "passed", "in", "get", "self", ".", "_oauth", "up", "and", "running" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L134-L163
train
232,108
freakboy3742/pyxero
xero/auth.py
PublicCredentials._init_oauth
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method )
python
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method )
[ "def", "_init_oauth", "(", "self", ",", "oauth_token", ",", "oauth_token_secret", ")", ":", "self", ".", "oauth_token", "=", "oauth_token", "self", ".", "oauth_token_secret", "=", "oauth_token_secret", "self", ".", "_oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "resource_owner_key", "=", "self", ".", "oauth_token", ",", "resource_owner_secret", "=", "self", ".", "oauth_token_secret", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")" ]
Store and initialize a verified set of OAuth credentials
[ "Store", "and", "initialize", "a", "verified", "set", "of", "OAuth", "credentials" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L165-L177
train
232,109
freakboy3742/pyxero
xero/auth.py
PublicCredentials._process_oauth_response
def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response)
python
def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response)
[ "def", "_process_oauth_response", "(", "self", ",", "response", ")", ":", "if", "response", ".", "status_code", "==", "200", ":", "credentials", "=", "parse_qs", "(", "response", ".", "text", ")", "# Initialize the oauth credentials", "self", ".", "_init_oauth", "(", "credentials", ".", "get", "(", "'oauth_token'", ")", "[", "0", "]", ",", "credentials", ".", "get", "(", "'oauth_token_secret'", ")", "[", "0", "]", ")", "# If tokens are refreshable, we'll get a session handle", "self", ".", "oauth_session_handle", "=", "credentials", ".", "get", "(", "'oauth_session_handle'", ",", "[", "None", "]", ")", "[", "0", "]", "# Calculate token/auth expiry", "oauth_expires_in", "=", "credentials", ".", "get", "(", "'oauth_expires_in'", ",", "[", "OAUTH_EXPIRY_SECONDS", "]", ")", "[", "0", "]", "oauth_authorisation_expires_in", "=", "credentials", ".", "get", "(", "'oauth_authorization_expires_in'", ",", "[", "OAUTH_EXPIRY_SECONDS", "]", ")", "[", "0", "]", "self", ".", "oauth_expires_at", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "oauth_expires_in", ")", ")", "self", ".", "oauth_authorization_expires_at", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "oauth_authorisation_expires_in", ")", ")", "else", ":", "self", ".", "_handle_error_response", "(", "response", ")" ]
Extracts the fields from an oauth response
[ "Extracts", "the", "fields", "from", "an", "oauth", "response" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L179-L210
train
232,110
freakboy3742/pyxero
xero/auth.py
PublicCredentials.state
def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None )
python
def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None )
[ "def", "state", "(", "self", ")", ":", "return", "dict", "(", "(", "attr", ",", "getattr", "(", "self", ",", "attr", ")", ")", "for", "attr", "in", "(", "'consumer_key'", ",", "'consumer_secret'", ",", "'callback_uri'", ",", "'verified'", ",", "'oauth_token'", ",", "'oauth_token_secret'", ",", "'oauth_session_handle'", ",", "'oauth_expires_at'", ",", "'oauth_authorization_expires_at'", ",", "'scope'", ")", "if", "getattr", "(", "self", ",", "attr", ")", "is", "not", "None", ")" ]
Obtain the useful state of this credentials object so that we can reconstruct it independently.
[ "Obtain", "the", "useful", "state", "of", "this", "credentials", "object", "so", "that", "we", "can", "reconstruct", "it", "independently", "." ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L245-L258
train
232,111
freakboy3742/pyxero
xero/auth.py
PublicCredentials.verify
def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True
python
def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True
[ "def", "verify", "(", "self", ",", "verifier", ")", ":", "# Construct the credentials for the verification request", "oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "resource_owner_key", "=", "self", ".", "oauth_token", ",", "resource_owner_secret", "=", "self", ".", "oauth_token_secret", ",", "verifier", "=", "verifier", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")", "# Make the verification request, gettiung back an access token", "url", "=", "self", ".", "base_url", "+", "ACCESS_TOKEN_URL", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "response", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "headers", ",", "auth", "=", "oauth", ")", "self", ".", "_process_oauth_response", "(", "response", ")", "self", ".", "verified", "=", "True" ]
Verify an OAuth token
[ "Verify", "an", "OAuth", "token" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L260-L279
train
232,112
freakboy3742/pyxero
xero/auth.py
PublicCredentials.url
def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url
python
def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url
[ "def", "url", "(", "self", ")", ":", "# The authorize url is always api.xero.com", "query_string", "=", "{", "'oauth_token'", ":", "self", ".", "oauth_token", "}", "if", "self", ".", "scope", ":", "query_string", "[", "'scope'", "]", "=", "self", ".", "scope", "url", "=", "XERO_BASE_URL", "+", "AUTHORIZE_URL", "+", "'?'", "+", "urlencode", "(", "query_string", ")", "return", "url" ]
Returns the URL that can be visited to obtain a verifier code
[ "Returns", "the", "URL", "that", "can", "be", "visited", "to", "obtain", "a", "verifier", "code" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L282-L292
train
232,113
freakboy3742/pyxero
xero/auth.py
PartnerCredentials.refresh
def refresh(self): "Refresh an expired token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, getting back an access token headers = {'User-Agent': self.user_agent} params = {'oauth_session_handle': self.oauth_session_handle} response = requests.post(url=self.base_url + ACCESS_TOKEN_URL, params=params, headers=headers, auth=oauth) self._process_oauth_response(response)
python
def refresh(self): "Refresh an expired token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, getting back an access token headers = {'User-Agent': self.user_agent} params = {'oauth_session_handle': self.oauth_session_handle} response = requests.post(url=self.base_url + ACCESS_TOKEN_URL, params=params, headers=headers, auth=oauth) self._process_oauth_response(response)
[ "def", "refresh", "(", "self", ")", ":", "# Construct the credentials for the verification request", "oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "resource_owner_key", "=", "self", ".", "oauth_token", ",", "resource_owner_secret", "=", "self", ".", "oauth_token_secret", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")", "# Make the verification request, getting back an access token", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "params", "=", "{", "'oauth_session_handle'", ":", "self", ".", "oauth_session_handle", "}", "response", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "base_url", "+", "ACCESS_TOKEN_URL", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "auth", "=", "oauth", ")", "self", ".", "_process_oauth_response", "(", "response", ")" ]
Refresh an expired token
[ "Refresh", "an", "expired", "token" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L375-L393
train
232,114
freakboy3742/pyxero
xero/filesmanager.py
FilesManager._get_files
def _get_files(self, folderId): """Retrieve the list of files contained in a folder""" uri = '/'.join([self.base_url, self.name, folderId, 'Files']) return uri, {}, 'get', None, None, False, None
python
def _get_files(self, folderId): """Retrieve the list of files contained in a folder""" uri = '/'.join([self.base_url, self.name, folderId, 'Files']) return uri, {}, 'get', None, None, False, None
[ "def", "_get_files", "(", "self", ",", "folderId", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "folderId", ",", "'Files'", "]", ")", "return", "uri", ",", "{", "}", ",", "'get'", ",", "None", ",", "None", ",", "False", ",", "None" ]
Retrieve the list of files contained in a folder
[ "Retrieve", "the", "list", "of", "files", "contained", "in", "a", "folder" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/filesmanager.py#L118-L121
train
232,115
dmulcahey/zha-device-handlers
zhaquirks/hivehome/__init__.py
MotionCluster.handle_cluster_request
def handle_cluster_request(self, tsn, command_id, args): """Handle the cluster command.""" if command_id == 0: if self._timer_handle: self._timer_handle.cancel() loop = asyncio.get_event_loop() self._timer_handle = loop.call_later(30, self._turn_off)
python
def handle_cluster_request(self, tsn, command_id, args): """Handle the cluster command.""" if command_id == 0: if self._timer_handle: self._timer_handle.cancel() loop = asyncio.get_event_loop() self._timer_handle = loop.call_later(30, self._turn_off)
[ "def", "handle_cluster_request", "(", "self", ",", "tsn", ",", "command_id", ",", "args", ")", ":", "if", "command_id", "==", "0", ":", "if", "self", ".", "_timer_handle", ":", "self", ".", "_timer_handle", ".", "cancel", "(", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "self", ".", "_timer_handle", "=", "loop", ".", "call_later", "(", "30", ",", "self", ".", "_turn_off", ")" ]
Handle the cluster command.
[ "Handle", "the", "cluster", "command", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/hivehome/__init__.py#L21-L27
train
232,116
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
BasicCluster._parse_attributes
def _parse_attributes(self, value): """Parse non standard atrributes.""" from zigpy.zcl import foundation as f attributes = {} attribute_names = { 1: BATTERY_VOLTAGE_MV, 3: TEMPERATURE, 4: XIAOMI_ATTR_4, 5: XIAOMI_ATTR_5, 6: XIAOMI_ATTR_6, 10: PATH } result = {} while value: skey = int(value[0]) svalue, value = f.TypeValue.deserialize(value[1:]) result[skey] = svalue.value for item, value in result.items(): key = attribute_names[item] \ if item in attribute_names else "0xff01-" + str(item) attributes[key] = value if BATTERY_VOLTAGE_MV in attributes: attributes[BATTERY_LEVEL] = int( self._calculate_remaining_battery_percentage( attributes[BATTERY_VOLTAGE_MV] ) ) return attributes
python
def _parse_attributes(self, value): """Parse non standard atrributes.""" from zigpy.zcl import foundation as f attributes = {} attribute_names = { 1: BATTERY_VOLTAGE_MV, 3: TEMPERATURE, 4: XIAOMI_ATTR_4, 5: XIAOMI_ATTR_5, 6: XIAOMI_ATTR_6, 10: PATH } result = {} while value: skey = int(value[0]) svalue, value = f.TypeValue.deserialize(value[1:]) result[skey] = svalue.value for item, value in result.items(): key = attribute_names[item] \ if item in attribute_names else "0xff01-" + str(item) attributes[key] = value if BATTERY_VOLTAGE_MV in attributes: attributes[BATTERY_LEVEL] = int( self._calculate_remaining_battery_percentage( attributes[BATTERY_VOLTAGE_MV] ) ) return attributes
[ "def", "_parse_attributes", "(", "self", ",", "value", ")", ":", "from", "zigpy", ".", "zcl", "import", "foundation", "as", "f", "attributes", "=", "{", "}", "attribute_names", "=", "{", "1", ":", "BATTERY_VOLTAGE_MV", ",", "3", ":", "TEMPERATURE", ",", "4", ":", "XIAOMI_ATTR_4", ",", "5", ":", "XIAOMI_ATTR_5", ",", "6", ":", "XIAOMI_ATTR_6", ",", "10", ":", "PATH", "}", "result", "=", "{", "}", "while", "value", ":", "skey", "=", "int", "(", "value", "[", "0", "]", ")", "svalue", ",", "value", "=", "f", ".", "TypeValue", ".", "deserialize", "(", "value", "[", "1", ":", "]", ")", "result", "[", "skey", "]", "=", "svalue", ".", "value", "for", "item", ",", "value", "in", "result", ".", "items", "(", ")", ":", "key", "=", "attribute_names", "[", "item", "]", "if", "item", "in", "attribute_names", "else", "\"0xff01-\"", "+", "str", "(", "item", ")", "attributes", "[", "key", "]", "=", "value", "if", "BATTERY_VOLTAGE_MV", "in", "attributes", ":", "attributes", "[", "BATTERY_LEVEL", "]", "=", "int", "(", "self", ".", "_calculate_remaining_battery_percentage", "(", "attributes", "[", "BATTERY_VOLTAGE_MV", "]", ")", ")", "return", "attributes" ]
Parse non standard atrributes.
[ "Parse", "non", "standard", "atrributes", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L64-L91
train
232,117
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
BasicCluster._calculate_remaining_battery_percentage
def _calculate_remaining_battery_percentage(self, voltage): """Calculate percentage.""" min_voltage = 2500 max_voltage = 3000 percent = (voltage - min_voltage) / (max_voltage - min_voltage) * 200 return min(200, percent)
python
def _calculate_remaining_battery_percentage(self, voltage): """Calculate percentage.""" min_voltage = 2500 max_voltage = 3000 percent = (voltage - min_voltage) / (max_voltage - min_voltage) * 200 return min(200, percent)
[ "def", "_calculate_remaining_battery_percentage", "(", "self", ",", "voltage", ")", ":", "min_voltage", "=", "2500", "max_voltage", "=", "3000", "percent", "=", "(", "voltage", "-", "min_voltage", ")", "/", "(", "max_voltage", "-", "min_voltage", ")", "*", "200", "return", "min", "(", "200", ",", "percent", ")" ]
Calculate percentage.
[ "Calculate", "percentage", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L93-L98
train
232,118
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
PowerConfigurationCluster.battery_reported
def battery_reported(self, voltage, rawVoltage): """Battery reported.""" self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage) self._update_attribute(self.BATTERY_VOLTAGE_ATTR, int(rawVoltage / 100))
python
def battery_reported(self, voltage, rawVoltage): """Battery reported.""" self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage) self._update_attribute(self.BATTERY_VOLTAGE_ATTR, int(rawVoltage / 100))
[ "def", "battery_reported", "(", "self", ",", "voltage", ",", "rawVoltage", ")", ":", "self", ".", "_update_attribute", "(", "BATTERY_PERCENTAGE_REMAINING", ",", "voltage", ")", "self", ".", "_update_attribute", "(", "self", ".", "BATTERY_VOLTAGE_ATTR", ",", "int", "(", "rawVoltage", "/", "100", ")", ")" ]
Battery reported.
[ "Battery", "reported", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L122-L126
train
232,119
dmulcahey/zha-device-handlers
zhaquirks/smartthings/tag_v4.py
FastPollingPowerConfigurationCluster.configure_reporting
async def configure_reporting(self, attribute, min_interval, max_interval, reportable_change): """Configure reporting.""" result = await super().configure_reporting( PowerConfigurationCluster.BATTERY_VOLTAGE_ATTR, self.FREQUENCY, self.FREQUENCY, self.MINIMUM_CHANGE ) return result
python
async def configure_reporting(self, attribute, min_interval, max_interval, reportable_change): """Configure reporting.""" result = await super().configure_reporting( PowerConfigurationCluster.BATTERY_VOLTAGE_ATTR, self.FREQUENCY, self.FREQUENCY, self.MINIMUM_CHANGE ) return result
[ "async", "def", "configure_reporting", "(", "self", ",", "attribute", ",", "min_interval", ",", "max_interval", ",", "reportable_change", ")", ":", "result", "=", "await", "super", "(", ")", ".", "configure_reporting", "(", "PowerConfigurationCluster", ".", "BATTERY_VOLTAGE_ATTR", ",", "self", ".", "FREQUENCY", ",", "self", ".", "FREQUENCY", ",", "self", ".", "MINIMUM_CHANGE", ")", "return", "result" ]
Configure reporting.
[ "Configure", "reporting", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/smartthings/tag_v4.py#L23-L32
train
232,120
F5Networks/f5-common-python
f5/bigip/tm/sys/folder.py
Folder.update
def update(self, **kwargs): '''Update the object, removing device group if inherited If inheritedDevicegroup is the string "true" we need to remove deviceGroup from the args before we update or we get the following error: The floating traffic-group: /Common/traffic-group-1 can only be set on /testfolder if its device-group is inherited from the root folder ''' inherit_device_group = self.__dict__.get('inheritedDevicegroup', False) if inherit_device_group == 'true': self.__dict__.pop('deviceGroup') return self._update(**kwargs)
python
def update(self, **kwargs): '''Update the object, removing device group if inherited If inheritedDevicegroup is the string "true" we need to remove deviceGroup from the args before we update or we get the following error: The floating traffic-group: /Common/traffic-group-1 can only be set on /testfolder if its device-group is inherited from the root folder ''' inherit_device_group = self.__dict__.get('inheritedDevicegroup', False) if inherit_device_group == 'true': self.__dict__.pop('deviceGroup') return self._update(**kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "inherit_device_group", "=", "self", ".", "__dict__", ".", "get", "(", "'inheritedDevicegroup'", ",", "False", ")", "if", "inherit_device_group", "==", "'true'", ":", "self", ".", "__dict__", ".", "pop", "(", "'deviceGroup'", ")", "return", "self", ".", "_update", "(", "*", "*", "kwargs", ")" ]
Update the object, removing device group if inherited If inheritedDevicegroup is the string "true" we need to remove deviceGroup from the args before we update or we get the following error: The floating traffic-group: /Common/traffic-group-1 can only be set on /testfolder if its device-group is inherited from the root folder
[ "Update", "the", "object", "removing", "device", "group", "if", "inherited" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/folder.py#L90-L103
train
232,121
F5Networks/f5-common-python
f5/bigip/tm/cm/device_group.py
Device_Group.sync_to
def sync_to(self): """Wrapper method that synchronizes configuration to DG. Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd` method to sync the configuration TO the device-group. :note:: Both sync_to, and sync_from methods are convenience methods which usually are not what this SDK offers. It is best to execute config-sync with the use of exec_cmd() method on the cm endpoint. """ device_group_collection = self._meta_data['container'] cm = device_group_collection._meta_data['container'] sync_cmd = 'config-sync to-group %s' % self.name cm.exec_cmd('run', utilCmdArgs=sync_cmd)
python
def sync_to(self): """Wrapper method that synchronizes configuration to DG. Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd` method to sync the configuration TO the device-group. :note:: Both sync_to, and sync_from methods are convenience methods which usually are not what this SDK offers. It is best to execute config-sync with the use of exec_cmd() method on the cm endpoint. """ device_group_collection = self._meta_data['container'] cm = device_group_collection._meta_data['container'] sync_cmd = 'config-sync to-group %s' % self.name cm.exec_cmd('run', utilCmdArgs=sync_cmd)
[ "def", "sync_to", "(", "self", ")", ":", "device_group_collection", "=", "self", ".", "_meta_data", "[", "'container'", "]", "cm", "=", "device_group_collection", ".", "_meta_data", "[", "'container'", "]", "sync_cmd", "=", "'config-sync to-group %s'", "%", "self", ".", "name", "cm", ".", "exec_cmd", "(", "'run'", ",", "utilCmdArgs", "=", "sync_cmd", ")" ]
Wrapper method that synchronizes configuration to DG. Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd` method to sync the configuration TO the device-group. :note:: Both sync_to, and sync_from methods are convenience methods which usually are not what this SDK offers. It is best to execute config-sync with the use of exec_cmd() method on the cm endpoint.
[ "Wrapper", "method", "that", "synchronizes", "configuration", "to", "DG", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/cm/device_group.py#L62-L77
train
232,122
F5Networks/f5-common-python
f5/bigip/tm/sys/application.py
Service._create
def _create(self, **kwargs): '''Create service on device and create accompanying Python object. :params kwargs: keyword arguments passed in from create call :raises: HTTPError :returns: Python Service object ''' try: return super(Service, self)._create(**kwargs) except HTTPError as ex: if "The configuration was updated successfully but could not be " \ "retrieved" not in ex.response.text: raise # BIG-IP® will create in Common partition if none is given. # In order to create the uri properly in this class's load, # drop in Common as the partition in kwargs. if 'partition' not in kwargs: kwargs['partition'] = 'Common' # Pop all but the necessary load kwargs from the kwargs given to # create. Otherwise, load may fail. kwargs_copy = kwargs.copy() for key in kwargs_copy: if key not in self._meta_data['required_load_parameters']: kwargs.pop(key) # If response was created successfully, do a local_update. # If not, call to overridden _load method via load return self.load(**kwargs)
python
def _create(self, **kwargs): '''Create service on device and create accompanying Python object. :params kwargs: keyword arguments passed in from create call :raises: HTTPError :returns: Python Service object ''' try: return super(Service, self)._create(**kwargs) except HTTPError as ex: if "The configuration was updated successfully but could not be " \ "retrieved" not in ex.response.text: raise # BIG-IP® will create in Common partition if none is given. # In order to create the uri properly in this class's load, # drop in Common as the partition in kwargs. if 'partition' not in kwargs: kwargs['partition'] = 'Common' # Pop all but the necessary load kwargs from the kwargs given to # create. Otherwise, load may fail. kwargs_copy = kwargs.copy() for key in kwargs_copy: if key not in self._meta_data['required_load_parameters']: kwargs.pop(key) # If response was created successfully, do a local_update. # If not, call to overridden _load method via load return self.load(**kwargs)
[ "def", "_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "super", "(", "Service", ",", "self", ")", ".", "_create", "(", "*", "*", "kwargs", ")", "except", "HTTPError", "as", "ex", ":", "if", "\"The configuration was updated successfully but could not be \"", "\"retrieved\"", "not", "in", "ex", ".", "response", ".", "text", ":", "raise", "# BIG-IP® will create in Common partition if none is given.", "# In order to create the uri properly in this class's load,", "# drop in Common as the partition in kwargs.", "if", "'partition'", "not", "in", "kwargs", ":", "kwargs", "[", "'partition'", "]", "=", "'Common'", "# Pop all but the necessary load kwargs from the kwargs given to", "# create. Otherwise, load may fail.", "kwargs_copy", "=", "kwargs", ".", "copy", "(", ")", "for", "key", "in", "kwargs_copy", ":", "if", "key", "not", "in", "self", ".", "_meta_data", "[", "'required_load_parameters'", "]", ":", "kwargs", ".", "pop", "(", "key", ")", "# If response was created successfully, do a local_update.", "# If not, call to overridden _load method via load", "return", "self", ".", "load", "(", "*", "*", "kwargs", ")" ]
Create service on device and create accompanying Python object. :params kwargs: keyword arguments passed in from create call :raises: HTTPError :returns: Python Service object
[ "Create", "service", "on", "device", "and", "create", "accompanying", "Python", "object", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/application.py#L105-L133
train
232,123
F5Networks/f5-common-python
f5/bigip/tm/sys/application.py
Service._build_service_uri
def _build_service_uri(self, base_uri, partition, name): '''Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri for container :param partition: str -- partition for this service :param name: str -- name of the service :returns: str -- uri to access this service ''' name = name.replace('/', '~') return '%s~%s~%s.app~%s' % (base_uri, partition, name, name)
python
def _build_service_uri(self, base_uri, partition, name): '''Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri for container :param partition: str -- partition for this service :param name: str -- name of the service :returns: str -- uri to access this service ''' name = name.replace('/', '~') return '%s~%s~%s.app~%s' % (base_uri, partition, name, name)
[ "def", "_build_service_uri", "(", "self", ",", "base_uri", ",", "partition", ",", "name", ")", ":", "name", "=", "name", ".", "replace", "(", "'/'", ",", "'~'", ")", "return", "'%s~%s~%s.app~%s'", "%", "(", "base_uri", ",", "partition", ",", "name", ",", "name", ")" ]
Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri for container :param partition: str -- partition for this service :param name: str -- name of the service :returns: str -- uri to access this service
[ "Build", "the", "proper", "uri", "for", "a", "service", "resource", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/application.py#L168-L180
train
232,124
F5Networks/f5-common-python
f5/bigiq/cm/device/licensing/pool/utility.py
Members.delete
def delete(self, **kwargs): """Deletes a member from a 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 'id' not in kwargs: # BIG-IQ requires that you provide the ID of the members to revoke # a license from. This ID is already part of the deletion URL though. # Therefore, if you do not provide it, we enumerate it for you. delete_uri = self._meta_data['uri'] if delete_uri.endswith('/'): delete_uri = delete_uri[0:-1] kwargs['id'] = os.path.basename(delete_uri) uid = uuid.UUID(kwargs['id'], version=4) if uid.hex != kwargs['id'].replace('-', ''): raise F5SDKError( "The specified ID is invalid" ) 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} # This sleep is necessary to prevent BIG-IQ from being able to remove # a license. It happens in certain cases that assignments can be revoked # (and license deletion started) too quickly. Therefore, we must introduce # an artificial delay here to prevent revoking from returning before # BIG-IQ would be ready to remove the license. time.sleep(1)
python
def delete(self, **kwargs): """Deletes a member from a 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 'id' not in kwargs: # BIG-IQ requires that you provide the ID of the members to revoke # a license from. This ID is already part of the deletion URL though. # Therefore, if you do not provide it, we enumerate it for you. delete_uri = self._meta_data['uri'] if delete_uri.endswith('/'): delete_uri = delete_uri[0:-1] kwargs['id'] = os.path.basename(delete_uri) uid = uuid.UUID(kwargs['id'], version=4) if uid.hex != kwargs['id'].replace('-', ''): raise F5SDKError( "The specified ID is invalid" ) 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} # This sleep is necessary to prevent BIG-IQ from being able to remove # a license. It happens in certain cases that assignments can be revoked # (and license deletion started) too quickly. Therefore, we must introduce # an artificial delay here to prevent revoking from returning before # BIG-IQ would be ready to remove the license. time.sleep(1)
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'id'", "not", "in", "kwargs", ":", "# BIG-IQ requires that you provide the ID of the members to revoke", "# a license from. This ID is already part of the deletion URL though.", "# Therefore, if you do not provide it, we enumerate it for you.", "delete_uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "if", "delete_uri", ".", "endswith", "(", "'/'", ")", ":", "delete_uri", "=", "delete_uri", "[", "0", ":", "-", "1", "]", "kwargs", "[", "'id'", "]", "=", "os", ".", "path", ".", "basename", "(", "delete_uri", ")", "uid", "=", "uuid", ".", "UUID", "(", "kwargs", "[", "'id'", "]", ",", "version", "=", "4", ")", "if", "uid", ".", "hex", "!=", "kwargs", "[", "'id'", "]", ".", "replace", "(", "'-'", ",", "''", ")", ":", "raise", "F5SDKError", "(", "\"The specified ID is invalid\"", ")", "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", "}", "# This sleep is necessary to prevent BIG-IQ from being able to remove", "# a license. It happens in certain cases that assignments can be revoked", "# (and license deletion started) too quickly. Therefore, we must introduce", "# an artificial delay here to prevent revoking from returning before", "# BIG-IQ would be ready to remove the license.", "time", ".", "sleep", "(", "1", ")" ]
Deletes a member from a 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", "a", "license", "pool" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigiq/cm/device/licensing/pool/utility.py#L137-L187
train
232,125
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._set_attributes
def _set_attributes(self, **kwargs): '''Set attributes for instance in one place :param kwargs: dict -- dictionary of keyword arguments ''' self.devices = kwargs['devices'][:] self.partition = kwargs['partition'] self.device_group_name = 'device_trust_group' self.device_group_type = 'sync-only'
python
def _set_attributes(self, **kwargs): '''Set attributes for instance in one place :param kwargs: dict -- dictionary of keyword arguments ''' self.devices = kwargs['devices'][:] self.partition = kwargs['partition'] self.device_group_name = 'device_trust_group' self.device_group_type = 'sync-only'
[ "def", "_set_attributes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "devices", "=", "kwargs", "[", "'devices'", "]", "[", ":", "]", "self", ".", "partition", "=", "kwargs", "[", "'partition'", "]", "self", ".", "device_group_name", "=", "'device_trust_group'", "self", ".", "device_group_type", "=", "'sync-only'" ]
Set attributes for instance in one place :param kwargs: dict -- dictionary of keyword arguments
[ "Set", "attributes", "for", "instance", "in", "one", "place" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L76-L85
train
232,126
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain.validate
def validate(self): '''Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted ''' self._populate_domain() missing = [] for domain_device in self.domain: for truster, trustees in iteritems(self.domain): if domain_device not in trustees: missing.append((domain_device, truster, trustees)) if missing: msg = '' for item in missing: msg += '\n%r is not trusted by %r, which trusts: %r' % \ (item[0], item[1], item[2]) raise DeviceNotTrusted(msg) self.device_group = DeviceGroup( devices=self.devices, device_group_name=self.device_group_name, device_group_type=self.device_group_type, device_group_partition=self.partition )
python
def validate(self): '''Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted ''' self._populate_domain() missing = [] for domain_device in self.domain: for truster, trustees in iteritems(self.domain): if domain_device not in trustees: missing.append((domain_device, truster, trustees)) if missing: msg = '' for item in missing: msg += '\n%r is not trusted by %r, which trusts: %r' % \ (item[0], item[1], item[2]) raise DeviceNotTrusted(msg) self.device_group = DeviceGroup( devices=self.devices, device_group_name=self.device_group_name, device_group_type=self.device_group_type, device_group_partition=self.partition )
[ "def", "validate", "(", "self", ")", ":", "self", ".", "_populate_domain", "(", ")", "missing", "=", "[", "]", "for", "domain_device", "in", "self", ".", "domain", ":", "for", "truster", ",", "trustees", "in", "iteritems", "(", "self", ".", "domain", ")", ":", "if", "domain_device", "not", "in", "trustees", ":", "missing", ".", "append", "(", "(", "domain_device", ",", "truster", ",", "trustees", ")", ")", "if", "missing", ":", "msg", "=", "''", "for", "item", "in", "missing", ":", "msg", "+=", "'\\n%r is not trusted by %r, which trusts: %r'", "%", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ",", "item", "[", "2", "]", ")", "raise", "DeviceNotTrusted", "(", "msg", ")", "self", ".", "device_group", "=", "DeviceGroup", "(", "devices", "=", "self", ".", "devices", ",", "device_group_name", "=", "self", ".", "device_group_name", ",", "device_group_type", "=", "self", ".", "device_group_type", ",", "device_group_partition", "=", "self", ".", "partition", ")" ]
Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted
[ "Validate", "that", "devices", "are", "each", "trusted", "by", "one", "another" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L87-L112
train
232,127
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._populate_domain
def _populate_domain(self): '''Populate TrustDomain's domain attribute. This entails an inspection of each device's certificate-authority devices in its trust domain and recording them. After which, we get a dictionary of who trusts who in the domain. ''' self.domain = {} for device in self.devices: device_name = get_device_info(device).name ca_devices = \ device.tm.cm.trust_domains.trust_domain.load( name='Root' ).caDevices self.domain[device_name] = [ d.replace('/%s/' % self.partition, '') for d in ca_devices ]
python
def _populate_domain(self): '''Populate TrustDomain's domain attribute. This entails an inspection of each device's certificate-authority devices in its trust domain and recording them. After which, we get a dictionary of who trusts who in the domain. ''' self.domain = {} for device in self.devices: device_name = get_device_info(device).name ca_devices = \ device.tm.cm.trust_domains.trust_domain.load( name='Root' ).caDevices self.domain[device_name] = [ d.replace('/%s/' % self.partition, '') for d in ca_devices ]
[ "def", "_populate_domain", "(", "self", ")", ":", "self", ".", "domain", "=", "{", "}", "for", "device", "in", "self", ".", "devices", ":", "device_name", "=", "get_device_info", "(", "device", ")", ".", "name", "ca_devices", "=", "device", ".", "tm", ".", "cm", ".", "trust_domains", ".", "trust_domain", ".", "load", "(", "name", "=", "'Root'", ")", ".", "caDevices", "self", ".", "domain", "[", "device_name", "]", "=", "[", "d", ".", "replace", "(", "'/%s/'", "%", "self", ".", "partition", ",", "''", ")", "for", "d", "in", "ca_devices", "]" ]
Populate TrustDomain's domain attribute. This entails an inspection of each device's certificate-authority devices in its trust domain and recording them. After which, we get a dictionary of who trusts who in the domain.
[ "Populate", "TrustDomain", "s", "domain", "attribute", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L114-L131
train
232,128
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain.create
def create(self, **kwargs): '''Add trusted peers to the root bigip device. When adding a trusted device to a device, the trust is reflexive. That is, the truster trusts the trustee and the trustee trusts the truster. So we only need to add the trusted devices to one device. :param kwargs: dict -- devices and partition ''' self._set_attributes(**kwargs) for device in self.devices[1:]: self._add_trustee(device) pollster(self.validate)()
python
def create(self, **kwargs): '''Add trusted peers to the root bigip device. When adding a trusted device to a device, the trust is reflexive. That is, the truster trusts the trustee and the trustee trusts the truster. So we only need to add the trusted devices to one device. :param kwargs: dict -- devices and partition ''' self._set_attributes(**kwargs) for device in self.devices[1:]: self._add_trustee(device) pollster(self.validate)()
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_set_attributes", "(", "*", "*", "kwargs", ")", "for", "device", "in", "self", ".", "devices", "[", "1", ":", "]", ":", "self", ".", "_add_trustee", "(", "device", ")", "pollster", "(", "self", ".", "validate", ")", "(", ")" ]
Add trusted peers to the root bigip device. When adding a trusted device to a device, the trust is reflexive. That is, the truster trusts the trustee and the trustee trusts the truster. So we only need to add the trusted devices to one device. :param kwargs: dict -- devices and partition
[ "Add", "trusted", "peers", "to", "the", "root", "bigip", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L133-L146
train
232,129
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain.teardown
def teardown(self): '''Teardown trust domain by removing trusted devices.''' for device in self.devices: self._remove_trustee(device) self._populate_domain() self.domain = {}
python
def teardown(self): '''Teardown trust domain by removing trusted devices.''' for device in self.devices: self._remove_trustee(device) self._populate_domain() self.domain = {}
[ "def", "teardown", "(", "self", ")", ":", "for", "device", "in", "self", ".", "devices", ":", "self", ".", "_remove_trustee", "(", "device", ")", "self", ".", "_populate_domain", "(", ")", "self", ".", "domain", "=", "{", "}" ]
Teardown trust domain by removing trusted devices.
[ "Teardown", "trust", "domain", "by", "removing", "trusted", "devices", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L148-L154
train
232,130
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._add_trustee
def _add_trustee(self, device): '''Add a single trusted device to the trust domain. :param device: ManagementRoot object -- device to add to trust domain ''' device_name = get_device_info(device).name if device_name in self.domain: msg = 'Device: %r is already in this trust domain.' % device_name raise DeviceAlreadyInTrustDomain(msg) self._modify_trust(self.devices[0], self._get_add_trustee_cmd, device)
python
def _add_trustee(self, device): '''Add a single trusted device to the trust domain. :param device: ManagementRoot object -- device to add to trust domain ''' device_name = get_device_info(device).name if device_name in self.domain: msg = 'Device: %r is already in this trust domain.' % device_name raise DeviceAlreadyInTrustDomain(msg) self._modify_trust(self.devices[0], self._get_add_trustee_cmd, device)
[ "def", "_add_trustee", "(", "self", ",", "device", ")", ":", "device_name", "=", "get_device_info", "(", "device", ")", ".", "name", "if", "device_name", "in", "self", ".", "domain", ":", "msg", "=", "'Device: %r is already in this trust domain.'", "%", "device_name", "raise", "DeviceAlreadyInTrustDomain", "(", "msg", ")", "self", ".", "_modify_trust", "(", "self", ".", "devices", "[", "0", "]", ",", "self", ".", "_get_add_trustee_cmd", ",", "device", ")" ]
Add a single trusted device to the trust domain. :param device: ManagementRoot object -- device to add to trust domain
[ "Add", "a", "single", "trusted", "device", "to", "the", "trust", "domain", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L156-L166
train
232,131
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._remove_trustee
def _remove_trustee(self, device): '''Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove ''' trustee_name = get_device_info(device).name name_object_map = get_device_names_to_objects(self.devices) delete_func = self._get_delete_trustee_cmd for truster in self.domain: if trustee_name in self.domain[truster] and \ truster != trustee_name: truster_obj = name_object_map[truster] self._modify_trust(truster_obj, delete_func, trustee_name) self._populate_domain() for trustee in self.domain[trustee_name]: if trustee_name != trustee: self._modify_trust(device, delete_func, trustee) self.devices.remove(name_object_map[trustee_name])
python
def _remove_trustee(self, device): '''Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove ''' trustee_name = get_device_info(device).name name_object_map = get_device_names_to_objects(self.devices) delete_func = self._get_delete_trustee_cmd for truster in self.domain: if trustee_name in self.domain[truster] and \ truster != trustee_name: truster_obj = name_object_map[truster] self._modify_trust(truster_obj, delete_func, trustee_name) self._populate_domain() for trustee in self.domain[trustee_name]: if trustee_name != trustee: self._modify_trust(device, delete_func, trustee) self.devices.remove(name_object_map[trustee_name])
[ "def", "_remove_trustee", "(", "self", ",", "device", ")", ":", "trustee_name", "=", "get_device_info", "(", "device", ")", ".", "name", "name_object_map", "=", "get_device_names_to_objects", "(", "self", ".", "devices", ")", "delete_func", "=", "self", ".", "_get_delete_trustee_cmd", "for", "truster", "in", "self", ".", "domain", ":", "if", "trustee_name", "in", "self", ".", "domain", "[", "truster", "]", "and", "truster", "!=", "trustee_name", ":", "truster_obj", "=", "name_object_map", "[", "truster", "]", "self", ".", "_modify_trust", "(", "truster_obj", ",", "delete_func", ",", "trustee_name", ")", "self", ".", "_populate_domain", "(", ")", "for", "trustee", "in", "self", ".", "domain", "[", "trustee_name", "]", ":", "if", "trustee_name", "!=", "trustee", ":", "self", ".", "_modify_trust", "(", "device", ",", "delete_func", ",", "trustee", ")", "self", ".", "devices", ".", "remove", "(", "name_object_map", "[", "trustee_name", "]", ")" ]
Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove
[ "Remove", "a", "trustee", "from", "the", "trust", "domain", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L168-L189
train
232,132
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._modify_trust
def _modify_trust(self, truster, mod_peer_func, trustee): '''Modify a trusted peer device by deploying an iapp. :param truster: ManagementRoot object -- device on which to perform commands :param mod_peer_func: function -- function to call to modify peer :param trustee: ManagementRoot object or str -- device to modify ''' iapp_name = 'trusted_device' mod_peer_cmd = mod_peer_func(trustee) iapp_actions = self.iapp_actions.copy() iapp_actions['definition']['implementation'] = mod_peer_cmd self._deploy_iapp(iapp_name, iapp_actions, truster) self._delete_iapp(iapp_name, truster)
python
def _modify_trust(self, truster, mod_peer_func, trustee): '''Modify a trusted peer device by deploying an iapp. :param truster: ManagementRoot object -- device on which to perform commands :param mod_peer_func: function -- function to call to modify peer :param trustee: ManagementRoot object or str -- device to modify ''' iapp_name = 'trusted_device' mod_peer_cmd = mod_peer_func(trustee) iapp_actions = self.iapp_actions.copy() iapp_actions['definition']['implementation'] = mod_peer_cmd self._deploy_iapp(iapp_name, iapp_actions, truster) self._delete_iapp(iapp_name, truster)
[ "def", "_modify_trust", "(", "self", ",", "truster", ",", "mod_peer_func", ",", "trustee", ")", ":", "iapp_name", "=", "'trusted_device'", "mod_peer_cmd", "=", "mod_peer_func", "(", "trustee", ")", "iapp_actions", "=", "self", ".", "iapp_actions", ".", "copy", "(", ")", "iapp_actions", "[", "'definition'", "]", "[", "'implementation'", "]", "=", "mod_peer_cmd", "self", ".", "_deploy_iapp", "(", "iapp_name", ",", "iapp_actions", ",", "truster", ")", "self", ".", "_delete_iapp", "(", "iapp_name", ",", "truster", ")" ]
Modify a trusted peer device by deploying an iapp. :param truster: ManagementRoot object -- device on which to perform commands :param mod_peer_func: function -- function to call to modify peer :param trustee: ManagementRoot object or str -- device to modify
[ "Modify", "a", "trusted", "peer", "device", "by", "deploying", "an", "iapp", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L191-L206
train
232,133
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._delete_iapp
def _delete_iapp(self, iapp_name, deploying_device): '''Delete an iapp service and template on the root device. :param iapp_name: str -- name of iapp :param deploying_device: ManagementRoot object -- device where the iapp will be deleted ''' iapp = deploying_device.tm.sys.application iapp_serv = iapp.services.service.load( name=iapp_name, partition=self.partition ) iapp_serv.delete() iapp_tmpl = iapp.templates.template.load( name=iapp_name, partition=self.partition ) iapp_tmpl.delete()
python
def _delete_iapp(self, iapp_name, deploying_device): '''Delete an iapp service and template on the root device. :param iapp_name: str -- name of iapp :param deploying_device: ManagementRoot object -- device where the iapp will be deleted ''' iapp = deploying_device.tm.sys.application iapp_serv = iapp.services.service.load( name=iapp_name, partition=self.partition ) iapp_serv.delete() iapp_tmpl = iapp.templates.template.load( name=iapp_name, partition=self.partition ) iapp_tmpl.delete()
[ "def", "_delete_iapp", "(", "self", ",", "iapp_name", ",", "deploying_device", ")", ":", "iapp", "=", "deploying_device", ".", "tm", ".", "sys", ".", "application", "iapp_serv", "=", "iapp", ".", "services", ".", "service", ".", "load", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ")", "iapp_serv", ".", "delete", "(", ")", "iapp_tmpl", "=", "iapp", ".", "templates", ".", "template", ".", "load", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ")", "iapp_tmpl", ".", "delete", "(", ")" ]
Delete an iapp service and template on the root device. :param iapp_name: str -- name of iapp :param deploying_device: ManagementRoot object -- device where the iapp will be deleted
[ "Delete", "an", "iapp", "service", "and", "template", "on", "the", "root", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L208-L224
train
232,134
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._deploy_iapp
def _deploy_iapp(self, iapp_name, actions, deploying_device): '''Deploy iapp to add trusted device :param iapp_name: str -- name of iapp :param actions: dict -- actions definition of iapp sections :param deploying_device: ManagementRoot object -- device where the iapp will be created ''' tmpl = deploying_device.tm.sys.application.templates.template serv = deploying_device.tm.sys.application.services.service tmpl.create(name=iapp_name, partition=self.partition, actions=actions) pollster(deploying_device.tm.sys.application.templates.template.load)( name=iapp_name, partition=self.partition ) serv.create( name=iapp_name, partition=self.partition, template='/%s/%s' % (self.partition, iapp_name) )
python
def _deploy_iapp(self, iapp_name, actions, deploying_device): '''Deploy iapp to add trusted device :param iapp_name: str -- name of iapp :param actions: dict -- actions definition of iapp sections :param deploying_device: ManagementRoot object -- device where the iapp will be created ''' tmpl = deploying_device.tm.sys.application.templates.template serv = deploying_device.tm.sys.application.services.service tmpl.create(name=iapp_name, partition=self.partition, actions=actions) pollster(deploying_device.tm.sys.application.templates.template.load)( name=iapp_name, partition=self.partition ) serv.create( name=iapp_name, partition=self.partition, template='/%s/%s' % (self.partition, iapp_name) )
[ "def", "_deploy_iapp", "(", "self", ",", "iapp_name", ",", "actions", ",", "deploying_device", ")", ":", "tmpl", "=", "deploying_device", ".", "tm", ".", "sys", ".", "application", ".", "templates", ".", "template", "serv", "=", "deploying_device", ".", "tm", ".", "sys", ".", "application", ".", "services", ".", "service", "tmpl", ".", "create", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ",", "actions", "=", "actions", ")", "pollster", "(", "deploying_device", ".", "tm", ".", "sys", ".", "application", ".", "templates", ".", "template", ".", "load", ")", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ")", "serv", ".", "create", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ",", "template", "=", "'/%s/%s'", "%", "(", "self", ".", "partition", ",", "iapp_name", ")", ")" ]
Deploy iapp to add trusted device :param iapp_name: str -- name of iapp :param actions: dict -- actions definition of iapp sections :param deploying_device: ManagementRoot object -- device where the iapp will be created
[ "Deploy", "iapp", "to", "add", "trusted", "device" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L226-L245
train
232,135
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._get_add_trustee_cmd
def _get_add_trustee_cmd(self, trustee): '''Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee ''' trustee_info = pollster(get_device_info)(trustee) username = trustee._meta_data['username'] password = trustee._meta_data['password'] return 'tmsh::modify cm trust-domain Root ca-devices add ' \ '\\{ %s \\} name %s username %s password %s' % \ (trustee_info.managementIp, trustee_info.name, username, password)
python
def _get_add_trustee_cmd(self, trustee): '''Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee ''' trustee_info = pollster(get_device_info)(trustee) username = trustee._meta_data['username'] password = trustee._meta_data['password'] return 'tmsh::modify cm trust-domain Root ca-devices add ' \ '\\{ %s \\} name %s username %s password %s' % \ (trustee_info.managementIp, trustee_info.name, username, password)
[ "def", "_get_add_trustee_cmd", "(", "self", ",", "trustee", ")", ":", "trustee_info", "=", "pollster", "(", "get_device_info", ")", "(", "trustee", ")", "username", "=", "trustee", ".", "_meta_data", "[", "'username'", "]", "password", "=", "trustee", ".", "_meta_data", "[", "'password'", "]", "return", "'tmsh::modify cm trust-domain Root ca-devices add '", "'\\\\{ %s \\\\} name %s username %s password %s'", "%", "(", "trustee_info", ".", "managementIp", ",", "trustee_info", ".", "name", ",", "username", ",", "password", ")" ]
Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee
[ "Get", "tmsh", "command", "to", "add", "a", "trusted", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L247-L259
train
232,136
F5Networks/f5-common-python
f5/bigip/tm/vcmp/virtual_disk.py
Virtual_Disk.load
def load(self, **kwargs): """Loads a given resource Loads a given resource provided a 'name' and an optional 'slot' parameter. The 'slot' parameter is not a required load parameter because it is provided as an optional way of constructing the correct 'name' of the vCMP resource. :param kwargs: :return: """ kwargs['transform_name'] = True kwargs = self._mutate_name(kwargs) return self._load(**kwargs)
python
def load(self, **kwargs): """Loads a given resource Loads a given resource provided a 'name' and an optional 'slot' parameter. The 'slot' parameter is not a required load parameter because it is provided as an optional way of constructing the correct 'name' of the vCMP resource. :param kwargs: :return: """ kwargs['transform_name'] = True kwargs = self._mutate_name(kwargs) return self._load(**kwargs)
[ "def", "load", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'transform_name'", "]", "=", "True", "kwargs", "=", "self", ".", "_mutate_name", "(", "kwargs", ")", "return", "self", ".", "_load", "(", "*", "*", "kwargs", ")" ]
Loads a given resource Loads a given resource provided a 'name' and an optional 'slot' parameter. The 'slot' parameter is not a required load parameter because it is provided as an optional way of constructing the correct 'name' of the vCMP resource. :param kwargs: :return:
[ "Loads", "a", "given", "resource" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/vcmp/virtual_disk.py#L53-L66
train
232,137
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_section_end_index
def _get_section_end_index(self, section, section_start): '''Get end of section's content. In the loop to match braces, we must not count curly braces that are within a doubly quoted string. :param section: string name of section :param section_start: integer index of section's beginning :return: integer index of section's end :raises: CurlyBraceMismatchException ''' brace_count = 0 in_quote = False in_escape = False for index, char in enumerate(self.template_str[section_start:]): # This check is to look for items inside of an escape sequence. # # For example, in the iApp team's iApps, there is a proc called # "iapp_get_items" which has a line that looks like this. # # set val [string map {\" ""} $val] # # This will cause this parser to fail because of the unbalanced # quotes. Therefore, this conditional takes this into consideration # if char == '\\' and not in_escape: in_escape = True elif char == '\\' and in_escape: in_escape = False if not in_escape: if char == '"' and not in_quote: in_quote = True elif char == '"' and in_quote: in_quote = False if char == '{' and not in_quote: brace_count += 1 elif char == '}' and not in_quote: brace_count -= 1 if brace_count is 0: return index + section_start if brace_count is not 0: raise CurlyBraceMismatchException( 'Curly braces mismatch in section %s.' % section )
python
def _get_section_end_index(self, section, section_start): '''Get end of section's content. In the loop to match braces, we must not count curly braces that are within a doubly quoted string. :param section: string name of section :param section_start: integer index of section's beginning :return: integer index of section's end :raises: CurlyBraceMismatchException ''' brace_count = 0 in_quote = False in_escape = False for index, char in enumerate(self.template_str[section_start:]): # This check is to look for items inside of an escape sequence. # # For example, in the iApp team's iApps, there is a proc called # "iapp_get_items" which has a line that looks like this. # # set val [string map {\" ""} $val] # # This will cause this parser to fail because of the unbalanced # quotes. Therefore, this conditional takes this into consideration # if char == '\\' and not in_escape: in_escape = True elif char == '\\' and in_escape: in_escape = False if not in_escape: if char == '"' and not in_quote: in_quote = True elif char == '"' and in_quote: in_quote = False if char == '{' and not in_quote: brace_count += 1 elif char == '}' and not in_quote: brace_count -= 1 if brace_count is 0: return index + section_start if brace_count is not 0: raise CurlyBraceMismatchException( 'Curly braces mismatch in section %s.' % section )
[ "def", "_get_section_end_index", "(", "self", ",", "section", ",", "section_start", ")", ":", "brace_count", "=", "0", "in_quote", "=", "False", "in_escape", "=", "False", "for", "index", ",", "char", "in", "enumerate", "(", "self", ".", "template_str", "[", "section_start", ":", "]", ")", ":", "# This check is to look for items inside of an escape sequence.", "#", "# For example, in the iApp team's iApps, there is a proc called", "# \"iapp_get_items\" which has a line that looks like this.", "#", "# set val [string map {\\\" \"\"} $val]", "#", "# This will cause this parser to fail because of the unbalanced", "# quotes. Therefore, this conditional takes this into consideration", "#", "if", "char", "==", "'\\\\'", "and", "not", "in_escape", ":", "in_escape", "=", "True", "elif", "char", "==", "'\\\\'", "and", "in_escape", ":", "in_escape", "=", "False", "if", "not", "in_escape", ":", "if", "char", "==", "'\"'", "and", "not", "in_quote", ":", "in_quote", "=", "True", "elif", "char", "==", "'\"'", "and", "in_quote", ":", "in_quote", "=", "False", "if", "char", "==", "'{'", "and", "not", "in_quote", ":", "brace_count", "+=", "1", "elif", "char", "==", "'}'", "and", "not", "in_quote", ":", "brace_count", "-=", "1", "if", "brace_count", "is", "0", ":", "return", "index", "+", "section_start", "if", "brace_count", "is", "not", "0", ":", "raise", "CurlyBraceMismatchException", "(", "'Curly braces mismatch in section %s.'", "%", "section", ")" ]
Get end of section's content. In the loop to match braces, we must not count curly braces that are within a doubly quoted string. :param section: string name of section :param section_start: integer index of section's beginning :return: integer index of section's end :raises: CurlyBraceMismatchException
[ "Get", "end", "of", "section", "s", "content", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L80-L129
train
232,138
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_section_start_index
def _get_section_start_index(self, section): '''Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException ''' sec_start_re = r'%s\s*\{' % section found = re.search(sec_start_re, self.template_str) if found: return found.end() - 1 raise NonextantSectionException( 'Section %s not found in template' % section )
python
def _get_section_start_index(self, section): '''Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException ''' sec_start_re = r'%s\s*\{' % section found = re.search(sec_start_re, self.template_str) if found: return found.end() - 1 raise NonextantSectionException( 'Section %s not found in template' % section )
[ "def", "_get_section_start_index", "(", "self", ",", "section", ")", ":", "sec_start_re", "=", "r'%s\\s*\\{'", "%", "section", "found", "=", "re", ".", "search", "(", "sec_start_re", ",", "self", ".", "template_str", ")", "if", "found", ":", "return", "found", ".", "end", "(", ")", "-", "1", "raise", "NonextantSectionException", "(", "'Section %s not found in template'", "%", "section", ")" ]
Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException
[ "Get", "start", "of", "a", "section", "s", "content", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L131-L147
train
232,139
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_template_name
def _get_template_name(self): '''Find template name. :returns: string of template name :raises: NonextantTemplateNameException ''' start_pattern = r"sys application template\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" template_start = re.search(start_pattern, self.template_str) if template_start: return template_start.group('name') raise NonextantTemplateNameException('Template name not found.')
python
def _get_template_name(self): '''Find template name. :returns: string of template name :raises: NonextantTemplateNameException ''' start_pattern = r"sys application template\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" template_start = re.search(start_pattern, self.template_str) if template_start: return template_start.group('name') raise NonextantTemplateNameException('Template name not found.')
[ "def", "_get_template_name", "(", "self", ")", ":", "start_pattern", "=", "r\"sys application template\\s+\"", "r\"(\\/[\\w\\.\\-]+\\/)?\"", "r\"(?P<name>[\\w\\.\\-]+)\\s*\\{\"", "template_start", "=", "re", ".", "search", "(", "start_pattern", ",", "self", ".", "template_str", ")", "if", "template_start", ":", "return", "template_start", ".", "group", "(", "'name'", ")", "raise", "NonextantTemplateNameException", "(", "'Template name not found.'", ")" ]
Find template name. :returns: string of template name :raises: NonextantTemplateNameException
[ "Find", "template", "name", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L149-L164
train
232,140
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_template_attr
def _get_template_attr(self, attr): '''Find the attribute value for a specific attribute. :param attr: string of attribute name :returns: string of attribute value ''' attr_re = r'{0}\s+.*'.format(attr) attr_found = re.search(attr_re, self.template_str) if attr_found: attr_value = attr_found.group(0).replace(attr, '', 1) return attr_value.strip()
python
def _get_template_attr(self, attr): '''Find the attribute value for a specific attribute. :param attr: string of attribute name :returns: string of attribute value ''' attr_re = r'{0}\s+.*'.format(attr) attr_found = re.search(attr_re, self.template_str) if attr_found: attr_value = attr_found.group(0).replace(attr, '', 1) return attr_value.strip()
[ "def", "_get_template_attr", "(", "self", ",", "attr", ")", ":", "attr_re", "=", "r'{0}\\s+.*'", ".", "format", "(", "attr", ")", "attr_found", "=", "re", ".", "search", "(", "attr_re", ",", "self", ".", "template_str", ")", "if", "attr_found", ":", "attr_value", "=", "attr_found", ".", "group", "(", "0", ")", ".", "replace", "(", "attr", ",", "''", ",", "1", ")", "return", "attr_value", ".", "strip", "(", ")" ]
Find the attribute value for a specific attribute. :param attr: string of attribute name :returns: string of attribute value
[ "Find", "the", "attribute", "value", "for", "a", "specific", "attribute", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L166-L178
train
232,141
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._add_sections
def _add_sections(self): '''Add the found and required sections to the templ_dict.''' for section in self.template_sections: try: sec_start = self._get_section_start_index(section) except NonextantSectionException: if section in self.sections_not_required: continue raise sec_end = self._get_section_end_index(section, sec_start) section_value = self.template_str[sec_start+1:sec_end].strip() section, section_value = self._transform_key_value( section, section_value, self.section_map ) self.templ_dict['actions']['definition'][section] = section_value self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
python
def _add_sections(self): '''Add the found and required sections to the templ_dict.''' for section in self.template_sections: try: sec_start = self._get_section_start_index(section) except NonextantSectionException: if section in self.sections_not_required: continue raise sec_end = self._get_section_end_index(section, sec_start) section_value = self.template_str[sec_start+1:sec_end].strip() section, section_value = self._transform_key_value( section, section_value, self.section_map ) self.templ_dict['actions']['definition'][section] = section_value self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
[ "def", "_add_sections", "(", "self", ")", ":", "for", "section", "in", "self", ".", "template_sections", ":", "try", ":", "sec_start", "=", "self", ".", "_get_section_start_index", "(", "section", ")", "except", "NonextantSectionException", ":", "if", "section", "in", "self", ".", "sections_not_required", ":", "continue", "raise", "sec_end", "=", "self", ".", "_get_section_end_index", "(", "section", ",", "sec_start", ")", "section_value", "=", "self", ".", "template_str", "[", "sec_start", "+", "1", ":", "sec_end", "]", ".", "strip", "(", ")", "section", ",", "section_value", "=", "self", ".", "_transform_key_value", "(", "section", ",", "section_value", ",", "self", ".", "section_map", ")", "self", ".", "templ_dict", "[", "'actions'", "]", "[", "'definition'", "]", "[", "section", "]", "=", "section_value", "self", ".", "template_str", "=", "self", ".", "template_str", "[", ":", "sec_start", "+", "1", "]", "+", "self", ".", "template_str", "[", "sec_end", ":", "]" ]
Add the found and required sections to the templ_dict.
[ "Add", "the", "found", "and", "required", "sections", "to", "the", "templ_dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L180-L198
train
232,142
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._add_cli_scripts
def _add_cli_scripts(self): '''Add the found external sections to the templ_dict.''' pattern = r"cli script\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" sections = re.finditer(pattern, self.template_str) for section in sections: if 'scripts' not in self.templ_dict: self.templ_dict['scripts'] = [] try: sec_start = self._get_section_start_index( section.group('name') ) except NonextantSectionException: continue sec_end = self._get_section_end_index( section.group('name'), sec_start ) section_value = self.template_str[sec_start+1:sec_end].strip() self.templ_dict['scripts'].append(dict( name=section.group('name'), script=section_value )) self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
python
def _add_cli_scripts(self): '''Add the found external sections to the templ_dict.''' pattern = r"cli script\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" sections = re.finditer(pattern, self.template_str) for section in sections: if 'scripts' not in self.templ_dict: self.templ_dict['scripts'] = [] try: sec_start = self._get_section_start_index( section.group('name') ) except NonextantSectionException: continue sec_end = self._get_section_end_index( section.group('name'), sec_start ) section_value = self.template_str[sec_start+1:sec_end].strip() self.templ_dict['scripts'].append(dict( name=section.group('name'), script=section_value )) self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
[ "def", "_add_cli_scripts", "(", "self", ")", ":", "pattern", "=", "r\"cli script\\s+\"", "r\"(\\/[\\w\\.\\-]+\\/)?\"", "r\"(?P<name>[\\w\\.\\-]+)\\s*\\{\"", "sections", "=", "re", ".", "finditer", "(", "pattern", ",", "self", ".", "template_str", ")", "for", "section", "in", "sections", ":", "if", "'scripts'", "not", "in", "self", ".", "templ_dict", ":", "self", ".", "templ_dict", "[", "'scripts'", "]", "=", "[", "]", "try", ":", "sec_start", "=", "self", ".", "_get_section_start_index", "(", "section", ".", "group", "(", "'name'", ")", ")", "except", "NonextantSectionException", ":", "continue", "sec_end", "=", "self", ".", "_get_section_end_index", "(", "section", ".", "group", "(", "'name'", ")", ",", "sec_start", ")", "section_value", "=", "self", ".", "template_str", "[", "sec_start", "+", "1", ":", "sec_end", "]", ".", "strip", "(", ")", "self", ".", "templ_dict", "[", "'scripts'", "]", ".", "append", "(", "dict", "(", "name", "=", "section", ".", "group", "(", "'name'", ")", ",", "script", "=", "section_value", ")", ")", "self", ".", "template_str", "=", "self", ".", "template_str", "[", ":", "sec_start", "+", "1", "]", "+", "self", ".", "template_str", "[", "sec_end", ":", "]" ]
Add the found external sections to the templ_dict.
[ "Add", "the", "found", "external", "sections", "to", "the", "templ_dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L200-L230
train
232,143
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._add_attrs
def _add_attrs(self): '''Add the found and required attrs to the templ_dict.''' for attr in self.template_attrs: attr_value = self._get_template_attr(attr) if not attr_value: continue attr, attr_value = self._transform_key_value( attr, attr_value, self.attr_map ) self.templ_dict[attr] = attr_value
python
def _add_attrs(self): '''Add the found and required attrs to the templ_dict.''' for attr in self.template_attrs: attr_value = self._get_template_attr(attr) if not attr_value: continue attr, attr_value = self._transform_key_value( attr, attr_value, self.attr_map ) self.templ_dict[attr] = attr_value
[ "def", "_add_attrs", "(", "self", ")", ":", "for", "attr", "in", "self", ".", "template_attrs", ":", "attr_value", "=", "self", ".", "_get_template_attr", "(", "attr", ")", "if", "not", "attr_value", ":", "continue", "attr", ",", "attr_value", "=", "self", ".", "_transform_key_value", "(", "attr", ",", "attr_value", ",", "self", ".", "attr_map", ")", "self", ".", "templ_dict", "[", "attr", "]", "=", "attr_value" ]
Add the found and required attrs to the templ_dict.
[ "Add", "the", "found", "and", "required", "attrs", "to", "the", "templ_dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L232-L245
train
232,144
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._parse_tcl_list
def _parse_tcl_list(self, attr, list_str): '''Turns a string representation of a TCL list into a Python list. :param attr: string name of attribute :param list_str: string representation of a list :returns: Python list ''' list_str = list_str.strip() if not list_str: return [] if list_str[0] != '{' and list_str[-1] != '}': if list_str.find('none') >= 0: return list_str if not re.search(self.tcl_list_patterns[attr], list_str): raise MalformedTCLListException( 'TCL list for "%s" is malformed. ' % attr ) list_str = list_str.strip('{').strip('}') list_str = list_str.strip() return list_str.split()
python
def _parse_tcl_list(self, attr, list_str): '''Turns a string representation of a TCL list into a Python list. :param attr: string name of attribute :param list_str: string representation of a list :returns: Python list ''' list_str = list_str.strip() if not list_str: return [] if list_str[0] != '{' and list_str[-1] != '}': if list_str.find('none') >= 0: return list_str if not re.search(self.tcl_list_patterns[attr], list_str): raise MalformedTCLListException( 'TCL list for "%s" is malformed. ' % attr ) list_str = list_str.strip('{').strip('}') list_str = list_str.strip() return list_str.split()
[ "def", "_parse_tcl_list", "(", "self", ",", "attr", ",", "list_str", ")", ":", "list_str", "=", "list_str", ".", "strip", "(", ")", "if", "not", "list_str", ":", "return", "[", "]", "if", "list_str", "[", "0", "]", "!=", "'{'", "and", "list_str", "[", "-", "1", "]", "!=", "'}'", ":", "if", "list_str", ".", "find", "(", "'none'", ")", ">=", "0", ":", "return", "list_str", "if", "not", "re", ".", "search", "(", "self", ".", "tcl_list_patterns", "[", "attr", "]", ",", "list_str", ")", ":", "raise", "MalformedTCLListException", "(", "'TCL list for \"%s\" is malformed. '", "%", "attr", ")", "list_str", "=", "list_str", ".", "strip", "(", "'{'", ")", ".", "strip", "(", "'}'", ")", "list_str", "=", "list_str", ".", "strip", "(", ")", "return", "list_str", ".", "split", "(", ")" ]
Turns a string representation of a TCL list into a Python list. :param attr: string name of attribute :param list_str: string representation of a list :returns: Python list
[ "Turns", "a", "string", "representation", "of", "a", "TCL", "list", "into", "a", "Python", "list", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L247-L271
train
232,145
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._transform_key_value
def _transform_key_value(self, key, value, map_dict): '''Massage keys and values for iapp dict to look like JSON. :param key: string dictionary key :param value: string dictionary value :param map_dict: dictionary to map key names ''' if key in self.tcl_list_patterns: value = self._parse_tcl_list(key, value) if key in map_dict: key = map_dict[key] return key, value
python
def _transform_key_value(self, key, value, map_dict): '''Massage keys and values for iapp dict to look like JSON. :param key: string dictionary key :param value: string dictionary value :param map_dict: dictionary to map key names ''' if key in self.tcl_list_patterns: value = self._parse_tcl_list(key, value) if key in map_dict: key = map_dict[key] return key, value
[ "def", "_transform_key_value", "(", "self", ",", "key", ",", "value", ",", "map_dict", ")", ":", "if", "key", "in", "self", ".", "tcl_list_patterns", ":", "value", "=", "self", ".", "_parse_tcl_list", "(", "key", ",", "value", ")", "if", "key", "in", "map_dict", ":", "key", "=", "map_dict", "[", "key", "]", "return", "key", ",", "value" ]
Massage keys and values for iapp dict to look like JSON. :param key: string dictionary key :param value: string dictionary value :param map_dict: dictionary to map key names
[ "Massage", "keys", "and", "values", "for", "iapp", "dict", "to", "look", "like", "JSON", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L273-L287
train
232,146
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser.parse_template
def parse_template(self): '''Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template ''' self.templ_dict = {'actions': {'definition': {}}} self.templ_dict['name'] = self._get_template_name() self._add_cli_scripts() self._add_sections() self._add_attrs() return self.templ_dict
python
def parse_template(self): '''Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template ''' self.templ_dict = {'actions': {'definition': {}}} self.templ_dict['name'] = self._get_template_name() self._add_cli_scripts() self._add_sections() self._add_attrs() return self.templ_dict
[ "def", "parse_template", "(", "self", ")", ":", "self", ".", "templ_dict", "=", "{", "'actions'", ":", "{", "'definition'", ":", "{", "}", "}", "}", "self", ".", "templ_dict", "[", "'name'", "]", "=", "self", ".", "_get_template_name", "(", ")", "self", ".", "_add_cli_scripts", "(", ")", "self", ".", "_add_sections", "(", ")", "self", ".", "_add_attrs", "(", ")", "return", "self", ".", "templ_dict" ]
Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template
[ "Parse", "the", "template", "string", "into", "a", "dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L289-L307
train
232,147
F5Networks/f5-common-python
f5/bigip/shared/authn.py
Root._create
def _create(self, **kwargs): """wrapped by `create` 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) self._check_exclusive_parameters(**kwargs) requests_params = self._handle_requests_params(kwargs) self._minimum_one_is_missing(**kwargs) self._check_create_parameters(**kwargs) kwargs = self._check_for_python_keywords(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'] kwargs = self._prepare_request_json(kwargs) # Invoke the REST operation on the device. response = session.post(_create_uri, json=kwargs, **requests_params) # Make new instance of self result = self._produce_instance(response) return result
python
def _create(self, **kwargs): """wrapped by `create` 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) self._check_exclusive_parameters(**kwargs) requests_params = self._handle_requests_params(kwargs) self._minimum_one_is_missing(**kwargs) self._check_create_parameters(**kwargs) kwargs = self._check_for_python_keywords(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'] kwargs = self._prepare_request_json(kwargs) # Invoke the REST operation on the device. response = session.post(_create_uri, json=kwargs, **requests_params) # Make new instance of self result = self._produce_instance(response) return result
[ "def", "_create", "(", "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", ")", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "self", ".", "_minimum_one_is_missing", "(", "*", "*", "kwargs", ")", "self", ".", "_check_create_parameters", "(", "*", "*", "kwargs", ")", "kwargs", "=", "self", ".", "_check_for_python_keywords", "(", "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'", "]", "kwargs", "=", "self", ".", "_prepare_request_json", "(", "kwargs", ")", "# Invoke the REST operation on the device.", "response", "=", "session", ".", "post", "(", "_create_uri", ",", "json", "=", "kwargs", ",", "*", "*", "requests_params", ")", "# Make new instance of self", "result", "=", "self", ".", "_produce_instance", "(", "response", ")", "return", "result" ]
wrapped by `create` override that in subclasses to customize
[ "wrapped", "by", "create", "override", "that", "in", "subclasses", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/shared/authn.py#L55-L83
train
232,148
F5Networks/f5-common-python
f5sdk_plugins/fixtures.py
peer
def peer(opt_peer, opt_username, opt_password, scope="module"): '''peer bigip fixture''' p = BigIP(opt_peer, opt_username, opt_password) return p
python
def peer(opt_peer, opt_username, opt_password, scope="module"): '''peer bigip fixture''' p = BigIP(opt_peer, opt_username, opt_password) return p
[ "def", "peer", "(", "opt_peer", ",", "opt_username", ",", "opt_password", ",", "scope", "=", "\"module\"", ")", ":", "p", "=", "BigIP", "(", "opt_peer", ",", "opt_username", ",", "opt_password", ")", "return", "p" ]
peer bigip fixture
[ "peer", "bigip", "fixture" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5sdk_plugins/fixtures.py#L116-L119
train
232,149
F5Networks/f5-common-python
f5/bigip/tm/gtm/topology.py
Topology.exists
def exists(self, **kwargs): """Providing a partition is not necessary on topology; causes errors""" kwargs.pop('partition', None) kwargs['transform_name'] = True return self._exists(**kwargs)
python
def exists(self, **kwargs): """Providing a partition is not necessary on topology; causes errors""" kwargs.pop('partition', None) kwargs['transform_name'] = True return self._exists(**kwargs)
[ "def", "exists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "pop", "(", "'partition'", ",", "None", ")", "kwargs", "[", "'transform_name'", "]", "=", "True", "return", "self", ".", "_exists", "(", "*", "*", "kwargs", ")" ]
Providing a partition is not necessary on topology; causes errors
[ "Providing", "a", "partition", "is", "not", "necessary", "on", "topology", ";", "causes", "errors" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/gtm/topology.py#L149-L153
train
232,150
F5Networks/f5-common-python
f5/utils/responses/handlers.py
Stats._key_dot_replace
def _key_dot_replace(self, rdict): """Replace fullstops in returned keynames""" temp_dict = {} for key, value in iteritems(rdict): if isinstance(value, dict): value = self._key_dot_replace(value) temp_dict[key.replace('.', '_')] = value return temp_dict
python
def _key_dot_replace(self, rdict): """Replace fullstops in returned keynames""" temp_dict = {} for key, value in iteritems(rdict): if isinstance(value, dict): value = self._key_dot_replace(value) temp_dict[key.replace('.', '_')] = value return temp_dict
[ "def", "_key_dot_replace", "(", "self", ",", "rdict", ")", ":", "temp_dict", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "rdict", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "value", "=", "self", ".", "_key_dot_replace", "(", "value", ")", "temp_dict", "[", "key", ".", "replace", "(", "'.'", ",", "'_'", ")", "]", "=", "value", "return", "temp_dict" ]
Replace fullstops in returned keynames
[ "Replace", "fullstops", "in", "returned", "keynames" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/responses/handlers.py#L43-L50
train
232,151
F5Networks/f5-common-python
f5/utils/responses/handlers.py
Stats._get_nest_stats
def _get_nest_stats(self): """Helper method to deal with nestedStats as json format changed in v12.x """ for x in self.rdict: check = urlparse(x) if check.scheme: nested_dict = self.rdict[x]['nestedStats'] tmp_dict = nested_dict['entries'] return self._key_dot_replace(tmp_dict) return self._key_dot_replace(self.rdict)
python
def _get_nest_stats(self): """Helper method to deal with nestedStats as json format changed in v12.x """ for x in self.rdict: check = urlparse(x) if check.scheme: nested_dict = self.rdict[x]['nestedStats'] tmp_dict = nested_dict['entries'] return self._key_dot_replace(tmp_dict) return self._key_dot_replace(self.rdict)
[ "def", "_get_nest_stats", "(", "self", ")", ":", "for", "x", "in", "self", ".", "rdict", ":", "check", "=", "urlparse", "(", "x", ")", "if", "check", ".", "scheme", ":", "nested_dict", "=", "self", ".", "rdict", "[", "x", "]", "[", "'nestedStats'", "]", "tmp_dict", "=", "nested_dict", "[", "'entries'", "]", "return", "self", ".", "_key_dot_replace", "(", "tmp_dict", ")", "return", "self", ".", "_key_dot_replace", "(", "self", ".", "rdict", ")" ]
Helper method to deal with nestedStats as json format changed in v12.x
[ "Helper", "method", "to", "deal", "with", "nestedStats" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/responses/handlers.py#L52-L64
train
232,152
F5Networks/f5-common-python
f5/utils/responses/handlers.py
Stats.refresh
def refresh(self, **kwargs): """Refreshes stats attached to an object""" self.resource.refresh(**kwargs) self.rdict = self.resource.entries self._update_stats()
python
def refresh(self, **kwargs): """Refreshes stats attached to an object""" self.resource.refresh(**kwargs) self.rdict = self.resource.entries self._update_stats()
[ "def", "refresh", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "resource", ".", "refresh", "(", "*", "*", "kwargs", ")", "self", ".", "rdict", "=", "self", ".", "resource", ".", "entries", "self", ".", "_update_stats", "(", ")" ]
Refreshes stats attached to an object
[ "Refreshes", "stats", "attached", "to", "an", "object" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/responses/handlers.py#L71-L75
train
232,153
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
train
232,154
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
train
232,155
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
train
232,156
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
train
232,157
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
train
232,158
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
train
232,159
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
train
232,160
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
train
232,161
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
train
232,162
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
train
232,163
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
train
232,164
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
train
232,165
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
train
232,166
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
train
232,167
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
train
232,168
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
train
232,169
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
train
232,170
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
train
232,171
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
train
232,172
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
train
232,173
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
train
232,174
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
train
232,175
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
train
232,176
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
train
232,177
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
train
232,178
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
train
232,179
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
train
232,180
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
train
232,181
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
train
232,182
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
train
232,183
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
train
232,184
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
train
232,185
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
train
232,186
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
train
232,187
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
train
232,188
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
train
232,189
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
train
232,190
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
train
232,191
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
train
232,192
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
train
232,193
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
train
232,194
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
train
232,195
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
train
232,196
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
train
232,197
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
train
232,198
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
train
232,199