code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for i in range(self.node['properties']['adapters']): port = {'id': self.port_id, 'name': 'Ethernet%s' % i, 'port_number': i} self.node['ports'].append(port) self.port_id += 1
def add_vm_ethernet_ports(self)
Add ethernet ports to Virtualbox and Qemu nodes
4.523361
4.721767
0.957981
valid_devices = {'ASA': 'asa', 'PIX': 'PIX_firewall', 'JUNOS': 'router', 'IDS': 'ids'} if self.device_info['from'] in valid_devices \ and 'default_symbol' not in self.node \ and 'hover_symbol' not in self.node: self.set_symbol...
def set_qemu_symbol(self)
Set the appropriate symbol for QEMU Devices
8.346752
7.398958
1.128098
if symbol == 'EtherSwitch router': symbol = 'multilayer_switch' elif symbol == 'Host': symbol = 'computer' normal = ':/symbols/%s.normal.svg' % symbol selected = ':/symbols/%s.selected.svg' % symbol self.node['default_symbol'] = normal s...
def set_symbol(self, symbol)
Set a symbol for a device :param str symbol: Symbol to use
8.40218
9.545721
0.880204
# Port String - access 1 SW2 1 # 0: type 1: vlan 2: destination device 3: destination port port_def = port_def.split(' ') if len(port_def) == 4: destination = {'device': port_def[2], 'port': port_def[3]} else: destinatio...
def calc_ethsw_port(self, port_num, port_def)
Split and create the port entry for an Ethernet Switch :param port_num: port number :type port_num: str or int :param str port_def: port definition
4.133711
4.074811
1.014455
model = self.device_info['model'] chassis = self.device_info['chassis'] num_ports = MODEL_MATRIX[model][chassis]['ports'] ports = [] if num_ports > 0: port_type = MODEL_MATRIX[model][chassis]['type'] # Create the ports dict for i in ...
def calc_mb_ports(self)
Add the default ports to add to a router
3.551348
3.45478
1.027952
if destination['device'] == 'NIO': destination['port'] = destination['port'].lower() link = {'source_node_id': src_id, 'source_port_id': src_port, 'source_port_name': src_port_name, 'source_dev': self.node['properties']['name'], ...
def calc_link(self, src_id, src_port, src_port_name, destination)
Add a link item for processing later :param int src_id: Source node ID :param int src_port: Source port ID :param str src_port_name: Source port name :param dict destination: Destination
3.318674
3.407037
0.974064
if self.device_info['type'] == 'Router': self.node['description'] = '%s %s' % (self.device_info['type'], self.device_info['model']) else: self.node['description'] = self.device_info['desc']
def set_description(self)
Set the node description
3.266538
3.123999
1.045627
if self.device_info['type'] == 'Router': self.node['type'] = self.device_info['model'].upper() else: self.node['type'] = self.device_info['type']
def set_type(self)
Set the node type
3.783918
3.444443
1.098557
for connection in self.interfaces: int_type = connection['from'][0] int_name = connection['from'].replace(int_type, PORT_TYPES[int_type.upper()]) # Get the source port id src_port = None for po...
def calc_device_links(self)
Calculate a router or VirtualBox link
3.647011
3.544564
1.028903
# Connection String - SW1:1:nio_gen_eth:eth0 # 0: Destination device 1: Destination port # 2: NIO 3: NIO Destination self.node['properties']['nios'] = [] if self.connections is None: return None else: self.connections = self.connections.sp...
def calc_cloud_connection(self)
Add the ports and nios for a cloud connection :return: None on success or RuntimeError on error
5.184366
4.725897
1.097012
for mapping_a in self.mappings: for mapping_b in self.mappings: if mapping_a['source'] == mapping_b['dest']: self.mappings.remove(mapping_b) break self.node['properties']['mappings'] = {} mappings = self.node['properti...
def process_mappings(self)
Process the mappings for a Frame Relay switch. Removes duplicates and adds the mappings to the node properties
2.640569
2.34758
1.124805
if '\\' in path: path = path.replace('\\', '/') path = os.path.normpath(path) return path
def fix_path(path)
Fix windows path's. Linux path's will remain unaltered :param str path: The path to be fixed :return: The fixed path :rtype: str
2.993278
4.053142
0.738508
configspec = resource_stream(__name__, 'configspec') try: handle = open(self._topology) handle.close() try: config = ConfigObj(self._topology, configspec=configspec, raise_e...
def read_topology(self)
Read the ini-style topology file using ConfigObj :return config: Topology parsed by :py:mod:`ConfigObj` :rtype: ConfigObj
4.028797
4.000717
1.007019
sections = self.get_sections(old_top) topo = LegacyTopology(sections, old_top) for instance in sorted(sections): if instance.startswith('vbox') or instance.startswith('qemu'): if instance.startswith('qemu') and \ 'qemupath' in old_to...
def process_topology(self, old_top)
Processes the sections returned by get_instances :param ConfigObj old_top: old topology as processed by :py:meth:`read_topology` :returns: tuple of dicts containing hypervisors, devices and artwork :rtype: tuple
4.734756
4.532355
1.044657
nodes = [] devices = topology['devices'] hypervisors = topology['conf'] for device in sorted(devices): hv_id = devices[device]['hv_id'] try: tmp_node = Node(hypervisors[hv_id], self.port_id) except IndexError: ...
def generate_nodes(self, topology)
Generate a list of nodes for the new topology :param dict topology: processed topology from :py:meth:`process_topology` :return: a list of dicts on nodes :rtype: list
2.966138
2.98466
0.993794
new_links = [] for link in self.links: # Expand port name if required if INTERFACE_RE.search(link['dest_port'])\ or VBQ_INT_RE.search(link['dest_port']): int_type = link['dest_port'][0] dest_port = link['dest_port'].re...
def generate_links(self, nodes)
Generate a list of links :param list nodes: A list of nodes from :py:meth:`generate_nodes` :return: list of links :rtype: list
2.806762
2.833031
0.990728
device_id = None for node in nodes: if device_name == node['properties']['name']: device_id = node['id'] break return device_id
def device_id_from_name(device_name, nodes)
Get the device ID when given a device name :param str device_name: device name :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: device ID :rtype: int
2.395146
3.047597
0.785913
port_id = None for node in nodes: if device_id == node['id']: for port in node['ports']: if port_name == port['name']: port_id = port['id'] break break return port_id
def port_id_from_name(port_name, device_id, nodes)
Get the port ID when given a port name :param str port_name: port name :param str device_id: device ID :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: port ID :rtype: int
1.929426
2.352103
0.820298
device_id = None device_name = None port_id = None if destination_node != 'NIO': for node in nodes: if destination_node == node['properties']['name']: device_id = node['id'] device_name = destination_node ...
def convert_destination_to_id(destination_node, destination_port, nodes)
Convert a destination to device and port ID :param str destination_node: Destination node name :param str destination_port: Destination port name :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: dict containing device ID, device name and port ID :rtype: d...
2.255017
2.119931
1.063722
node_name = '' for node in nodes: if node['id'] == node_id: node_name = node['properties']['name'] break return node_name
def get_node_name_from_id(node_id, nodes)
Get the name of a node when given the node_id :param int node_id: The ID of a node :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: node name :rtype: str
2.247798
2.690564
0.835438
port_name = '' for node in nodes: if node['id'] == node_id: for port in node['ports']: if port['id'] == port_id: port_name = port['name'] break return port_name
def get_port_name_from_id(node_id, port_id, nodes)
Get the name of a port for a given node and port ID :param int node_id: node ID :param int port_id: port ID :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: port name :rtype: str
1.705183
2.047781
0.832698
# Description src_desc = 'connected to %s on port %s' % \ (self.get_node_name_from_id(link['destination_node_id'], nodes), self.get_port_name_from_id(link['destination_node_id'], ...
def add_node_connection(self, link, nodes)
Add a connection to a node :param dict link: link definition :param list nodes: list of nodes from :py:meth:`generate_nodes`
1.794743
1.863521
0.963092
new_shapes = {'ellipse': [], 'rectangle': []} for shape in shapes: tmp_shape = {} for shape_item in shapes[shape]: if shape_item != 'type': tmp_shape[shape_item] = shapes[shape][shape_item] new_shapes[shapes[shape]['type'...
def generate_shapes(shapes)
Generate the shapes for the topology :param dict shapes: A dict of converted shapes from the old topology :return: dict containing two lists (ellipse, rectangle) :rtype: dict
2.834408
2.475232
1.145108
new_notes = [] for note in notes: tmp_note = {} for note_item in notes[note]: tmp_note[note_item] = notes[note][note_item] new_notes.append(tmp_note) return new_notes
def generate_notes(notes)
Generate the notes list :param dict notes: A dict of converted notes from the old topology :return: List of notes for the the topology :rtype: list
2.562262
2.629789
0.974322
new_images = [] for image in pixmaps: tmp_image = {} for img_item in pixmaps[image]: if img_item == 'path': path = os.path.join('images', os.path.basename( ...
def generate_images(self, pixmaps)
Generate the images list and store the images to copy :param dict pixmaps: A dict of converted pixmaps from the old topology :return: A list of images :rtype: list
2.69082
2.686911
1.001455
if 'interface' in self.old_top[instance][item]: pass else: (item_type, item_id) = item.split(' ') self.artwork[item_type][item_id] = {} for s_item in sorted(self.old_top[instance][item]): if self.old_top[instance][item][s_item] is ...
def add_artwork_item(self, instance, item)
Add an artwork item e.g. Shapes, Notes and Pixmaps :param instance: Hypervisor instance :param item: Item to add
2.485091
2.496757
0.995328
tmp_conf = {'qemu_path': self.old_top[instance]['qemupath']} if len(self.topology['conf']) == 0: self.topology['conf'].append(tmp_conf) else: self.topology['conf'][self.hv_id].update(tmp_conf)
def add_qemu_path(self, instance)
Add the qemu path to the hypervisor conf data :param instance: Hypervisor instance
5.702278
6.019
0.94738
tmp_conf = {} if item not in EXTRA_CONF: tmp_conf['model'] = MODEL_TRANSFORM[item] for s_item in sorted(self.old_top[instance][item]): if self.old_top[instance][item][s_item] is not None: tmp_conf[s_item] = self.old_top[instance][item][s_item] ...
def add_conf_item(self, instance, item)
Add a hypervisor configuration item :param instance: Hypervisor instance :param item: Item to add
3.272892
3.440894
0.951175
(name, dev_type) = self.device_typename(item) self.topology['devices'][name] = {} self.topology['devices'][name]['hv_id'] = self.hv_id self.topology['devices'][name]['node_id'] = self.nid self.topology['devices'][name]['from'] = dev_type['from'] self.topology['de...
def add_physical_item(self, instance, item)
Add a physical item e.g router, cloud etc :param instance: Hypervisor instance :param item: Item to add
2.650198
2.688726
0.98567
dev_type = {'ROUTER': {'from': 'ROUTER', 'desc': 'Router', 'type': 'Router', 'label_x': 19.5}, 'QEMU': {'from': 'QEMU', 'desc': 'QEMU VM', ...
def device_typename(item)
Convert the old names to new-style names and types :param str item: A device in the form of 'TYPE NAME' :return: tuple containing device name and type details
2.519093
2.467665
1.020841
topology = {'name': self._name, 'resources_type': 'local', 'topology': {}, 'type': 'topology', 'version': '1.0'} if self._links: topology['topology']['links'] = self._links if self._nodes: ...
def get_topology(self)
Get the converted topology ready for JSON encoding :return: converted topology assembled into a single dict :rtype: dict
2.545153
2.666424
0.954519
vbox_list = [] vbox_max = None for node in self.nodes: if node['type'] == 'VirtualBoxVM': vbox_list.append(node['vbox_id']) if len(vbox_list) > 0: vbox_max = max(vbox_list) return vbox_max
def get_vboxes(self)
Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int
2.871835
2.707918
1.060533
qemu_vm_list = [] qemu_vm_max = None for node in self.nodes: if node['type'] == 'QemuVM': qemu_vm_list.append(node['qemu_id']) if len(qemu_vm_list) > 0: qemu_vm_max = max(qemu_vm_list) return qemu_vm_max
def get_qemus(self)
Get the maximum ID of the Qemu VMs :return: Maximum Qemu VM ID :rtype: int
2.476672
2.256486
1.097579
'Get a list of child elements' #If no tag name is specified, return the all children if not name: return self.children else: # else return only those children with a matching tag name elements = [] for element in self.children: if element.name == name: elements.append(element) return ele...
def getElements(self,name='')
Get a list of child elements
3.10705
3.131676
0.992136
'SAX start element even handler' # Instantiate an Element object element = Element(name.encode(),attributes) # Push element onto the stack and make it a child of parent if len(self.nodeStack) > 0: parent = self.nodeStack[-1] parent.AddChild(element) else: self.root = element self.nodeStack.app...
def StartElement(self,name,attributes)
SAX start element even handler
4.090895
3.52956
1.159038
'SAX character data event handler' ## HACK: to preserve the newlines #if string.strip(data): data = data.encode("utf-8") element = self.nodeStack[-1] element.cdata += data return
def CharacterData(self,data)
SAX character data event handler
9.133906
7.795669
1.171664
new_dict = {} old2new = {} new2old = {} for key in from_dict: k = normalizeUnicode(key,'identifier') if k != key: i = '' while new_dict.has_key("%s%s" % (k,i) ): if not i: i = 1 else: i += 1 k = "%s%s" % (k,i) old2new[key] = k new2old[k] = key new_dict[k] = from_dict[key] r...
def key_dict( from_dict )
Returns dict from_dict['unicode_save_field'] = 'original key with unicode'
2.472928
2.425242
1.019663
if xml == 0: print 'Errorcode:', self.errorcode print print 'Product information:' for key in self.product.keys(): print ' ', key.encode('UTF-8'), print '->', self.product[key].encode('UTF-8') print print 'Database information:' for key in self.database.keys(): print ' ...
def doShow(self, xml=0)
Shows the contents of our resultset.
2.481472
2.416316
1.026965
if type(maxRec) == int: self._maxRecords = maxRec elif type(maxRec) == str and (maxRec.lower == 'all' or maxRec.isdigit()): self._maxRecords = maxRec.lower else: raise FMError, 'Unsupported -max value (not a number or "all").'
def _setMaxRecords(self, maxRec)
Specifies the maximum number of records you want returned (number or constant 'all')
4.220541
3.859184
1.093636
if type(skipRec) == int or (type(skipRec) == str and skipRec.isdigit()): self._skipRecords = skipRec else: raise FMError, 'Unsupported -skip value (not a number).'
def _setSkipRecords(self, skipRec)
Specifies how many records to skip in the found set
5.314059
5.508851
0.96464
if not lop.lower() in ['and', 'or']: raise FMError, 'Unsupported logical operator (not one of "and" or "or").' self._lop = lop.lower()
def _setLogicalOperator(self, lop)
Sets the way the find fields should be combined together.
4.828535
4.360547
1.107323
if oper != '': validOperators = { 'eq':'eq', 'equals':'eq', '=':'eq', '==':'eq', 'cn':'cn', 'contains':'cn', '%%':'cn', '%':'cn', '*':'cn', 'bw':'bw', 'begins with':'bw', '^':'bw', 'ew':'ew', 'ends with':'ew', '$':'ew', 'gt':'gt', 'greater tha...
def _setComparasionOperator(self, field, oper)
Sets correct operator for given string representation
2.283069
2.308266
0.989084
if name[-4:] == '__OP': return self._setComparasionOperator(name[:-4], value) if name[-3:] == '.op': return self._setComparasionOperator(name[:-3], value) if name.find('__') != -1: import re name = name.replace('__','::') elif name.find('.') != -1: name = name.replace('.','::') self._dbPar...
def _addDBParam(self, name, value)
Adds a database parameter
3.569131
3.463882
1.030385
if order != '': validSortOrders = { 'ascend':'ascend', 'ascending':'ascend', '<':'ascend', 'descend':'descend', 'descending':'descend', '>':'descend' } if not string.lower(order) in validSortOrders.keys(): raise FMError, 'Invalid sort order for "' + field + '"' self._sortP...
def _addSortParam(self, field, order='')
Adds a sort parameter, order have to be in ['ascend', 'ascending','descend', 'descending','custom']
3.45064
3.013336
1.145123
find = re.match('/fmi/xml/cnt/([\w\d.-]+)\.([\w]+)?-*', file_xml_uri) file_name = find.group(1) file_extension = find.group(2) file_binary = self._doRequest(is_file=True, file_xml_uri=file_xml_uri) return (file_name, file_extension, file_binary)
def getFile(self, file_xml_uri)
This will execute cmd to fetch file data from FMServer
4.943105
4.653555
1.062221
request = [ uu({'-db': self._db }), uu({'-lay': self._layout }), uu({'-script': script_name}) ] if params: request.append(uu({'-script.param': params })) request.append(uu({'-findall': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) try: # Try to ret...
def doScript(self, script_name, params=None, return_all=False)
This function executes the script for given layout for the current db.
5.327239
4.972079
1.071431
request = [ uu({'-script': script_name}) ] if params: request.append(uu({'-script.param': params })) self._extra_script = request return func(**func_kwargs)
def doScriptAfter(self, func, func_kwargs={}, script_name='', params=None)
This function will execute extra script after passed function
8.002098
8.262063
0.968535
request = [] request.append(uu({'-dbnames': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) dbNames = [] for dbName in result.resultset: dbNames.append(string.lower(dbName['DATABASE_NAME'])) return dbNames
def getDbNames(self)
This function returns the list of open databases
7.72263
7.558364
1.021733
if self._db == '': raise FMError, 'No database was selected' request = [] request.append(uu({'-db': self._db })) request.append(uu({'-layoutnames': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) layoutNames = [] for layoutName in result.resultset: layoutNa...
def getLayoutNames(self)
This function returns the list of layouts for the current db.
5.565289
5.127442
1.085393
if self._db == '': raise FMError, 'No database was selected' request = [] request.append(uu({'-db': self._db })) request.append(uu({'-scriptnames': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) scriptNames = [] for scriptName in result.resultset: scriptNa...
def getScriptNames(self)
This function returns the list of layouts for the current db.
5.3761
5.060808
1.062301
if hasattr(WHAT, '_modified'): self._addDBParam('RECORDID', WHAT.RECORDID) elif type(WHAT)==dict: for key in WHAT: self._addDBParam(key, WHAT[key]) else: raise FMError, 'Python Runtime: Object type (%s) given to on of function doFind* as argument WHAT cannot be used.' % type(WHAT) for key in S...
def _preFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND')
This function will process attributtes for all -find* commands.
5.486202
5.323546
1.030554
self._preFind(WHAT, SORT, SKIP, MAX, LOP) for key in params: self._addDBParam(key, params[key]) try: return self._doAction('-find') except FMServerError as e: if e.args[0] in [401, 8]: return []
def doFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params)
This function will perform the command -find.
5.123885
5.060962
1.012433
self._preFind(WHAT, SORT, SKIP, MAX) return self._doAction('-findall')
def doFindAll(self, WHAT={}, SORT=[], SKIP=None, MAX=None)
This function will perform the command -findall.
10.851859
8.828437
1.229194
self._preFind(WHAT, SORT, SKIP, MAX, LOP) for key in params: self._addDBParam(key, params[key]) return self._doAction('-findany')
def doFindAny(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params)
This function will perform the command -findany.
5.268399
4.726688
1.114607
if hasattr(WHAT, '_modified'): self._addDBParam('RECORDID', WHAT.RECORDID) self._addDBParam('MODID', WHAT.MODID) elif type(WHAT) == dict and WHAT.has_key('RECORDID'): self._addDBParam('RECORDID', WHAT['RECORDID']) else: raise FMError, 'Python Runtime: Object type (%s) given to function doDelete as...
def doDelete(self, WHAT={})
This function will perform the command -delete.
5.402381
5.34869
1.010038
if hasattr(WHAT, '_modified'): for key in WHAT: if key not in ['RECORDID','MODID']: if WHAT.__new2old__.has_key(key): self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), WHAT[key]) else: self._addDBParam(key, WHAT[key]) elif type(WHAT)==dict: for key in WHAT: self._addDBP...
def doNew(self, WHAT={}, **params)
This function will perform the command -new.
4.474206
4.491862
0.996069
if hasattr(WHAT, '_modified'): for key, value in WHAT._modified(): if WHAT.__new2old__.has_key(key): self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), value) else: self._addDBParam(key, value) self._addDBParam('RECORDID', WHAT.RECORDID) self._addDBParam('MODID', WHAT.MODID) elif...
def doDup(self, WHAT={}, **params)
This function will perform the command -dup.
4.133333
4.182498
0.988245
if self._db == '': raise FMError, 'No database was selected' result = '' try: request = [ uu({'-db': self._db }) ] if self._layout != '': request.append(uu({'-lay': self._layout })) if action == '-find' and self._lop != 'and': request.append(uu({'-lop': self._lop })) if acti...
def _doAction(self, action)
This function will perform a FileMaker action.
2.914417
2.875029
1.0137
return '%(protocol)s://%(host)s:%(port)s%(address)s'%{ 'protocol': self._protocol, 'host': self._host, 'port': self._port, 'address': self._address, }
def _buildUrl(self)
Builds url for normal FM requests.
2.188451
2.197615
0.99583
return '%(protocol)s://%(host)s:%(port)s%(xml_req)s'%{ 'protocol': self._protocol, 'host': self._host, 'port': self._port, 'xml_req': xml_req, }
def _buildFileUrl(self, xml_req)
Builds url for fetching the files from FM.
2.092094
2.100858
0.995828
if request is None: request = [] if is_file and file_xml_uri: url = self._buildFileUrl(file_xml_uri) else: request = '&'.join(request) url = "%s?%s" % (self._buildUrl(), request) if self._debug: print '[PyFileMaker DEBUG] ', url resp = requests.get( url = url, auth = (self._login, s...
def _doRequest(self, request=None, is_file=False, file_xml_uri='')
This function will perform the specified request on the FileMaker server, and it will return the raw result from FileMaker.
2.857767
2.669514
1.07052
if not num in FMErrorNum.keys(): raise FMServerError, (num, FMErrorNum[-1]) elif num == 102: raise FMFieldError, (num, FMErrorNum[num]) else: raise FMServerError, (num, FMErrorNum[num])
def FMErrorByNum( num )
This function raises an error based on the specified error code.
4.560266
3.989855
1.142965
parser = xml2obj.Xml2Obj() # Not valid document comming from FMServer if self.data[-6:] == '</COL>': self.data += '</ROW></RESULTSET></FMPXMLRESULT>' xobj = parser.ParseString( self.data ) try: el = xobj.getElements( 'ERRORCODE') if el: self.errorcode = int( el[0].getData() ) else: ...
def doParseXMLData( self )
This function parses the XML output of FileMaker.
6.274474
5.996083
1.046429
if text == "": return "" unicodeinput = True if not isinstance(text, unicode): text = unicode(text, 'utf-8') unicodeinput = False res = '' global allowed, allowedid if encoding == 'humanascii' or encoding == 'identifier': enc = 'ascii' else: enc = enco...
def normalizeUnicode(text, encoding='humanascii')
This method is used for normalization of unicode characters to the base ASCII letters. Output is ASCII encoded string (or char) with only ASCII letters, digits, punctuation and whitespace characters. Case is preserved.
3.921741
3.84839
1.01906
# Create an ordered dictionary with the Python version, which # should go first. answer = collections.OrderedDict(( ('gl-python', platform.python_version()), )) # Add anything that already appears in the passed metrics headers, # in order. for key, value in collections.OrderedD...
def fill(metrics_headers=())
Add the metrics headers known to GAX. Return an OrderedDict with all of the metrics headers provided to this function, as well as the metrics known to GAX (such as its own version, the GRPC version, etc.).
6.884057
5.596215
1.230127
metrics_headers = collections.OrderedDict(metrics_headers) return ' '.join(['%s/%s' % (k, v) for k, v in metrics_headers.items()])
def stringify(metrics_headers=())
Convert the provided metrics headers to a string. Iterate over the metrics headers (a dictionary, usually ordered) and return a properly-formatted space-separated string (e.g. foo/1.2.3 bar/3.14.159).
3.535576
2.786473
1.268836
for part in name.split('.'): obj = getattr(obj, part) return str(obj) if obj else None
def _str_dotted_getattr(obj, name)
Expands extends getattr to allow dots in x to indicate nested objects. Args: obj (object): an object. name (str): a name for a field in the object. Returns: Any: the value of named attribute. Raises: AttributeError: if the named attribute does not exist.
3.36391
6.836269
0.492068
return sum(len(str(e)) for elts in self._in_deque for e in elts)
def request_bytesize(self)
The size of in bytes of the bundled field elements.
13.612203
12.873661
1.057368
if not self._in_deque: return req = self._bundling_request del getattr(req, self.bundled_field)[:] getattr(req, self.bundled_field).extend( [e for elts in self._in_deque for e in elts]) subresponse_field = self.subresponse_field if subres...
def run(self)
Call the task's func. The task's func will be called with the bundling requests func
5.314838
4.915553
1.081229
# Use a copy, not a reference, as it is later necessary to mutate # the proto field from which elts are drawn in order to construct # the bundled request. elts = elts[:] self._in_deque.append(elts) event = self._event_for(elts) self._event_deque.append(ev...
def extend(self, elts)
Adds elts to the tasks. Args: elts (Sequence): a iterable of elements that can be appended to the task's bundle_field. Returns: Event: an event that can be used to wait on the response.
10.52457
9.980702
1.054492
event = Event() event.canceller = self._canceller_for(elts, event) return event
def _event_for(self, elts)
Creates an Event that is set when the bundle with elts is sent.
5.823731
4.876366
1.194277
def canceller(): try: self._event_deque.remove(event) self._in_deque.remove(elts) return True except ValueError: return False return canceller
def _canceller_for(self, elts, event)
Obtains a cancellation function that removes elts. The returned cancellation function returns ``True`` if all elements was removed successfully from the _in_deque, and false if it was not.
4.822772
3.812554
1.264972
kwargs = kwargs or dict() bundle = self._bundle_for(api_call, bundle_id, bundle_desc, bundling_request, kwargs) elts = getattr(bundling_request, bundle_desc.bundled_field) event = bundle.extend(elts) # Run the bundle if the count thresh...
def schedule(self, api_call, bundle_id, bundle_desc, bundling_request, kwargs=None)
Schedules bundle_desc of bundling_request as part of bundle_id. The returned value an :class:`Event` that * has a ``result`` attribute that will eventually be set to the result the api call * will be used to wait for the response * holds the canceller function for canceling t...
3.746399
3.829466
0.978308
if channel is None: target = '{}:{}'.format(service_path, service_port) if credentials is None: credentials = _grpc_google_auth.get_default_credentials(scopes) channel = _grpc_google_auth.secure_authorized_channel( credentials, target, ssl_credentials=ssl_crede...
def create_stub(generated_create_stub, channel=None, service_path=None, service_port=None, credentials=None, scopes=None, ssl_credentials=None)
Creates a gRPC client stub. Args: generated_create_stub (Callable): The generated gRPC method to create a stub. channel (grpc.Channel): A Channel object through which to make calls. If None, a secure channel is constructed. If specified, all remaining arguments a...
2.629921
2.834595
0.927795
credentials, _ = google.auth.default(scopes=scopes) return credentials
def get_default_credentials(scopes)
Gets the Application Default Credentials.
3.252063
2.795145
1.163468
http_request = _request_factory() return google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, target, ssl_credentials=ssl_credentials)
def secure_authorized_channel( credentials, target, ssl_credentials=None)
Creates a secure authorized gRPC channel.
3.32967
3.343754
0.995788
def inner(*args): updated_args = args + (timeout,) return a_func(*updated_args, **kwargs) return inner
def add_timeout_arg(a_func, timeout, **kwargs)
Updates a_func so that it gets called with the timeout as its final arg. This converts a callable, a_func, into another callable with an additional positional arg. Args: a_func (callable): a callable to be updated timeout (int): to be added to the original callable as it final positional ...
5.705629
6.862834
0.831381
delay_mult = retry_options.backoff_settings.retry_delay_multiplier max_delay_millis = retry_options.backoff_settings.max_retry_delay_millis has_timeout_settings = _has_timeout_settings(retry_options.backoff_settings) if has_timeout_settings: timeout_mult = retry_options.backoff_settings.rp...
def retryable(a_func, retry_options, **kwargs)
Creates a function equivalent to a_func, but that retries on certain exceptions. Args: a_func (callable): A callable. retry_options (RetryOptions): Configures the exceptions upon which the callable should retry, and the parameters to the exponential backoff retry algorithm. kw...
2.978736
3.002583
0.992058
status_code = config.exc_to_code(cause) status_name = config.NAME_STATUS_CODES.get(status_code) if status_name == 'INVALID_ARGUMENT': return InvalidArgumentError(msg, cause=cause) else: return GaxError(msg, cause=cause)
def create_error(msg, cause=None)
Creates a ``GaxError`` or subclass. Attributes: msg (string): describes the error that occurred. cause (Exception, optional): the exception raised by a lower layer of the RPC stack (for example, gRPC) that caused this exception, or None if this exception originated in GAX. ...
5.041973
5.221167
0.965679
# Create the request object. request = operations_pb2.GetOperationRequest(name=name) return self._get_operation(request, options)
def get_operation(self, name, options=None)
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: >>> from google.gapic.longrunning import operations_client >>> api = operations_client.OperationsClient() ...
4.279561
3.941307
1.085823
# Create the request object. request = operations_pb2.ListOperationsRequest( name=name, filter=filter_, page_size=page_size) return self._list_operations(request, options)
def list_operations(self, name, filter_, page_size=0, options=None)
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns ``UNIMPLEMENTED``. NOTE: the ``name`` binding below allows API services to override the binding to use different resource name schemes, such as ``users/*/operations``. ...
2.729542
2.942695
0.927565
# Create the request object. request = operations_pb2.CancelOperationRequest(name=name) self._cancel_operation(request, options)
def cancel_operation(self, name, options=None)
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns ``google.rpc.Code.UNIMPLEMENTED``. Clients can use ``Operations.GetOperation`` or ...
4.337374
3.985769
1.088215
# Create the request object. request = operations_pb2.DeleteOperationRequest(name=name) self._delete_operation(request, options)
def delete_operation(self, name, options=None)
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns ``google.rpc.Code.UNIMPLEMENTED``. Example: >>> from google.gapic.lo...
4.264923
3.975122
1.072904
# Sanity check: If no keyword arguments were sent, this is fine. if not kwargs: return None not_nones = [val for val in kwargs.values() if val is not None] if len(not_nones) > 1: raise ValueError('Only one of {fields} should be set.'.format( fields=', '.join(sorted(kwar...
def check_oneof(**kwargs)
Raise ValueError if more than one keyword argument is not none. Args: kwargs (dict): The keyword arguments sent to the function. Returns: None Raises: ValueError: If more than one entry in kwargs is not none.
3.927753
3.987156
0.985101
def inner(a_func, settings, request, **kwargs): if not settings.bundler: return a_func(request, **kwargs) the_id = bundling.compute_bundle_id( request, desc.request_discriminator_fields) return settings.bundler.schedule(a_func, the_id, desc, request, kw...
def _bundleable(desc)
Creates a function that transforms an API call into a bundling call. It transform a_func from an API call that receives the requests and returns the response into a callable that receives the same request, and returns a :class:`bundling.Event`. The returned Event object can be used to obtain the event...
8.859711
6.642024
1.333887
def inner(a_func, settings, request, **kwargs): page_iterator = gax.PageIterator( a_func, page_descriptor, settings.page_token, request, **kwargs) if settings.flatten_pages: return gax.ResourceIterator(page_iterator) else: return page_iterat...
def _page_streamable(page_descriptor)
Creates a function that yields an iterable to performs page-streaming. Args: page_descriptor (:class:`PageDescriptor`): indicates the structure of page streaming to be performed. Returns: Callable: A function that returns an iterator.
7.392677
7.12401
1.037713
if bundle_config and bundle_descriptor: bundler = bundling.Executor(gax.BundleOptions( element_count_threshold=bundle_config.get( 'element_count_threshold', 0), element_count_limit=bundle_config.get('element_count_limit', 0), request_byte_threshold=bu...
def _construct_bundling(bundle_config, bundle_descriptor)
Helper for ``construct_settings()``. Args: bundle_config (dict): A dictionary specifying a bundle parameters, the value for 'bundling' field in a method config (See ``construct_settings()`` for information on this config.) bundle_descriptor (BundleDescriptor): A BundleDescriptor object ...
2.509028
2.375185
1.056351
if method_config is None: return None codes = None if retry_codes and 'retry_codes_name' in method_config: codes_name = method_config['retry_codes_name'] if codes_name in retry_codes and retry_codes[codes_name]: codes = [retry_names[name] for name in retry_codes[cod...
def _construct_retry(method_config, retry_codes, retry_params, retry_names)
Helper for ``construct_settings()``. Args: method_config (dict): A dictionary representing a single ``methods`` entry of the standard API client config file. (See ``construct_settings()`` for information on this yaml.) retry_codes (dict): A dictionary parsed from the ``retry_codes`` ent...
2.179232
2.159773
1.00901
if overrides is None: return None if overrides.retry_codes is None and overrides.backoff_settings is None: return retry_options codes = retry_options.retry_codes if overrides.retry_codes is not None: codes = overrides.retry_codes backoff_settings = retry_options.backof...
def _merge_retry_options(retry_options, overrides)
Helper for ``construct_settings()``. Takes two retry options, and merges them into a single RetryOption instance. Args: retry_options (RetryOptions): The base RetryOptions. overrides (RetryOptions): The RetryOptions used for overriding ``retry``. Use the values if it is not None. If entire...
2.173801
2.258885
0.962334
def inner(*args, **kwargs): try: return a_func(*args, **kwargs) # pylint: disable=catching-non-exception except tuple(to_catch) as exception: utils.raise_with_traceback( gax.errors.create_error('RPC failed', cause=exception)) return ...
def _catch_errors(a_func, to_catch)
Updates a_func to wrap exceptions with GaxError Args: a_func (callable): A callable. to_catch (list[Exception]): Configures the exceptions to wrap. Returns: Callable: A function that will wrap certain exceptions with GaxError
5.051665
4.950755
1.020383
if not options: return options kwargs = options.kwargs if kwargs == gax.OPTION_INHERIT or 'metadata' not in kwargs: return options kwarg_meta_dict = {} merged_kwargs = options.kwargs.copy() for kwarg_meta in merged_kwargs['metadata']: kwarg_meta_dict[kwarg_meta[0].l...
def _merge_options_metadata(options, settings)
Merge metadata list (add all missing tuples)
2.974569
2.844888
1.045584
def base_caller(api_call, _, *args): return api_call(*args) def inner(request, options=None): this_options = _merge_options_metadata(options, settings) this_settings = settings.merge(this_options) if this_settings.retry and this_settings.retry.retry_codes...
def create_api_call(func, settings)
Converts an rpc call into an API call governed by the settings. In typical usage, ``func`` will be a callable used to make an rpc request. This will mostly likely be a bound method from a request stub used to make an rpc call. The result is created by applying a series of function decorators defined ...
4.353967
4.182588
1.040974
# We may need to get a nested key. Resolve this. key, subkey = _resolve_subkeys(key) # Attempt to get the value from the two types of objects we know baout. # If we get something else, complain. if isinstance(pb_or_dict, Message): answer = getattr(pb_or_dict, key, default) elif isi...
def get(pb_or_dict, key, default=_SENTINEL)
Retrieve the given key off of the object. If a default is specified, return it if the key is not found, otherwise raise KeyError. Args: pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object in question. ...
4.275731
4.671372
0.915305
# pylint: disable=redefined-builtin,too-many-branches # redefined-builtin: We want 'set' to be part of the public interface. # too-many-branches: This method is inherently complex. # Sanity check: Is our target object valid? if not isinstance(pb_or_dict, (collections.MutableMapping, Message)):...
def set(pb_or_dict, key, value)
Set the given key on the object. Args: pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key on the object in question. value (Any): The value to set. Raises: TypeError: If pb_or_dict is not a Message or Mapping.
2.923857
2.939767
0.994588
if not get(pb_or_dict, key, default=None): set(pb_or_dict, key, value)
def setdefault(pb_or_dict, key, value)
Set the key on the object to the value if the current value is falsy. Because protobuf Messages do not distinguish between unset values and falsy ones particularly well, this method treats any falsy value (e.g. 0, empty list) as a target to be overwritten, on both Messages and dictionaries. Args: ...
2.839994
5.234917
0.54251
subkey = None if separator in key: index = key.index(separator) subkey = key[index + 1:] key = key[:index] return key, subkey
def _resolve_subkeys(key, separator='.')
Given a key which may actually be a nested key, return the top level key and any nested subkeys as separate values. Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and ...
2.465827
3.067599
0.80383
if not options: return _CallSettings( timeout=self.timeout, retry=self.retry, page_descriptor=self.page_descriptor, page_token=self.page_token, bundler=self.bundler, bundle_descriptor=self.bundle_descriptor, kwa...
def merge(self, options)
Returns new _CallSettings merged from this and a CallOptions object. Note that passing if the CallOptions instance specifies a page_token, the merged _CallSettings will have ``flatten_pages`` disabled. This permits toggling per-resource/per-page page streaming. Args: option...
2.031702
1.809709
1.122668
if self.done(): return False self._client.cancel_operation(self._operation.name) return True
def cancel(self)
If last Operation's value of `done` is true, returns false; otherwise, issues OperationsClient.cancel_operation and returns true.
8.302535
3.978746
2.086721
# Check exceptional case: raise if no response if not self._poll(timeout).HasField('response'): raise GaxError(self._operation.error.message) # Return expected result return _from_any(self._result_type, self._operation.response)
def result(self, timeout=None)
Enters polling loop on OperationsClient.get_operation, and once Operation.done is true, then returns Operation.response if successful or throws GaxError if not successful. This method will wait up to timeout seconds. If the call hasn't completed in timeout seconds, then a RetryError wil...
13.803932
10.445478
1.321522
# Check exceptional case: return none if no error if not self._poll(timeout).HasField('error'): return None # Return expected error return self._operation.error
def exception(self, timeout=None)
Similar to result(), except returns the exception if any.
15.738523
15.065417
1.044679