text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def define_magic(self, name, func): """[Deprecated] Expose own function as magic function for IPython. Example:: def foo_impl(self, parameter_s=''): 'My very own magic!. (Use docstrings, IPython reads them).' print 'Magic function. Passed parameter is between < >:' print '<%s>' % parameter_s print 'The self object is:', self ip.define_magic('foo',foo_impl) """ meth = types.MethodType(func, self.user_magics) setattr(self.user_magics, name, meth) record_magic(self.magics, 'line', name, meth)
[ "def", "define_magic", "(", "self", ",", "name", ",", "func", ")", ":", "meth", "=", "types", ".", "MethodType", "(", "func", ",", "self", ".", "user_magics", ")", "setattr", "(", "self", ".", "user_magics", ",", "name", ",", "meth", ")", "record_magic", "(", "self", ".", "magics", ",", "'line'", ",", "name", ",", "meth", ")" ]
38.625
16.8125
def list_joined_groups(self, user_alias=None): """ 已加入的小组列表 :param user_alias: 用户名,默认为当前用户名 :return: 单页列表 """ xml = self.api.xml(API_GROUP_LIST_JOINED_GROUPS % (user_alias or self.api.user_alias)) xml_results = xml.xpath('//div[@class="group-list group-cards"]/ul/li') results = [] for item in xml_results: try: icon = item.xpath('.//img/@src')[0] link = item.xpath('.//div[@class="title"]/a')[0] url = link.get('href') name = link.text alias = url.rstrip('/').rsplit('/', 1)[1] user_count = int(item.xpath('.//span[@class="num"]/text()')[0][1:-1]) results.append({ 'icon': icon, 'alias': alias, 'url': url, 'name': name, 'user_count': user_count, }) except Exception as e: self.api.logger.exception('parse joined groups exception: %s' % e) return build_list_result(results, xml)
[ "def", "list_joined_groups", "(", "self", ",", "user_alias", "=", "None", ")", ":", "xml", "=", "self", ".", "api", ".", "xml", "(", "API_GROUP_LIST_JOINED_GROUPS", "%", "(", "user_alias", "or", "self", ".", "api", ".", "user_alias", ")", ")", "xml_results", "=", "xml", ".", "xpath", "(", "'//div[@class=\"group-list group-cards\"]/ul/li'", ")", "results", "=", "[", "]", "for", "item", "in", "xml_results", ":", "try", ":", "icon", "=", "item", ".", "xpath", "(", "'.//img/@src'", ")", "[", "0", "]", "link", "=", "item", ".", "xpath", "(", "'.//div[@class=\"title\"]/a'", ")", "[", "0", "]", "url", "=", "link", ".", "get", "(", "'href'", ")", "name", "=", "link", ".", "text", "alias", "=", "url", ".", "rstrip", "(", "'/'", ")", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "1", "]", "user_count", "=", "int", "(", "item", ".", "xpath", "(", "'.//span[@class=\"num\"]/text()'", ")", "[", "0", "]", "[", "1", ":", "-", "1", "]", ")", "results", ".", "append", "(", "{", "'icon'", ":", "icon", ",", "'alias'", ":", "alias", ",", "'url'", ":", "url", ",", "'name'", ":", "name", ",", "'user_count'", ":", "user_count", ",", "}", ")", "except", "Exception", "as", "e", ":", "self", ".", "api", ".", "logger", ".", "exception", "(", "'parse joined groups exception: %s'", "%", "e", ")", "return", "build_list_result", "(", "results", ",", "xml", ")" ]
39.607143
16.107143
def bb_photlam_arcsec(wave, temperature): """Evaluate Planck's law in ``photlam`` per square arcsec. .. note:: Uses :func:`llam_SI` for calculation, and then converts SI units back to CGS. Parameters ---------- wave : array_like Wavelength values in Angstrom. temperature : float Blackbody temperature in Kelvin. Returns ------- result : array_like Blackbody radiation in ``photlam`` per square arcsec. """ lam = wave * 1.0E-10 # Angstrom -> meter return F * llam_SI(lam, temperature) / (HS * C / lam)
[ "def", "bb_photlam_arcsec", "(", "wave", ",", "temperature", ")", ":", "lam", "=", "wave", "*", "1.0E-10", "# Angstrom -> meter", "return", "F", "*", "llam_SI", "(", "lam", ",", "temperature", ")", "/", "(", "HS", "*", "C", "/", "lam", ")" ]
23
22.08
def _pys2row_heights(self, line): """Updates row_heights in code_array""" # Split with maxsplit 3 split_line = self._split_tidy(line) key = row, tab = self._get_key(*split_line[:2]) height = float(split_line[2]) shape = self.code_array.shape try: if row < shape[0] and tab < shape[2]: self.code_array.row_heights[key] = height except ValueError: pass
[ "def", "_pys2row_heights", "(", "self", ",", "line", ")", ":", "# Split with maxsplit 3", "split_line", "=", "self", ".", "_split_tidy", "(", "line", ")", "key", "=", "row", ",", "tab", "=", "self", ".", "_get_key", "(", "*", "split_line", "[", ":", "2", "]", ")", "height", "=", "float", "(", "split_line", "[", "2", "]", ")", "shape", "=", "self", ".", "code_array", ".", "shape", "try", ":", "if", "row", "<", "shape", "[", "0", "]", "and", "tab", "<", "shape", "[", "2", "]", ":", "self", ".", "code_array", ".", "row_heights", "[", "key", "]", "=", "height", "except", "ValueError", ":", "pass" ]
27.6875
18.25
def migrate_abci_chain(self): """Generate and record a new ABCI chain ID. New blocks are not accepted until we receive an InitChain ABCI request with the matching chain ID and validator set. Chain ID is generated based on the current chain and height. `chain-X` => `chain-X-migrated-at-height-5`. `chain-X-migrated-at-height-5` => `chain-X-migrated-at-height-21`. If there is no known chain (we are at genesis), the function returns. """ latest_chain = self.get_latest_abci_chain() if latest_chain is None: return block = self.get_latest_block() suffix = '-migrated-at-height-' chain_id = latest_chain['chain_id'] block_height_str = str(block['height']) new_chain_id = chain_id.split(suffix)[0] + suffix + block_height_str self.store_abci_chain(block['height'] + 1, new_chain_id, False)
[ "def", "migrate_abci_chain", "(", "self", ")", ":", "latest_chain", "=", "self", ".", "get_latest_abci_chain", "(", ")", "if", "latest_chain", "is", "None", ":", "return", "block", "=", "self", ".", "get_latest_block", "(", ")", "suffix", "=", "'-migrated-at-height-'", "chain_id", "=", "latest_chain", "[", "'chain_id'", "]", "block_height_str", "=", "str", "(", "block", "[", "'height'", "]", ")", "new_chain_id", "=", "chain_id", ".", "split", "(", "suffix", ")", "[", "0", "]", "+", "suffix", "+", "block_height_str", "self", ".", "store_abci_chain", "(", "block", "[", "'height'", "]", "+", "1", ",", "new_chain_id", ",", "False", ")" ]
39.521739
20.608696
def to_unicode(value): """Returns a unicode string from a string, using UTF-8 to decode if needed. This function comes from `Tornado`_. :param value: A unicode or string to be decoded. :returns: The decoded string. """ if isinstance(value, str): return value.decode('utf-8') assert isinstance(value, unicode) return value
[ "def", "to_unicode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", ".", "decode", "(", "'utf-8'", ")", "assert", "isinstance", "(", "value", ",", "unicode", ")", "return", "value" ]
22.533333
17.6
def purge(context, resource, **kwargs): """Purge resource type.""" uri = '%s/%s/purge' % (context.dci_cs_api, resource) if 'force' in kwargs and kwargs['force']: r = context.session.post(uri, timeout=HTTP_TIMEOUT) else: r = context.session.get(uri, timeout=HTTP_TIMEOUT) return r
[ "def", "purge", "(", "context", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "'%s/%s/purge'", "%", "(", "context", ".", "dci_cs_api", ",", "resource", ")", "if", "'force'", "in", "kwargs", "and", "kwargs", "[", "'force'", "]", ":", "r", "=", "context", ".", "session", ".", "post", "(", "uri", ",", "timeout", "=", "HTTP_TIMEOUT", ")", "else", ":", "r", "=", "context", ".", "session", ".", "get", "(", "uri", ",", "timeout", "=", "HTTP_TIMEOUT", ")", "return", "r" ]
38.5
14.75
def update(self, pbar): """ Handle progress bar updates @type pbar: ProgressBar @rtype: str """ if pbar.label != self._label: self.label = pbar.label return self.label
[ "def", "update", "(", "self", ",", "pbar", ")", ":", "if", "pbar", ".", "label", "!=", "self", ".", "_label", ":", "self", ".", "label", "=", "pbar", ".", "label", "return", "self", ".", "label" ]
23.1
11.1
def mail_sent_count(self, count): """ Test that `count` mails have been sent. Syntax: I have sent `count` emails Example: .. code-block:: gherkin Then I have sent 2 emails """ expected = int(count) actual = len(mail.outbox) assert expected == actual, \ "Expected to send {0} email(s), got {1}.".format(expected, actual)
[ "def", "mail_sent_count", "(", "self", ",", "count", ")", ":", "expected", "=", "int", "(", "count", ")", "actual", "=", "len", "(", "mail", ".", "outbox", ")", "assert", "expected", "==", "actual", ",", "\"Expected to send {0} email(s), got {1}.\"", ".", "format", "(", "expected", ",", "actual", ")" ]
20.388889
20.055556
def _lookup(self, skip_cache, fun, *args, **kwargs): """ Checks for cached responses, before requesting from web-service """ if args not in self.cache or skip_cache: self.cache[args] = fun(*args, **kwargs) return self.cache[args]
[ "def", "_lookup", "(", "self", ",", "skip_cache", ",", "fun", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "not", "in", "self", ".", "cache", "or", "skip_cache", ":", "self", ".", "cache", "[", "args", "]", "=", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "cache", "[", "args", "]" ]
35.5
10.125
def qos_map_dscp_cos_dscp_cos_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") dscp_cos = ET.SubElement(map, "dscp-cos") dscp_cos_map_name = ET.SubElement(dscp_cos, "dscp-cos-map-name") dscp_cos_map_name.text = kwargs.pop('dscp_cos_map_name') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "qos_map_dscp_cos_dscp_cos_map_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "qos", "=", "ET", ".", "SubElement", "(", "config", ",", "\"qos\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade-qos\"", ")", "map", "=", "ET", ".", "SubElement", "(", "qos", ",", "\"map\"", ")", "dscp_cos", "=", "ET", ".", "SubElement", "(", "map", ",", "\"dscp-cos\"", ")", "dscp_cos_map_name", "=", "ET", ".", "SubElement", "(", "dscp_cos", ",", "\"dscp-cos-map-name\"", ")", "dscp_cos_map_name", ".", "text", "=", "kwargs", ".", "pop", "(", "'dscp_cos_map_name'", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "return", "callback", "(", "config", ")" ]
44.083333
16.166667
def _resolve_lookup_chain(self, chain, instance): """Return the value of inst.chain[0].chain[1].chain[...].chain[n].""" value = instance for link in chain: value = getattr(value, link) return value
[ "def", "_resolve_lookup_chain", "(", "self", ",", "chain", ",", "instance", ")", ":", "value", "=", "instance", "for", "link", "in", "chain", ":", "value", "=", "getattr", "(", "value", ",", "link", ")", "return", "value" ]
29.5
17.375
def sniff_extension(file_path,verbose=True): '''sniff_extension will attempt to determine the file type based on the extension, and return the proper mimetype :param file_path: the full path to the file to sniff :param verbose: print stuff out ''' mime_types = { "xls": 'application/vnd.ms-excel', "xlsx": 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', "xml": 'text/xml', "ods": 'application/vnd.oasis.opendocument.spreadsheet', "csv": 'text/plain', "tmpl": 'text/plain', "pdf": 'application/pdf', "php": 'application/x-httpd-php', "jpg": 'image/jpeg', "png": 'image/png', "gif": 'image/gif', "bmp": 'image/bmp', "txt": 'text/plain', "doc": 'application/msword', "js": 'text/js', "swf": 'application/x-shockwave-flash', "mp3": 'audio/mpeg', "zip": 'application/zip', "simg": 'application/zip', "rar": 'application/rar', "tar": 'application/tar', "arj": 'application/arj', "cab": 'application/cab', "html": 'text/html', "htm": 'text/html', "default": 'application/octet-stream', "folder": 'application/vnd.google-apps.folder', "img" : "application/octet-stream" } ext = os.path.basename(file_path).split('.')[-1] mime_type = mime_types.get(ext,None) if mime_type == None: mime_type = mime_types['txt'] if verbose==True: bot.info("%s --> %s" %(file_path, mime_type)) return mime_type
[ "def", "sniff_extension", "(", "file_path", ",", "verbose", "=", "True", ")", ":", "mime_types", "=", "{", "\"xls\"", ":", "'application/vnd.ms-excel'", ",", "\"xlsx\"", ":", "'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'", ",", "\"xml\"", ":", "'text/xml'", ",", "\"ods\"", ":", "'application/vnd.oasis.opendocument.spreadsheet'", ",", "\"csv\"", ":", "'text/plain'", ",", "\"tmpl\"", ":", "'text/plain'", ",", "\"pdf\"", ":", "'application/pdf'", ",", "\"php\"", ":", "'application/x-httpd-php'", ",", "\"jpg\"", ":", "'image/jpeg'", ",", "\"png\"", ":", "'image/png'", ",", "\"gif\"", ":", "'image/gif'", ",", "\"bmp\"", ":", "'image/bmp'", ",", "\"txt\"", ":", "'text/plain'", ",", "\"doc\"", ":", "'application/msword'", ",", "\"js\"", ":", "'text/js'", ",", "\"swf\"", ":", "'application/x-shockwave-flash'", ",", "\"mp3\"", ":", "'audio/mpeg'", ",", "\"zip\"", ":", "'application/zip'", ",", "\"simg\"", ":", "'application/zip'", ",", "\"rar\"", ":", "'application/rar'", ",", "\"tar\"", ":", "'application/tar'", ",", "\"arj\"", ":", "'application/arj'", ",", "\"cab\"", ":", "'application/cab'", ",", "\"html\"", ":", "'text/html'", ",", "\"htm\"", ":", "'text/html'", ",", "\"default\"", ":", "'application/octet-stream'", ",", "\"folder\"", ":", "'application/vnd.google-apps.folder'", ",", "\"img\"", ":", "\"application/octet-stream\"", "}", "ext", "=", "os", ".", "path", ".", "basename", "(", "file_path", ")", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "mime_type", "=", "mime_types", ".", "get", "(", "ext", ",", "None", ")", "if", "mime_type", "==", "None", ":", "mime_type", "=", "mime_types", "[", "'txt'", "]", "if", "verbose", "==", "True", ":", "bot", ".", "info", "(", "\"%s --> %s\"", "%", "(", "file_path", ",", "mime_type", ")", ")", "return", "mime_type" ]
41.76087
14.934783
def _keynat(string): """A natural sort helper function for sort() and sorted() without using regular expression. """ r = [] for c in string: if c.isdigit(): if r and isinstance(r[-1], int): r[-1] = r[-1] * 10 + int(c) else: r.append(int(c)) else: r.append(9 + ord(c)) return r
[ "def", "_keynat", "(", "string", ")", ":", "r", "=", "[", "]", "for", "c", "in", "string", ":", "if", "c", ".", "isdigit", "(", ")", ":", "if", "r", "and", "isinstance", "(", "r", "[", "-", "1", "]", ",", "int", ")", ":", "r", "[", "-", "1", "]", "=", "r", "[", "-", "1", "]", "*", "10", "+", "int", "(", "c", ")", "else", ":", "r", ".", "append", "(", "int", "(", "c", ")", ")", "else", ":", "r", ".", "append", "(", "9", "+", "ord", "(", "c", ")", ")", "return", "r" ]
26.5
13.642857
def set_max_entries(self): """ Define the maximum of entries for computing the priority of each items later. """ if self.cache: self.max_entries = float(max([i[0] for i in self.cache.values()]))
[ "def", "set_max_entries", "(", "self", ")", ":", "if", "self", ".", "cache", ":", "self", ".", "max_entries", "=", "float", "(", "max", "(", "[", "i", "[", "0", "]", "for", "i", "in", "self", ".", "cache", ".", "values", "(", ")", "]", ")", ")" ]
34.285714
15.142857
def parse_response(cls, response_string): """JSONRPC allows for **batch** responses to be communicated as arrays of dicts. This method parses out each individual element in the batch and returns a list of tuples, each tuple a result of parsing of each item in the batch. :Returns: | tuple of (results, is_batch_mode_flag) | where: | - results is a tuple describing the request | - Is_batch_mode_flag is a Bool indicating if the | request came in in batch mode (as array of requests) or not. :Raises: RPCParseError, RPCInvalidRequest """ try: batch = cls.json_loads(response_string) except ValueError as err: raise errors.RPCParseError("No valid JSON. (%s)" % str(err)) if isinstance(batch, (list, tuple)) and batch: # batch is true batch. # list of parsed request objects, is_batch_mode_flag return [cls._parse_single_response_trap_errors(response) for response in batch], True elif isinstance(batch, dict): # `batch` is actually single response object return [cls._parse_single_response_trap_errors(batch)], False raise errors.RPCParseError("Neither a batch array nor a single response object found in the response.")
[ "def", "parse_response", "(", "cls", ",", "response_string", ")", ":", "try", ":", "batch", "=", "cls", ".", "json_loads", "(", "response_string", ")", "except", "ValueError", "as", "err", ":", "raise", "errors", ".", "RPCParseError", "(", "\"No valid JSON. (%s)\"", "%", "str", "(", "err", ")", ")", "if", "isinstance", "(", "batch", ",", "(", "list", ",", "tuple", ")", ")", "and", "batch", ":", "# batch is true batch.", "# list of parsed request objects, is_batch_mode_flag", "return", "[", "cls", ".", "_parse_single_response_trap_errors", "(", "response", ")", "for", "response", "in", "batch", "]", ",", "True", "elif", "isinstance", "(", "batch", ",", "dict", ")", ":", "# `batch` is actually single response object", "return", "[", "cls", ".", "_parse_single_response_trap_errors", "(", "batch", ")", "]", ",", "False", "raise", "errors", ".", "RPCParseError", "(", "\"Neither a batch array nor a single response object found in the response.\"", ")" ]
48.642857
24.107143
def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1): """ Build a pyramid of specified base size `s` and `height`, centered at `pos`. """ return Cone(pos, s, height, axis, c, alpha, 4)
[ "def", "Pyramid", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "s", "=", "1", ",", "height", "=", "1", ",", "axis", "=", "(", "0", ",", "0", ",", "1", ")", ",", "c", "=", "\"dg\"", ",", "alpha", "=", "1", ")", ":", "return", "Cone", "(", "pos", ",", "s", ",", "height", ",", "axis", ",", "c", ",", "alpha", ",", "4", ")" ]
43.6
16.8
def get_headers_global(): """Defines the so-called global column headings for Arbin .res-files""" headers = dict() # - global column headings (specific for Arbin) headers["applications_path_txt"] = 'Applications_Path' headers["channel_index_txt"] = 'Channel_Index' headers["channel_number_txt"] = 'Channel_Number' headers["channel_type_txt"] = 'Channel_Type' headers["comments_txt"] = 'Comments' headers["creator_txt"] = 'Creator' headers["daq_index_txt"] = 'DAQ_Index' headers["item_id_txt"] = 'Item_ID' headers["log_aux_data_flag_txt"] = 'Log_Aux_Data_Flag' headers["log_chanstat_data_flag_txt"] = 'Log_ChanStat_Data_Flag' headers["log_event_data_flag_txt"] = 'Log_Event_Data_Flag' headers["log_smart_battery_data_flag_txt"] = 'Log_Smart_Battery_Data_Flag' headers["mapped_aux_conc_cnumber_txt"] = 'Mapped_Aux_Conc_CNumber' headers["mapped_aux_di_cnumber_txt"] = 'Mapped_Aux_DI_CNumber' headers["mapped_aux_do_cnumber_txt"] = 'Mapped_Aux_DO_CNumber' headers["mapped_aux_flow_rate_cnumber_txt"] = 'Mapped_Aux_Flow_Rate_CNumber' headers["mapped_aux_ph_number_txt"] = 'Mapped_Aux_PH_Number' headers["mapped_aux_pressure_number_txt"] = 'Mapped_Aux_Pressure_Number' headers["mapped_aux_temperature_number_txt"] = 'Mapped_Aux_Temperature_Number' headers["mapped_aux_voltage_number_txt"] = 'Mapped_Aux_Voltage_Number' headers["schedule_file_name_txt"] = 'Schedule_File_Name' # KEEP FOR CELLPY FILE FORMAT headers["start_datetime_txt"] = 'Start_DateTime' headers["test_id_txt"] = 'Test_ID' # KEEP FOR CELLPY FILE FORMAT headers["test_name_txt"] = 'Test_Name' # KEEP FOR CELLPY FILE FORMAT return headers
[ "def", "get_headers_global", "(", ")", ":", "headers", "=", "dict", "(", ")", "# - global column headings (specific for Arbin)", "headers", "[", "\"applications_path_txt\"", "]", "=", "'Applications_Path'", "headers", "[", "\"channel_index_txt\"", "]", "=", "'Channel_Index'", "headers", "[", "\"channel_number_txt\"", "]", "=", "'Channel_Number'", "headers", "[", "\"channel_type_txt\"", "]", "=", "'Channel_Type'", "headers", "[", "\"comments_txt\"", "]", "=", "'Comments'", "headers", "[", "\"creator_txt\"", "]", "=", "'Creator'", "headers", "[", "\"daq_index_txt\"", "]", "=", "'DAQ_Index'", "headers", "[", "\"item_id_txt\"", "]", "=", "'Item_ID'", "headers", "[", "\"log_aux_data_flag_txt\"", "]", "=", "'Log_Aux_Data_Flag'", "headers", "[", "\"log_chanstat_data_flag_txt\"", "]", "=", "'Log_ChanStat_Data_Flag'", "headers", "[", "\"log_event_data_flag_txt\"", "]", "=", "'Log_Event_Data_Flag'", "headers", "[", "\"log_smart_battery_data_flag_txt\"", "]", "=", "'Log_Smart_Battery_Data_Flag'", "headers", "[", "\"mapped_aux_conc_cnumber_txt\"", "]", "=", "'Mapped_Aux_Conc_CNumber'", "headers", "[", "\"mapped_aux_di_cnumber_txt\"", "]", "=", "'Mapped_Aux_DI_CNumber'", "headers", "[", "\"mapped_aux_do_cnumber_txt\"", "]", "=", "'Mapped_Aux_DO_CNumber'", "headers", "[", "\"mapped_aux_flow_rate_cnumber_txt\"", "]", "=", "'Mapped_Aux_Flow_Rate_CNumber'", "headers", "[", "\"mapped_aux_ph_number_txt\"", "]", "=", "'Mapped_Aux_PH_Number'", "headers", "[", "\"mapped_aux_pressure_number_txt\"", "]", "=", "'Mapped_Aux_Pressure_Number'", "headers", "[", "\"mapped_aux_temperature_number_txt\"", "]", "=", "'Mapped_Aux_Temperature_Number'", "headers", "[", "\"mapped_aux_voltage_number_txt\"", "]", "=", "'Mapped_Aux_Voltage_Number'", "headers", "[", "\"schedule_file_name_txt\"", "]", "=", "'Schedule_File_Name'", "# KEEP FOR CELLPY FILE FORMAT", "headers", "[", "\"start_datetime_txt\"", "]", "=", "'Start_DateTime'", "headers", "[", "\"test_id_txt\"", "]", "=", "'Test_ID'", "# KEEP FOR CELLPY FILE FORMAT", "headers", "[", "\"test_name_txt\"", "]", "=", "'Test_Name'", "# KEEP FOR CELLPY FILE FORMAT", "return", "headers" ]
61.931034
23.965517
def dense_to_sparse(x, ignore_value=None, name=None): """Converts dense `Tensor` to `SparseTensor`, dropping `ignore_value` cells. Args: x: A `Tensor`. ignore_value: Entries in `x` equal to this value will be absent from the return `SparseTensor`. If `None`, default value of `x` dtype will be used (e.g. '' for `str`, 0 for `int`). name: Python `str` prefix for ops created by this function. Returns: sparse_x: A `tf.SparseTensor` with the same shape as `x`. Raises: ValueError: when `x`'s rank is `None`. """ # Copied (with modifications) from: # tensorflow/contrib/layers/python/ops/sparse_ops.py. with tf.compat.v1.name_scope(name, 'dense_to_sparse', [x, ignore_value]): x = tf.convert_to_tensor(value=x, name='x') if ignore_value is None: if x.dtype.base_dtype == tf.string: # Exception due to TF strings are converted to numpy objects by default. ignore_value = '' else: ignore_value = x.dtype.as_numpy_dtype(0) ignore_value = tf.cast(ignore_value, x.dtype, name='ignore_value') indices = tf.where(tf.not_equal(x, ignore_value), name='indices') return tf.SparseTensor( indices=indices, values=tf.gather_nd(x, indices, name='values'), dense_shape=tf.shape(input=x, out_type=tf.int64, name='dense_shape'))
[ "def", "dense_to_sparse", "(", "x", ",", "ignore_value", "=", "None", ",", "name", "=", "None", ")", ":", "# Copied (with modifications) from:", "# tensorflow/contrib/layers/python/ops/sparse_ops.py.", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "'dense_to_sparse'", ",", "[", "x", ",", "ignore_value", "]", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "x", ",", "name", "=", "'x'", ")", "if", "ignore_value", "is", "None", ":", "if", "x", ".", "dtype", ".", "base_dtype", "==", "tf", ".", "string", ":", "# Exception due to TF strings are converted to numpy objects by default.", "ignore_value", "=", "''", "else", ":", "ignore_value", "=", "x", ".", "dtype", ".", "as_numpy_dtype", "(", "0", ")", "ignore_value", "=", "tf", ".", "cast", "(", "ignore_value", ",", "x", ".", "dtype", ",", "name", "=", "'ignore_value'", ")", "indices", "=", "tf", ".", "where", "(", "tf", ".", "not_equal", "(", "x", ",", "ignore_value", ")", ",", "name", "=", "'indices'", ")", "return", "tf", ".", "SparseTensor", "(", "indices", "=", "indices", ",", "values", "=", "tf", ".", "gather_nd", "(", "x", ",", "indices", ",", "name", "=", "'values'", ")", ",", "dense_shape", "=", "tf", ".", "shape", "(", "input", "=", "x", ",", "out_type", "=", "tf", ".", "int64", ",", "name", "=", "'dense_shape'", ")", ")" ]
40.96875
21.125
def _mirrorStructure(dictionary, value): ''' create a new nested dictionary object with the same structure as 'dictionary', but with all scalar values replaced with 'value' ''' result = type(dictionary)() for k in dictionary.keys(): if isinstance(dictionary[k], dict): result[k] = _mirrorStructure(dictionary[k], value) else: result[k] = value return result
[ "def", "_mirrorStructure", "(", "dictionary", ",", "value", ")", ":", "result", "=", "type", "(", "dictionary", ")", "(", ")", "for", "k", "in", "dictionary", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "dictionary", "[", "k", "]", ",", "dict", ")", ":", "result", "[", "k", "]", "=", "_mirrorStructure", "(", "dictionary", "[", "k", "]", ",", "value", ")", "else", ":", "result", "[", "k", "]", "=", "value", "return", "result" ]
37.727273
18.090909
def spent_outputs(self): """Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index. """ return ( input_.fulfills.to_dict() for input_ in self.inputs if input_.fulfills )
[ "def", "spent_outputs", "(", "self", ")", ":", "return", "(", "input_", ".", "fulfills", ".", "to_dict", "(", ")", "for", "input_", "in", "self", ".", "inputs", "if", "input_", ".", "fulfills", ")" ]
35
15.444444
def inventory(self, modules_inventory=False): """ Get chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read. """ self.c_info = self.get_attributes() for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()): if int(m_portcounts): module = XenaModule(parent=self, index=m_index) if modules_inventory: module.inventory()
[ "def", "inventory", "(", "self", ",", "modules_inventory", "=", "False", ")", ":", "self", ".", "c_info", "=", "self", ".", "get_attributes", "(", ")", "for", "m_index", ",", "m_portcounts", "in", "enumerate", "(", "self", ".", "c_info", "[", "'c_portcounts'", "]", ".", "split", "(", ")", ")", ":", "if", "int", "(", "m_portcounts", ")", ":", "module", "=", "XenaModule", "(", "parent", "=", "self", ",", "index", "=", "m_index", ")", "if", "modules_inventory", ":", "module", ".", "inventory", "(", ")" ]
39.333333
17.583333
def unit(self): """ Returns the unit attribute of the underlying ncdf variable. If the units has a length (e.g is a list) and has precisely one element per field, the unit for this field is returned. """ unit = ncVarUnit(self._ncVar) fieldNames = self._ncVar.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # return the missing value for field that equals the self.nodeName. if hasattr(unit, '__len__') and len(unit) == len(fieldNames): idx = fieldNames.index(self.nodeName) return unit[idx] else: return unit
[ "def", "unit", "(", "self", ")", ":", "unit", "=", "ncVarUnit", "(", "self", ".", "_ncVar", ")", "fieldNames", "=", "self", ".", "_ncVar", ".", "dtype", ".", "names", "# If the missing value attribute is a list with the same length as the number of fields,", "# return the missing value for field that equals the self.nodeName.", "if", "hasattr", "(", "unit", ",", "'__len__'", ")", "and", "len", "(", "unit", ")", "==", "len", "(", "fieldNames", ")", ":", "idx", "=", "fieldNames", ".", "index", "(", "self", ".", "nodeName", ")", "return", "unit", "[", "idx", "]", "else", ":", "return", "unit" ]
42.0625
22.4375
def auto_delete_files_on_instance_delete(instance: Any, fieldnames: Iterable[str]) -> None: """ Deletes files from filesystem when object is deleted. """ for fieldname in fieldnames: filefield = getattr(instance, fieldname, None) if filefield: if os.path.isfile(filefield.path): os.remove(filefield.path)
[ "def", "auto_delete_files_on_instance_delete", "(", "instance", ":", "Any", ",", "fieldnames", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "fieldname", "in", "fieldnames", ":", "filefield", "=", "getattr", "(", "instance", ",", "fieldname", ",", "None", ")", "if", "filefield", ":", "if", "os", ".", "path", ".", "isfile", "(", "filefield", ".", "path", ")", ":", "os", ".", "remove", "(", "filefield", ".", "path", ")" ]
39.6
11.6
def geometry(self): """returns the feature geometry""" if arcpyFound: if self._geom is None: if 'feature' in self._dict: self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True) elif 'geometry' in self._dict: self._geom = arcpy.AsShape(self._dict['geometry'], esri_json=True) return self._geom return None
[ "def", "geometry", "(", "self", ")", ":", "if", "arcpyFound", ":", "if", "self", ".", "_geom", "is", "None", ":", "if", "'feature'", "in", "self", ".", "_dict", ":", "self", ".", "_geom", "=", "arcpy", ".", "AsShape", "(", "self", ".", "_dict", "[", "'feature'", "]", "[", "'geometry'", "]", ",", "esri_json", "=", "True", ")", "elif", "'geometry'", "in", "self", ".", "_dict", ":", "self", ".", "_geom", "=", "arcpy", ".", "AsShape", "(", "self", ".", "_dict", "[", "'geometry'", "]", ",", "esri_json", "=", "True", ")", "return", "self", ".", "_geom", "return", "None" ]
43.7
18.9
def a10_allocate_ip_from_dhcp_range(self, subnet, interface_id, mac, port_id): """Search for an available IP.addr from unallocated nmodels.IPAllocationPool range. If no addresses are available then an error is raised. Returns the address as a string. This search is conducted by a difference of the nmodels.IPAllocationPool set_a and the current IP allocations. """ subnet_id = subnet["id"] network_id = subnet["network_id"] iprange_result = self.get_ipallocationpool_by_subnet_id(subnet_id) ip_in_use_list = [x.ip_address for x in self.get_ipallocations_by_subnet_id(subnet_id)] range_begin, range_end = iprange_result.first_ip, iprange_result.last_ip ip_address = IPHelpers.find_unused_ip(range_begin, range_end, ip_in_use_list) if not ip_address: msg = "Cannot allocate from subnet {0}".format(subnet) LOG.error(msg) # TODO(mdurrant) - Raise neutron exception raise Exception mark_in_use = { "ip_address": ip_address, "network_id": network_id, "port_id": port_id, "subnet_id": subnet["id"] } self.create_ipallocation(mark_in_use) return ip_address, subnet["cidr"], mark_in_use["port_id"]
[ "def", "a10_allocate_ip_from_dhcp_range", "(", "self", ",", "subnet", ",", "interface_id", ",", "mac", ",", "port_id", ")", ":", "subnet_id", "=", "subnet", "[", "\"id\"", "]", "network_id", "=", "subnet", "[", "\"network_id\"", "]", "iprange_result", "=", "self", ".", "get_ipallocationpool_by_subnet_id", "(", "subnet_id", ")", "ip_in_use_list", "=", "[", "x", ".", "ip_address", "for", "x", "in", "self", ".", "get_ipallocations_by_subnet_id", "(", "subnet_id", ")", "]", "range_begin", ",", "range_end", "=", "iprange_result", ".", "first_ip", ",", "iprange_result", ".", "last_ip", "ip_address", "=", "IPHelpers", ".", "find_unused_ip", "(", "range_begin", ",", "range_end", ",", "ip_in_use_list", ")", "if", "not", "ip_address", ":", "msg", "=", "\"Cannot allocate from subnet {0}\"", ".", "format", "(", "subnet", ")", "LOG", ".", "error", "(", "msg", ")", "# TODO(mdurrant) - Raise neutron exception", "raise", "Exception", "mark_in_use", "=", "{", "\"ip_address\"", ":", "ip_address", ",", "\"network_id\"", ":", "network_id", ",", "\"port_id\"", ":", "port_id", ",", "\"subnet_id\"", ":", "subnet", "[", "\"id\"", "]", "}", "self", ".", "create_ipallocation", "(", "mark_in_use", ")", "return", "ip_address", ",", "subnet", "[", "\"cidr\"", "]", ",", "mark_in_use", "[", "\"port_id\"", "]" ]
41.612903
23.870968
def minimum_spanning_subtree(self): '''Returns the (undirected) minimum spanning tree subgraph.''' dist = self.matrix('dense', copy=True) dist[dist==0] = np.inf np.fill_diagonal(dist, 0) mst = ssc.minimum_spanning_tree(dist) return self.__class__.from_adj_matrix(mst + mst.T)
[ "def", "minimum_spanning_subtree", "(", "self", ")", ":", "dist", "=", "self", ".", "matrix", "(", "'dense'", ",", "copy", "=", "True", ")", "dist", "[", "dist", "==", "0", "]", "=", "np", ".", "inf", "np", ".", "fill_diagonal", "(", "dist", ",", "0", ")", "mst", "=", "ssc", ".", "minimum_spanning_tree", "(", "dist", ")", "return", "self", ".", "__class__", ".", "from_adj_matrix", "(", "mst", "+", "mst", ".", "T", ")" ]
41.857143
10.428571
def parse_args(self): """Parses the command-line arguments to this script, and parse the given configuration file (if any). Returns a Namespace containing the resulting options. This method will use the configuration file parameters if any exist, otherwise it will use the command-line arguments.""" # Parse sys.argv cli_args = self.parser.parse_args() if cli_args.config: # Parse the configuration file config_file = open(cli_args.config, 'r') config_json = json.load(config_file) config_opts = config_json.get('options', {}) # Validate the configuration file ConfigurationValidator.validate_config_json(config_json) # Turn JSON options into a flat list of strings for the parser args = reduce(lambda l, t: l + [str(t[0]), str(t[1])], config_opts.items(), []) args = filter(lambda x: x is not None, args) # Pass the configuration file options to the parser config_args = self.parser.parse_args(args=args) config_args.tests = config_json.get('tests', []) config_args.configuration = config_json.get('configuration', {}) config_args.environments = config_json.get('environments', []) args = config_args else: args = cli_args if args.log_level == "INFO": args.log_level = LogLevel.INFO elif args.log_level == "WARN": args.log_level = LogLevel.WARN elif args.log_level == "DEBUG": args.log_level = LogLevel.DEBUG else: args.log_level = LogLevel.ERROR return args
[ "def", "parse_args", "(", "self", ")", ":", "# Parse sys.argv", "cli_args", "=", "self", ".", "parser", ".", "parse_args", "(", ")", "if", "cli_args", ".", "config", ":", "# Parse the configuration file", "config_file", "=", "open", "(", "cli_args", ".", "config", ",", "'r'", ")", "config_json", "=", "json", ".", "load", "(", "config_file", ")", "config_opts", "=", "config_json", ".", "get", "(", "'options'", ",", "{", "}", ")", "# Validate the configuration file", "ConfigurationValidator", ".", "validate_config_json", "(", "config_json", ")", "# Turn JSON options into a flat list of strings for the parser", "args", "=", "reduce", "(", "lambda", "l", ",", "t", ":", "l", "+", "[", "str", "(", "t", "[", "0", "]", ")", ",", "str", "(", "t", "[", "1", "]", ")", "]", ",", "config_opts", ".", "items", "(", ")", ",", "[", "]", ")", "args", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "args", ")", "# Pass the configuration file options to the parser", "config_args", "=", "self", ".", "parser", ".", "parse_args", "(", "args", "=", "args", ")", "config_args", ".", "tests", "=", "config_json", ".", "get", "(", "'tests'", ",", "[", "]", ")", "config_args", ".", "configuration", "=", "config_json", ".", "get", "(", "'configuration'", ",", "{", "}", ")", "config_args", ".", "environments", "=", "config_json", ".", "get", "(", "'environments'", ",", "[", "]", ")", "args", "=", "config_args", "else", ":", "args", "=", "cli_args", "if", "args", ".", "log_level", "==", "\"INFO\"", ":", "args", ".", "log_level", "=", "LogLevel", ".", "INFO", "elif", "args", ".", "log_level", "==", "\"WARN\"", ":", "args", ".", "log_level", "=", "LogLevel", ".", "WARN", "elif", "args", ".", "log_level", "==", "\"DEBUG\"", ":", "args", ".", "log_level", "=", "LogLevel", ".", "DEBUG", "else", ":", "args", ".", "log_level", "=", "LogLevel", ".", "ERROR", "return", "args" ]
37.97619
19.97619
def get(self): """ Returns the value for the slot. :return: the entry value """ values = [e.get() for e in self._entries] if len(self._entries) == 1: return values[0] else: return values
[ "def", "get", "(", "self", ")", ":", "values", "=", "[", "e", ".", "get", "(", ")", "for", "e", "in", "self", ".", "_entries", "]", "if", "len", "(", "self", ".", "_entries", ")", "==", "1", ":", "return", "values", "[", "0", "]", "else", ":", "return", "values" ]
25.7
10.3
def _patch_argument_parser(self): ''' Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser figure out which subparsers need to be activated (then recursively monkey-patch those). We save all active ArgumentParsers to extract all their possible option names later. ''' active_parsers = [self._parser] parsed_args = argparse.Namespace() visited_actions = [] def patch(parser): parser.__class__ = IntrospectiveArgumentParser for action in parser._actions: # TODO: accomplish this with super class IntrospectAction(action.__class__): def __call__(self, parser, namespace, values, option_string=None): debug('Action stub called on', self) debug('\targs:', parser, namespace, values, option_string) debug('\torig class:', self._orig_class) debug('\torig callable:', self._orig_callable) visited_actions.append(self) if self._orig_class == argparse._SubParsersAction: debug('orig class is a subparsers action: patching and running it') active_subparser = self._name_parser_map[values[0]] patch(active_subparser) active_parsers.append(active_subparser) self._orig_callable(parser, namespace, values, option_string=option_string) elif self._orig_class in safe_actions: self._orig_callable(parser, namespace, values, option_string=option_string) if getattr(action, "_orig_class", None): debug("Action", action, "already patched") action._orig_class = action.__class__ action._orig_callable = action.__call__ action.__class__ = IntrospectAction patch(self._parser) debug("Active parsers:", active_parsers) debug("Visited actions:", visited_actions) debug("Parse result namespace:", parsed_args) return active_parsers, parsed_args
[ "def", "_patch_argument_parser", "(", "self", ")", ":", "active_parsers", "=", "[", "self", ".", "_parser", "]", "parsed_args", "=", "argparse", ".", "Namespace", "(", ")", "visited_actions", "=", "[", "]", "def", "patch", "(", "parser", ")", ":", "parser", ".", "__class__", "=", "IntrospectiveArgumentParser", "for", "action", "in", "parser", ".", "_actions", ":", "# TODO: accomplish this with super", "class", "IntrospectAction", "(", "action", ".", "__class__", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "None", ")", ":", "debug", "(", "'Action stub called on'", ",", "self", ")", "debug", "(", "'\\targs:'", ",", "parser", ",", "namespace", ",", "values", ",", "option_string", ")", "debug", "(", "'\\torig class:'", ",", "self", ".", "_orig_class", ")", "debug", "(", "'\\torig callable:'", ",", "self", ".", "_orig_callable", ")", "visited_actions", ".", "append", "(", "self", ")", "if", "self", ".", "_orig_class", "==", "argparse", ".", "_SubParsersAction", ":", "debug", "(", "'orig class is a subparsers action: patching and running it'", ")", "active_subparser", "=", "self", ".", "_name_parser_map", "[", "values", "[", "0", "]", "]", "patch", "(", "active_subparser", ")", "active_parsers", ".", "append", "(", "active_subparser", ")", "self", ".", "_orig_callable", "(", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "option_string", ")", "elif", "self", ".", "_orig_class", "in", "safe_actions", ":", "self", ".", "_orig_callable", "(", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "option_string", ")", "if", "getattr", "(", "action", ",", "\"_orig_class\"", ",", "None", ")", ":", "debug", "(", "\"Action\"", ",", "action", ",", "\"already patched\"", ")", "action", ".", "_orig_class", "=", "action", ".", "__class__", "action", ".", "_orig_callable", "=", "action", ".", "__call__", "action", ".", "__class__", "=", "IntrospectAction", "patch", "(", "self", ".", "_parser", ")", "debug", "(", "\"Active parsers:\"", ",", "active_parsers", ")", "debug", "(", "\"Visited actions:\"", ",", "visited_actions", ")", "debug", "(", "\"Parse result namespace:\"", ",", "parsed_args", ")", "return", "active_parsers", ",", "parsed_args" ]
52.644444
27.977778
def _add_thousand_g(self, variant_obj, info_dict): """Add the thousand genomes frequency Args: variant_obj (puzzle.models.Variant) info_dict (dict): A info dictionary """ thousand_g = info_dict.get('1000GAF') if thousand_g: logger.debug("Updating thousand_g to: {0}".format( thousand_g)) variant_obj.thousand_g = float(thousand_g) variant_obj.add_frequency('1000GAF', variant_obj.get('thousand_g'))
[ "def", "_add_thousand_g", "(", "self", ",", "variant_obj", ",", "info_dict", ")", ":", "thousand_g", "=", "info_dict", ".", "get", "(", "'1000GAF'", ")", "if", "thousand_g", ":", "logger", ".", "debug", "(", "\"Updating thousand_g to: {0}\"", ".", "format", "(", "thousand_g", ")", ")", "variant_obj", ".", "thousand_g", "=", "float", "(", "thousand_g", ")", "variant_obj", ".", "add_frequency", "(", "'1000GAF'", ",", "variant_obj", ".", "get", "(", "'thousand_g'", ")", ")" ]
37.071429
16.071429
def revisionId(self): """ revisionId differs from id, it is details of implementation use self.id :return: RevisionId """ log.warning("'RevisionId' requested, ensure that you are don't need 'id'") revision_id = self.json()['revisionId'] assert revision_id == self.id, "RevisionId differs id-{}!=revisionId-{}".format(self.id, revision_id) return revision_id
[ "def", "revisionId", "(", "self", ")", ":", "log", ".", "warning", "(", "\"'RevisionId' requested, ensure that you are don't need 'id'\"", ")", "revision_id", "=", "self", ".", "json", "(", ")", "[", "'revisionId'", "]", "assert", "revision_id", "==", "self", ".", "id", ",", "\"RevisionId differs id-{}!=revisionId-{}\"", ".", "format", "(", "self", ".", "id", ",", "revision_id", ")", "return", "revision_id" ]
45.888889
22.555556
def get_current_info(self, symbolList, columns=None): """get_current_info() uses the yahoo.finance.quotes datatable to get all of the stock information presented in the main table on a typical stock page and a bunch of data from the key statistics page. """ response = self.select('yahoo.finance.quotes',columns).where(['symbol','in',symbolList]) return response
[ "def", "get_current_info", "(", "self", ",", "symbolList", ",", "columns", "=", "None", ")", ":", "response", "=", "self", ".", "select", "(", "'yahoo.finance.quotes'", ",", "columns", ")", ".", "where", "(", "[", "'symbol'", ",", "'in'", ",", "symbolList", "]", ")", "return", "response" ]
66.333333
17.166667
def list_nodes_full(conn=None, call=None): ''' Return a list of the VMs that are on the provider, with all fields ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or ' '--function.' ) if not conn: conn = get_conn() ret = {} nodes = conn.list_servers() for node in nodes: ret[node['name']] = node return ret
[ "def", "list_nodes_full", "(", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_full function must be called with -f or '", "'--function.'", ")", "if", "not", "conn", ":", "conn", "=", "get_conn", "(", ")", "ret", "=", "{", "}", "nodes", "=", "conn", ".", "list_servers", "(", ")", "for", "node", "in", "nodes", ":", "ret", "[", "node", "[", "'name'", "]", "]", "=", "node", "return", "ret" ]
21.95
24.15
def GetDateRangeWithOrigins(self): """Returns a tuple of (earliest, latest, earliest_origin, latest_origin) dates on which the service periods in the schedule define service, in YYYYMMDD form. The origins specify where the earliest or latest dates come from. In particular, whether the date is a regular ServicePeriod start_date or end_date in calendar.txt, a service exception of type add in calendar_dates.txt, or feed start/end date defined in feed_info.txt. """ period_list = self.GetServicePeriodList() ranges = [period.GetDateRange() for period in period_list] starts = filter(lambda x: x, [item[0] for item in ranges]) ends = filter(lambda x: x, [item[1] for item in ranges]) if not starts or not ends: return (None, None, None, None) minvalue, minindex = min(itertools.izip(starts, itertools.count())) maxvalue, maxindex = max(itertools.izip(ends, itertools.count())) minreason = (period_list[minindex].HasDateExceptionOn(minvalue) and "earliest service exception date in calendar_dates.txt" or "earliest service date in calendar.txt") maxreason = (period_list[maxindex].HasDateExceptionOn(maxvalue) and "last service exception date in calendar_dates.txt" or "last service date in calendar.txt") # Override with feed_info.txt feed_start_date and feed_end_date values, if # defined if self.feed_info and self.feed_info.feed_start_date: minvalue = self.feed_info.feed_start_date minreason = "feed_start_date in feed_info.txt" if self.feed_info and self.feed_info.feed_end_date: maxvalue = self.feed_info.feed_end_date maxreason = "feed_end_date in feed_info.txt" return (minvalue, maxvalue, minreason, maxreason)
[ "def", "GetDateRangeWithOrigins", "(", "self", ")", ":", "period_list", "=", "self", ".", "GetServicePeriodList", "(", ")", "ranges", "=", "[", "period", ".", "GetDateRange", "(", ")", "for", "period", "in", "period_list", "]", "starts", "=", "filter", "(", "lambda", "x", ":", "x", ",", "[", "item", "[", "0", "]", "for", "item", "in", "ranges", "]", ")", "ends", "=", "filter", "(", "lambda", "x", ":", "x", ",", "[", "item", "[", "1", "]", "for", "item", "in", "ranges", "]", ")", "if", "not", "starts", "or", "not", "ends", ":", "return", "(", "None", ",", "None", ",", "None", ",", "None", ")", "minvalue", ",", "minindex", "=", "min", "(", "itertools", ".", "izip", "(", "starts", ",", "itertools", ".", "count", "(", ")", ")", ")", "maxvalue", ",", "maxindex", "=", "max", "(", "itertools", ".", "izip", "(", "ends", ",", "itertools", ".", "count", "(", ")", ")", ")", "minreason", "=", "(", "period_list", "[", "minindex", "]", ".", "HasDateExceptionOn", "(", "minvalue", ")", "and", "\"earliest service exception date in calendar_dates.txt\"", "or", "\"earliest service date in calendar.txt\"", ")", "maxreason", "=", "(", "period_list", "[", "maxindex", "]", ".", "HasDateExceptionOn", "(", "maxvalue", ")", "and", "\"last service exception date in calendar_dates.txt\"", "or", "\"last service date in calendar.txt\"", ")", "# Override with feed_info.txt feed_start_date and feed_end_date values, if", "# defined", "if", "self", ".", "feed_info", "and", "self", ".", "feed_info", ".", "feed_start_date", ":", "minvalue", "=", "self", ".", "feed_info", ".", "feed_start_date", "minreason", "=", "\"feed_start_date in feed_info.txt\"", "if", "self", ".", "feed_info", "and", "self", ".", "feed_info", ".", "feed_end_date", ":", "maxvalue", "=", "self", ".", "feed_info", ".", "feed_end_date", "maxreason", "=", "\"feed_end_date in feed_info.txt\"", "return", "(", "minvalue", ",", "maxvalue", ",", "minreason", ",", "maxreason", ")" ]
46.657895
22.789474
def business_hours_schedule_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/schedules#delete-a-schedule" api_path = "/api/v2/business_hours/schedules/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "business_hours_schedule_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/business_hours/schedules/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"DELETE\"", ",", "*", "*", "kwargs", ")" ]
61.2
21.2
def subscribe(self, frame): """ Handle the SUBSCRIBE command: Adds this connection to destination. """ ack = frame.headers.get('ack') reliable = ack and ack.lower() == 'client' self.engine.connection.reliable_subscriber = reliable dest = frame.headers.get('destination') if not dest: raise ProtocolError('Missing destination for SUBSCRIBE command.') if dest.startswith('/queue/'): self.engine.queue_manager.subscribe(self.engine.connection, dest) else: self.engine.topic_manager.subscribe(self.engine.connection, dest)
[ "def", "subscribe", "(", "self", ",", "frame", ")", ":", "ack", "=", "frame", ".", "headers", ".", "get", "(", "'ack'", ")", "reliable", "=", "ack", "and", "ack", ".", "lower", "(", ")", "==", "'client'", "self", ".", "engine", ".", "connection", ".", "reliable_subscriber", "=", "reliable", "dest", "=", "frame", ".", "headers", ".", "get", "(", "'destination'", ")", "if", "not", "dest", ":", "raise", "ProtocolError", "(", "'Missing destination for SUBSCRIBE command.'", ")", "if", "dest", ".", "startswith", "(", "'/queue/'", ")", ":", "self", ".", "engine", ".", "queue_manager", ".", "subscribe", "(", "self", ".", "engine", ".", "connection", ",", "dest", ")", "else", ":", "self", ".", "engine", ".", "topic_manager", ".", "subscribe", "(", "self", ".", "engine", ".", "connection", ",", "dest", ")" ]
36.529412
21.588235
def parse_redir(self, redir_cmd): """ Parse a command :redir content. """ redir_cmd_str = redir_cmd['str'] matched = re.match(r'redir?!?\s*(=>>?\s*)(\S+)', redir_cmd_str) if matched: redir_cmd_op = matched.group(1) redir_cmd_body = matched.group(2) arg_pos = redir_cmd['ea']['argpos'] # Position of the "redir_cmd_body" start_pos = { 'col': arg_pos['col'] + len(redir_cmd_op), 'i': arg_pos['i'] + len(redir_cmd_op), 'lnum': arg_pos['lnum'], } # NOTE: This is a hack to parse variable node. raw_ast = self.parse_string('echo ' + redir_cmd_body) # We need the left node of ECHO node redir_cmd_ast = raw_ast['body'][0]['list'][0] def adjust_position(node): pos = node['pos'] # Care 1-based index and the length of "echo ". pos['col'] += start_pos['col'] - 1 - 5 # Care the length of "echo ". pos['i'] += start_pos['i'] - 5 # Care 1-based index pos['lnum'] += start_pos['lnum'] - 1 traverse(redir_cmd_ast, on_enter=adjust_position) return redir_cmd_ast return None
[ "def", "parse_redir", "(", "self", ",", "redir_cmd", ")", ":", "redir_cmd_str", "=", "redir_cmd", "[", "'str'", "]", "matched", "=", "re", ".", "match", "(", "r'redir?!?\\s*(=>>?\\s*)(\\S+)'", ",", "redir_cmd_str", ")", "if", "matched", ":", "redir_cmd_op", "=", "matched", ".", "group", "(", "1", ")", "redir_cmd_body", "=", "matched", ".", "group", "(", "2", ")", "arg_pos", "=", "redir_cmd", "[", "'ea'", "]", "[", "'argpos'", "]", "# Position of the \"redir_cmd_body\"", "start_pos", "=", "{", "'col'", ":", "arg_pos", "[", "'col'", "]", "+", "len", "(", "redir_cmd_op", ")", ",", "'i'", ":", "arg_pos", "[", "'i'", "]", "+", "len", "(", "redir_cmd_op", ")", ",", "'lnum'", ":", "arg_pos", "[", "'lnum'", "]", ",", "}", "# NOTE: This is a hack to parse variable node.", "raw_ast", "=", "self", ".", "parse_string", "(", "'echo '", "+", "redir_cmd_body", ")", "# We need the left node of ECHO node", "redir_cmd_ast", "=", "raw_ast", "[", "'body'", "]", "[", "0", "]", "[", "'list'", "]", "[", "0", "]", "def", "adjust_position", "(", "node", ")", ":", "pos", "=", "node", "[", "'pos'", "]", "# Care 1-based index and the length of \"echo \".", "pos", "[", "'col'", "]", "+=", "start_pos", "[", "'col'", "]", "-", "1", "-", "5", "# Care the length of \"echo \".", "pos", "[", "'i'", "]", "+=", "start_pos", "[", "'i'", "]", "-", "5", "# Care 1-based index", "pos", "[", "'lnum'", "]", "+=", "start_pos", "[", "'lnum'", "]", "-", "1", "traverse", "(", "redir_cmd_ast", ",", "on_enter", "=", "adjust_position", ")", "return", "redir_cmd_ast", "return", "None" ]
32.2
19.625
def populationStability(vectors, numSamples=None): """ Returns the stability for the population averaged over multiple time steps Parameters: ----------------------------------------------- vectors: the vectors for which the stability is calculated numSamples the number of time steps where stability is counted At each time step, count the fraction of the active elements which are stable from the previous step Average all the fraction """ # ---------------------------------------------------------------------- # Calculate the stability numVectors = len(vectors) if numSamples is None: numSamples = numVectors-1 countOn = range(numVectors-1) else: countOn = numpy.random.randint(0, numVectors-1, numSamples) sigmap = 0.0 for i in countOn: match = checkMatch(vectors[i], vectors[i+1], sparse=False) # Ignore reset vectors (all 0's) if match[1] != 0: sigmap += float(match[0])/match[1] return sigmap / numSamples
[ "def", "populationStability", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "# ----------------------------------------------------------------------", "# Calculate the stability", "numVectors", "=", "len", "(", "vectors", ")", "if", "numSamples", "is", "None", ":", "numSamples", "=", "numVectors", "-", "1", "countOn", "=", "range", "(", "numVectors", "-", "1", ")", "else", ":", "countOn", "=", "numpy", ".", "random", ".", "randint", "(", "0", ",", "numVectors", "-", "1", ",", "numSamples", ")", "sigmap", "=", "0.0", "for", "i", "in", "countOn", ":", "match", "=", "checkMatch", "(", "vectors", "[", "i", "]", ",", "vectors", "[", "i", "+", "1", "]", ",", "sparse", "=", "False", ")", "# Ignore reset vectors (all 0's)", "if", "match", "[", "1", "]", "!=", "0", ":", "sigmap", "+=", "float", "(", "match", "[", "0", "]", ")", "/", "match", "[", "1", "]", "return", "sigmap", "/", "numSamples" ]
28.558824
23.088235
def ide(self): """ Generates a IDE number (9 digits). http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html """ def _checksum(digits): factors = (5, 4, 3, 2, 7, 6, 5, 4) sum_ = 0 for i in range(len(digits)): sum_ += digits[i] * factors[i] return sum_ % 11 while True: # create an array of first 8 elements initialized randomly digits = self.generator.random.sample(range(10), 8) # sum those 8 digits according to (part of) the "modulo 11" sum_ = _checksum(digits) # determine the last digit to make it qualify the test control_number = 11 - sum_ if control_number != 10: digits.append(control_number) break digits = ''.join([str(digit) for digit in digits]) # finally return our random but valid BSN return 'CHE-' + digits[0:3] + '.'\ + digits[3:6] + '.'\ + digits[6:9]
[ "def", "ide", "(", "self", ")", ":", "def", "_checksum", "(", "digits", ")", ":", "factors", "=", "(", "5", ",", "4", ",", "3", ",", "2", ",", "7", ",", "6", ",", "5", ",", "4", ")", "sum_", "=", "0", "for", "i", "in", "range", "(", "len", "(", "digits", ")", ")", ":", "sum_", "+=", "digits", "[", "i", "]", "*", "factors", "[", "i", "]", "return", "sum_", "%", "11", "while", "True", ":", "# create an array of first 8 elements initialized randomly", "digits", "=", "self", ".", "generator", ".", "random", ".", "sample", "(", "range", "(", "10", ")", ",", "8", ")", "# sum those 8 digits according to (part of) the \"modulo 11\"", "sum_", "=", "_checksum", "(", "digits", ")", "# determine the last digit to make it qualify the test", "control_number", "=", "11", "-", "sum_", "if", "control_number", "!=", "10", ":", "digits", ".", "append", "(", "control_number", ")", "break", "digits", "=", "''", ".", "join", "(", "[", "str", "(", "digit", ")", "for", "digit", "in", "digits", "]", ")", "# finally return our random but valid BSN", "return", "'CHE-'", "+", "digits", "[", "0", ":", "3", "]", "+", "'.'", "+", "digits", "[", "3", ":", "6", "]", "+", "'.'", "+", "digits", "[", "6", ":", "9", "]" ]
37.857143
14.428571
def _mark_candidate_indexes(lines, candidate): """Mark candidate indexes with markers Markers: * c - line that could be a signature line * l - long line * d - line that starts with dashes but has other chars as well >>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3]) 'cdc' """ # at first consider everything to be potential signature lines markers = list('c' * len(candidate)) # mark lines starting from bottom up for i, line_idx in reversed(list(enumerate(candidate))): if len(lines[line_idx].strip()) > TOO_LONG_SIGNATURE_LINE: markers[i] = 'l' else: line = lines[line_idx].strip() if line.startswith('-') and line.strip("-"): markers[i] = 'd' return "".join(markers)
[ "def", "_mark_candidate_indexes", "(", "lines", ",", "candidate", ")", ":", "# at first consider everything to be potential signature lines", "markers", "=", "list", "(", "'c'", "*", "len", "(", "candidate", ")", ")", "# mark lines starting from bottom up", "for", "i", ",", "line_idx", "in", "reversed", "(", "list", "(", "enumerate", "(", "candidate", ")", ")", ")", ":", "if", "len", "(", "lines", "[", "line_idx", "]", ".", "strip", "(", ")", ")", ">", "TOO_LONG_SIGNATURE_LINE", ":", "markers", "[", "i", "]", "=", "'l'", "else", ":", "line", "=", "lines", "[", "line_idx", "]", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "'-'", ")", "and", "line", ".", "strip", "(", "\"-\"", ")", ":", "markers", "[", "i", "]", "=", "'d'", "return", "\"\"", ".", "join", "(", "markers", ")" ]
31.48
19.92
def find(name, path=(), parent=None): """ Return a Module instance describing the first matching module found on the search path. :param str name: Module name. :param list path: List of directory names to search for the module. :param Module parent: Optional module parent. """ assert isinstance(path, tuple) head, _, tail = name.partition('.') try: tup = imp.find_module(head, list(path)) except ImportError: return parent fp, modpath, (suffix, mode, kind) = tup if fp: fp.close() if parent and modpath == parent.path: # 'from timeout import timeout', where 'timeout' is a function but also # the name of the module being imported. return None if kind == imp.PKG_DIRECTORY: modpath = os.path.join(modpath, '__init__.py') module = Module(head, modpath, kind, parent) # TODO: this code is entirely wrong on Python 3.x, but works well enough # for Ansible. We need a new find_child() that only looks in the package # directory, never falling back to the parent search path. if tail and kind == imp.PKG_DIRECTORY: return find_relative(module, tail, path) return module
[ "def", "find", "(", "name", ",", "path", "=", "(", ")", ",", "parent", "=", "None", ")", ":", "assert", "isinstance", "(", "path", ",", "tuple", ")", "head", ",", "_", ",", "tail", "=", "name", ".", "partition", "(", "'.'", ")", "try", ":", "tup", "=", "imp", ".", "find_module", "(", "head", ",", "list", "(", "path", ")", ")", "except", "ImportError", ":", "return", "parent", "fp", ",", "modpath", ",", "(", "suffix", ",", "mode", ",", "kind", ")", "=", "tup", "if", "fp", ":", "fp", ".", "close", "(", ")", "if", "parent", "and", "modpath", "==", "parent", ".", "path", ":", "# 'from timeout import timeout', where 'timeout' is a function but also", "# the name of the module being imported.", "return", "None", "if", "kind", "==", "imp", ".", "PKG_DIRECTORY", ":", "modpath", "=", "os", ".", "path", ".", "join", "(", "modpath", ",", "'__init__.py'", ")", "module", "=", "Module", "(", "head", ",", "modpath", ",", "kind", ",", "parent", ")", "# TODO: this code is entirely wrong on Python 3.x, but works well enough", "# for Ansible. We need a new find_child() that only looks in the package", "# directory, never falling back to the parent search path.", "if", "tail", "and", "kind", "==", "imp", ".", "PKG_DIRECTORY", ":", "return", "find_relative", "(", "module", ",", "tail", ",", "path", ")", "return", "module" ]
31.710526
19.131579
def cli(ctx, obj): """Show Alerta server and client versions.""" client = obj['client'] click.echo('alerta {}'.format(client.mgmt_status()['version'])) click.echo('alerta client {}'.format(client_version)) click.echo('requests {}'.format(requests_version)) click.echo('click {}'.format(click.__version__)) ctx.exit()
[ "def", "cli", "(", "ctx", ",", "obj", ")", ":", "client", "=", "obj", "[", "'client'", "]", "click", ".", "echo", "(", "'alerta {}'", ".", "format", "(", "client", ".", "mgmt_status", "(", ")", "[", "'version'", "]", ")", ")", "click", ".", "echo", "(", "'alerta client {}'", ".", "format", "(", "client_version", ")", ")", "click", ".", "echo", "(", "'requests {}'", ".", "format", "(", "requests_version", ")", ")", "click", ".", "echo", "(", "'click {}'", ".", "format", "(", "click", ".", "__version__", ")", ")", "ctx", ".", "exit", "(", ")" ]
42.125
16.5
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, timestamp_compare, observable_timestamp_compare, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_references, artifact_mime_type, character_set, language, software_language, patterns, language_contents, ] # --strict-types if options.strict_types: validator_list.append(types_strict) # --strict-properties if options.strict_properties: validator_list.append(properties_strict) return validator_list
[ "def", "list_musts", "(", "options", ")", ":", "validator_list", "=", "[", "timestamp", ",", "timestamp_compare", ",", "observable_timestamp_compare", ",", "object_marking_circular_refs", ",", "granular_markings_circular_refs", ",", "marking_selector_syntax", ",", "observable_object_references", ",", "artifact_mime_type", ",", "character_set", ",", "language", ",", "software_language", ",", "patterns", ",", "language_contents", ",", "]", "# --strict-types", "if", "options", ".", "strict_types", ":", "validator_list", ".", "append", "(", "types_strict", ")", "# --strict-properties", "if", "options", ".", "strict_properties", ":", "validator_list", ".", "append", "(", "properties_strict", ")", "return", "validator_list" ]
25.571429
15.25
def _trampoline(name, module, *args, **kwargs): """Trampoline function for decorators. Lookups the function between the registered ones; if not found, forces its registering and then executes it. """ function = _function_lookup(name, module) return function(*args, **kwargs)
[ "def", "_trampoline", "(", "name", ",", "module", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "function", "=", "_function_lookup", "(", "name", ",", "module", ")", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
29.2
17.1
def get_by_id(self, id_networkv6): """Get IPv6 network :param id_networkv4: ID for NetworkIPv6 :return: IPv6 Network """ uri = 'api/networkv4/%s/' % id_networkv6 return super(ApiNetworkIPv6, self).get(uri)
[ "def", "get_by_id", "(", "self", ",", "id_networkv6", ")", ":", "uri", "=", "'api/networkv4/%s/'", "%", "id_networkv6", "return", "super", "(", "ApiNetworkIPv6", ",", "self", ")", ".", "get", "(", "uri", ")" ]
24.7
16.3
def text_array_to_html(text_arr): """Take a numpy.ndarray containing strings, and convert it into html. If the ndarray contains a single scalar string, that string is converted to html via our sanitized markdown parser. If it contains an array of strings, the strings are individually converted to html and then composed into a table using make_table. If the array contains dimensionality greater than 2, all but two of the dimensions are removed, and a warning message is prefixed to the table. Args: text_arr: A numpy.ndarray containing strings. Returns: The array converted to html. """ if not text_arr.shape: # It is a scalar. No need to put it in a table, just apply markdown return plugin_util.markdown_to_safe_html(np.asscalar(text_arr)) warning = '' if len(text_arr.shape) > 2: warning = plugin_util.markdown_to_safe_html(WARNING_TEMPLATE % len(text_arr.shape)) text_arr = reduce_to_2d(text_arr) html_arr = [plugin_util.markdown_to_safe_html(x) for x in text_arr.reshape(-1)] html_arr = np.array(html_arr).reshape(text_arr.shape) return warning + make_table(html_arr)
[ "def", "text_array_to_html", "(", "text_arr", ")", ":", "if", "not", "text_arr", ".", "shape", ":", "# It is a scalar. No need to put it in a table, just apply markdown", "return", "plugin_util", ".", "markdown_to_safe_html", "(", "np", ".", "asscalar", "(", "text_arr", ")", ")", "warning", "=", "''", "if", "len", "(", "text_arr", ".", "shape", ")", ">", "2", ":", "warning", "=", "plugin_util", ".", "markdown_to_safe_html", "(", "WARNING_TEMPLATE", "%", "len", "(", "text_arr", ".", "shape", ")", ")", "text_arr", "=", "reduce_to_2d", "(", "text_arr", ")", "html_arr", "=", "[", "plugin_util", ".", "markdown_to_safe_html", "(", "x", ")", "for", "x", "in", "text_arr", ".", "reshape", "(", "-", "1", ")", "]", "html_arr", "=", "np", ".", "array", "(", "html_arr", ")", ".", "reshape", "(", "text_arr", ".", "shape", ")", "return", "warning", "+", "make_table", "(", "html_arr", ")" ]
38.966667
23.1
def replace_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs): """Replace ZipCodesGeoZone Replace all attributes of ZipCodesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_zip_codes_geo_zone_by_id(zip_codes_geo_zone_id, zip_codes_geo_zone, async=True) >>> result = thread.get() :param async bool :param str zip_codes_geo_zone_id: ID of zipCodesGeoZone to replace (required) :param ZipCodesGeoZone zip_codes_geo_zone: Attributes of zipCodesGeoZone to replace (required) :return: ZipCodesGeoZone If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs) else: (data) = cls._replace_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs) return data
[ "def", "replace_zip_codes_geo_zone_by_id", "(", "cls", ",", "zip_codes_geo_zone_id", ",", "zip_codes_geo_zone", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_replace_zip_codes_geo_zone_by_id_with_http_info", "(", "zip_codes_geo_zone_id", ",", "zip_codes_geo_zone", ",", "*", "*", "kwargs", ")", "else", ":", "(", "data", ")", "=", "cls", ".", "_replace_zip_codes_geo_zone_by_id_with_http_info", "(", "zip_codes_geo_zone_id", ",", "zip_codes_geo_zone", ",", "*", "*", "kwargs", ")", "return", "data" ]
53.363636
29.772727
def attach_alternative(self, content, mimetype=None): """Attach an alternative content representation.""" self.attach(content=content, mimetype=mimetype)
[ "def", "attach_alternative", "(", "self", ",", "content", ",", "mimetype", "=", "None", ")", ":", "self", ".", "attach", "(", "content", "=", "content", ",", "mimetype", "=", "mimetype", ")" ]
56.333333
9.666667
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) unquoted special characters appear only at the beginning and/or the end of the source string. It also properly differentiates between unquoted and quoted special characters. :param string source: First string value :param string target: Second string value :returns: The comparison relation among input strings. :rtype: int """ start = 0 end = len(source) begins = 0 ends = 0 # Reading of initial wildcard in source if source.startswith(CPEComponent2_3_WFN.WILDCARD_MULTI): # Source starts with "*" start = 1 begins = -1 else: while ((start < len(source)) and source.startswith(CPEComponent2_3_WFN.WILDCARD_ONE, start, start)): # Source starts with one or more "?" start += 1 begins += 1 # Reading of final wildcard in source if (source.endswith(CPEComponent2_3_WFN.WILDCARD_MULTI) and CPESet2_3._is_even_wildcards(source, end - 1)): # Source ends in "*" end -= 1 ends = -1 else: while ((end > 0) and source.endswith(CPEComponent2_3_WFN.WILDCARD_ONE, end - 1, end) and CPESet2_3._is_even_wildcards(source, end - 1)): # Source ends in "?" end -= 1 ends += 1 source = source[start: end] index = -1 leftover = len(target) while (leftover > 0): index = target.find(source, index + 1) if (index == -1): break escapes = target.count("\\", 0, index) if ((index > 0) and (begins != -1) and (begins < (index - escapes))): break escapes = target.count("\\", index + 1, len(target)) leftover = len(target) - index - escapes - len(source) if ((leftover > 0) and ((ends != -1) and (leftover > ends))): continue return CPESet2_3.LOGICAL_VALUE_SUPERSET return CPESet2_3.LOGICAL_VALUE_DISJOINT
[ "def", "_compare_strings", "(", "cls", ",", "source", ",", "target", ")", ":", "start", "=", "0", "end", "=", "len", "(", "source", ")", "begins", "=", "0", "ends", "=", "0", "# Reading of initial wildcard in source", "if", "source", ".", "startswith", "(", "CPEComponent2_3_WFN", ".", "WILDCARD_MULTI", ")", ":", "# Source starts with \"*\"", "start", "=", "1", "begins", "=", "-", "1", "else", ":", "while", "(", "(", "start", "<", "len", "(", "source", ")", ")", "and", "source", ".", "startswith", "(", "CPEComponent2_3_WFN", ".", "WILDCARD_ONE", ",", "start", ",", "start", ")", ")", ":", "# Source starts with one or more \"?\"", "start", "+=", "1", "begins", "+=", "1", "# Reading of final wildcard in source", "if", "(", "source", ".", "endswith", "(", "CPEComponent2_3_WFN", ".", "WILDCARD_MULTI", ")", "and", "CPESet2_3", ".", "_is_even_wildcards", "(", "source", ",", "end", "-", "1", ")", ")", ":", "# Source ends in \"*\"", "end", "-=", "1", "ends", "=", "-", "1", "else", ":", "while", "(", "(", "end", ">", "0", ")", "and", "source", ".", "endswith", "(", "CPEComponent2_3_WFN", ".", "WILDCARD_ONE", ",", "end", "-", "1", ",", "end", ")", "and", "CPESet2_3", ".", "_is_even_wildcards", "(", "source", ",", "end", "-", "1", ")", ")", ":", "# Source ends in \"?\"", "end", "-=", "1", "ends", "+=", "1", "source", "=", "source", "[", "start", ":", "end", "]", "index", "=", "-", "1", "leftover", "=", "len", "(", "target", ")", "while", "(", "leftover", ">", "0", ")", ":", "index", "=", "target", ".", "find", "(", "source", ",", "index", "+", "1", ")", "if", "(", "index", "==", "-", "1", ")", ":", "break", "escapes", "=", "target", ".", "count", "(", "\"\\\\\"", ",", "0", ",", "index", ")", "if", "(", "(", "index", ">", "0", ")", "and", "(", "begins", "!=", "-", "1", ")", "and", "(", "begins", "<", "(", "index", "-", "escapes", ")", ")", ")", ":", "break", "escapes", "=", "target", ".", "count", "(", "\"\\\\\"", ",", "index", "+", "1", ",", "len", "(", "target", ")", ")", "leftover", "=", "len", "(", "target", ")", "-", "index", "-", "escapes", "-", "len", "(", "source", ")", "if", "(", "(", "leftover", ">", "0", ")", "and", "(", "(", "ends", "!=", "-", "1", ")", "and", "(", "leftover", ">", "ends", ")", ")", ")", ":", "continue", "return", "CPESet2_3", ".", "LOGICAL_VALUE_SUPERSET", "return", "CPESet2_3", ".", "LOGICAL_VALUE_DISJOINT" ]
33.013333
20.506667
def multithread_predict_dataflow(dataflows, model_funcs): """ Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `DetectionDataset.eval_or_save_inference_results` """ num_worker = len(model_funcs) assert len(dataflows) == num_worker if num_worker == 1: return predict_dataflow(dataflows[0], model_funcs[0]) kwargs = {'thread_name_prefix': 'EvalWorker'} if sys.version_info.minor >= 6 else {} with ThreadPoolExecutor(max_workers=num_worker, **kwargs) as executor, \ tqdm.tqdm(total=sum([df.size() for df in dataflows])) as pbar: futures = [] for dataflow, pred in zip(dataflows, model_funcs): futures.append(executor.submit(predict_dataflow, dataflow, pred, pbar)) all_results = list(itertools.chain(*[fut.result() for fut in futures])) return all_results
[ "def", "multithread_predict_dataflow", "(", "dataflows", ",", "model_funcs", ")", ":", "num_worker", "=", "len", "(", "model_funcs", ")", "assert", "len", "(", "dataflows", ")", "==", "num_worker", "if", "num_worker", "==", "1", ":", "return", "predict_dataflow", "(", "dataflows", "[", "0", "]", ",", "model_funcs", "[", "0", "]", ")", "kwargs", "=", "{", "'thread_name_prefix'", ":", "'EvalWorker'", "}", "if", "sys", ".", "version_info", ".", "minor", ">=", "6", "else", "{", "}", "with", "ThreadPoolExecutor", "(", "max_workers", "=", "num_worker", ",", "*", "*", "kwargs", ")", "as", "executor", ",", "tqdm", ".", "tqdm", "(", "total", "=", "sum", "(", "[", "df", ".", "size", "(", ")", "for", "df", "in", "dataflows", "]", ")", ")", "as", "pbar", ":", "futures", "=", "[", "]", "for", "dataflow", ",", "pred", "in", "zip", "(", "dataflows", ",", "model_funcs", ")", ":", "futures", ".", "append", "(", "executor", ".", "submit", "(", "predict_dataflow", ",", "dataflow", ",", "pred", ",", "pbar", ")", ")", "all_results", "=", "list", "(", "itertools", ".", "chain", "(", "*", "[", "fut", ".", "result", "(", ")", "for", "fut", "in", "futures", "]", ")", ")", "return", "all_results" ]
45.541667
24.791667
def resolve_one_step(self): """ Resolves model references. """ metamodel = self.parser.metamodel current_crossrefs = self.parser._crossrefs # print("DEBUG: Current crossrefs #: {}". # format(len(current_crossrefs))) new_crossrefs = [] self.delayed_crossrefs = [] resolved_crossref_count = 0 # ------------------------- # start of resolve-loop # ------------------------- default_scope = DefaultScopeProvider() for obj, attr, crossref in current_crossrefs: if (get_model(obj) == self.model): attr_value = getattr(obj, attr.name) attr_refs = [obj.__class__.__name__ + "." + attr.name, "*." + attr.name, obj.__class__.__name__ + ".*", "*.*"] for attr_ref in attr_refs: if attr_ref in metamodel.scope_providers: if self.parser.debug: self.parser.dprint(" FOUND {}".format(attr_ref)) resolved = metamodel.scope_providers[attr_ref]( obj, attr, crossref) break else: resolved = default_scope(obj, attr, crossref) # Collect cross-references for textx-tools if resolved and not type(resolved) is Postponed: if metamodel.textx_tools_support: self.pos_crossref_list.append( RefRulePosition( name=crossref.obj_name, ref_pos_start=crossref.position, ref_pos_end=crossref.position + len( resolved.name), def_pos_start=resolved._tx_position, def_pos_end=resolved._tx_position_end)) if not resolved: # As a fall-back search builtins if given if metamodel.builtins: if crossref.obj_name in metamodel.builtins: # TODO: Classes must match resolved = metamodel.builtins[crossref.obj_name] if not resolved: line, col = self.parser.pos_to_linecol(crossref.position) raise TextXSemanticError( message='Unknown object "{}" of class "{}"'.format( crossref.obj_name, crossref.cls.__name__), line=line, col=col, err_type=UNKNOWN_OBJ_ERROR, expected_obj_cls=crossref.cls, filename=self.model._tx_filename) if type(resolved) is Postponed: self.delayed_crossrefs.append((obj, attr, crossref)) new_crossrefs.append((obj, attr, crossref)) else: resolved_crossref_count += 1 if attr.mult in [MULT_ONEORMORE, MULT_ZEROORMORE]: attr_value.append(resolved) else: setattr(obj, attr.name, resolved) else: # crossref not in model new_crossrefs.append((obj, attr, crossref)) # ------------------------- # end of resolve-loop # ------------------------- # store cross-refs from other models in the parser list (for later # processing) self.parser._crossrefs = new_crossrefs # print("DEBUG: Next crossrefs #: {}".format(len(new_crossrefs))) return (resolved_crossref_count, self.delayed_crossrefs)
[ "def", "resolve_one_step", "(", "self", ")", ":", "metamodel", "=", "self", ".", "parser", ".", "metamodel", "current_crossrefs", "=", "self", ".", "parser", ".", "_crossrefs", "# print(\"DEBUG: Current crossrefs #: {}\".", "# format(len(current_crossrefs)))", "new_crossrefs", "=", "[", "]", "self", ".", "delayed_crossrefs", "=", "[", "]", "resolved_crossref_count", "=", "0", "# -------------------------", "# start of resolve-loop", "# -------------------------", "default_scope", "=", "DefaultScopeProvider", "(", ")", "for", "obj", ",", "attr", ",", "crossref", "in", "current_crossrefs", ":", "if", "(", "get_model", "(", "obj", ")", "==", "self", ".", "model", ")", ":", "attr_value", "=", "getattr", "(", "obj", ",", "attr", ".", "name", ")", "attr_refs", "=", "[", "obj", ".", "__class__", ".", "__name__", "+", "\".\"", "+", "attr", ".", "name", ",", "\"*.\"", "+", "attr", ".", "name", ",", "obj", ".", "__class__", ".", "__name__", "+", "\".*\"", ",", "\"*.*\"", "]", "for", "attr_ref", "in", "attr_refs", ":", "if", "attr_ref", "in", "metamodel", ".", "scope_providers", ":", "if", "self", ".", "parser", ".", "debug", ":", "self", ".", "parser", ".", "dprint", "(", "\" FOUND {}\"", ".", "format", "(", "attr_ref", ")", ")", "resolved", "=", "metamodel", ".", "scope_providers", "[", "attr_ref", "]", "(", "obj", ",", "attr", ",", "crossref", ")", "break", "else", ":", "resolved", "=", "default_scope", "(", "obj", ",", "attr", ",", "crossref", ")", "# Collect cross-references for textx-tools", "if", "resolved", "and", "not", "type", "(", "resolved", ")", "is", "Postponed", ":", "if", "metamodel", ".", "textx_tools_support", ":", "self", ".", "pos_crossref_list", ".", "append", "(", "RefRulePosition", "(", "name", "=", "crossref", ".", "obj_name", ",", "ref_pos_start", "=", "crossref", ".", "position", ",", "ref_pos_end", "=", "crossref", ".", "position", "+", "len", "(", "resolved", ".", "name", ")", ",", "def_pos_start", "=", "resolved", ".", "_tx_position", ",", "def_pos_end", "=", "resolved", ".", "_tx_position_end", ")", ")", "if", "not", "resolved", ":", "# As a fall-back search builtins if given", "if", "metamodel", ".", "builtins", ":", "if", "crossref", ".", "obj_name", "in", "metamodel", ".", "builtins", ":", "# TODO: Classes must match", "resolved", "=", "metamodel", ".", "builtins", "[", "crossref", ".", "obj_name", "]", "if", "not", "resolved", ":", "line", ",", "col", "=", "self", ".", "parser", ".", "pos_to_linecol", "(", "crossref", ".", "position", ")", "raise", "TextXSemanticError", "(", "message", "=", "'Unknown object \"{}\" of class \"{}\"'", ".", "format", "(", "crossref", ".", "obj_name", ",", "crossref", ".", "cls", ".", "__name__", ")", ",", "line", "=", "line", ",", "col", "=", "col", ",", "err_type", "=", "UNKNOWN_OBJ_ERROR", ",", "expected_obj_cls", "=", "crossref", ".", "cls", ",", "filename", "=", "self", ".", "model", ".", "_tx_filename", ")", "if", "type", "(", "resolved", ")", "is", "Postponed", ":", "self", ".", "delayed_crossrefs", ".", "append", "(", "(", "obj", ",", "attr", ",", "crossref", ")", ")", "new_crossrefs", ".", "append", "(", "(", "obj", ",", "attr", ",", "crossref", ")", ")", "else", ":", "resolved_crossref_count", "+=", "1", "if", "attr", ".", "mult", "in", "[", "MULT_ONEORMORE", ",", "MULT_ZEROORMORE", "]", ":", "attr_value", ".", "append", "(", "resolved", ")", "else", ":", "setattr", "(", "obj", ",", "attr", ".", "name", ",", "resolved", ")", "else", ":", "# crossref not in model", "new_crossrefs", ".", "append", "(", "(", "obj", ",", "attr", ",", "crossref", ")", ")", "# -------------------------", "# end of resolve-loop", "# -------------------------", "# store cross-refs from other models in the parser list (for later", "# processing)", "self", ".", "parser", ".", "_crossrefs", "=", "new_crossrefs", "# print(\"DEBUG: Next crossrefs #: {}\".format(len(new_crossrefs)))", "return", "(", "resolved_crossref_count", ",", "self", ".", "delayed_crossrefs", ")" ]
46.225
17.625
def _handle_presentation(self, msg): """Process a MQTT presentation message.""" ret_msg = handle_presentation(msg) if msg.child_id == 255 or ret_msg is None: return # this is a presentation of a child sensor topics = [ '{}/{}/{}/{}/+/+'.format( self._in_prefix, str(msg.node_id), str(msg.child_id), msg_type) for msg_type in (int(self.const.MessageType.set), int(self.const.MessageType.req)) ] topics.append('{}/{}/+/{}/+/+'.format( self._in_prefix, str(msg.node_id), int(self.const.MessageType.stream))) self._handle_subscription(topics)
[ "def", "_handle_presentation", "(", "self", ",", "msg", ")", ":", "ret_msg", "=", "handle_presentation", "(", "msg", ")", "if", "msg", ".", "child_id", "==", "255", "or", "ret_msg", "is", "None", ":", "return", "# this is a presentation of a child sensor", "topics", "=", "[", "'{}/{}/{}/{}/+/+'", ".", "format", "(", "self", ".", "_in_prefix", ",", "str", "(", "msg", ".", "node_id", ")", ",", "str", "(", "msg", ".", "child_id", ")", ",", "msg_type", ")", "for", "msg_type", "in", "(", "int", "(", "self", ".", "const", ".", "MessageType", ".", "set", ")", ",", "int", "(", "self", ".", "const", ".", "MessageType", ".", "req", ")", ")", "]", "topics", ".", "append", "(", "'{}/{}/+/{}/+/+'", ".", "format", "(", "self", ".", "_in_prefix", ",", "str", "(", "msg", ".", "node_id", ")", ",", "int", "(", "self", ".", "const", ".", "MessageType", ".", "stream", ")", ")", ")", "self", ".", "_handle_subscription", "(", "topics", ")" ]
41.588235
12.411765
def _get_type(self, value): """Get the data type for *value*.""" if value is None: return type(None) elif type(value) in int_types: return int elif type(value) in float_types: return float elif isinstance(value, binary_type): return binary_type else: return text_type
[ "def", "_get_type", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "type", "(", "None", ")", "elif", "type", "(", "value", ")", "in", "int_types", ":", "return", "int", "elif", "type", "(", "value", ")", "in", "float_types", ":", "return", "float", "elif", "isinstance", "(", "value", ",", "binary_type", ")", ":", "return", "binary_type", "else", ":", "return", "text_type" ]
30.333333
10.666667
def parse_field_path(api_repr): """Parse a **field path** from into a list of nested field names. See :func:`field_path` for more on **field paths**. Args: api_repr (str): The unique Firestore api representation which consists of either simple or UTF-8 field names. It cannot exceed 1500 bytes, and cannot be empty. Simple field names match ``'^[_a-zA-Z][_a-zA-Z0-9]*$'``. All other field names are escaped by surrounding them with backticks. Returns: List[str, ...]: The list of field names in the field path. """ # code dredged back up from # https://github.com/googleapis/google-cloud-python/pull/5109/files field_names = [] for field_name in split_field_path(api_repr): # non-simple field name if field_name[0] == "`" and field_name[-1] == "`": field_name = field_name[1:-1] field_name = field_name.replace(_ESCAPED_BACKTICK, _BACKTICK) field_name = field_name.replace(_ESCAPED_BACKSLASH, _BACKSLASH) field_names.append(field_name) return field_names
[ "def", "parse_field_path", "(", "api_repr", ")", ":", "# code dredged back up from", "# https://github.com/googleapis/google-cloud-python/pull/5109/files", "field_names", "=", "[", "]", "for", "field_name", "in", "split_field_path", "(", "api_repr", ")", ":", "# non-simple field name", "if", "field_name", "[", "0", "]", "==", "\"`\"", "and", "field_name", "[", "-", "1", "]", "==", "\"`\"", ":", "field_name", "=", "field_name", "[", "1", ":", "-", "1", "]", "field_name", "=", "field_name", ".", "replace", "(", "_ESCAPED_BACKTICK", ",", "_BACKTICK", ")", "field_name", "=", "field_name", ".", "replace", "(", "_ESCAPED_BACKSLASH", ",", "_BACKSLASH", ")", "field_names", ".", "append", "(", "field_name", ")", "return", "field_names" ]
41
20.62963
def CreateGaugeMetadata(metric_name, value_type, fields=None, docstring=None, units=None): """Helper function for creating MetricMetadata for gauge metrics.""" return rdf_stats.MetricMetadata( varname=metric_name, metric_type=rdf_stats.MetricMetadata.MetricType.GAUGE, value_type=MetricValueTypeFromPythonType(value_type), fields_defs=FieldDefinitionProtosFromTuples(fields or []), docstring=docstring, units=units)
[ "def", "CreateGaugeMetadata", "(", "metric_name", ",", "value_type", ",", "fields", "=", "None", ",", "docstring", "=", "None", ",", "units", "=", "None", ")", ":", "return", "rdf_stats", ".", "MetricMetadata", "(", "varname", "=", "metric_name", ",", "metric_type", "=", "rdf_stats", ".", "MetricMetadata", ".", "MetricType", ".", "GAUGE", ",", "value_type", "=", "MetricValueTypeFromPythonType", "(", "value_type", ")", ",", "fields_defs", "=", "FieldDefinitionProtosFromTuples", "(", "fields", "or", "[", "]", ")", ",", "docstring", "=", "docstring", ",", "units", "=", "units", ")" ]
41.461538
10.538462
def __replace(config, wildcards, config_file): """For each kvp in config, do wildcard substitution on the values""" for config_key in config: config_value = config[config_key] original_value = config_value if isinstance(config_value, str): for token in wildcards: if wildcards[token]: config_value = config_value.replace(token, wildcards[token]) found = re.findall(r'\${[A-Z_]+}', config_value) if found: raise ValueError("%s=%s in file %s contains unsupported or unset wildcard tokens: %s" % (config_key, original_value, config_file, ", ".join(found))) config[config_key] = config_value return config
[ "def", "__replace", "(", "config", ",", "wildcards", ",", "config_file", ")", ":", "for", "config_key", "in", "config", ":", "config_value", "=", "config", "[", "config_key", "]", "original_value", "=", "config_value", "if", "isinstance", "(", "config_value", ",", "str", ")", ":", "for", "token", "in", "wildcards", ":", "if", "wildcards", "[", "token", "]", ":", "config_value", "=", "config_value", ".", "replace", "(", "token", ",", "wildcards", "[", "token", "]", ")", "found", "=", "re", ".", "findall", "(", "r'\\${[A-Z_]+}'", ",", "config_value", ")", "if", "found", ":", "raise", "ValueError", "(", "\"%s=%s in file %s contains unsupported or unset wildcard tokens: %s\"", "%", "(", "config_key", ",", "original_value", ",", "config_file", ",", "\", \"", ".", "join", "(", "found", ")", ")", ")", "config", "[", "config_key", "]", "=", "config_value", "return", "config" ]
45.333333
16.666667
def symbolic(self, A): """ Return the symbolic factorization of sparse matrix ``A`` Parameters ---------- sparselib Library name in ``umfpack`` and ``klu`` A Sparse matrix Returns symbolic factorization ------- """ if self.sparselib == 'umfpack': return umfpack.symbolic(A) elif self.sparselib == 'klu': return klu.symbolic(A)
[ "def", "symbolic", "(", "self", ",", "A", ")", ":", "if", "self", ".", "sparselib", "==", "'umfpack'", ":", "return", "umfpack", ".", "symbolic", "(", "A", ")", "elif", "self", ".", "sparselib", "==", "'klu'", ":", "return", "klu", ".", "symbolic", "(", "A", ")" ]
20.636364
19.909091
def AppendData(self, data, custom_properties=None): """Appends new data to the table. Data is appended in rows. Data must comply with the table schema passed in to __init__(). See CoerceValue() for a list of acceptable data types. See the class documentation for more information and examples of schema and data values. Args: data: The row to add to the table. The data must conform to the table description format. custom_properties: A dictionary of string to string, representing the custom properties to add to all the rows. Raises: DataTableException: The data structure does not match the description. """ # If the maximal depth is 0, we simply iterate over the data table # lines and insert them using _InnerAppendData. Otherwise, we simply # let the _InnerAppendData handle all the levels. if not self.__columns[-1]["depth"]: for row in data: self._InnerAppendData(({}, custom_properties), row, 0) else: self._InnerAppendData(({}, custom_properties), data, 0)
[ "def", "AppendData", "(", "self", ",", "data", ",", "custom_properties", "=", "None", ")", ":", "# If the maximal depth is 0, we simply iterate over the data table", "# lines and insert them using _InnerAppendData. Otherwise, we simply", "# let the _InnerAppendData handle all the levels.", "if", "not", "self", ".", "__columns", "[", "-", "1", "]", "[", "\"depth\"", "]", ":", "for", "row", "in", "data", ":", "self", ".", "_InnerAppendData", "(", "(", "{", "}", ",", "custom_properties", ")", ",", "row", ",", "0", ")", "else", ":", "self", ".", "_InnerAppendData", "(", "(", "{", "}", ",", "custom_properties", ")", ",", "data", ",", "0", ")" ]
42.88
23.44
def run(self, callback=None, limit=0): """ Start pcap's loop over the interface, calling the given callback for each packet :param callback: a function receiving (win_pcap, param, header, pkt_data) for each packet intercepted :param limit: how many packets to capture (A value of -1 or 0 is equivalent to infinity) """ if self._handle is None: raise self.DeviceIsNotOpen() # Set new callback self._callback = callback # Run loop with callback wrapper wtypes.pcap_loop(self._handle, limit, self._callback_wrapper, None)
[ "def", "run", "(", "self", ",", "callback", "=", "None", ",", "limit", "=", "0", ")", ":", "if", "self", ".", "_handle", "is", "None", ":", "raise", "self", ".", "DeviceIsNotOpen", "(", ")", "# Set new callback", "self", ".", "_callback", "=", "callback", "# Run loop with callback wrapper", "wtypes", ".", "pcap_loop", "(", "self", ".", "_handle", ",", "limit", ",", "self", ".", "_callback_wrapper", ",", "None", ")" ]
49.916667
19.916667
def get_name(model_id): """ Get the name for a model. :returns str: The model's name. If the id has no associated name, then "id = {ID} (no name)" is returned. """ name = _names.get(model_id) if name is None: name = 'id = %s (no name)' % str(model_id) return name
[ "def", "get_name", "(", "model_id", ")", ":", "name", "=", "_names", ".", "get", "(", "model_id", ")", "if", "name", "is", "None", ":", "name", "=", "'id = %s (no name)'", "%", "str", "(", "model_id", ")", "return", "name" ]
29.2
20.2
def get_component_types(topic_id, remoteci_id, db_conn=None): """Returns either the topic component types or the rconfigration's component types.""" db_conn = db_conn or flask.g.db_conn rconfiguration = remotecis.get_remoteci_configuration(topic_id, remoteci_id, db_conn=db_conn) # if there is no rconfiguration associated to the remoteci or no # component types then use the topic's one. if (rconfiguration is not None and rconfiguration['component_types'] is not None): component_types = rconfiguration['component_types'] else: component_types = get_component_types_from_topic(topic_id, db_conn=db_conn) return component_types, rconfiguration
[ "def", "get_component_types", "(", "topic_id", ",", "remoteci_id", ",", "db_conn", "=", "None", ")", ":", "db_conn", "=", "db_conn", "or", "flask", ".", "g", ".", "db_conn", "rconfiguration", "=", "remotecis", ".", "get_remoteci_configuration", "(", "topic_id", ",", "remoteci_id", ",", "db_conn", "=", "db_conn", ")", "# if there is no rconfiguration associated to the remoteci or no", "# component types then use the topic's one.", "if", "(", "rconfiguration", "is", "not", "None", "and", "rconfiguration", "[", "'component_types'", "]", "is", "not", "None", ")", ":", "component_types", "=", "rconfiguration", "[", "'component_types'", "]", "else", ":", "component_types", "=", "get_component_types_from_topic", "(", "topic_id", ",", "db_conn", "=", "db_conn", ")", "return", "component_types", ",", "rconfiguration" ]
45.578947
21
def download_and_parse_mnist_file(fname, target_dir=None, force=False): """Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array. Parameters ---------- fname : str File name to download and parse target_dir : str Directory where to store the file force : bool Force downloading the file, if it already exists Returns ------- data : numpy.ndarray Numpy array with the dimensions and the data in the IDX file """ fname = download_file(fname, target_dir=target_dir, force=force) fopen = gzip.open if os.path.splitext(fname)[1] == '.gz' else open with fopen(fname, 'rb') as fd: return parse_idx(fd)
[ "def", "download_and_parse_mnist_file", "(", "fname", ",", "target_dir", "=", "None", ",", "force", "=", "False", ")", ":", "fname", "=", "download_file", "(", "fname", ",", "target_dir", "=", "target_dir", ",", "force", "=", "force", ")", "fopen", "=", "gzip", ".", "open", "if", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "1", "]", "==", "'.gz'", "else", "open", "with", "fopen", "(", "fname", ",", "'rb'", ")", "as", "fd", ":", "return", "parse_idx", "(", "fd", ")" ]
30
21.375
def close_streaming_interface(self): """Called when someone closes the streaming interface to the device. This method will automatically notify sensor_graph that there is a no longer a streaming interface opened. """ super(ReferenceDevice, self).close_streaming_interface() self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_CLOSED)
[ "def", "close_streaming_interface", "(", "self", ")", ":", "super", "(", "ReferenceDevice", ",", "self", ")", ".", "close_streaming_interface", "(", ")", "self", ".", "rpc", "(", "8", ",", "rpcs", ".", "SG_GRAPH_INPUT", ",", "8", ",", "streams", ".", "COMM_TILE_CLOSED", ")" ]
37.7
21.8
def add_toc_entry(self, title, level, slide_number): """ Adds a new entry to current presentation Table of Contents. """ self.__toc.append({'title': title, 'number': slide_number, 'level': level})
[ "def", "add_toc_entry", "(", "self", ",", "title", ",", "level", ",", "slide_number", ")", ":", "self", ".", "__toc", ".", "append", "(", "{", "'title'", ":", "title", ",", "'number'", ":", "slide_number", ",", "'level'", ":", "level", "}", ")" ]
48.6
8.2
def _increase_logging(self, loggers): """! @brief Increase logging level for a set of subloggers.""" if self._log_level_delta <= 0: level = max(1, self._default_log_level + self._log_level_delta - 10) for logger in loggers: logging.getLogger(logger).setLevel(level)
[ "def", "_increase_logging", "(", "self", ",", "loggers", ")", ":", "if", "self", ".", "_log_level_delta", "<=", "0", ":", "level", "=", "max", "(", "1", ",", "self", ".", "_default_log_level", "+", "self", ".", "_log_level_delta", "-", "10", ")", "for", "logger", "in", "loggers", ":", "logging", ".", "getLogger", "(", "logger", ")", ".", "setLevel", "(", "level", ")" ]
52.666667
11.333333
def setCustomColorRamp(self, colors=[], interpolatedPoints=10): """ Accepts a list of RGB tuples and interpolates between them to create a custom color ramp. Returns the color ramp as a list of RGB tuples. """ self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, interpolatedPoints)
[ "def", "setCustomColorRamp", "(", "self", ",", "colors", "=", "[", "]", ",", "interpolatedPoints", "=", "10", ")", ":", "self", ".", "_colorRamp", "=", "ColorRampGenerator", ".", "generateCustomColorRamp", "(", "colors", ",", "interpolatedPoints", ")" ]
55.5
25.166667
def can_access_api(self): """ :return: True when we can access the REST API """ try: version_dict = self.get_version() except Exception, e: msg = 'An exception was raised when connecting to REST API: "%s"' raise APIException(msg % e) else: """ This is an example response from the REST API { "branch": "develop", "dirty": "Yes", "revision": "f1cae98161 - 24 Jun 2015 16:29", "version": "1.7.2" } """ if 'version' in version_dict: # Yup, this looks like a w3af REST API return True msg = 'Unexpected HTTP response when connecting to REST API' raise APIException(msg)
[ "def", "can_access_api", "(", "self", ")", ":", "try", ":", "version_dict", "=", "self", ".", "get_version", "(", ")", "except", "Exception", ",", "e", ":", "msg", "=", "'An exception was raised when connecting to REST API: \"%s\"'", "raise", "APIException", "(", "msg", "%", "e", ")", "else", ":", "\"\"\"\n This is an example response from the REST API\n {\n \"branch\": \"develop\",\n \"dirty\": \"Yes\",\n \"revision\": \"f1cae98161 - 24 Jun 2015 16:29\",\n \"version\": \"1.7.2\"\n }\n \"\"\"", "if", "'version'", "in", "version_dict", ":", "# Yup, this looks like a w3af REST API", "return", "True", "msg", "=", "'Unexpected HTTP response when connecting to REST API'", "raise", "APIException", "(", "msg", ")" ]
32.72
14.16
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(PRC, self).fix_config(options) opt = "class_index" if opt not in options: options[opt] = [0] if opt not in self.help: self.help[opt] = "The list of 0-based class-label indices to display (list)." opt = "key_loc" if opt not in options: options[opt] = "lower center" if opt not in self.help: self.help[opt] = "The location of the key in the plot (str)." opt = "title" if opt not in options: options[opt] = None if opt not in self.help: self.help[opt] = "The title for the plot (str)." opt = "outfile" if opt not in options: options[opt] = None if opt not in self.help: self.help[opt] = "The file to store the plot in (str)." opt = "wait" if opt not in options: options[opt] = True if opt not in self.help: self.help[opt] = "Whether to wait for user to close the plot window (bool)." return options
[ "def", "fix_config", "(", "self", ",", "options", ")", ":", "options", "=", "super", "(", "PRC", ",", "self", ")", ".", "fix_config", "(", "options", ")", "opt", "=", "\"class_index\"", "if", "opt", "not", "in", "options", ":", "options", "[", "opt", "]", "=", "[", "0", "]", "if", "opt", "not", "in", "self", ".", "help", ":", "self", ".", "help", "[", "opt", "]", "=", "\"The list of 0-based class-label indices to display (list).\"", "opt", "=", "\"key_loc\"", "if", "opt", "not", "in", "options", ":", "options", "[", "opt", "]", "=", "\"lower center\"", "if", "opt", "not", "in", "self", ".", "help", ":", "self", ".", "help", "[", "opt", "]", "=", "\"The location of the key in the plot (str).\"", "opt", "=", "\"title\"", "if", "opt", "not", "in", "options", ":", "options", "[", "opt", "]", "=", "None", "if", "opt", "not", "in", "self", ".", "help", ":", "self", ".", "help", "[", "opt", "]", "=", "\"The title for the plot (str).\"", "opt", "=", "\"outfile\"", "if", "opt", "not", "in", "options", ":", "options", "[", "opt", "]", "=", "None", "if", "opt", "not", "in", "self", ".", "help", ":", "self", ".", "help", "[", "opt", "]", "=", "\"The file to store the plot in (str).\"", "opt", "=", "\"wait\"", "if", "opt", "not", "in", "options", ":", "options", "[", "opt", "]", "=", "True", "if", "opt", "not", "in", "self", ".", "help", ":", "self", ".", "help", "[", "opt", "]", "=", "\"Whether to wait for user to close the plot window (bool).\"", "return", "options" ]
31.547619
19.309524
def separate(df, column, into, sep="[\W_]+", remove=True, convert=False, extra='drop', fill='right'): """ Splits columns into multiple columns. Args: df (pandas.DataFrame): DataFrame passed in through the pipe. column (str, symbolic): Label of column to split. into (list): List of string names for new columns. Kwargs: sep (str or list): If a string, the regex string used to split the column. If a list, a list of integer positions to split strings on. remove (bool): Boolean indicating whether to remove the original column. convert (bool): Boolean indicating whether the new columns should be converted to the appropriate type. extra (str): either `'drop'`, where split pieces beyond the specified new columns are dropped, or `'merge'`, where the final split piece contains the remainder of the original column. fill (str): either `'right'`, where `np.nan` values are filled in the right-most columns for missing pieces, or `'left'` where `np.nan` values are filled in the left-most columns. """ assert isinstance(into, (tuple, list)) if isinstance(sep, (tuple, list)): inds = [0] + list(sep) if len(inds) > len(into): if extra == 'drop': inds = inds[:len(into) + 1] elif extra == 'merge': inds = inds[:len(into)] + [None] else: inds = inds + [None] splits = df[column].map(lambda x: [str(x)[slice(inds[i], inds[i + 1])] if i < len(inds) - 1 else np.nan for i in range(len(into))]) else: maxsplit = len(into) - 1 if extra == 'merge' else 0 splits = df[column].map(lambda x: re.split(sep, x, maxsplit)) right_filler = lambda x: x + [np.nan for i in range(len(into) - len(x))] left_filler = lambda x: [np.nan for i in range(len(into) - len(x))] + x if fill == 'right': splits = [right_filler(x) for x in splits] elif fill == 'left': splits = [left_filler(x) for x in splits] for i, split_col in enumerate(into): df[split_col] = [x[i] if not x[i] == '' else np.nan for x in splits] if convert: df = convert_type(df, into) if remove: df.drop(column, axis=1, inplace=True) return df
[ "def", "separate", "(", "df", ",", "column", ",", "into", ",", "sep", "=", "\"[\\W_]+\"", ",", "remove", "=", "True", ",", "convert", "=", "False", ",", "extra", "=", "'drop'", ",", "fill", "=", "'right'", ")", ":", "assert", "isinstance", "(", "into", ",", "(", "tuple", ",", "list", ")", ")", "if", "isinstance", "(", "sep", ",", "(", "tuple", ",", "list", ")", ")", ":", "inds", "=", "[", "0", "]", "+", "list", "(", "sep", ")", "if", "len", "(", "inds", ")", ">", "len", "(", "into", ")", ":", "if", "extra", "==", "'drop'", ":", "inds", "=", "inds", "[", ":", "len", "(", "into", ")", "+", "1", "]", "elif", "extra", "==", "'merge'", ":", "inds", "=", "inds", "[", ":", "len", "(", "into", ")", "]", "+", "[", "None", "]", "else", ":", "inds", "=", "inds", "+", "[", "None", "]", "splits", "=", "df", "[", "column", "]", ".", "map", "(", "lambda", "x", ":", "[", "str", "(", "x", ")", "[", "slice", "(", "inds", "[", "i", "]", ",", "inds", "[", "i", "+", "1", "]", ")", "]", "if", "i", "<", "len", "(", "inds", ")", "-", "1", "else", "np", ".", "nan", "for", "i", "in", "range", "(", "len", "(", "into", ")", ")", "]", ")", "else", ":", "maxsplit", "=", "len", "(", "into", ")", "-", "1", "if", "extra", "==", "'merge'", "else", "0", "splits", "=", "df", "[", "column", "]", ".", "map", "(", "lambda", "x", ":", "re", ".", "split", "(", "sep", ",", "x", ",", "maxsplit", ")", ")", "right_filler", "=", "lambda", "x", ":", "x", "+", "[", "np", ".", "nan", "for", "i", "in", "range", "(", "len", "(", "into", ")", "-", "len", "(", "x", ")", ")", "]", "left_filler", "=", "lambda", "x", ":", "[", "np", ".", "nan", "for", "i", "in", "range", "(", "len", "(", "into", ")", "-", "len", "(", "x", ")", ")", "]", "+", "x", "if", "fill", "==", "'right'", ":", "splits", "=", "[", "right_filler", "(", "x", ")", "for", "x", "in", "splits", "]", "elif", "fill", "==", "'left'", ":", "splits", "=", "[", "left_filler", "(", "x", ")", "for", "x", "in", "splits", "]", "for", "i", ",", "split_col", "in", "enumerate", "(", "into", ")", ":", "df", "[", "split_col", "]", "=", "[", "x", "[", "i", "]", "if", "not", "x", "[", "i", "]", "==", "''", "else", "np", ".", "nan", "for", "x", "in", "splits", "]", "if", "convert", ":", "df", "=", "convert_type", "(", "df", ",", "into", ")", "if", "remove", ":", "df", ".", "drop", "(", "column", ",", "axis", "=", "1", ",", "inplace", "=", "True", ")", "return", "df" ]
38.063492
23.904762
def update_currency_by_id(cls, currency_id, currency, **kwargs): """Update Currency Update attributes of Currency This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_currency_by_id(currency_id, currency, async=True) >>> result = thread.get() :param async bool :param str currency_id: ID of currency to update. (required) :param Currency currency: Attributes of currency to update. (required) :return: Currency If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_currency_by_id_with_http_info(currency_id, currency, **kwargs) else: (data) = cls._update_currency_by_id_with_http_info(currency_id, currency, **kwargs) return data
[ "def", "update_currency_by_id", "(", "cls", ",", "currency_id", ",", "currency", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_update_currency_by_id_with_http_info", "(", "currency_id", ",", "currency", ",", "*", "*", "kwargs", ")", "else", ":", "(", "data", ")", "=", "cls", ".", "_update_currency_by_id_with_http_info", "(", "currency_id", ",", "currency", ",", "*", "*", "kwargs", ")", "return", "data" ]
44.636364
22.318182
def sphere(radius=0.5, sectors=32, rings=16) -> VAO: """ Creates a sphere. Keyword Args: radius (float): Radius or the sphere rings (int): number or horizontal rings sectors (int): number of vertical segments Returns: A :py:class:`demosys.opengl.vao.VAO` instance """ R = 1.0 / (rings - 1) S = 1.0 / (sectors - 1) vertices = [0] * (rings * sectors * 3) normals = [0] * (rings * sectors * 3) uvs = [0] * (rings * sectors * 2) v, n, t = 0, 0, 0 for r in range(rings): for s in range(sectors): y = math.sin(-math.pi / 2 + math.pi * r * R) x = math.cos(2 * math.pi * s * S) * math.sin(math.pi * r * R) z = math.sin(2 * math.pi * s * S) * math.sin(math.pi * r * R) uvs[t] = s * S uvs[t + 1] = r * R vertices[v] = x * radius vertices[v + 1] = y * radius vertices[v + 2] = z * radius normals[n] = x normals[n + 1] = y normals[n + 2] = z t += 2 v += 3 n += 3 indices = [0] * rings * sectors * 6 i = 0 for r in range(rings - 1): for s in range(sectors - 1): indices[i] = r * sectors + s indices[i + 1] = (r + 1) * sectors + (s + 1) indices[i + 2] = r * sectors + (s + 1) indices[i + 3] = r * sectors + s indices[i + 4] = (r + 1) * sectors + s indices[i + 5] = (r + 1) * sectors + (s + 1) i += 6 vbo_vertices = numpy.array(vertices, dtype=numpy.float32) vbo_normals = numpy.array(normals, dtype=numpy.float32) vbo_uvs = numpy.array(uvs, dtype=numpy.float32) vbo_elements = numpy.array(indices, dtype=numpy.uint32) vao = VAO("sphere", mode=mlg.TRIANGLES) # VBOs vao.buffer(vbo_vertices, '3f', ['in_position']) vao.buffer(vbo_normals, '3f', ['in_normal']) vao.buffer(vbo_uvs, '2f', ['in_uv']) vao.index_buffer(vbo_elements, index_element_size=4) return vao
[ "def", "sphere", "(", "radius", "=", "0.5", ",", "sectors", "=", "32", ",", "rings", "=", "16", ")", "->", "VAO", ":", "R", "=", "1.0", "/", "(", "rings", "-", "1", ")", "S", "=", "1.0", "/", "(", "sectors", "-", "1", ")", "vertices", "=", "[", "0", "]", "*", "(", "rings", "*", "sectors", "*", "3", ")", "normals", "=", "[", "0", "]", "*", "(", "rings", "*", "sectors", "*", "3", ")", "uvs", "=", "[", "0", "]", "*", "(", "rings", "*", "sectors", "*", "2", ")", "v", ",", "n", ",", "t", "=", "0", ",", "0", ",", "0", "for", "r", "in", "range", "(", "rings", ")", ":", "for", "s", "in", "range", "(", "sectors", ")", ":", "y", "=", "math", ".", "sin", "(", "-", "math", ".", "pi", "/", "2", "+", "math", ".", "pi", "*", "r", "*", "R", ")", "x", "=", "math", ".", "cos", "(", "2", "*", "math", ".", "pi", "*", "s", "*", "S", ")", "*", "math", ".", "sin", "(", "math", ".", "pi", "*", "r", "*", "R", ")", "z", "=", "math", ".", "sin", "(", "2", "*", "math", ".", "pi", "*", "s", "*", "S", ")", "*", "math", ".", "sin", "(", "math", ".", "pi", "*", "r", "*", "R", ")", "uvs", "[", "t", "]", "=", "s", "*", "S", "uvs", "[", "t", "+", "1", "]", "=", "r", "*", "R", "vertices", "[", "v", "]", "=", "x", "*", "radius", "vertices", "[", "v", "+", "1", "]", "=", "y", "*", "radius", "vertices", "[", "v", "+", "2", "]", "=", "z", "*", "radius", "normals", "[", "n", "]", "=", "x", "normals", "[", "n", "+", "1", "]", "=", "y", "normals", "[", "n", "+", "2", "]", "=", "z", "t", "+=", "2", "v", "+=", "3", "n", "+=", "3", "indices", "=", "[", "0", "]", "*", "rings", "*", "sectors", "*", "6", "i", "=", "0", "for", "r", "in", "range", "(", "rings", "-", "1", ")", ":", "for", "s", "in", "range", "(", "sectors", "-", "1", ")", ":", "indices", "[", "i", "]", "=", "r", "*", "sectors", "+", "s", "indices", "[", "i", "+", "1", "]", "=", "(", "r", "+", "1", ")", "*", "sectors", "+", "(", "s", "+", "1", ")", "indices", "[", "i", "+", "2", "]", "=", "r", "*", "sectors", "+", "(", "s", "+", "1", ")", "indices", "[", "i", "+", "3", "]", "=", "r", "*", "sectors", "+", "s", "indices", "[", "i", "+", "4", "]", "=", "(", "r", "+", "1", ")", "*", "sectors", "+", "s", "indices", "[", "i", "+", "5", "]", "=", "(", "r", "+", "1", ")", "*", "sectors", "+", "(", "s", "+", "1", ")", "i", "+=", "6", "vbo_vertices", "=", "numpy", ".", "array", "(", "vertices", ",", "dtype", "=", "numpy", ".", "float32", ")", "vbo_normals", "=", "numpy", ".", "array", "(", "normals", ",", "dtype", "=", "numpy", ".", "float32", ")", "vbo_uvs", "=", "numpy", ".", "array", "(", "uvs", ",", "dtype", "=", "numpy", ".", "float32", ")", "vbo_elements", "=", "numpy", ".", "array", "(", "indices", ",", "dtype", "=", "numpy", ".", "uint32", ")", "vao", "=", "VAO", "(", "\"sphere\"", ",", "mode", "=", "mlg", ".", "TRIANGLES", ")", "# VBOs", "vao", ".", "buffer", "(", "vbo_vertices", ",", "'3f'", ",", "[", "'in_position'", "]", ")", "vao", ".", "buffer", "(", "vbo_normals", ",", "'3f'", ",", "[", "'in_normal'", "]", ")", "vao", ".", "buffer", "(", "vbo_uvs", ",", "'2f'", ",", "[", "'in_uv'", "]", ")", "vao", ".", "index_buffer", "(", "vbo_elements", ",", "index_element_size", "=", "4", ")", "return", "vao" ]
29.776119
18.044776
def cell_value(self, column_family_id, column, index=0): """Get a single cell value stored on this instance. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_row_cell_value] :end-before: [END bigtable_row_cell_value] Args: column_family_id (str): The ID of the column family. Must be of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``. column (bytes): The column within the column family where the cell is located. index (Optional[int]): The offset within the series of values. If not specified, will return the first cell. Returns: ~google.cloud.bigtable.row_data.Cell value: The cell value stored in the specified column and specified index. Raises: KeyError: If ``column_family_id`` is not among the cells stored in this row. KeyError: If ``column`` is not among the cells stored in this row for the given ``column_family_id``. IndexError: If ``index`` cannot be found within the cells stored in this row for the given ``column_family_id``, ``column`` pair. """ cells = self.find_cells(column_family_id, column) try: cell = cells[index] except (TypeError, IndexError): num_cells = len(cells) msg = _MISSING_INDEX.format(index, column, column_family_id, num_cells) raise IndexError(msg) return cell.value
[ "def", "cell_value", "(", "self", ",", "column_family_id", ",", "column", ",", "index", "=", "0", ")", ":", "cells", "=", "self", ".", "find_cells", "(", "column_family_id", ",", "column", ")", "try", ":", "cell", "=", "cells", "[", "index", "]", "except", "(", "TypeError", ",", "IndexError", ")", ":", "num_cells", "=", "len", "(", "cells", ")", "msg", "=", "_MISSING_INDEX", ".", "format", "(", "index", ",", "column", ",", "column_family_id", ",", "num_cells", ")", "raise", "IndexError", "(", "msg", ")", "return", "cell", ".", "value" ]
39.175
23.725
def convert(self, converters, in_place=False): """ Applies transformations to the dataset. :param converters: A dictionary specifying the function to apply to each field. If a field is missing from the dictionary, then it will not be transformed. :param in_place: Whether to perform the transformation in place or create a new dataset instance :return: the transformed dataset instance """ dataset = self if in_place else self.__class__(OrderedDict([(name, data[:]) for name, data in self.fields.items()])) for name, convert in converters.items(): if name not in self.fields.keys(): raise InvalidFieldsException('Converter specified for non-existent field {}'.format(name)) for i, d in enumerate(dataset.fields[name]): dataset.fields[name][i] = convert(d) return dataset
[ "def", "convert", "(", "self", ",", "converters", ",", "in_place", "=", "False", ")", ":", "dataset", "=", "self", "if", "in_place", "else", "self", ".", "__class__", "(", "OrderedDict", "(", "[", "(", "name", ",", "data", "[", ":", "]", ")", "for", "name", ",", "data", "in", "self", ".", "fields", ".", "items", "(", ")", "]", ")", ")", "for", "name", ",", "convert", "in", "converters", ".", "items", "(", ")", ":", "if", "name", "not", "in", "self", ".", "fields", ".", "keys", "(", ")", ":", "raise", "InvalidFieldsException", "(", "'Converter specified for non-existent field {}'", ".", "format", "(", "name", ")", ")", "for", "i", ",", "d", "in", "enumerate", "(", "dataset", ".", "fields", "[", "name", "]", ")", ":", "dataset", ".", "fields", "[", "name", "]", "[", "i", "]", "=", "convert", "(", "d", ")", "return", "dataset" ]
52.058824
31.705882
def mkdirs(remote_dir, use_sudo=False): """ Wrapper around mkdir -pv Returns a list of directories created """ func = use_sudo and sudo or run result = func(' '.join(['mkdir -pv',remote_dir])).split('\n') #extract dir list from ["mkdir: created directory `example.com/some/dir'"] if result[0]: result = [dir.split(' ')[3][1:-1] for dir in result if dir] return result
[ "def", "mkdirs", "(", "remote_dir", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "sudo", "or", "run", "result", "=", "func", "(", "' '", ".", "join", "(", "[", "'mkdir -pv'", ",", "remote_dir", "]", ")", ")", ".", "split", "(", "'\\n'", ")", "#extract dir list from [\"mkdir: created directory `example.com/some/dir'\"]", "if", "result", "[", "0", "]", ":", "result", "=", "[", "dir", ".", "split", "(", "' '", ")", "[", "3", "]", "[", "1", ":", "-", "1", "]", "for", "dir", "in", "result", "if", "dir", "]", "return", "result" ]
36.181818
16.181818
def update(self): """Update the FS stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Grab the stats using the psutil disk_partitions # If 'all'=False return physical devices only (e.g. hard disks, cd-rom drives, USB keys) # and ignore all others (e.g. memory partitions such as /dev/shm) try: fs_stat = psutil.disk_partitions(all=False) except UnicodeDecodeError: return self.stats # Optionnal hack to allow logicals mounts points (issue #448) # Ex: Had to put 'allow=zfs' in the [fs] section of the conf file # to allow zfs monitoring for fstype in self.get_conf_value('allow'): try: fs_stat += [f for f in psutil.disk_partitions(all=True) if f.fstype.find(fstype) >= 0] except UnicodeDecodeError: return self.stats # Loop over fs for fs in fs_stat: # Do not take hidden file system into account if self.is_hide(fs.mountpoint): continue # Grab the disk usage try: fs_usage = psutil.disk_usage(fs.mountpoint) except OSError: # Correct issue #346 # Disk is ejected during the command continue fs_current = { 'device_name': fs.device, 'fs_type': fs.fstype, # Manage non breaking space (see issue #1065) 'mnt_point': u(fs.mountpoint).replace(u'\u00A0', ' '), 'size': fs_usage.total, 'used': fs_usage.used, 'free': fs_usage.free, 'percent': fs_usage.percent, 'key': self.get_key()} stats.append(fs_current) elif self.input_method == 'snmp': # Update stats using SNMP # SNMP bulk command to get all file system in one shot try: fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], bulk=True) except KeyError: fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid['default'], bulk=True) # Loop over fs if self.short_system_name in ('windows', 'esxi'): # Windows or ESXi tips for fs in fs_stat: # Memory stats are grabbed in the same OID table (ignore it) if fs == 'Virtual Memory' or fs == 'Physical Memory' or fs == 'Real Memory': continue size = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit']) used = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit']) percent = float(used * 100 / size) fs_current = { 'device_name': '', 'mnt_point': fs.partition(' ')[0], 'size': size, 'used': used, 'percent': percent, 'key': self.get_key()} stats.append(fs_current) else: # Default behavior for fs in fs_stat: fs_current = { 'device_name': fs_stat[fs]['device_name'], 'mnt_point': fs, 'size': int(fs_stat[fs]['size']) * 1024, 'used': int(fs_stat[fs]['used']) * 1024, 'percent': float(fs_stat[fs]['percent']), 'key': self.get_key()} stats.append(fs_current) # Update the stats self.stats = stats return self.stats
[ "def", "update", "(", "self", ")", ":", "# Init new stats", "stats", "=", "self", ".", "get_init_value", "(", ")", "if", "self", ".", "input_method", "==", "'local'", ":", "# Update stats using the standard system lib", "# Grab the stats using the psutil disk_partitions", "# If 'all'=False return physical devices only (e.g. hard disks, cd-rom drives, USB keys)", "# and ignore all others (e.g. memory partitions such as /dev/shm)", "try", ":", "fs_stat", "=", "psutil", ".", "disk_partitions", "(", "all", "=", "False", ")", "except", "UnicodeDecodeError", ":", "return", "self", ".", "stats", "# Optionnal hack to allow logicals mounts points (issue #448)", "# Ex: Had to put 'allow=zfs' in the [fs] section of the conf file", "# to allow zfs monitoring", "for", "fstype", "in", "self", ".", "get_conf_value", "(", "'allow'", ")", ":", "try", ":", "fs_stat", "+=", "[", "f", "for", "f", "in", "psutil", ".", "disk_partitions", "(", "all", "=", "True", ")", "if", "f", ".", "fstype", ".", "find", "(", "fstype", ")", ">=", "0", "]", "except", "UnicodeDecodeError", ":", "return", "self", ".", "stats", "# Loop over fs", "for", "fs", "in", "fs_stat", ":", "# Do not take hidden file system into account", "if", "self", ".", "is_hide", "(", "fs", ".", "mountpoint", ")", ":", "continue", "# Grab the disk usage", "try", ":", "fs_usage", "=", "psutil", ".", "disk_usage", "(", "fs", ".", "mountpoint", ")", "except", "OSError", ":", "# Correct issue #346", "# Disk is ejected during the command", "continue", "fs_current", "=", "{", "'device_name'", ":", "fs", ".", "device", ",", "'fs_type'", ":", "fs", ".", "fstype", ",", "# Manage non breaking space (see issue #1065)", "'mnt_point'", ":", "u", "(", "fs", ".", "mountpoint", ")", ".", "replace", "(", "u'\\u00A0'", ",", "' '", ")", ",", "'size'", ":", "fs_usage", ".", "total", ",", "'used'", ":", "fs_usage", ".", "used", ",", "'free'", ":", "fs_usage", ".", "free", ",", "'percent'", ":", "fs_usage", ".", "percent", ",", "'key'", ":", "self", ".", "get_key", "(", ")", "}", "stats", ".", "append", "(", "fs_current", ")", "elif", "self", ".", "input_method", "==", "'snmp'", ":", "# Update stats using SNMP", "# SNMP bulk command to get all file system in one shot", "try", ":", "fs_stat", "=", "self", ".", "get_stats_snmp", "(", "snmp_oid", "=", "snmp_oid", "[", "self", ".", "short_system_name", "]", ",", "bulk", "=", "True", ")", "except", "KeyError", ":", "fs_stat", "=", "self", ".", "get_stats_snmp", "(", "snmp_oid", "=", "snmp_oid", "[", "'default'", "]", ",", "bulk", "=", "True", ")", "# Loop over fs", "if", "self", ".", "short_system_name", "in", "(", "'windows'", ",", "'esxi'", ")", ":", "# Windows or ESXi tips", "for", "fs", "in", "fs_stat", ":", "# Memory stats are grabbed in the same OID table (ignore it)", "if", "fs", "==", "'Virtual Memory'", "or", "fs", "==", "'Physical Memory'", "or", "fs", "==", "'Real Memory'", ":", "continue", "size", "=", "int", "(", "fs_stat", "[", "fs", "]", "[", "'size'", "]", ")", "*", "int", "(", "fs_stat", "[", "fs", "]", "[", "'alloc_unit'", "]", ")", "used", "=", "int", "(", "fs_stat", "[", "fs", "]", "[", "'used'", "]", ")", "*", "int", "(", "fs_stat", "[", "fs", "]", "[", "'alloc_unit'", "]", ")", "percent", "=", "float", "(", "used", "*", "100", "/", "size", ")", "fs_current", "=", "{", "'device_name'", ":", "''", ",", "'mnt_point'", ":", "fs", ".", "partition", "(", "' '", ")", "[", "0", "]", ",", "'size'", ":", "size", ",", "'used'", ":", "used", ",", "'percent'", ":", "percent", ",", "'key'", ":", "self", ".", "get_key", "(", ")", "}", "stats", ".", "append", "(", "fs_current", ")", "else", ":", "# Default behavior", "for", "fs", "in", "fs_stat", ":", "fs_current", "=", "{", "'device_name'", ":", "fs_stat", "[", "fs", "]", "[", "'device_name'", "]", ",", "'mnt_point'", ":", "fs", ",", "'size'", ":", "int", "(", "fs_stat", "[", "fs", "]", "[", "'size'", "]", ")", "*", "1024", ",", "'used'", ":", "int", "(", "fs_stat", "[", "fs", "]", "[", "'used'", "]", ")", "*", "1024", ",", "'percent'", ":", "float", "(", "fs_stat", "[", "fs", "]", "[", "'percent'", "]", ")", ",", "'key'", ":", "self", ".", "get_key", "(", ")", "}", "stats", ".", "append", "(", "fs_current", ")", "# Update the stats", "self", ".", "stats", "=", "stats", "return", "self", ".", "stats" ]
42.797872
17.787234
def rm_compressed(ctx, dataset, kwargs): "removes the compressed files" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_compressed(**kwargs)
[ "def", "rm_compressed", "(", "ctx", ",", "dataset", ",", "kwargs", ")", ":", "kwargs", "=", "parse_kwargs", "(", "kwargs", ")", "data", "(", "dataset", ",", "*", "*", "ctx", ".", "obj", ")", ".", "rm_compressed", "(", "*", "*", "kwargs", ")" ]
31.8
13
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: """ Takes a number of wei and converts it to any other ether unit. """ if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if number == 0: return 0 if number < MIN_WEI or number > MAX_WEI: raise ValueError("value must be between 1 and 2**256 - 1") unit_value = units[unit.lower()] with localcontext() as ctx: ctx.prec = 999 d_number = decimal.Decimal(value=number, context=ctx) result_value = d_number / unit_value return result_value
[ "def", "from_wei", "(", "number", ":", "int", ",", "unit", ":", "str", ")", "->", "Union", "[", "int", ",", "decimal", ".", "Decimal", "]", ":", "if", "unit", ".", "lower", "(", ")", "not", "in", "units", ":", "raise", "ValueError", "(", "\"Unknown unit. Must be one of {0}\"", ".", "format", "(", "\"/\"", ".", "join", "(", "units", ".", "keys", "(", ")", ")", ")", ")", "if", "number", "==", "0", ":", "return", "0", "if", "number", "<", "MIN_WEI", "or", "number", ">", "MAX_WEI", ":", "raise", "ValueError", "(", "\"value must be between 1 and 2**256 - 1\"", ")", "unit_value", "=", "units", "[", "unit", ".", "lower", "(", ")", "]", "with", "localcontext", "(", ")", "as", "ctx", ":", "ctx", ".", "prec", "=", "999", "d_number", "=", "decimal", ".", "Decimal", "(", "value", "=", "number", ",", "context", "=", "ctx", ")", "result_value", "=", "d_number", "/", "unit_value", "return", "result_value" ]
28.478261
21.434783
def handle(self, connection_id, message_content): """ The simplest authorization type will be Trust. If Trust authorization is enabled, the validator will trust the connection and approve any roles requested that are available on that endpoint. If the requester wishes to gain access to every role it has permission to access, it can request access to the role ALL, and the validator will respond with all available roles. If the permission verifier deems the connection to not have access to a role, the connection has not sent a ConnectionRequest or a the connection has already recieved a AuthorizationTrustResponse, an AuthorizatinViolation will be returned and the connection will be closed. """ if self._network.get_connection_status(connection_id) != \ ConnectionStatus.CONNECTION_REQUEST: LOGGER.debug("Connection's previous message was not a" " ConnectionRequest, Remove connection to %s", connection_id) violation = AuthorizationViolation( violation=RoleType.Value("NETWORK")) return HandlerResult( HandlerStatus.RETURN_AND_CLOSE, message_out=violation, message_type=validator_pb2.Message .AUTHORIZATION_VIOLATION) request = AuthorizationTrustRequest() request.ParseFromString(message_content) # Check that the connection's public key is allowed by the network role roles = self._network.roles for role in request.roles: if role == RoleType.Value("NETWORK") or role == \ RoleType.Value("ALL"): permitted = False if "network" in roles: permitted = self._permission_verifier.check_network_role( request.public_key) if not permitted: violation = AuthorizationViolation( violation=RoleType.Value("NETWORK")) return HandlerResult( HandlerStatus.RETURN_AND_CLOSE, message_out=violation, message_type=validator_pb2.Message .AUTHORIZATION_VIOLATION) self._network.update_connection_public_key(connection_id, request.public_key) if RoleType.Value("NETWORK") in request.roles: # Need to send ConnectionRequest to authorize ourself with the # connection if they initialized the connection try: is_outbound_connection = self._network.is_outbound_connection( connection_id) except KeyError: # Connection has gone away, drop message return HandlerResult(HandlerStatus.DROP) if not is_outbound_connection: self._network.send_connect_request(connection_id) else: # If this is an outbound connection, authorization is complete # for both connections and peering can begin. self._gossip.connect_success(connection_id) auth_trust_response = AuthorizationTrustResponse( roles=[RoleType.Value("NETWORK")]) LOGGER.debug("Connection: %s is approved", connection_id) self._network.update_connection_status( connection_id, ConnectionStatus.CONNECTED) return HandlerResult( HandlerStatus.RETURN, message_out=auth_trust_response, message_type=validator_pb2.Message.AUTHORIZATION_TRUST_RESPONSE)
[ "def", "handle", "(", "self", ",", "connection_id", ",", "message_content", ")", ":", "if", "self", ".", "_network", ".", "get_connection_status", "(", "connection_id", ")", "!=", "ConnectionStatus", ".", "CONNECTION_REQUEST", ":", "LOGGER", ".", "debug", "(", "\"Connection's previous message was not a\"", "\" ConnectionRequest, Remove connection to %s\"", ",", "connection_id", ")", "violation", "=", "AuthorizationViolation", "(", "violation", "=", "RoleType", ".", "Value", "(", "\"NETWORK\"", ")", ")", "return", "HandlerResult", "(", "HandlerStatus", ".", "RETURN_AND_CLOSE", ",", "message_out", "=", "violation", ",", "message_type", "=", "validator_pb2", ".", "Message", ".", "AUTHORIZATION_VIOLATION", ")", "request", "=", "AuthorizationTrustRequest", "(", ")", "request", ".", "ParseFromString", "(", "message_content", ")", "# Check that the connection's public key is allowed by the network role", "roles", "=", "self", ".", "_network", ".", "roles", "for", "role", "in", "request", ".", "roles", ":", "if", "role", "==", "RoleType", ".", "Value", "(", "\"NETWORK\"", ")", "or", "role", "==", "RoleType", ".", "Value", "(", "\"ALL\"", ")", ":", "permitted", "=", "False", "if", "\"network\"", "in", "roles", ":", "permitted", "=", "self", ".", "_permission_verifier", ".", "check_network_role", "(", "request", ".", "public_key", ")", "if", "not", "permitted", ":", "violation", "=", "AuthorizationViolation", "(", "violation", "=", "RoleType", ".", "Value", "(", "\"NETWORK\"", ")", ")", "return", "HandlerResult", "(", "HandlerStatus", ".", "RETURN_AND_CLOSE", ",", "message_out", "=", "violation", ",", "message_type", "=", "validator_pb2", ".", "Message", ".", "AUTHORIZATION_VIOLATION", ")", "self", ".", "_network", ".", "update_connection_public_key", "(", "connection_id", ",", "request", ".", "public_key", ")", "if", "RoleType", ".", "Value", "(", "\"NETWORK\"", ")", "in", "request", ".", "roles", ":", "# Need to send ConnectionRequest to authorize ourself with the", "# connection if they initialized the connection", "try", ":", "is_outbound_connection", "=", "self", ".", "_network", ".", "is_outbound_connection", "(", "connection_id", ")", "except", "KeyError", ":", "# Connection has gone away, drop message", "return", "HandlerResult", "(", "HandlerStatus", ".", "DROP", ")", "if", "not", "is_outbound_connection", ":", "self", ".", "_network", ".", "send_connect_request", "(", "connection_id", ")", "else", ":", "# If this is an outbound connection, authorization is complete", "# for both connections and peering can begin.", "self", ".", "_gossip", ".", "connect_success", "(", "connection_id", ")", "auth_trust_response", "=", "AuthorizationTrustResponse", "(", "roles", "=", "[", "RoleType", ".", "Value", "(", "\"NETWORK\"", ")", "]", ")", "LOGGER", ".", "debug", "(", "\"Connection: %s is approved\"", ",", "connection_id", ")", "self", ".", "_network", ".", "update_connection_status", "(", "connection_id", ",", "ConnectionStatus", ".", "CONNECTED", ")", "return", "HandlerResult", "(", "HandlerStatus", ".", "RETURN", ",", "message_out", "=", "auth_trust_response", ",", "message_type", "=", "validator_pb2", ".", "Message", ".", "AUTHORIZATION_TRUST_RESPONSE", ")" ]
46.15
19.875
def add_region_location(self, region, locations=None, use_live=True): # type: (str, Optional[List[str]], bool) -> bool """Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a region name. If any country is already added, it is ignored. Args: region (str): M49 region, intermediate region or subregion to add locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX. use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True. Returns: bool: True if all countries in region added or False if any already present. """ return self.add_country_locations(Country.get_countries_in_region(region, exception=HDXError, use_live=use_live), locations=locations)
[ "def", "add_region_location", "(", "self", ",", "region", ",", "locations", "=", "None", ",", "use_live", "=", "True", ")", ":", "# type: (str, Optional[List[str]], bool) -> bool", "return", "self", ".", "add_country_locations", "(", "Country", ".", "get_countries_in_region", "(", "region", ",", "exception", "=", "HDXError", ",", "use_live", "=", "use_live", ")", ",", "locations", "=", "locations", ")" ]
63.466667
37.8
def monitor_module(module, summary_writer, track_data=True, track_grad=True, track_update=True, track_update_ratio=False, # this is usually unnecessary bins=51): """ Allows for remote monitoring of a module's params and buffers. The following may be monitored: 1. Forward Values - Histograms of the values for parameter and buffer tensors 2. Gradient Values - Histograms of the gradients for parameter and buffer tensors 3. Update Values - Histograms of the change in parameter and buffer tensor values from the last recorded forward pass 4. Update Ratios - Histograms of the ratio of change in value for parameter and value tensors from the last iteration to the actual values. I.e., what is the relative size of the update. Generally we like to see values of about .001. See [cite Andrej Karpathy's babysitting dnn's blog post] """ # The module will need additional information module.track_data = track_data module.track_grad = track_grad module.track_update = track_update module.track_update_ratio = track_update_ratio if not hasattr(module, 'global_step'): module.global_step = 0 if not hasattr(module, 'is_monitoring'): module.is_monitoring = True if not hasattr(module, 'monitoring'): set_monitoring(module) if not hasattr(module, 'last_state_dict'): module.last_state_dict = dict() if not hasattr(module, 'var_hooks'): module.var_hooks = dict() if not hasattr(module, 'param_hooks'): module.param_hooks = dict() # All submodules need to have these for name, mod in module.named_modules(): if not hasattr(mod, 'monitor'): set_monitor(mod) if not hasattr(mod, 'monitored_vars'): mod.monitored_vars = dict() module.monitoring(True) # remove previous grad hooks before handles go stale module.register_forward_pre_hook(remove_grad_hooks) # set forward hook that monitors forward activations and sets new grad hooks monitor_forward_and_backward = get_monitor_forward_and_backward(summary_writer, bins) module.register_forward_hook(monitor_forward_and_backward)
[ "def", "monitor_module", "(", "module", ",", "summary_writer", ",", "track_data", "=", "True", ",", "track_grad", "=", "True", ",", "track_update", "=", "True", ",", "track_update_ratio", "=", "False", ",", "# this is usually unnecessary", "bins", "=", "51", ")", ":", "# The module will need additional information", "module", ".", "track_data", "=", "track_data", "module", ".", "track_grad", "=", "track_grad", "module", ".", "track_update", "=", "track_update", "module", ".", "track_update_ratio", "=", "track_update_ratio", "if", "not", "hasattr", "(", "module", ",", "'global_step'", ")", ":", "module", ".", "global_step", "=", "0", "if", "not", "hasattr", "(", "module", ",", "'is_monitoring'", ")", ":", "module", ".", "is_monitoring", "=", "True", "if", "not", "hasattr", "(", "module", ",", "'monitoring'", ")", ":", "set_monitoring", "(", "module", ")", "if", "not", "hasattr", "(", "module", ",", "'last_state_dict'", ")", ":", "module", ".", "last_state_dict", "=", "dict", "(", ")", "if", "not", "hasattr", "(", "module", ",", "'var_hooks'", ")", ":", "module", ".", "var_hooks", "=", "dict", "(", ")", "if", "not", "hasattr", "(", "module", ",", "'param_hooks'", ")", ":", "module", ".", "param_hooks", "=", "dict", "(", ")", "# All submodules need to have these", "for", "name", ",", "mod", "in", "module", ".", "named_modules", "(", ")", ":", "if", "not", "hasattr", "(", "mod", ",", "'monitor'", ")", ":", "set_monitor", "(", "mod", ")", "if", "not", "hasattr", "(", "mod", ",", "'monitored_vars'", ")", ":", "mod", ".", "monitored_vars", "=", "dict", "(", ")", "module", ".", "monitoring", "(", "True", ")", "# remove previous grad hooks before handles go stale", "module", ".", "register_forward_pre_hook", "(", "remove_grad_hooks", ")", "# set forward hook that monitors forward activations and sets new grad hooks", "monitor_forward_and_backward", "=", "get_monitor_forward_and_backward", "(", "summary_writer", ",", "bins", ")", "module", ".", "register_forward_hook", "(", "monitor_forward_and_backward", ")" ]
42.792453
16.056604
def get_local_key(module_and_var_name, default_module=None): """ Get local setting for the keys. :param module_and_var_name: for example: admin_account.admin_user, then you need to put admin_account.py in local/local_keys/ and add variable admin_user="real admin username", module_name_and_var_name should not contain "-" because :param default_module: If the template can not be directly imported, use this to specify the parent module. :return: value for the key """ if "-" in module_and_var_name: raise ModuleAndVarNameShouldNotHaveDashCharacter key_name_module_path = module_and_var_name.split(".") module_name = ".".join(key_name_module_path[0:-1]) attr_name = key_name_module_path[-1] c = ConfigurableAttributeGetter(module_name, default_module) return c.get_attr(attr_name)
[ "def", "get_local_key", "(", "module_and_var_name", ",", "default_module", "=", "None", ")", ":", "if", "\"-\"", "in", "module_and_var_name", ":", "raise", "ModuleAndVarNameShouldNotHaveDashCharacter", "key_name_module_path", "=", "module_and_var_name", ".", "split", "(", "\".\"", ")", "module_name", "=", "\".\"", ".", "join", "(", "key_name_module_path", "[", "0", ":", "-", "1", "]", ")", "attr_name", "=", "key_name_module_path", "[", "-", "1", "]", "c", "=", "ConfigurableAttributeGetter", "(", "module_name", ",", "default_module", ")", "return", "c", ".", "get_attr", "(", "attr_name", ")" ]
52.3125
21.6875
def set_instructions(self, instructions): """ Set the instructions :param instructions: the list of instructions :type instructions: a list of :class:`Instruction` """ if self.code == None: return [] return self.code.get_bc().set_instructions(instructions)
[ "def", "set_instructions", "(", "self", ",", "instructions", ")", ":", "if", "self", ".", "code", "==", "None", ":", "return", "[", "]", "return", "self", ".", "code", ".", "get_bc", "(", ")", ".", "set_instructions", "(", "instructions", ")" ]
32.8
14.2
def line_cont_after_delim(ctx, s, line_len=40, delim=(',',), line_cont_token='&'): """ Insert newline (with preceeding `line_cont_token`) afer passing over a delimiter after traversing at least `line_len` number of characters Mako convenience function. E.g. fortran does not accpet lines of arbitrary length. """ last = -1 s = str(s) for i, t in enumerate(s): if t in delim: if i > line_len: if last == -1: raise ValueError( 'No delimiter until already past line_len') i = last return s[:i+1] + line_cont_token + '\n ' + \ line_cont_after_delim( ctx, s[i+1:], line_len, delim) last = i return s
[ "def", "line_cont_after_delim", "(", "ctx", ",", "s", ",", "line_len", "=", "40", ",", "delim", "=", "(", "','", ",", ")", ",", "line_cont_token", "=", "'&'", ")", ":", "last", "=", "-", "1", "s", "=", "str", "(", "s", ")", "for", "i", ",", "t", "in", "enumerate", "(", "s", ")", ":", "if", "t", "in", "delim", ":", "if", "i", ">", "line_len", ":", "if", "last", "==", "-", "1", ":", "raise", "ValueError", "(", "'No delimiter until already past line_len'", ")", "i", "=", "last", "return", "s", "[", ":", "i", "+", "1", "]", "+", "line_cont_token", "+", "'\\n '", "+", "line_cont_after_delim", "(", "ctx", ",", "s", "[", "i", "+", "1", ":", "]", ",", "line_len", ",", "delim", ")", "last", "=", "i", "return", "s" ]
33.75
15.666667
def _frank_help(alpha, tau): """Compute first order debye function to estimate theta.""" def debye(t): return t / (np.exp(t) - 1) debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha return 4 * (debye_value - 1) / alpha + 1 - tau
[ "def", "_frank_help", "(", "alpha", ",", "tau", ")", ":", "def", "debye", "(", "t", ")", ":", "return", "t", "/", "(", "np", ".", "exp", "(", "t", ")", "-", "1", ")", "debye_value", "=", "integrate", ".", "quad", "(", "debye", ",", "EPSILON", ",", "alpha", ")", "[", "0", "]", "/", "alpha", "return", "4", "*", "(", "debye_value", "-", "1", ")", "/", "alpha", "+", "1", "-", "tau" ]
34.75
19.625
def importalma(asdm, ms): """Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa import tasks tasks.importalma('myalma.asdm', 'myalma.ms') """ from .scripting import CasapyScript script = os.path.join(os.path.dirname(__file__), 'cscript_importalma.py') with CasapyScript(script, asdm=asdm, ms=ms) as cs: pass
[ "def", "importalma", "(", "asdm", ",", "ms", ")", ":", "from", ".", "scripting", "import", "CasapyScript", "script", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'cscript_importalma.py'", ")", "with", "CasapyScript", "(", "script", ",", "asdm", "=", "asdm", ",", "ms", "=", "ms", ")", "as", "cs", ":", "pass" ]
26.636364
22.227273
def get_fields(desc2nts): """Return grouped, sorted namedtuples in either format: flat, sections.""" if 'flat' in desc2nts: nts_flat = desc2nts.get('flat') if nts_flat: return nts_flat[0]._fields if 'sections' in desc2nts: nts_sections = desc2nts.get('sections') if nts_sections: return nts_sections[0][1][0]._fields
[ "def", "get_fields", "(", "desc2nts", ")", ":", "if", "'flat'", "in", "desc2nts", ":", "nts_flat", "=", "desc2nts", ".", "get", "(", "'flat'", ")", "if", "nts_flat", ":", "return", "nts_flat", "[", "0", "]", ".", "_fields", "if", "'sections'", "in", "desc2nts", ":", "nts_sections", "=", "desc2nts", ".", "get", "(", "'sections'", ")", "if", "nts_sections", ":", "return", "nts_sections", "[", "0", "]", "[", "1", "]", "[", "0", "]", ".", "_fields" ]
41.1
8.7
def hardware_custom_profile_kap_custom_profile_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") custom_profile = ET.SubElement(hardware, "custom-profile") kap_custom_profile = ET.SubElement(custom_profile, "kap-custom-profile") name = ET.SubElement(kap_custom_profile, "name") name.text = kwargs.pop('name') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "hardware_custom_profile_kap_custom_profile_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "hardware", "=", "ET", ".", "SubElement", "(", "config", ",", "\"hardware\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade-hardware\"", ")", "custom_profile", "=", "ET", ".", "SubElement", "(", "hardware", ",", "\"custom-profile\"", ")", "kap_custom_profile", "=", "ET", ".", "SubElement", "(", "custom_profile", ",", "\"kap-custom-profile\"", ")", "name", "=", "ET", ".", "SubElement", "(", "kap_custom_profile", ",", "\"name\"", ")", "name", ".", "text", "=", "kwargs", ".", "pop", "(", "'name'", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "return", "callback", "(", "config", ")" ]
47.75
20
def doc_parser(): """Utility function to allow getting the arguments for a single command, for Sphinx documentation""" parser = argparse.ArgumentParser( prog='ambry', description='Ambry {}. Management interface for ambry, libraries ' 'and repositories. '.format(ambry._meta.__version__)) return parser
[ "def", "doc_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'ambry'", ",", "description", "=", "'Ambry {}. Management interface for ambry, libraries '", "'and repositories. '", ".", "format", "(", "ambry", ".", "_meta", ".", "__version__", ")", ")", "return", "parser" ]
38.111111
23.888889
def unbounded(self): """Whether solution is unbounded""" self._check_valid() status = self._problem._p.Status if (status == gurobipy.GRB.INF_OR_UNBD and self._problem._p.params.DualReductions): # Disable dual reductions to obtain a definitve answer self._problem._p.params.DualReductions = 0 try: self._problem._p.optimize() finally: self._problem._p.params.DualReductions = 1 status = self._problem._p.Status return status == gurobipy.GRB.UNBOUNDED
[ "def", "unbounded", "(", "self", ")", ":", "self", ".", "_check_valid", "(", ")", "status", "=", "self", ".", "_problem", ".", "_p", ".", "Status", "if", "(", "status", "==", "gurobipy", ".", "GRB", ".", "INF_OR_UNBD", "and", "self", ".", "_problem", ".", "_p", ".", "params", ".", "DualReductions", ")", ":", "# Disable dual reductions to obtain a definitve answer", "self", ".", "_problem", ".", "_p", ".", "params", ".", "DualReductions", "=", "0", "try", ":", "self", ".", "_problem", ".", "_p", ".", "optimize", "(", ")", "finally", ":", "self", ".", "_problem", ".", "_p", ".", "params", ".", "DualReductions", "=", "1", "status", "=", "self", ".", "_problem", ".", "_p", ".", "Status", "return", "status", "==", "gurobipy", ".", "GRB", ".", "UNBOUNDED" ]
36.5
15.9375
def entropy(string): """Compute entropy on the string""" p, lns = Counter(string), float(len(string)) return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
[ "def", "entropy", "(", "string", ")", ":", "p", ",", "lns", "=", "Counter", "(", "string", ")", ",", "float", "(", "len", "(", "string", ")", ")", "return", "-", "sum", "(", "count", "/", "lns", "*", "math", ".", "log", "(", "count", "/", "lns", ",", "2", ")", "for", "count", "in", "p", ".", "values", "(", ")", ")" ]
45.5
15.75
def first(self, **kwargs): """ Retrieve the first node from the set matching supplied parameters :param kwargs: same syntax as `filter()` :return: node """ result = result = self._get(limit=1, **kwargs) if result: return result[0] else: raise self.source_class.DoesNotExist(repr(kwargs))
[ "def", "first", "(", "self", ",", "*", "*", "kwargs", ")", ":", "result", "=", "result", "=", "self", ".", "_get", "(", "limit", "=", "1", ",", "*", "*", "kwargs", ")", "if", "result", ":", "return", "result", "[", "0", "]", "else", ":", "raise", "self", ".", "source_class", ".", "DoesNotExist", "(", "repr", "(", "kwargs", ")", ")" ]
30.416667
17.583333
def invcdf(x): """Inverse of normal cumulative density function.""" x_flat = np.ravel(x) x_trans = np.array([flib.ppnd16(y, 1) for y in x_flat]) return np.reshape(x_trans, np.shape(x))
[ "def", "invcdf", "(", "x", ")", ":", "x_flat", "=", "np", ".", "ravel", "(", "x", ")", "x_trans", "=", "np", ".", "array", "(", "[", "flib", ".", "ppnd16", "(", "y", ",", "1", ")", "for", "y", "in", "x_flat", "]", ")", "return", "np", ".", "reshape", "(", "x_trans", ",", "np", ".", "shape", "(", "x", ")", ")" ]
39.2
12.8
def gabor(image, labels, frequency, theta): '''Gabor-filter the objects in an image image - 2-d grayscale image to filter labels - a similarly shaped labels matrix frequency - cycles per trip around the circle theta - angle of the filter. 0 to 2 pi Calculate the Gabor filter centered on the centroids of each object in the image. Summing the resulting image over the labels matrix will yield a texture measure per object. ''' # # The code inscribes the X and Y position of each pixel relative to # the centroid of that pixel's object. After that, the Gabor filter # for the image can be calculated per-pixel and the image can be # multiplied by the filter to get the filtered image. # nobjects = np.max(labels) if nobjects == 0: return image centers = centers_of_labels(labels) areas = fix(scind.sum(np.ones(image.shape),labels, np.arange(nobjects, dtype=np.int32)+1)) mask = labels > 0 i,j = np.mgrid[0:image.shape[0],0:image.shape[1]].astype(float) i = i[mask] j = j[mask] image = image[mask] lm = labels[mask] - 1 i -= centers[0,lm] j -= centers[1,lm] sigma = np.sqrt(areas/np.pi) / 3.0 sigma = sigma[lm] g_exp = 1000.0/(2.0*np.pi*sigma**2) * np.exp(-(i**2 + j**2)/(2*sigma**2)) g_angle = 2*np.pi/frequency*(i*np.cos(theta)+j*np.sin(theta)) g_cos = g_exp * np.cos(g_angle) g_sin = g_exp * np.sin(g_angle) # # Normalize so that the sum of the filter over each object is zero # and so that there is no bias-value within each object. # g_cos_mean = fix(scind.mean(g_cos,lm, np.arange(nobjects))) i_mean = fix(scind.mean(image, lm, np.arange(nobjects))) i_norm = image - i_mean[lm] g_sin_mean = fix(scind.mean(g_sin,lm, np.arange(nobjects))) g_cos -= g_cos_mean[lm] g_sin -= g_sin_mean[lm] g = np.zeros(mask.shape,dtype=np.complex) g[mask] = i_norm *g_cos+i_norm * g_sin*1j return g
[ "def", "gabor", "(", "image", ",", "labels", ",", "frequency", ",", "theta", ")", ":", "#", "# The code inscribes the X and Y position of each pixel relative to", "# the centroid of that pixel's object. After that, the Gabor filter", "# for the image can be calculated per-pixel and the image can be", "# multiplied by the filter to get the filtered image.", "#", "nobjects", "=", "np", ".", "max", "(", "labels", ")", "if", "nobjects", "==", "0", ":", "return", "image", "centers", "=", "centers_of_labels", "(", "labels", ")", "areas", "=", "fix", "(", "scind", ".", "sum", "(", "np", ".", "ones", "(", "image", ".", "shape", ")", ",", "labels", ",", "np", ".", "arange", "(", "nobjects", ",", "dtype", "=", "np", ".", "int32", ")", "+", "1", ")", ")", "mask", "=", "labels", ">", "0", "i", ",", "j", "=", "np", ".", "mgrid", "[", "0", ":", "image", ".", "shape", "[", "0", "]", ",", "0", ":", "image", ".", "shape", "[", "1", "]", "]", ".", "astype", "(", "float", ")", "i", "=", "i", "[", "mask", "]", "j", "=", "j", "[", "mask", "]", "image", "=", "image", "[", "mask", "]", "lm", "=", "labels", "[", "mask", "]", "-", "1", "i", "-=", "centers", "[", "0", ",", "lm", "]", "j", "-=", "centers", "[", "1", ",", "lm", "]", "sigma", "=", "np", ".", "sqrt", "(", "areas", "/", "np", ".", "pi", ")", "/", "3.0", "sigma", "=", "sigma", "[", "lm", "]", "g_exp", "=", "1000.0", "/", "(", "2.0", "*", "np", ".", "pi", "*", "sigma", "**", "2", ")", "*", "np", ".", "exp", "(", "-", "(", "i", "**", "2", "+", "j", "**", "2", ")", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "g_angle", "=", "2", "*", "np", ".", "pi", "/", "frequency", "*", "(", "i", "*", "np", ".", "cos", "(", "theta", ")", "+", "j", "*", "np", ".", "sin", "(", "theta", ")", ")", "g_cos", "=", "g_exp", "*", "np", ".", "cos", "(", "g_angle", ")", "g_sin", "=", "g_exp", "*", "np", ".", "sin", "(", "g_angle", ")", "#", "# Normalize so that the sum of the filter over each object is zero", "# and so that there is no bias-value within each object.", "#", "g_cos_mean", "=", "fix", "(", "scind", ".", "mean", "(", "g_cos", ",", "lm", ",", "np", ".", "arange", "(", "nobjects", ")", ")", ")", "i_mean", "=", "fix", "(", "scind", ".", "mean", "(", "image", ",", "lm", ",", "np", ".", "arange", "(", "nobjects", ")", ")", ")", "i_norm", "=", "image", "-", "i_mean", "[", "lm", "]", "g_sin_mean", "=", "fix", "(", "scind", ".", "mean", "(", "g_sin", ",", "lm", ",", "np", ".", "arange", "(", "nobjects", ")", ")", ")", "g_cos", "-=", "g_cos_mean", "[", "lm", "]", "g_sin", "-=", "g_sin_mean", "[", "lm", "]", "g", "=", "np", ".", "zeros", "(", "mask", ".", "shape", ",", "dtype", "=", "np", ".", "complex", ")", "g", "[", "mask", "]", "=", "i_norm", "*", "g_cos", "+", "i_norm", "*", "g_sin", "*", "1j", "return", "g" ]
38.54
19.98
def find_importer_frame(): """Returns the outer frame importing this "end" module. If this module is being imported by other means than import statement, None is returned. Returns: A frame object or None. """ byte = lambda ch: ord(ch) if PY2 else ch frame = inspect.currentframe() try: while frame: code = frame.f_code lasti = frame.f_lasti if byte(code.co_code[lasti]) == dis.opmap['IMPORT_NAME']: # FIXME: Support EXTENDED_ARG. arg = ( byte(code.co_code[lasti + 1]) + byte(code.co_code[lasti + 2]) * 256) name = code.co_names[arg] if name == 'end': break end end frame = frame.f_back end return frame finally: del frame end
[ "def", "find_importer_frame", "(", ")", ":", "byte", "=", "lambda", "ch", ":", "ord", "(", "ch", ")", "if", "PY2", "else", "ch", "frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "while", "frame", ":", "code", "=", "frame", ".", "f_code", "lasti", "=", "frame", ".", "f_lasti", "if", "byte", "(", "code", ".", "co_code", "[", "lasti", "]", ")", "==", "dis", ".", "opmap", "[", "'IMPORT_NAME'", "]", ":", "# FIXME: Support EXTENDED_ARG.", "arg", "=", "(", "byte", "(", "code", ".", "co_code", "[", "lasti", "+", "1", "]", ")", "+", "byte", "(", "code", ".", "co_code", "[", "lasti", "+", "2", "]", ")", "*", "256", ")", "name", "=", "code", ".", "co_names", "[", "arg", "]", "if", "name", "==", "'end'", ":", "break", "end", "end", "frame", "=", "frame", ".", "f_back", "end", "return", "frame", "finally", ":", "del", "frame", "end" ]
28.290323
17.774194
def list_datastore_clusters(kwargs=None, call=None): ''' List all the datastore clusters for this VMware environment CLI Example: .. code-block:: bash salt-cloud -f list_datastore_clusters my-vmware-config ''' if call != 'function': raise SaltCloudSystemExit( 'The list_datastore_clusters function must be called with ' '-f or --function.' ) return {'Datastore Clusters': salt.utils.vmware.list_datastore_clusters(_get_si())}
[ "def", "list_datastore_clusters", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_datastore_clusters function must be called with '", "'-f or --function.'", ")", "return", "{", "'Datastore Clusters'", ":", "salt", ".", "utils", ".", "vmware", ".", "list_datastore_clusters", "(", "_get_si", "(", ")", ")", "}" ]
28.764706
27.117647
def plot_eq_cont(fignum, DIblock, color_map='coolwarm'): """ plots dec inc block as a color contour Parameters __________________ Input: fignum : figure number DIblock : nested pairs of [Declination, Inclination] color_map : matplotlib color map [default is coolwarm] Output: figure """ import random plt.figure(num=fignum) plt.axis("off") XY = [] centres = [] counter = 0 for rec in DIblock: counter = counter + 1 X = pmag.dir2cart([rec[0], rec[1], 1.]) # from Collinson 1983 R = old_div(np.sqrt(1. - X[2]), (np.sqrt(X[0]**2 + X[1]**2))) XY.append([X[0] * R, X[1] * R]) # radius of the circle radius = (old_div(3., (np.sqrt(np.pi * (9. + float(counter)))))) + 0.01 num = 2. * (old_div(1., radius)) # number of circles # a,b are the extent of the grids over which the circles are equispaced a1, a2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.)) b1, b2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.)) # this is to get an array (a list of list wont do) of x,y values xlist = np.linspace(a1, a2, int(np.ceil(num))) ylist = np.linspace(b1, b2, int(np.ceil(num))) X, Y = np.meshgrid(xlist, ylist) # to put z in the array I just multiply both x,y with zero. I will add to # the zero values later Z = X * Y * 0. # keeping the centres of the circles as a separate list instead of in # array helps later for j in range(len(ylist)): for i in range(len(xlist)): centres.append([xlist[i], ylist[j]]) # the following lines are to figure out what happens at the edges where part of a circle might lie outside # a thousand random numbers are generated within the x,y limit of the circles and tested whether it is contained in # the eq area net space....their ratio gives the fraction of circle # contained in the net fraction = [] beta, alpha = 0.001, 0.001 # to avoid those 'division by float' thingy for i in range(0, int(np.ceil(num))**2): if np.sqrt(((centres[i][0])**2) + ((centres[i][1])**2)) - 1. < radius: for j in range(1, 1000): rnd1 = random.uniform( centres[i][0] - radius, centres[i][0] + radius) rnd2 = random.uniform( centres[i][1] - radius, centres[i][1] + radius) if ((centres[i][0] - rnd1)**2 + (centres[i][1] - rnd2)**2) <= radius**2: if (rnd1**2) + (rnd2**2) < 1.: alpha = alpha + 1. beta = beta + 1. else: alpha = alpha + 1. fraction.append(old_div(alpha, beta)) alpha, beta = 0.001, 0.001 else: fraction.append(1.) # if the whole circle lies in the net # for every circle count the number of points lying in it count = 0 dotspercircle = 0. for j in range(0, int(np.ceil(num))): for i in range(0, int(np.ceil(num))): for k in range(0, counter): if (XY[k][0] - centres[count][0])**2 + (XY[k][1] - centres[count][1])**2 <= radius**2: dotspercircle += 1. Z[i][j] = Z[i][j] + (dotspercircle * fraction[count]) count += 1 dotspercircle = 0. im = plt.imshow(Z, interpolation='bilinear', origin='lower', # cmap=plt.color_map.hot, extent=(-1., 1., -1., 1.)) cmap=color_map, extent=(-1., 1., -1., 1.)) plt.colorbar(shrink=0.5) x, y = [], [] # Draws the border for i in range(0, 360): x.append(np.sin((old_div(np.pi, 180.)) * float(i))) y.append(np.cos((old_div(np.pi, 180.)) * float(i))) plt.plot(x, y, 'w-') x, y = [], [] # the map will be a square of 1X1..this is how I erase the redundant area for j in range(1, 4): for i in range(0, 360): x.append(np.sin((old_div(np.pi, 180.)) * float(i)) * (1. + (old_div(float(j), 10.)))) y.append(np.cos((old_div(np.pi, 180.)) * float(i)) * (1. + (old_div(float(j), 10.)))) plt.plot(x, y, 'w-', linewidth=26) x, y = [], [] # the axes plt.axis("equal")
[ "def", "plot_eq_cont", "(", "fignum", ",", "DIblock", ",", "color_map", "=", "'coolwarm'", ")", ":", "import", "random", "plt", ".", "figure", "(", "num", "=", "fignum", ")", "plt", ".", "axis", "(", "\"off\"", ")", "XY", "=", "[", "]", "centres", "=", "[", "]", "counter", "=", "0", "for", "rec", "in", "DIblock", ":", "counter", "=", "counter", "+", "1", "X", "=", "pmag", ".", "dir2cart", "(", "[", "rec", "[", "0", "]", ",", "rec", "[", "1", "]", ",", "1.", "]", ")", "# from Collinson 1983", "R", "=", "old_div", "(", "np", ".", "sqrt", "(", "1.", "-", "X", "[", "2", "]", ")", ",", "(", "np", ".", "sqrt", "(", "X", "[", "0", "]", "**", "2", "+", "X", "[", "1", "]", "**", "2", ")", ")", ")", "XY", ".", "append", "(", "[", "X", "[", "0", "]", "*", "R", ",", "X", "[", "1", "]", "*", "R", "]", ")", "# radius of the circle", "radius", "=", "(", "old_div", "(", "3.", ",", "(", "np", ".", "sqrt", "(", "np", ".", "pi", "*", "(", "9.", "+", "float", "(", "counter", ")", ")", ")", ")", ")", ")", "+", "0.01", "num", "=", "2.", "*", "(", "old_div", "(", "1.", ",", "radius", ")", ")", "# number of circles", "# a,b are the extent of the grids over which the circles are equispaced", "a1", ",", "a2", "=", "(", "0.", "-", "(", "radius", "*", "num", "/", "2.", ")", ")", ",", "(", "0.", "+", "(", "radius", "*", "num", "/", "2.", ")", ")", "b1", ",", "b2", "=", "(", "0.", "-", "(", "radius", "*", "num", "/", "2.", ")", ")", ",", "(", "0.", "+", "(", "radius", "*", "num", "/", "2.", ")", ")", "# this is to get an array (a list of list wont do) of x,y values", "xlist", "=", "np", ".", "linspace", "(", "a1", ",", "a2", ",", "int", "(", "np", ".", "ceil", "(", "num", ")", ")", ")", "ylist", "=", "np", ".", "linspace", "(", "b1", ",", "b2", ",", "int", "(", "np", ".", "ceil", "(", "num", ")", ")", ")", "X", ",", "Y", "=", "np", ".", "meshgrid", "(", "xlist", ",", "ylist", ")", "# to put z in the array I just multiply both x,y with zero. I will add to", "# the zero values later", "Z", "=", "X", "*", "Y", "*", "0.", "# keeping the centres of the circles as a separate list instead of in", "# array helps later", "for", "j", "in", "range", "(", "len", "(", "ylist", ")", ")", ":", "for", "i", "in", "range", "(", "len", "(", "xlist", ")", ")", ":", "centres", ".", "append", "(", "[", "xlist", "[", "i", "]", ",", "ylist", "[", "j", "]", "]", ")", "# the following lines are to figure out what happens at the edges where part of a circle might lie outside", "# a thousand random numbers are generated within the x,y limit of the circles and tested whether it is contained in", "# the eq area net space....their ratio gives the fraction of circle", "# contained in the net", "fraction", "=", "[", "]", "beta", ",", "alpha", "=", "0.001", ",", "0.001", "# to avoid those 'division by float' thingy", "for", "i", "in", "range", "(", "0", ",", "int", "(", "np", ".", "ceil", "(", "num", ")", ")", "**", "2", ")", ":", "if", "np", ".", "sqrt", "(", "(", "(", "centres", "[", "i", "]", "[", "0", "]", ")", "**", "2", ")", "+", "(", "(", "centres", "[", "i", "]", "[", "1", "]", ")", "**", "2", ")", ")", "-", "1.", "<", "radius", ":", "for", "j", "in", "range", "(", "1", ",", "1000", ")", ":", "rnd1", "=", "random", ".", "uniform", "(", "centres", "[", "i", "]", "[", "0", "]", "-", "radius", ",", "centres", "[", "i", "]", "[", "0", "]", "+", "radius", ")", "rnd2", "=", "random", ".", "uniform", "(", "centres", "[", "i", "]", "[", "1", "]", "-", "radius", ",", "centres", "[", "i", "]", "[", "1", "]", "+", "radius", ")", "if", "(", "(", "centres", "[", "i", "]", "[", "0", "]", "-", "rnd1", ")", "**", "2", "+", "(", "centres", "[", "i", "]", "[", "1", "]", "-", "rnd2", ")", "**", "2", ")", "<=", "radius", "**", "2", ":", "if", "(", "rnd1", "**", "2", ")", "+", "(", "rnd2", "**", "2", ")", "<", "1.", ":", "alpha", "=", "alpha", "+", "1.", "beta", "=", "beta", "+", "1.", "else", ":", "alpha", "=", "alpha", "+", "1.", "fraction", ".", "append", "(", "old_div", "(", "alpha", ",", "beta", ")", ")", "alpha", ",", "beta", "=", "0.001", ",", "0.001", "else", ":", "fraction", ".", "append", "(", "1.", ")", "# if the whole circle lies in the net", "# for every circle count the number of points lying in it", "count", "=", "0", "dotspercircle", "=", "0.", "for", "j", "in", "range", "(", "0", ",", "int", "(", "np", ".", "ceil", "(", "num", ")", ")", ")", ":", "for", "i", "in", "range", "(", "0", ",", "int", "(", "np", ".", "ceil", "(", "num", ")", ")", ")", ":", "for", "k", "in", "range", "(", "0", ",", "counter", ")", ":", "if", "(", "XY", "[", "k", "]", "[", "0", "]", "-", "centres", "[", "count", "]", "[", "0", "]", ")", "**", "2", "+", "(", "XY", "[", "k", "]", "[", "1", "]", "-", "centres", "[", "count", "]", "[", "1", "]", ")", "**", "2", "<=", "radius", "**", "2", ":", "dotspercircle", "+=", "1.", "Z", "[", "i", "]", "[", "j", "]", "=", "Z", "[", "i", "]", "[", "j", "]", "+", "(", "dotspercircle", "*", "fraction", "[", "count", "]", ")", "count", "+=", "1", "dotspercircle", "=", "0.", "im", "=", "plt", ".", "imshow", "(", "Z", ",", "interpolation", "=", "'bilinear'", ",", "origin", "=", "'lower'", ",", "# cmap=plt.color_map.hot, extent=(-1., 1., -1., 1.))", "cmap", "=", "color_map", ",", "extent", "=", "(", "-", "1.", ",", "1.", ",", "-", "1.", ",", "1.", ")", ")", "plt", ".", "colorbar", "(", "shrink", "=", "0.5", ")", "x", ",", "y", "=", "[", "]", ",", "[", "]", "# Draws the border", "for", "i", "in", "range", "(", "0", ",", "360", ")", ":", "x", ".", "append", "(", "np", ".", "sin", "(", "(", "old_div", "(", "np", ".", "pi", ",", "180.", ")", ")", "*", "float", "(", "i", ")", ")", ")", "y", ".", "append", "(", "np", ".", "cos", "(", "(", "old_div", "(", "np", ".", "pi", ",", "180.", ")", ")", "*", "float", "(", "i", ")", ")", ")", "plt", ".", "plot", "(", "x", ",", "y", ",", "'w-'", ")", "x", ",", "y", "=", "[", "]", ",", "[", "]", "# the map will be a square of 1X1..this is how I erase the redundant area", "for", "j", "in", "range", "(", "1", ",", "4", ")", ":", "for", "i", "in", "range", "(", "0", ",", "360", ")", ":", "x", ".", "append", "(", "np", ".", "sin", "(", "(", "old_div", "(", "np", ".", "pi", ",", "180.", ")", ")", "*", "float", "(", "i", ")", ")", "*", "(", "1.", "+", "(", "old_div", "(", "float", "(", "j", ")", ",", "10.", ")", ")", ")", ")", "y", ".", "append", "(", "np", ".", "cos", "(", "(", "old_div", "(", "np", ".", "pi", ",", "180.", ")", ")", "*", "float", "(", "i", ")", ")", "*", "(", "1.", "+", "(", "old_div", "(", "float", "(", "j", ")", ",", "10.", ")", ")", ")", ")", "plt", ".", "plot", "(", "x", ",", "y", ",", "'w-'", ",", "linewidth", "=", "26", ")", "x", ",", "y", "=", "[", "]", ",", "[", "]", "# the axes", "plt", ".", "axis", "(", "\"equal\"", ")" ]
42.606061
19.333333
def find_lexer_class(name): """Lookup a lexer class by name. Return None if not found. """ if name in _lexer_cache: return _lexer_cache[name] # lookup builtin lexers for module_name, lname, aliases, _, _ in itervalues(LEXERS): if name == lname: _load_lexers(module_name) return _lexer_cache[name] # continue with lexers from setuptools entrypoints for cls in find_plugin_lexers(): if cls.name == name: return cls
[ "def", "find_lexer_class", "(", "name", ")", ":", "if", "name", "in", "_lexer_cache", ":", "return", "_lexer_cache", "[", "name", "]", "# lookup builtin lexers", "for", "module_name", ",", "lname", ",", "aliases", ",", "_", ",", "_", "in", "itervalues", "(", "LEXERS", ")", ":", "if", "name", "==", "lname", ":", "_load_lexers", "(", "module_name", ")", "return", "_lexer_cache", "[", "name", "]", "# continue with lexers from setuptools entrypoints", "for", "cls", "in", "find_plugin_lexers", "(", ")", ":", "if", "cls", ".", "name", "==", "name", ":", "return", "cls" ]
30.625
11.8125
def is_ssl(self): """ Read-only boolean property indicating whether SSL is used for this connection. If this property is true, then all communication between this object and the Couchbase cluster is encrypted using SSL. See :meth:`__init__` for more information on connection options. """ mode = self._cntl(op=_LCB.LCB_CNTL_SSL_MODE, value_type='int') return mode & _LCB.LCB_SSL_ENABLED != 0
[ "def", "is_ssl", "(", "self", ")", ":", "mode", "=", "self", ".", "_cntl", "(", "op", "=", "_LCB", ".", "LCB_CNTL_SSL_MODE", ",", "value_type", "=", "'int'", ")", "return", "mode", "&", "_LCB", ".", "LCB_SSL_ENABLED", "!=", "0" ]
37.833333
22.5
def CLI(ctx, config, list_lookups): """Lookup basic phone number information or send SMS messages""" loglevel = 'info' verbosity = getattr(logging, loglevel.upper(), 'INFO') #verbosity = logging.DEBUG ctx.obj = { 'verbosity': verbosity, 'logfile': None, 'config': {'lookups': {}}, } #logfmt = '%(levelname)-8s | %(message)s' logfmt = '%(message)s' logging.basicConfig(format=logfmt, level=verbosity) debug('CLI > CWD="{0}"'.format(os.getcwd())) with open(CONFIG_FILE, 'ab+') as phonedb: phonedb.seek(0) rawdata = phonedb.read() if rawdata: data = json.loads(rawdata, object_pairs_hook=OrderedDict) debug(data) ctx.obj['config'] = data if 'lookups' not in ctx.obj['config']: ctx.obj['config']['lookups'] = {} if 'sms_gateways' not in ctx.obj['config']: """ gwsorted = sorted(ctx.obj['config']['sms_gateways'].items()) gwordered = OrderedDict() for (k, v) in gwsorted: gwordered[k] = v ctx.obj['config']['sms_gateways'] = gwordered """ info('loading SMS gateways...') sms_gateways = {} with open('carrier-gateways', 'rb') as gateways: gwdata = gateways.read() import re re_carrier = r'(?P<carrier>\w+[\w\&\(\)\-\'\s]*[\w\)\(]+)\s+' re_gateway = r'10digitphonenumber(?P<gateway>\@\w[\w\.]*\w)\s+' gwre = re.compile(re_carrier + re_gateway) gws = gwre.findall(gwdata) for gw in gwre.finditer(gwdata): gwinfo = gw.groupdict() debug(gw.groupdict()) sms_gateways[gwinfo['carrier']] = gwinfo['gateway'] num_lines = len([l for l in gwdata.split('\n') if len(l)]) debug('lines={0} ({1} / 2)'.format(num_lines/2, num_lines)) debug('matches={0}'.format(len(data))) ctx.obj['config']['sms_gateways'] = sms_gateways with open(CONFIG_FILE, 'wb') as cfg: cfg.write(json.dumps(ctx.obj['config'], indent=2)) info('SMS gateways written to config') if list_lookups: sms_updated = False from fuzzywuzzy import fuzz from fuzzywuzzy import process lookups = ctx.obj['config']['lookups'] info('cached lookups:') for number, pinfo in lookups.iteritems(): owner = pinfo['comment'] common = pinfo['body']['national_format'] carrier = pinfo['body']['carrier']['name'] pntype = pinfo['body']['carrier']['type'] info(' {0}: {1}'.format(owner, common)) info(' - carrier: {0}'.format(carrier)) info(' - type: {0}'.format(pntype)) debug(' - unformatted: {0}'.format(number)) if 'sms' not in lookups[number]: carriers = ctx.obj['config']['sms_gateways'].keys() fuzzy = process.extract(carrier, carriers) fuzz_max = 0 result = [] gateway_key = None for f in fuzzy: if f[1] >= fuzz_max: fuzz_max = f[1] result.append(f[0]) debug(result) if len(result) > 1: if len(sorted(result)[0]) <= len(carrier): gateway_key = sorted(result)[0] else: gateway_key = result[0] else: gateway_key = result[0] gw_suffix = ctx.obj['config']['sms_gateways'][gateway_key] ctx.obj['config']['lookups'][number]['sms'] = '{0}{1}'.format( number, gw_suffix) sms_updated = True info(' - SMS gateway: {0}'.format( ctx.obj['config']['lookups'][number]['sms'])) if sms_updated: with open(CONFIG_FILE, 'wb') as cfg: cfg.write(json.dumps(ctx.obj['config'], indent=2)) ctx.exit()
[ "def", "CLI", "(", "ctx", ",", "config", ",", "list_lookups", ")", ":", "loglevel", "=", "'info'", "verbosity", "=", "getattr", "(", "logging", ",", "loglevel", ".", "upper", "(", ")", ",", "'INFO'", ")", "#verbosity = logging.DEBUG", "ctx", ".", "obj", "=", "{", "'verbosity'", ":", "verbosity", ",", "'logfile'", ":", "None", ",", "'config'", ":", "{", "'lookups'", ":", "{", "}", "}", ",", "}", "#logfmt = '%(levelname)-8s | %(message)s'", "logfmt", "=", "'%(message)s'", "logging", ".", "basicConfig", "(", "format", "=", "logfmt", ",", "level", "=", "verbosity", ")", "debug", "(", "'CLI > CWD=\"{0}\"'", ".", "format", "(", "os", ".", "getcwd", "(", ")", ")", ")", "with", "open", "(", "CONFIG_FILE", ",", "'ab+'", ")", "as", "phonedb", ":", "phonedb", ".", "seek", "(", "0", ")", "rawdata", "=", "phonedb", ".", "read", "(", ")", "if", "rawdata", ":", "data", "=", "json", ".", "loads", "(", "rawdata", ",", "object_pairs_hook", "=", "OrderedDict", ")", "debug", "(", "data", ")", "ctx", ".", "obj", "[", "'config'", "]", "=", "data", "if", "'lookups'", "not", "in", "ctx", ".", "obj", "[", "'config'", "]", ":", "ctx", ".", "obj", "[", "'config'", "]", "[", "'lookups'", "]", "=", "{", "}", "if", "'sms_gateways'", "not", "in", "ctx", ".", "obj", "[", "'config'", "]", ":", "\"\"\"\n gwsorted = sorted(ctx.obj['config']['sms_gateways'].items())\n gwordered = OrderedDict()\n for (k, v) in gwsorted:\n gwordered[k] = v\n ctx.obj['config']['sms_gateways'] = gwordered\n \"\"\"", "info", "(", "'loading SMS gateways...'", ")", "sms_gateways", "=", "{", "}", "with", "open", "(", "'carrier-gateways'", ",", "'rb'", ")", "as", "gateways", ":", "gwdata", "=", "gateways", ".", "read", "(", ")", "import", "re", "re_carrier", "=", "r'(?P<carrier>\\w+[\\w\\&\\(\\)\\-\\'\\s]*[\\w\\)\\(]+)\\s+'", "re_gateway", "=", "r'10digitphonenumber(?P<gateway>\\@\\w[\\w\\.]*\\w)\\s+'", "gwre", "=", "re", ".", "compile", "(", "re_carrier", "+", "re_gateway", ")", "gws", "=", "gwre", ".", "findall", "(", "gwdata", ")", "for", "gw", "in", "gwre", ".", "finditer", "(", "gwdata", ")", ":", "gwinfo", "=", "gw", ".", "groupdict", "(", ")", "debug", "(", "gw", ".", "groupdict", "(", ")", ")", "sms_gateways", "[", "gwinfo", "[", "'carrier'", "]", "]", "=", "gwinfo", "[", "'gateway'", "]", "num_lines", "=", "len", "(", "[", "l", "for", "l", "in", "gwdata", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "l", ")", "]", ")", "debug", "(", "'lines={0} ({1} / 2)'", ".", "format", "(", "num_lines", "/", "2", ",", "num_lines", ")", ")", "debug", "(", "'matches={0}'", ".", "format", "(", "len", "(", "data", ")", ")", ")", "ctx", ".", "obj", "[", "'config'", "]", "[", "'sms_gateways'", "]", "=", "sms_gateways", "with", "open", "(", "CONFIG_FILE", ",", "'wb'", ")", "as", "cfg", ":", "cfg", ".", "write", "(", "json", ".", "dumps", "(", "ctx", ".", "obj", "[", "'config'", "]", ",", "indent", "=", "2", ")", ")", "info", "(", "'SMS gateways written to config'", ")", "if", "list_lookups", ":", "sms_updated", "=", "False", "from", "fuzzywuzzy", "import", "fuzz", "from", "fuzzywuzzy", "import", "process", "lookups", "=", "ctx", ".", "obj", "[", "'config'", "]", "[", "'lookups'", "]", "info", "(", "'cached lookups:'", ")", "for", "number", ",", "pinfo", "in", "lookups", ".", "iteritems", "(", ")", ":", "owner", "=", "pinfo", "[", "'comment'", "]", "common", "=", "pinfo", "[", "'body'", "]", "[", "'national_format'", "]", "carrier", "=", "pinfo", "[", "'body'", "]", "[", "'carrier'", "]", "[", "'name'", "]", "pntype", "=", "pinfo", "[", "'body'", "]", "[", "'carrier'", "]", "[", "'type'", "]", "info", "(", "' {0}: {1}'", ".", "format", "(", "owner", ",", "common", ")", ")", "info", "(", "' - carrier: {0}'", ".", "format", "(", "carrier", ")", ")", "info", "(", "' - type: {0}'", ".", "format", "(", "pntype", ")", ")", "debug", "(", "' - unformatted: {0}'", ".", "format", "(", "number", ")", ")", "if", "'sms'", "not", "in", "lookups", "[", "number", "]", ":", "carriers", "=", "ctx", ".", "obj", "[", "'config'", "]", "[", "'sms_gateways'", "]", ".", "keys", "(", ")", "fuzzy", "=", "process", ".", "extract", "(", "carrier", ",", "carriers", ")", "fuzz_max", "=", "0", "result", "=", "[", "]", "gateway_key", "=", "None", "for", "f", "in", "fuzzy", ":", "if", "f", "[", "1", "]", ">=", "fuzz_max", ":", "fuzz_max", "=", "f", "[", "1", "]", "result", ".", "append", "(", "f", "[", "0", "]", ")", "debug", "(", "result", ")", "if", "len", "(", "result", ")", ">", "1", ":", "if", "len", "(", "sorted", "(", "result", ")", "[", "0", "]", ")", "<=", "len", "(", "carrier", ")", ":", "gateway_key", "=", "sorted", "(", "result", ")", "[", "0", "]", "else", ":", "gateway_key", "=", "result", "[", "0", "]", "else", ":", "gateway_key", "=", "result", "[", "0", "]", "gw_suffix", "=", "ctx", ".", "obj", "[", "'config'", "]", "[", "'sms_gateways'", "]", "[", "gateway_key", "]", "ctx", ".", "obj", "[", "'config'", "]", "[", "'lookups'", "]", "[", "number", "]", "[", "'sms'", "]", "=", "'{0}{1}'", ".", "format", "(", "number", ",", "gw_suffix", ")", "sms_updated", "=", "True", "info", "(", "' - SMS gateway: {0}'", ".", "format", "(", "ctx", ".", "obj", "[", "'config'", "]", "[", "'lookups'", "]", "[", "number", "]", "[", "'sms'", "]", ")", ")", "if", "sms_updated", ":", "with", "open", "(", "CONFIG_FILE", ",", "'wb'", ")", "as", "cfg", ":", "cfg", ".", "write", "(", "json", ".", "dumps", "(", "ctx", ".", "obj", "[", "'config'", "]", ",", "indent", "=", "2", ")", ")", "ctx", ".", "exit", "(", ")" ]
41.666667
13.4375