text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def weave_module(module, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for "whole module weaving". .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """ if bag.has(module): return Nothing ent...
[ "def", "weave_module", "(", "module", ",", "aspect", ",", "methods", "=", "NORMAL_METHODS", ",", "lazy", "=", "False", ",", "bag", "=", "BrokenBag", ",", "*", "*", "options", ")", ":", "if", "bag", ".", "has", "(", "module", ")", ":", "return", "Noth...
44.172414
26.655172
def _opts_to_dict(*opts): '''Convert a tuple of options returned from getopt into a dictionary.''' ret = {} for key, val in opts: if key[:2] == '--': key = key[2:] elif key[:1] == '-': key = key[1:] if val == '': val = True ret[key.replace('-','_')] = val return ret
[ "def", "_opts_to_dict", "(", "*", "opts", ")", ":", "ret", "=", "{", "}", "for", "key", ",", "val", "in", "opts", ":", "if", "key", "[", ":", "2", "]", "==", "'--'", ":", "key", "=", "key", "[", "2", ":", "]", "elif", "key", "[", ":", "1", ...
23
22.5
def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2) """ len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1):...
[ "def", "pancake_sort", "(", "arr", ")", ":", "len_arr", "=", "len", "(", "arr", ")", "if", "len_arr", "<=", "1", ":", "return", "arr", "for", "cur", "in", "range", "(", "len", "(", "arr", ")", ",", "1", ",", "-", "1", ")", ":", "#Finding index of...
26.96
15.52
def send_game(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send a game. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendgame Parameters: :param ...
[ "def", "send_game", "(", "self", ",", "chat_id", ",", "game_short_name", ",", "disable_notification", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ")", ":", "from", "pytgbot", ".", "api_types", ".", "sendable", ".", ...
47.666667
34.403509
def _TypecheckFunction(function, parent_type_check_dict, stack_location, self_name): """Decorator function to collect and execute type checks.""" type_check_dict = _CollectTypeChecks(function, parent_type_check_dict, stack_location + 1, self_name) if not...
[ "def", "_TypecheckFunction", "(", "function", ",", "parent_type_check_dict", ",", "stack_location", ",", "self_name", ")", ":", "type_check_dict", "=", "_CollectTypeChecks", "(", "function", ",", "parent_type_check_dict", ",", "stack_location", "+", "1", ",", "self_na...
35.518519
18.925926
def _collapse_default(self, entry): """Collapses the list structure in entry to a single string representing the default value assigned to a variable or its dimensions. """ if isinstance(entry, tuple) or isinstance(entry, list): sets = [] i = 0 while i...
[ "def", "_collapse_default", "(", "self", ",", "entry", ")", ":", "if", "isinstance", "(", "entry", ",", "tuple", ")", "or", "isinstance", "(", "entry", ",", "list", ")", ":", "sets", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "e...
35.923077
15.333333
def fail_if_publish_binary_not_installed(binary, publish_target, install_link): """Exit (with error message) if ``binary` isn't installed""" if not shutil.which(binary): click.secho( "Publishing to {publish_target} requires {binary} to be installed and configured".format( pub...
[ "def", "fail_if_publish_binary_not_installed", "(", "binary", ",", "publish_target", ",", "install_link", ")", ":", "if", "not", "shutil", ".", "which", "(", "binary", ")", ":", "click", ".", "secho", "(", "\"Publishing to {publish_target} requires {binary} to be instal...
34.315789
22.105263
def _handle_dict_config(self, log_config): """Recursively walks and copies the `log_config` dict and searches for filenames. Translates filenames and creates directories if necessary. """ new_dict = dict() for key in log_config.keys(): if key == 'filename': ...
[ "def", "_handle_dict_config", "(", "self", ",", "log_config", ")", ":", "new_dict", "=", "dict", "(", ")", "for", "key", "in", "log_config", ".", "keys", "(", ")", ":", "if", "key", "==", "'filename'", ":", "filename", "=", "log_config", "[", "key", "]...
43.130435
14.956522
def logger(self, logger: typing.Union[logging.Logger, str, None]) -> None: """Logger instance to use as override.""" if logger is None or isinstance(logger, logging.Logger): self.__logger = logger else: self.__logger = logging.getLogger(logger)
[ "def", "logger", "(", "self", ",", "logger", ":", "typing", ".", "Union", "[", "logging", ".", "Logger", ",", "str", ",", "None", "]", ")", "->", "None", ":", "if", "logger", "is", "None", "or", "isinstance", "(", "logger", ",", "logging", ".", "Lo...
47.833333
17.333333
def etree_to_text(tree, guess_punct_space=True, guess_layout=True, newline_tags=NEWLINE_TAGS, double_newline_tags=DOUBLE_NEWLINE_TAGS): """ Convert a html tree to text. Tree should be cleaned with ``html_text.html_text.cleaner.clean_htm...
[ "def", "etree_to_text", "(", "tree", ",", "guess_punct_space", "=", "True", ",", "guess_layout", "=", "True", ",", "newline_tags", "=", "NEWLINE_TAGS", ",", "double_newline_tags", "=", "DOUBLE_NEWLINE_TAGS", ")", ":", "chunks", "=", "[", "]", "_NEWLINE", "=", ...
34.690141
16.070423
def subclasses(cls): """Return a set of all Ent subclasses, recursively.""" seen = set() queue = set([cls]) while queue: c = queue.pop() seen.add(c) sc = c.__subclasses__() for c in sc: if c not in seen: ...
[ "def", "subclasses", "(", "cls", ")", ":", "seen", "=", "set", "(", ")", "queue", "=", "set", "(", "[", "cls", "]", ")", "while", "queue", ":", "c", "=", "queue", ".", "pop", "(", ")", "seen", ".", "add", "(", "c", ")", "sc", "=", "c", ".",...
22.8125
18.5625
def adapter(data, headers, table_format=None, **kwargs): """Wrap terminaltables inside a function for TabularOutputFormatter.""" keys = ('title', ) table = table_format_handler[table_format] t = table([headers] + list(data), **filter_dict_by_key(kwargs, keys)) dimensions = terminaltables.width_an...
[ "def", "adapter", "(", "data", ",", "headers", ",", "table_format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "keys", "=", "(", "'title'", ",", ")", "table", "=", "table_format_handler", "[", "table_format", "]", "t", "=", "table", "(", "[", "h...
33.857143
20.357143
def map_sequence(stmts_in, **kwargs): """Map sequences using the SiteMapper. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to map. do_methionine_offset : boolean Whether to check for off-by-one errors in site position (possibly) attri...
[ "def", "map_sequence", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "from", "indra", ".", "preassembler", ".", "sitemapper", "import", "SiteMapper", ",", "default_site_map", "logger", ".", "info", "(", "'Mapping sites on %d statements...'", "%", "len", "(...
45.666667
19.894737
def get_mutations(study_id, gene_list, mutation_type=None, case_id=None): """Return mutations as a list of genes and list of amino acid changes. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' gene_list :...
[ "def", "get_mutations", "(", "study_id", ",", "gene_list", ",", "mutation_type", "=", "None", ",", "case_id", "=", "None", ")", ":", "genetic_profile", "=", "get_genetic_profiles", "(", "study_id", ",", "'mutation'", ")", "[", "0", "]", "gene_list_str", "=", ...
37.439024
17.121951
def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id ...
[ "def", "secgroup_delete", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The secgroup_delete function must be called with -f or --function.'", ")", "if", "kwargs", "is", "...
27.758621
25
def tendermint_version_is_compatible(running_tm_ver): """ Check Tendermint compatability with BigchainDB server :param running_tm_ver: Version number of the connected Tendermint instance :type running_tm_ver: str :return: True/False depending on the compatability with BigchainDB server :rtype: ...
[ "def", "tendermint_version_is_compatible", "(", "running_tm_ver", ")", ":", "# Splitting because version can look like this e.g. 0.22.8-40d6dc2e", "tm_ver", "=", "running_tm_ver", ".", "split", "(", "'-'", ")", "if", "not", "tm_ver", ":", "return", "False", "for", "ver", ...
33.833333
19.722222
def pre_scan(self): """ Prepare string for scanning. """ escape_re = re.compile(r'\\\n[\t ]+') self.source = escape_re.sub('', self.source)
[ "def", "pre_scan", "(", "self", ")", ":", "escape_re", "=", "re", ".", "compile", "(", "r'\\\\\\n[\\t ]+'", ")", "self", ".", "source", "=", "escape_re", ".", "sub", "(", "''", ",", "self", ".", "source", ")" ]
40
9.5
def xcorr(x, y, maxlags): """ Streamlined version of matplotlib's `xcorr`, without the plots. :param x, y: NumPy arrays to cross-correlate :param maxlags: Max number of lags; result will be `2*maxlags+1` in length """ xlen = len(x) ylen = len(y) assert xlen == ylen c = np.correlate...
[ "def", "xcorr", "(", "x", ",", "y", ",", "maxlags", ")", ":", "xlen", "=", "len", "(", "x", ")", "ylen", "=", "len", "(", "y", ")", "assert", "xlen", "==", "ylen", "c", "=", "np", ".", "correlate", "(", "x", ",", "y", ",", "mode", "=", "2",...
24.1
21.1
def jsonarrpop(self, name, path=Path.rootPath(), index=-1): """ Pops the element at ``index`` in the array JSON value under ``path`` at key ``name`` """ return self.execute_command('JSON.ARRPOP', name, str_path(path), index)
[ "def", "jsonarrpop", "(", "self", ",", "name", ",", "path", "=", "Path", ".", "rootPath", "(", ")", ",", "index", "=", "-", "1", ")", ":", "return", "self", ".", "execute_command", "(", "'JSON.ARRPOP'", ",", "name", ",", "str_path", "(", "path", ")",...
43.166667
19.5
def on_all_ok(self): """ This method is called when all tasks reach S_OK Ir runs `mrgddb` in sequential on the local machine to produce the final DDB file in the outdir of the `Work`. """ # Merge DDB files. out_ddb = self.merge_ddb_files() return self.Resu...
[ "def", "on_all_ok", "(", "self", ")", ":", "# Merge DDB files.", "out_ddb", "=", "self", ".", "merge_ddb_files", "(", ")", "return", "self", ".", "Results", "(", "node", "=", "self", ",", "returncode", "=", "0", ",", "message", "=", "\"DDB merge done\"", "...
40.666667
14.666667
def stringDecodeEntities(self, str, what, end, end2, end3): """Takes a entity string content and process to do the adequate substitutions. [67] Reference ::= EntityRef | CharRef [69] PEReference ::= '%' Name ';' """ ret = libxml2mod.xmlStringDecodeEntities(self._o, str, what, end,...
[ "def", "stringDecodeEntities", "(", "self", ",", "str", ",", "what", ",", "end", ",", "end2", ",", "end3", ")", ":", "ret", "=", "libxml2mod", ".", "xmlStringDecodeEntities", "(", "self", ".", "_o", ",", "str", ",", "what", ",", "end", ",", "end2", "...
57.666667
18.5
def to_0d_object_array(value: Any) -> np.ndarray: """Given a value, wrap it in a 0-D numpy.ndarray with dtype=object. """ result = np.empty((), dtype=object) result[()] = value return result
[ "def", "to_0d_object_array", "(", "value", ":", "Any", ")", "->", "np", ".", "ndarray", ":", "result", "=", "np", ".", "empty", "(", "(", ")", ",", "dtype", "=", "object", ")", "result", "[", "(", ")", "]", "=", "value", "return", "result" ]
34.166667
8.5
def _load_vocab_file(vocab_file, reserved_tokens=None): """Load vocabulary while ensuring reserved tokens are at the top.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS subtoken_list = [] with tf.gfile.Open(vocab_file, mode="r") as f: for line in f: subtoken = _native_to_unicode...
[ "def", "_load_vocab_file", "(", "vocab_file", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "RESERVED_TOKENS", "subtoken_list", "=", "[", "]", "with", "tf", ".", "gfile", ".", "Open", "(", ...
38.714286
14.142857
def create_css(self, fileid=None): """ Generate the final CSS string """ if fileid: rules = self._rules.get(fileid) or [] else: rules = self.rules compress = self._scss_opts.get('compress', True) if compress: sc, sp, tb, nl = F...
[ "def", "create_css", "(", "self", ",", "fileid", "=", "None", ")", ":", "if", "fileid", ":", "rules", "=", "self", ".", "_rules", ".", "get", "(", "fileid", ")", "or", "[", "]", "else", ":", "rules", "=", "self", ".", "rules", "compress", "=", "s...
31.117647
19.705882
def set_provider(self, provider_id): """Sets a provider. arg: provider_id (osid.id.Id): the new provider raise: InvalidArgument - ``provider_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``provider_id`` is ``null`` *c...
[ "def", "set_provider", "(", "self", ",", "provider_id", ")", ":", "if", "self", ".", "get_provider_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise", "errors", ".", "NoAccess", "(", ")", "if", "not", "self", ".", "_is_valid_id", "(", "prov...
40.8
15.466667
def sounds(self): """Return a dictionary of sounds recognized by Pushover and that can be used in a notification message. """ if not Pushover._SOUNDS: request = Request("get", SOUND_URL, {"token": self.token}) Pushover._SOUNDS = request.answer["sounds"] re...
[ "def", "sounds", "(", "self", ")", ":", "if", "not", "Pushover", ".", "_SOUNDS", ":", "request", "=", "Request", "(", "\"get\"", ",", "SOUND_URL", ",", "{", "\"token\"", ":", "self", ".", "token", "}", ")", "Pushover", ".", "_SOUNDS", "=", "request", ...
41.75
10.75
def resolve_dict_link(self, dct, array=None): """Convenience method for resolving links given a dict object. Extract link values and pass to the :func:`.resolve` method of this class. :param dct: (dict) Dictionary with the link data. :param array: (:class:`.Array`) Optional array resou...
[ "def", "resolve_dict_link", "(", "self", ",", "dct", ",", "array", "=", "None", ")", ":", "sys", "=", "dct", ".", "get", "(", "'sys'", ")", "return", "self", ".", "resolve", "(", "sys", "[", "'linkType'", "]", ",", "sys", "[", "'id'", "]", ",", "...
47.909091
24.545455
def _initRepository(self): """Have mercurial init the workdir as a repository (hg init) if needed. hg init will also create all needed intermediate directories. """ if self._isRepositoryReady(): return defer.succeed(None) log.msg('hgpoller: initializing working dir f...
[ "def", "_initRepository", "(", "self", ")", ":", "if", "self", ".", "_isRepositoryReady", "(", ")", ":", "return", "defer", ".", "succeed", "(", "None", ")", "log", ".", "msg", "(", "'hgpoller: initializing working dir from %s'", "%", "self", ".", "repourl", ...
46.625
16.375
def IsHuntStarted(self): """Is this hunt considered started? This method is used to check if new clients should be processed by this hunt. Note that child flow responses are always processed but new clients are not allowed to be scheduled unless the hunt is started. Returns: If a new cli...
[ "def", "IsHuntStarted", "(", "self", ")", ":", "state", "=", "self", ".", "hunt_obj", ".", "Get", "(", "self", ".", "hunt_obj", ".", "Schema", ".", "STATE", ")", "if", "state", "!=", "\"STARTED\"", ":", "return", "False", "# Stop the hunt due to expiry.", ...
26.47619
23.809524
def pfindall(path, *fnames): """Find all fnames in the closest ancestor directory. For the purposes of this function, we are our own closest ancestor. I.e. given the structure:: . `-- a |-- b | |-- c | | `-- x.txt ...
[ "def", "pfindall", "(", "path", ",", "*", "fnames", ")", ":", "wd", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "assert", "os", ".", "path", ".", "isdir", "(", "wd", ")", "def", "parents", "(", ")", ":", "\"\"\"yield successive parent d...
26.276596
19.446809
def _handle_tag_grains_refresh(self, tag, data): ''' Handle a grains_refresh event ''' if (data.get('force_refresh', False) or self.grains_cache != self.opts['grains']): self.pillar_refresh(force_refresh=True) self.grains_cache = self.opts['grains'...
[ "def", "_handle_tag_grains_refresh", "(", "self", ",", "tag", ",", "data", ")", ":", "if", "(", "data", ".", "get", "(", "'force_refresh'", ",", "False", ")", "or", "self", ".", "grains_cache", "!=", "self", ".", "opts", "[", "'grains'", "]", ")", ":",...
39.25
14.5
def next_message(self): """Block until a message(request or notification) is available. If any messages were previously enqueued, return the first in queue. If not, run the event loop until one is received. """ if self._is_running: raise Exception('Event loop already...
[ "def", "next_message", "(", "self", ")", ":", "if", "self", ".", "_is_running", ":", "raise", "Exception", "(", "'Event loop already running'", ")", "if", "self", ".", "_pending_messages", ":", "return", "self", ".", "_pending_messages", ".", "popleft", "(", "...
44.571429
16
def __GetAuthorizationTokenUsingMasterKey(verb, resource_id_or_fullname, resource_type, headers, master_key): """Gets the authorization token using `mas...
[ "def", "__GetAuthorizationTokenUsingMasterKey", "(", "verb", ",", "resource_id_or_fullname", ",", "resource_type", ",", "headers", ",", "master_key", ")", ":", "# decodes the master key which is encoded in base64 ", "key", "=", "base64", ".", "b64decode", "(", "master_ke...
38.021739
22.391304
def sens_power_board_send(self, timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp, force_mavlink1=False): ''' Mo...
[ "def", "sens_power_board_send", "(", "self", ",", "timestamp", ",", "pwr_brd_status", ",", "pwr_brd_led_status", ",", "pwr_brd_system_volt", ",", "pwr_brd_servo_volt", ",", "pwr_brd_mot_l_amp", ",", "pwr_brd_mot_r_amp", ",", "pwr_brd_servo_1_amp", ",", "pwr_brd_servo_2_amp"...
87.894737
60.736842
def configureEndpoint(self, hostName, portNumber): """ **Description** Used to configure the host name and port number the client tries to connect to. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureEndpoint("random.i...
[ "def", "configureEndpoint", "(", "self", ",", "hostName", ",", "portNumber", ")", ":", "endpoint_provider", "=", "EndpointProvider", "(", ")", "endpoint_provider", ".", "set_host", "(", "hostName", ")", "endpoint_provider", ".", "set_port", "(", "portNumber", ")",...
32.65625
28.90625
def HasStorage(self): """ Flag indicating if storage is available. Returns: bool: True if available. False otherwise. """ from neo.Core.State.ContractState import ContractPropertyState return self.ContractProperties & ContractPropertyState.HasStorage > 0
[ "def", "HasStorage", "(", "self", ")", ":", "from", "neo", ".", "Core", ".", "State", ".", "ContractState", "import", "ContractPropertyState", "return", "self", ".", "ContractProperties", "&", "ContractPropertyState", ".", "HasStorage", ">", "0" ]
34.111111
19
def _write_output_manifest(self, manifest, filestore_root): """ Adds the file path column to the manifest and writes the copy to the current directory. If the original manifest is in the current directory it is overwritten with a warning. """ output = os.path.basename(manifest) ...
[ "def", "_write_output_manifest", "(", "self", ",", "manifest", ",", "filestore_root", ")", ":", "output", "=", "os", ".", "path", ".", "basename", "(", "manifest", ")", "fieldnames", ",", "source_manifest", "=", "self", ".", "_parse_manifest", "(", "manifest",...
56.631579
21.263158
def match_blocks(hash_func, old_children, new_children): """Use difflib to find matching blocks.""" sm = difflib.SequenceMatcher( _is_junk, a=[hash_func(c) for c in old_children], b=[hash_func(c) for c in new_children], ) return sm
[ "def", "match_blocks", "(", "hash_func", ",", "old_children", ",", "new_children", ")", ":", "sm", "=", "difflib", ".", "SequenceMatcher", "(", "_is_junk", ",", "a", "=", "[", "hash_func", "(", "c", ")", "for", "c", "in", "old_children", "]", ",", "b", ...
33
15.25
def ReconcileShadow(self, store_type): """Verify that entries that claim to use shadow files have a shadow entry. If the entries of the non-shadowed file indicate that a shadow file is used, check that there is actually an entry for that file in shadow. Args: store_type: The type of password sto...
[ "def", "ReconcileShadow", "(", "self", ",", "store_type", ")", ":", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "entry", ")", ":", "if", "v", ".", "pw_entry", ".", "store", "==", "store_type", ":", "shadow_entry", "=", "self", ".", "sh...
36.764706
14.941176
def GetRelativePath(self, path_spec): """Returns the relative path based on a resolved path specification. The relative path is the location of the upper most path specification. The the location of the mount point is stripped off if relevant. Args: path_spec (PathSpec): path specification. ...
[ "def", "GetRelativePath", "(", "self", ",", "path_spec", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "if", "location", "is", "None", ":", "raise", "errors", ".", "PathSpecError", "(", "'Path specification missin...
37.136364
21.522727
def prune_empty_node(node, seen): """ Recursively remove empty branches and return whether this makes the node itself empty. The ``seen`` parameter is used to avoid infinite recursion due to cycles (you never know). """ if node.methods: return False if id(node) in seen: ...
[ "def", "prune_empty_node", "(", "node", ",", "seen", ")", ":", "if", "node", ".", "methods", ":", "return", "False", "if", "id", "(", "node", ")", "in", "seen", ":", "return", "True", "seen", "=", "seen", "|", "{", "id", "(", "node", ")", "}", "f...
27.368421
16.947368
def get_arp_table(self): """ Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) For example:: [ { ...
[ "def", "get_arp_table", "(", "self", ")", ":", "arp_table", "=", "[", "]", "command", "=", "'show arp | exclude Incomplete'", "output", "=", "self", ".", "_send_command", "(", "command", ")", "# Skip the first line which is a header", "output", "=", "output", ".", ...
34.367647
18.279412
def _split_field_list(field_list): """Split the list of fields for which to extract values into lists by extraction methods. - Remove any duplicated field names. - Raises ValueError with list of any invalid field names in ``field_list``. """ lookup_dict = {} generate_dict = {} for fie...
[ "def", "_split_field_list", "(", "field_list", ")", ":", "lookup_dict", "=", "{", "}", "generate_dict", "=", "{", "}", "for", "field_name", "in", "field_list", "or", "FIELD_NAME_TO_EXTRACT_DICT", ".", "keys", "(", ")", ":", "try", ":", "extract_dict", "=", "...
32.130435
20.26087
def center(a: Union[Set["Point2"], List["Point2"]]) -> "Point2": """ Returns the central point for points in list """ s = Point2((0, 0)) for p in a: s += p return s / len(a)
[ "def", "center", "(", "a", ":", "Union", "[", "Set", "[", "\"Point2\"", "]", ",", "List", "[", "\"Point2\"", "]", "]", ")", "->", "\"Point2\"", ":", "s", "=", "Point2", "(", "(", "0", ",", "0", ")", ")", "for", "p", "in", "a", ":", "s", "+=",...
35.333333
16
def resolve_parent_registry_name(self, registry_name, suffix): """ Subclasses should override to specify the default suffix, as the invocation is done without a suffix. """ if not registry_name.endswith(suffix): raise ValueError( "child module registr...
[ "def", "resolve_parent_registry_name", "(", "self", ",", "registry_name", ",", "suffix", ")", ":", "if", "not", "registry_name", ".", "endswith", "(", "suffix", ")", ":", "raise", "ValueError", "(", "\"child module registry name defined with invalid suffix \"", "\"('%s'...
42.272727
16.818182
def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ if not pid: pid = os.getpid() processes = dict(_iter_process()) def check_parent(pid, lvl=0): ppid = processes[pid].get('parent_pid') shell_name = _get_executable(p...
[ "def", "get_shell", "(", "pid", "=", "None", ",", "max_depth", "=", "6", ")", ":", "if", "not", "pid", ":", "pid", "=", "os", ".", "getpid", "(", ")", "processes", "=", "dict", "(", "_iter_process", "(", ")", ")", "def", "check_parent", "(", "pid",...
32.478261
14.521739
def accept(self): """Accept the option. Returns ------- an awaitable of :class:`IssueResult` """ return self._issue._nation._accept_issue(self._issue.id, self._id)
[ "def", "accept", "(", "self", ")", ":", "return", "self", ".", "_issue", ".", "_nation", ".", "_accept_issue", "(", "self", ".", "_issue", ".", "id", ",", "self", ".", "_id", ")" ]
25.625
18.875
def timeline(self, timeline="home", max_id=None, min_id=None, since_id=None, limit=None): """ Fetch statuses, most recent ones first. `timeline` can be 'home', 'local', 'public', 'tag/hashtag' or 'list/id'. See the following functions documentation for what those do. Local hashtag timeli...
[ "def", "timeline", "(", "self", ",", "timeline", "=", "\"home\"", ",", "max_id", "=", "None", ",", "min_id", "=", "None", ",", "since_id", "=", "None", ",", "limit", "=", "None", ")", ":", "if", "max_id", "!=", "None", ":", "max_id", "=", "self", "...
38.333333
23.533333
def make_butterworth_bandpass_b_a(CenterFreq, bandwidth, SampleFreq, order=5, btype='band'): """ Generates the b and a coefficients for a butterworth bandpass IIR filter. Parameters ---------- CenterFreq : float central frequency of bandpass bandwidth : float width of the bandpa...
[ "def", "make_butterworth_bandpass_b_a", "(", "CenterFreq", ",", "bandwidth", ",", "SampleFreq", ",", "order", "=", "5", ",", "btype", "=", "'band'", ")", ":", "lowcut", "=", "CenterFreq", "-", "bandwidth", "/", "2", "highcut", "=", "CenterFreq", "+", "bandwi...
32.928571
21.214286
def main(): """Create and use a logger.""" formatter = ColoredFormatter(log_colors={'TRACE': 'yellow'}) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger('example') logger.addHandler(handler) logger.setLevel('TRACE') logger.log(5, 'a message ...
[ "def", "main", "(", ")", ":", "formatter", "=", "ColoredFormatter", "(", "log_colors", "=", "{", "'TRACE'", ":", "'yellow'", "}", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "formatter", ")", "logger...
27.583333
17.916667
def from_dict(cls, d): """ Convert a dictionary into an xarray.Dataset. Input dict can take several forms:: d = {'t': {'dims': ('t'), 'data': t}, 'a': {'dims': ('t'), 'data': x}, 'b': {'dims': ('t'), 'data': y}} d = {'coords': {'t': {'...
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "if", "not", "set", "(", "[", "'coords'", ",", "'data_vars'", "]", ")", ".", "issubset", "(", "set", "(", "d", ")", ")", ":", "variables", "=", "d", ".", "items", "(", ")", "else", ":", "impor...
34.483333
21.65
def get_extract_method(path): """Returns `ExtractMethod` to use on resource at path. Cannot be None.""" info_path = _get_info_path(path) info = _read_info(info_path) fname = info.get('original_fname', path) if info else path return _guess_extract_method(fname)
[ "def", "get_extract_method", "(", "path", ")", ":", "info_path", "=", "_get_info_path", "(", "path", ")", "info", "=", "_read_info", "(", "info_path", ")", "fname", "=", "info", ".", "get", "(", "'original_fname'", ",", "path", ")", "if", "info", "else", ...
44.166667
8.333333
def decodeTagAttributes(self, text): """docstring for decodeTagAttributes""" attribs = {} if text.strip() == u'': return attribs scanner = _attributePat.scanner(text) match = scanner.search() while match: key, val1, val2, val3, val4 = match.groups() value = val1 or val2 or val3 or val4 if value:...
[ "def", "decodeTagAttributes", "(", "self", ",", "text", ")", ":", "attribs", "=", "{", "}", "if", "text", ".", "strip", "(", ")", "==", "u''", ":", "return", "attribs", "scanner", "=", "_attributePat", ".", "scanner", "(", "text", ")", "match", "=", ...
26
16.277778
def _AppendRecord(self): """Adds current record to result if well formed.""" # If no Values then don't output. if not self.values: return cur_record = [] for value in self.values: try: value.OnSaveRecord() except SkipRecord: self._ClearRecord() return ...
[ "def", "_AppendRecord", "(", "self", ")", ":", "# If no Values then don't output.", "if", "not", "self", ".", "values", ":", "return", "cur_record", "=", "[", "]", "for", "value", "in", "self", ".", "values", ":", "try", ":", "value", ".", "OnSaveRecord", ...
25.433333
20.866667
def lock_retention_policy(self, client=None): """Lock the bucket's retention policy. :raises ValueError: if the bucket has no metageneration (i.e., new or never reloaded); if the bucket has no retention policy assigned; if the bucket's retention policy is already loc...
[ "def", "lock_retention_policy", "(", "self", ",", "client", "=", "None", ")", ":", "if", "\"metageneration\"", "not", "in", "self", ".", "_properties", ":", "raise", "ValueError", "(", "\"Bucket has no retention policy assigned: try 'reload'?\"", ")", "policy", "=", ...
38.967742
24.483871
def templates_for_device(request, templates): """ Given a template name (or list of them), returns the template names as a list, with each name prefixed with the device directory inserted before it's associate default in the list. """ from yacms.conf import settings if not isinstance(templat...
[ "def", "templates_for_device", "(", "request", ",", "templates", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "if", "not", "isinstance", "(", "templates", ",", "(", "list", ",", "tuple", ")", ")", ":", "templates", "=", "[", "templates", ...
41.789474
13.052632
def scatter_norrec(self, filename=None, individual=False): """Create a scatter plot for all diff pairs Parameters ---------- filename : string, optional if given, save plot to file individual : bool, optional if set to True, return one figure for each ro...
[ "def", "scatter_norrec", "(", "self", ",", "filename", "=", "None", ",", "individual", "=", "False", ")", ":", "# if not otherwise specified, use these column pairs:", "std_diff_labels", "=", "{", "'r'", ":", "'rdiff'", ",", "'rpha'", ":", "'rphadiff'", ",", "}", ...
31.460526
16.039474
def _merge_command(run, full_result, offset, result): """Merge a write command result into the full bulk result. """ affected = result.get("n", 0) if run.op_type == _INSERT: full_result["nInserted"] += affected elif run.op_type == _DELETE: full_result["nRemoved"] += affected e...
[ "def", "_merge_command", "(", "run", ",", "full_result", ",", "offset", ",", "result", ")", ":", "affected", "=", "result", ".", "get", "(", "\"n\"", ",", "0", ")", "if", "run", ".", "op_type", "==", "_INSERT", ":", "full_result", "[", "\"nInserted\"", ...
35.973684
14.526316
def activityrequest(self, event): """ActivityMonitor event handler for incoming events :param event with incoming ActivityMonitor message """ # self.log("Event: '%s'" % event.__dict__) try: action = event.action data = event.data self.log("A...
[ "def", "activityrequest", "(", "self", ",", "event", ")", ":", "# self.log(\"Event: '%s'\" % event.__dict__)", "try", ":", "action", "=", "event", ".", "action", "data", "=", "event", ".", "data", "self", ".", "log", "(", "\"Activityrequest: \"", ",", "action", ...
29
19.333333
def convert_pointSource(self, node): """ Convert the given node into a point source object. :param node: a node with tag pointGeometry :returns: a :class:`openquake.hazardlib.source.PointSource` instance """ geom = node.pointGeometry lon_lat = ~geom.Point.pos ...
[ "def", "convert_pointSource", "(", "self", ",", "node", ")", ":", "geom", "=", "node", ".", "pointGeometry", "lon_lat", "=", "~", "geom", ".", "Point", ".", "pos", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ...
44.375
13.541667
def get_first_name_last_name(self): """ :rtype: str """ names = [] if self._get_first_names(): names += self._get_first_names() if self._get_additional_names(): names += self._get_additional_names() if self._get_last_names(): na...
[ "def", "get_first_name_last_name", "(", "self", ")", ":", "names", "=", "[", "]", "if", "self", ".", "_get_first_names", "(", ")", ":", "names", "+=", "self", ".", "_get_first_names", "(", ")", "if", "self", ".", "_get_additional_names", "(", ")", ":", "...
30.733333
9.266667
def mv_normal_cov_like(x, mu, C): R""" Multivariate normal log-likelihood parameterized by a covariance matrix. .. math:: f(x \mid \pi, C) = \frac{1}{(2\pi|C|)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}C^{-1}(x-\mu) \right\} :Parameters: - `x` : (n,k) - `mu` : (k) Locatio...
[ "def", "mv_normal_cov_like", "(", "x", ",", "mu", ",", "C", ")", ":", "# TODO: Vectorize in Fortran", "if", "len", "(", "np", ".", "shape", "(", "x", ")", ")", ">", "1", ":", "return", "np", ".", "sum", "(", "[", "flib", ".", "cov_mvnorm", "(", "r"...
29.666667
23.333333
def healpix_to_lonlat(self, healpix_index, dx=None, dy=None): """ Convert HEALPix indices (optionally with offsets) to longitudes/latitudes Parameters ---------- healpix_index : `~numpy.ndarray` 1-D array of HEALPix indices dx, dy : `~numpy.ndarray`, optional...
[ "def", "healpix_to_lonlat", "(", "self", ",", "healpix_index", ",", "dx", "=", "None", ",", "dy", "=", "None", ")", ":", "return", "healpix_to_lonlat", "(", "healpix_index", ",", "self", ".", "nside", ",", "dx", "=", "dx", ",", "dy", "=", "dy", ",", ...
39.809524
20.761905
def list_results(context, id, sort, limit): """list_result(context, id) List all job results. >>> dcictl job-results [OPTIONS] :param string id: ID of the job to consult result for [required] :param string sort: Field to apply sort :param integer limit: Max number of rows to return """ ...
[ "def", "list_results", "(", "context", ",", "id", ",", "sort", ",", "limit", ")", ":", "headers", "=", "[", "'filename'", ",", "'name'", ",", "'total'", ",", "'success'", ",", "'failures'", ",", "'errors'", ",", "'skips'", ",", "'time'", "]", "result", ...
33.6875
19.8125
def fixed_legend_position(self, fixed_legend_position): """Sets the fixed_legend_position of this ChartSettings. Where the fixed legend should be displayed with respect to the chart # noqa: E501 :param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501 ...
[ "def", "fixed_legend_position", "(", "self", ",", "fixed_legend_position", ")", ":", "allowed_values", "=", "[", "\"RIGHT\"", ",", "\"TOP\"", ",", "\"LEFT\"", ",", "\"BOTTOM\"", "]", "# noqa: E501", "if", "fixed_legend_position", "not", "in", "allowed_values", ":", ...
45.5
28.3125
def get_packages(self, offset=None, limit=None, api=None): """ Return list of packages that belong to this automation :param offset: Pagination offset. :param limit: Pagination limit. :param api: sevenbridges Api instance. :return: AutomationPackage collection """...
[ "def", "get_packages", "(", "self", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "api", "=", "None", ")", ":", "api", "=", "api", "or", "self", ".", "_API", "return", "AutomationPackage", ".", "query", "(", "automation", "=", "self", "...
38.166667
10.166667
def _aspirate_plunger_position(self, ul): """Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required """ m...
[ "def", "_aspirate_plunger_position", "(", "self", ",", "ul", ")", ":", "millimeters", "=", "ul", "/", "self", ".", "_ul_per_mm", "(", "ul", ",", "'aspirate'", ")", "destination_mm", "=", "self", ".", "_get_plunger_position", "(", "'bottom'", ")", "+", "milli...
43.181818
18.636364
def _FlagIsRegistered(self, flag_obj): """Checks whether a Flag object is registered under long name or short name. Args: flag_obj: A Flag object. Returns: A boolean: True iff flag_obj is registered under long name or short name. """ flag_dict = self.FlagDict() # Check whether flag...
[ "def", "_FlagIsRegistered", "(", "self", ",", "flag_obj", ")", ":", "flag_dict", "=", "self", ".", "FlagDict", "(", ")", "# Check whether flag_obj is registered under its long name.", "name", "=", "flag_obj", ".", "name", "if", "flag_dict", ".", "get", "(", "name"...
32.75
18
def streamer(frontend, backend): """Simple push/pull streamer :param int frontend: fontend zeromq port :param int backend: backend zeromq port """ try: context = zmq.Context() front_pull = context.socket(zmq.PULL) front_pull.set_hwm(0) front_pull.bind("tcp://*:%d" %...
[ "def", "streamer", "(", "frontend", ",", "backend", ")", ":", "try", ":", "context", "=", "zmq", ".", "Context", "(", ")", "front_pull", "=", "context", ".", "socket", "(", "zmq", ".", "PULL", ")", "front_pull", ".", "set_hwm", "(", "0", ")", "front_...
28.125
17.583333
def interface(cls): ''' Marks the decorated class as an abstract interface. Injects following classmethods: .. py:method:: .all(context) Returns a list of instances of each component in the ``context`` implementing this ``@interface`` :param context: context to look in ...
[ "def", "interface", "(", "cls", ")", ":", "if", "not", "cls", ":", "return", "None", "cls", ".", "implementations", "=", "[", "]", "# Inject methods", "def", "_all", "(", "cls", ",", "context", ",", "ignore_exceptions", "=", "False", ")", ":", "return", ...
27.075472
24.622642
def parse(self): """ Reads all lines from the current data source and yields each FileResult objects """ if self.data is None: raise ValueError('No input data provided, unable to parse') for line in self.data: parts = line.strip().split() try...
[ "def", "parse", "(", "self", ")", ":", "if", "self", ".", "data", "is", "None", ":", "raise", "ValueError", "(", "'No input data provided, unable to parse'", ")", "for", "line", "in", "self", ".", "data", ":", "parts", "=", "line", ".", "strip", "(", ")"...
30.21875
17.15625
def find_by_field(self, table, field, field_value): ''' 从数据库里查询指定条件的记录 Args: table: 表名字 str field: 字段名 field_value: 字段值 return: 成功: [dict] 保存的记录 失败: -1 并打印返回报错信息 ''' sql = "select * from {} where {} = '{}'".forma...
[ "def", "find_by_field", "(", "self", ",", "table", ",", "field", ",", "field_value", ")", ":", "sql", "=", "\"select * from {} where {} = '{}'\"", ".", "format", "(", "table", ",", "field", ",", "field_value", ")", "res", "=", "self", ".", "query", "(", "s...
26.4
17.2
def _prepare_base_image(self): """ I am a private method for creating (possibly cheap) copies of a base_image for start_instance to boot. """ if not self.base_image: return defer.succeed(True) if self.cheap_copy: clone_cmd = "qemu-img" ...
[ "def", "_prepare_base_image", "(", "self", ")", ":", "if", "not", "self", ".", "base_image", ":", "return", "defer", ".", "succeed", "(", "True", ")", "if", "self", ".", "cheap_copy", ":", "clone_cmd", "=", "\"qemu-img\"", "clone_args", "=", "\"create -b %(b...
27.457143
19.4
def login_with_password(self, username, password, limit=10): """Deprecated. Use ``login`` with ``sync=True``. Login to the homeserver. Args: username (str): Account username password (str): Account password limit (int): Deprecated. How many messages to retur...
[ "def", "login_with_password", "(", "self", ",", "username", ",", "password", ",", "limit", "=", "10", ")", ":", "warn", "(", "\"login_with_password is deprecated. Use login with sync=True.\"", ",", "DeprecationWarning", ")", "return", "self", ".", "login", "(", "use...
33.6
21.55
def besttype(x): """Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. .. Note:: Strings will be returned as Unicode strings (using :func:`to_unicode`). ...
[ "def", "besttype", "(", "x", ")", ":", "x", "=", "to_unicode", "(", "x", ")", "# make unicode as soon as possible", "try", ":", "x", "=", "x", ".", "strip", "(", ")", "except", "AttributeError", ":", "pass", "m", "=", "re", ".", "match", "(", "r\"\"\"[...
30.166667
21.033333
def limit(self, max_): """ Limit the result set to a given number of items. :param max_: Maximum number of items to return. :type max_: :class:`int` or :data:`None` :rtype: :class:`ResultSetMetadata` :return: A new request set up to request at most `max_` items. ...
[ "def", "limit", "(", "self", ",", "max_", ")", ":", "if", "isinstance", "(", "self", ",", "type", ")", ":", "result", "=", "self", "(", ")", "else", ":", "result", "=", "copy", ".", "deepcopy", "(", "self", ")", "result", ".", "max_", "=", "max_"...
35.095238
18.809524
def Calls(self, conditions=None): """Find the methods that evaluate data that meets this condition. Args: conditions: A tuple of (artifact, os_name, cpe, label) Returns: A list of methods that evaluate the data. """ results = set() if conditions is None: conditions = [None] ...
[ "def", "Calls", "(", "self", ",", "conditions", "=", "None", ")", ":", "results", "=", "set", "(", ")", "if", "conditions", "is", "None", ":", "conditions", "=", "[", "None", "]", "for", "condition", "in", "conditions", ":", "for", "c", "in", "self",...
27.75
16.5
def arc_distance(theta_1, phi_1, theta_2, phi_2): """ Calculates the pairwise arc distance between all points in vector a and b. """ temp = np.sin((theta_2-theta_1)/2)**2+np.cos(theta_1)*np.cos(theta_2)*np.sin((phi_2-phi_1)/2)**2 distance_matrix = 2 * (np.arctan2(np.sqrt(temp)...
[ "def", "arc_distance", "(", "theta_1", ",", "phi_1", ",", "theta_2", ",", "phi_2", ")", ":", "temp", "=", "np", ".", "sin", "(", "(", "theta_2", "-", "theta_1", ")", "/", "2", ")", "**", "2", "+", "np", ".", "cos", "(", "theta_1", ")", "*", "np...
44.75
18.75
def url(self): ''' Because invoice URLs are generally emailed, this includes the default site URL and the protocol specified in settings. ''' if self.id: return '%s://%s%s' % ( getConstant('email__linkProtocol'), Site.objects.ge...
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "id", ":", "return", "'%s://%s%s'", "%", "(", "getConstant", "(", "'email__linkProtocol'", ")", ",", "Site", ".", "objects", ".", "get_current", "(", ")", ".", "domain", ",", "reverse", "(", "'vie...
33.25
20.083333
def detectType(option, urlOrPaths, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar, responseMimeType='text/plain', services={'type': '/detect/stream'}): ''' Detect the MIME/media type of the stream and return it in text/plain. :param option: :pa...
[ "def", "detectType", "(", "option", ",", "urlOrPaths", ",", "serverEndpoint", "=", "ServerEndpoint", ",", "verbose", "=", "Verbose", ",", "tikaServerJar", "=", "TikaServerJar", ",", "responseMimeType", "=", "'text/plain'", ",", "services", "=", "{", "'type'", ":...
37.294118
24.705882
def _encrypt(self, archive): """Encrypts the compressed archive using GPG. If encryption fails for any reason, it should be logged by sos but not cause execution to stop. The assumption is that the unencrypted archive would still be of use to the user, and/or that the end user has anoth...
[ "def", "_encrypt", "(", "self", ",", "archive", ")", ":", "arc_name", "=", "archive", ".", "replace", "(", "\"sosreport-\"", ",", "\"secured-sosreport-\"", ")", "arc_name", "+=", "\".gpg\"", "enc_cmd", "=", "\"gpg --batch -o %s \"", "%", "arc_name", "env", "=", ...
45.880952
20.071429
def _load_client_secrets(filename): """Loads client secrets from the given filename. Args: filename: The name of the file containing the JSON secret key. Returns: A 2-tuple, the first item containing the client id, and the second item containing a client secret. """ client_...
[ "def", "_load_client_secrets", "(", "filename", ")", ":", "client_type", ",", "client_info", "=", "clientsecrets", ".", "loadfile", "(", "filename", ")", "if", "client_type", "!=", "clientsecrets", ".", "TYPE_WEB", ":", "raise", "ValueError", "(", "'The flow speci...
36.823529
21.470588
def delete_peer(self, name, peer_type="REPLICATION"): """ Delete a replication peer. @param name: The name of the peer. @param peer_type: Added in v11. The type of the peer. Defaults to 'REPLICATION'. @return: The deleted peer. @since: API v3 """ params = self._get_peer_type_param(peer_...
[ "def", "delete_peer", "(", "self", ",", "name", ",", "peer_type", "=", "\"REPLICATION\"", ")", ":", "params", "=", "self", ".", "_get_peer_type_param", "(", "peer_type", ")", "return", "self", ".", "_delete", "(", "\"peers/\"", "+", "name", ",", "ApiCmPeer",...
36.090909
17.363636
def get_pe(self): """Get the Streams processing element this operator is executing in. Returns: PE: Processing element for this operator. .. versionadded:: 1.9 """ return PE(self.rest_client.make_request(self.pe), self.rest_client)
[ "def", "get_pe", "(", "self", ")", ":", "return", "PE", "(", "self", ".", "rest_client", ".", "make_request", "(", "self", ".", "pe", ")", ",", "self", ".", "rest_client", ")" ]
30.777778
20.666667
def find_cycle(graph): """find a cycle in an undirected graph :param graph: undirected graph in listlist or listdict format :returns: list of vertices in a cycle or None :complexity: `O(|V|+|E|)` """ n = len(graph) prec = [None] * n # ancestor marks for visited vertices for u in range(...
[ "def", "find_cycle", "(", "graph", ")", ":", "n", "=", "len", "(", "graph", ")", "prec", "=", "[", "None", "]", "*", "n", "# ancestor marks for visited vertices", "for", "u", "in", "range", "(", "n", ")", ":", "if", "prec", "[", "u", "]", "is", "No...
42.222222
16.925926
def handle_err(*args): """ Handle fatal errors, caught in __main__ scope. If DEBUG is set, print a real traceback. Otherwise, `print_err` any arguments passed. """ if DEBUG: print_err(traceback.format_exc(), color=False) else: print_err(*args, newline=True)
[ "def", "handle_err", "(", "*", "args", ")", ":", "if", "DEBUG", ":", "print_err", "(", "traceback", ".", "format_exc", "(", ")", ",", "color", "=", "False", ")", "else", ":", "print_err", "(", "*", "args", ",", "newline", "=", "True", ")" ]
33
12.444444
def map(self, map_fn, name="Map"): """Applies a map operator to the stream. Attributes: map_fn (function): The user-defined logic of the map. """ op = Operator( _generate_uuid(), OpType.Map, name, map_fn, num_insta...
[ "def", "map", "(", "self", ",", "map_fn", ",", "name", "=", "\"Map\"", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "Map", ",", "name", ",", "map_fn", ",", "num_instances", "=", "self", ".", "env", ".", "con...
28.923077
15.615385
def compute_step(self, state, lstm_cell=None, input=None, additional_inputs=None): """ Compute one step in the RNN. :return: one variable for RNN and GRU, multiple variables for LSTM """ if not self.initialized: input_dim = None if input and hasattr(input....
[ "def", "compute_step", "(", "self", ",", "state", ",", "lstm_cell", "=", "None", ",", "input", "=", "None", ",", "additional_inputs", "=", "None", ")", ":", "if", "not", "self", ".", "initialized", ":", "input_dim", "=", "None", "if", "input", "and", "...
39.409091
15.409091
def _selectionParameters(self, param): """see docstring for selectedParameterTypes""" components = param['selection'] if len(components) == 0: return [] # extract the selected component names editable_sets = [] for comp in components: # all the key...
[ "def", "_selectionParameters", "(", "self", ",", "param", ")", ":", "components", "=", "param", "[", "'selection'", "]", "if", "len", "(", "components", ")", "==", "0", ":", "return", "[", "]", "# extract the selected component names", "editable_sets", "=", "[...
44.857143
11.571429
def gfrfov(inst, raydir, rframe, abcorr, obsrvr, step, cnfine, result=None): """ Determine time intervals when a specified ray intersects the space bounded by the field-of-view (FOV) of a specified instrument. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrfov_c.html :param inst: N...
[ "def", "gfrfov", "(", "inst", ",", "raydir", ",", "rframe", ",", "abcorr", ",", "obsrvr", ",", "step", ",", "cnfine", ",", "result", "=", "None", ")", ":", "assert", "isinstance", "(", "cnfine", ",", "stypes", ".", "SpiceCell", ")", "assert", "cnfine",...
39
15.390244
def registerDisplay(func): """ Registers a function to the display hook queue to be called on hook. Look at the sys.displayhook documentation for more information. :param func | <callable> """ setup() ref = weakref.ref(func) if ref not in _displayhooks: _displayhooks.ap...
[ "def", "registerDisplay", "(", "func", ")", ":", "setup", "(", ")", "ref", "=", "weakref", ".", "ref", "(", "func", ")", "if", "ref", "not", "in", "_displayhooks", ":", "_displayhooks", ".", "append", "(", "ref", ")" ]
29
15.727273
def to_sax(walker, handler): """Call SAX-like content handler based on treewalker walker :arg walker: the treewalker to use to walk the tree to convert it :arg handler: SAX handler to use """ handler.startDocument() for prefix, namespace in prefix_mapping.items(): handler.startPrefixM...
[ "def", "to_sax", "(", "walker", ",", "handler", ")", ":", "handler", ".", "startDocument", "(", ")", "for", "prefix", ",", "namespace", "in", "prefix_mapping", ".", "items", "(", ")", ":", "handler", ".", "startPrefixMapping", "(", "prefix", ",", "namespac...
36.421053
16.631579
def InstrumentsCandlesFactory(instrument, params=None): """InstrumentsCandlesFactory - generate InstrumentCandles requests. InstrumentsCandlesFactory is used to retrieve historical data by automatically generating consecutive requests when the OANDA limit of *count* records is exceeded. This is kn...
[ "def", "InstrumentsCandlesFactory", "(", "instrument", ",", "params", "=", "None", ")", ":", "RFC3339", "=", "\"%Y-%m-%dT%H:%M:%SZ\"", "# if not specified use the default of 'S5' as OANDA does", "gs", "=", "granularity_to_time", "(", "params", ".", "get", "(", "'granulari...
37.547009
22.82906
def JTl(self): r'''Joule Thomson coefficient of the chemical in the liquid phase at its current temperature and pressure, in units of [K/Pa]. .. math:: \mu_{JT} = \left(\frac{\partial T}{\partial P}\right)_H = \frac{1}{C_p} \left[T \left(\frac{\partial V}{\partial T}\rig...
[ "def", "JTl", "(", "self", ")", ":", "Vml", ",", "Cplm", ",", "isobaric_expansion_l", "=", "self", ".", "Vml", ",", "self", ".", "Cplm", ",", "self", ".", "isobaric_expansion_l", "if", "all", "(", "(", "Vml", ",", "Cplm", ",", "isobaric_expansion_l", "...
43.73913
27.73913
def parse_coverage_args(argv): """ Parse command line arguments, returning a dict of valid options: { 'coverage_xml': COVERAGE_XML, 'html_report': None | HTML_REPORT, 'external_css_file': None | CSS_FILE, } where `COVERAGE_XML`, `HTML_REPORT`, and `C...
[ "def", "parse_coverage_args", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "DESCRIPTION", ")", "parser", ".", "add_argument", "(", "'coverage_xml'", ",", "type", "=", "str", ",", "help", "=", "COVERAGE_XML_H...
20.465909
20.806818
async def getHealth(self, *args, **kwargs): """ Get EC2 account health metrics Give some basic stats on the health of our EC2 account This method gives output: ``v1/health.json#`` This method is ``experimental`` """ return await self._makeApiCall(self.funcinfo...
[ "async", "def", "getHealth", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"getHealth\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
28.333333
20.333333
def glob_config(pattern, *search_dirs): """Return glob results for all possible configuration locations. Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory. This is done for performance since this is usually used to find *all* configs for a cert...
[ "def", "glob_config", "(", "pattern", ",", "*", "search_dirs", ")", ":", "patterns", "=", "config_search_paths", "(", "pattern", ",", "*", "search_dirs", ",", "check_exists", "=", "False", ")", "for", "pattern", "in", "patterns", ":", "for", "path", "in", ...
45.818182
26.454545
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): ''' Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=adm...
[ "def", "endpoint_get", "(", "service", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "interface", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "services", "=", "...
38.655172
26.172414
def epcr_threads(self, formattedprimers, ampliconsize=10000): """ Run ePCR in a multi-threaded fashion """ # Create the threads for the ePCR analysis for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': threads = Thread(target=self....
[ "def", "epcr_threads", "(", "self", ",", "formattedprimers", ",", "ampliconsize", "=", "10000", ")", ":", "# Create the threads for the ePCR analysis", "for", "sample", "in", "self", ".", "metadata", ":", "if", "sample", ".", "general", ".", "bestassemblyfile", "!...
59.46
22.7
def isoutside(coords, shape): r""" Identifies points that lie outside the specified region. Parameters ---------- domain_size : array_like The size and shape of the domain beyond which points should be trimmed. The argument is treated as follows: **sphere** : If a scalar or...
[ "def", "isoutside", "(", "coords", ",", "shape", ")", ":", "# Label external pores for trimming below", "if", "len", "(", "shape", ")", "==", "1", ":", "# Spherical", "# Find external points", "r", "=", "sp", ".", "sqrt", "(", "sp", ".", "sum", "(", "coords"...
33.833333
18.888889