text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _ibis_sqlite_regex_extract(string, pattern, index): """Extract match of regular expression `pattern` from `string` at `index`. Parameters ---------- string : str pattern : str index : int Returns ------- result : str or None """ result = re.search(pattern, string) i...
[ "def", "_ibis_sqlite_regex_extract", "(", "string", ",", "pattern", ",", "index", ")", ":", "result", "=", "re", ".", "search", "(", "pattern", ",", "string", ")", "if", "result", "is", "not", "None", "and", "0", "<=", "index", "<=", "(", "result", "."...
24.647059
0.002299
def _generate_date_indicators(catalog, tolerance=0.2, only_numeric=False): """Genera indicadores relacionados a las fechas de publicación y actualización del catálogo pasado por parámetro. La evaluación de si un catálogo se encuentra actualizado o no tiene un porcentaje de tolerancia hasta que se lo con...
[ "def", "_generate_date_indicators", "(", "catalog", ",", "tolerance", "=", "0.2", ",", "only_numeric", "=", "False", ")", ":", "result", "=", "{", "'datasets_desactualizados_cant'", ":", "None", ",", "'datasets_actualizados_cant'", ":", "None", ",", "'datasets_actua...
37.598131
0.000242
def unarmor(pem_bytes, multiple=False): """ Convert a PEM-encoded byte string into a DER-encoded byte string :param pem_bytes: A byte string of the PEM-encoded data :param multiple: If True, function will return a generator :raises: ValueError - when the pem_bytes do not a...
[ "def", "unarmor", "(", "pem_bytes", ",", "multiple", "=", "False", ")", ":", "generator", "=", "_unarmor", "(", "pem_bytes", ")", "if", "not", "multiple", ":", "return", "next", "(", "generator", ")", "return", "generator" ]
29.62963
0.001211
def _merge_files(windows, nb_cpu): # type: (Iterable[pd.DataFrame], int) -> pd.DataFrame """Merge lists of chromosome bin df chromosome-wise. windows is an OrderedDict where the keys are files, the values are lists of dfs, one per chromosome. Returns a list of dataframes, one per chromosome, with ...
[ "def", "_merge_files", "(", "windows", ",", "nb_cpu", ")", ":", "# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame", "# windows is a list of chromosome dfs per file", "windows", "=", "iter", "(", "windows", ")", "# can iterate over because it is odict_values", "merged", "=", ...
36.217391
0.002339
def fast_1d_tensor_mult(ndarr, onedim_arrs, axes=None, out=None): """Fast multiplication of an n-dim array with an outer product. This method implements the multiplication of an n-dimensional array with an outer product of one-dimensional arrays, e.g.:: a = np.ones((10, 10, 10)) x = np.ran...
[ "def", "fast_1d_tensor_mult", "(", "ndarr", ",", "onedim_arrs", ",", "axes", "=", "None", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "np", ".", "array", "(", "ndarr", ",", "copy", "=", "True", ")", "else", ":", ...
33.75
0.000248
def check_required_fields(method, uri, body, field_names): """ Check required fields in the request body. Raises: BadRequestError with reason 3: Missing request body BadRequestError with reason 5: Missing required field in request body """ # Check presence of request body if body i...
[ "def", "check_required_fields", "(", "method", ",", "uri", ",", "body", ",", "field_names", ")", ":", "# Check presence of request body", "if", "body", "is", "None", ":", "raise", "BadRequestError", "(", "method", ",", "uri", ",", "reason", "=", "3", ",", "m...
36.45
0.001337
def generate(self, local_go_targets): """Automatically generates a Go target graph for the given local go targets. :param iter local_go_targets: The target roots to fill in a target graph for. :raises: :class:`GoTargetGenerator.GenerationError` if any missing targets cannot be generated. """ visite...
[ "def", "generate", "(", "self", ",", "local_go_targets", ")", ":", "visited", "=", "{", "l", ".", "import_path", ":", "l", ".", "address", "for", "l", "in", "local_go_targets", "}", "with", "temporary_dir", "(", ")", "as", "gopath", ":", "for", "local_go...
52
0.009449
def train_rdp_classifier( training_seqs_file, taxonomy_file, model_output_dir, max_memory=None, tmp_dir=tempfile.gettempdir()): """ Train RDP Classifier, saving to model_output_dir training_seqs_file, taxonomy_file: file-like objects used to train the RDP Classifier (see RdpTrai...
[ "def", "train_rdp_classifier", "(", "training_seqs_file", ",", "taxonomy_file", ",", "model_output_dir", ",", "max_memory", "=", "None", ",", "tmp_dir", "=", "tempfile", ".", "gettempdir", "(", ")", ")", ":", "app_kwargs", "=", "{", "}", "if", "tmp_dir", "is",...
36.483871
0.000861
def flatten_kwarg(key, obj): """ Recursive call to flatten sections of a kwarg to be combined :param key: The partial keyword to add to the full keyword :type key: str :param obj: The object to translate into a kwarg. If the type is `dict`, the key parameter will be added to the keyword bet...
[ "def", "flatten_kwarg", "(", "key", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "# Add the word (e.g. \"[key]\")", "new_list", "=", "[", "]", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", ":", "for", "tup...
39.027778
0.000694
def create_report(outdirname, report_filename, **kwargs): """Creates a LaTeX report. :param report_filename: the name of the file. :param outdirname: the name of the output directory. :type report_filename: str :type outdirname: str """ # Checking the required variables if "steps" in ...
[ "def", "create_report", "(", "outdirname", ",", "report_filename", ",", "*", "*", "kwargs", ")", ":", "# Checking the required variables", "if", "\"steps\"", "in", "kwargs", ":", "assert", "\"descriptions\"", "in", "kwargs", "assert", "\"long_descriptions\"", "in", ...
38.341935
0.000164
def annotate_distance_in_km(self, latitude, longitude): """ Return all records with non-null latitude/longitude values with the annotation value `distance_in_km` which is the distance between the record and the given `latitude`/`longitude` location. """ # Great circle dis...
[ "def", "annotate_distance_in_km", "(", "self", ",", "latitude", ",", "longitude", ")", ":", "# Great circle distance formula, taken on faith from StackOverflow link", "# above, see also https://en.wikipedia.org/wiki/Great-circle_distance", "# NOTE: We use psql-specific COALESCE() to choose m...
39.054054
0.00135
def firmware_updates(self, firmware_updates): """ Sets the firmware_updates of this ReportBillingData. :param firmware_updates: The firmware_updates of this ReportBillingData. :type: int """ if firmware_updates is None: raise ValueError("Invalid value for `fi...
[ "def", "firmware_updates", "(", "self", ",", "firmware_updates", ")", ":", "if", "firmware_updates", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `firmware_updates`, must not be `None`\"", ")", "if", "firmware_updates", "is", "not", "None", "and",...
44.384615
0.008489
def mac(self, algorithm, key, data): """ Generate message authentication code. Args: algorithm(CryptographicAlgorithm): An enumeration specifying the algorithm for which the MAC operation will use. key(bytes): secret key used in the MAC operation ...
[ "def", "mac", "(", "self", ",", "algorithm", ",", "key", ",", "data", ")", ":", "mac_data", "=", "None", "if", "algorithm", "in", "self", ".", "_hash_algorithms", ".", "keys", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Generating a hash...
39.283582
0.000741
def create(self, virtual_interfaces): """ Method to create Virtual Interfaces :param Virtual Interfaces: List containing Virtual Interfaces desired to be created on database :return: None """ data = {'virtual_interfaces': virtual_interfaces} return super(ApiV4Vi...
[ "def", "create", "(", "self", ",", "virtual_interfaces", ")", ":", "data", "=", "{", "'virtual_interfaces'", ":", "virtual_interfaces", "}", "return", "super", "(", "ApiV4VirtualInterface", ",", "self", ")", ".", "post", "(", "'api/v4/virtual-interface/'", ",", ...
35
0.010127
def generate_binding_credentials(self, binding): """Generate binding credentials This function will permit to define the configuration to connect to the instance. Those credentials will be stored on a secret and exposed to a a Pod. We should at least returns the...
[ "def", "generate_binding_credentials", "(", "self", ",", "binding", ")", ":", "uri", "=", "self", ".", "clusters", ".", "get", "(", "binding", ".", "instance", ".", "get_cluster", "(", ")", ",", "None", ")", "if", "not", "uri", ":", "raise", "ErrClusterC...
31.868421
0.014423
def order(self, *args): """Return a new Query with additional sort order(s) applied.""" # q.order(Employee.name, -Employee.age) if not args: return self orders = [] o = self.orders if o: orders.append(o) for arg in args: if isinstance(arg, model.Property): orders.ap...
[ "def", "order", "(", "self", ",", "*", "args", ")", ":", "# q.order(Employee.name, -Employee.age)", "if", "not", "args", ":", "return", "self", "orders", "=", "[", "]", "o", "=", "self", ".", "orders", "if", "o", ":", "orders", ".", "append", "(", "o",...
37.214286
0.008419
def selector_to_text(sel, guess_punct_space=True, guess_layout=True): """ Convert a cleaned parsel.Selector to text. See html_text.extract_text docstring for description of the approach and options. """ import parsel if isinstance(sel, parsel.SelectorList): # if selecting a specific xpat...
[ "def", "selector_to_text", "(", "sel", ",", "guess_punct_space", "=", "True", ",", "guess_layout", "=", "True", ")", ":", "import", "parsel", "if", "isinstance", "(", "sel", ",", "parsel", ".", "SelectorList", ")", ":", "# if selecting a specific xpath", "text",...
33.818182
0.001307
def flatten (d, *keys): """Flattens the dictionary d by merging keys in order such that later keys take precedence over earlier keys. """ flat = { } for k in keys: flat = merge(flat, d.pop(k, { })) return flat
[ "def", "flatten", "(", "d", ",", "*", "keys", ")", ":", "flat", "=", "{", "}", "for", "k", "in", "keys", ":", "flat", "=", "merge", "(", "flat", ",", "d", ".", "pop", "(", "k", ",", "{", "}", ")", ")", "return", "flat" ]
21.272727
0.016393
def make_path_relative(path, rel_to): """ Make a filename relative, where the filename path, and it is relative to rel_to >>> make_path_relative('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../../../something/a-file.pth' ...
[ "def", "make_path_relative", "(", "path", ",", "rel_to", ")", ":", "path_filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "path", "=", "os", ".", "path", ".", "n...
43.444444
0.000834
def right_ascension_at_time(self,t): '''RA of prime meridian''' α0 = self.right_ascension_at_epoch t0 = self.epoch ω = self.rotational_speed return (α0 + ω * (t - t0)) % (2*π)
[ "def", "right_ascension_at_time", "(", "self", ",", "t", ")", ":", "α0 ", " ", "elf.", "r", "ight_ascension_at_epoch", "t0", "=", "self", ".", "epoch", "ω ", " ", "elf.", "r", "otational_speed", "return", "(", "α0 ", " ", " *", "(", " ", "-", "t", "))"...
35
0.013953
def p_expression_minus(self, p): 'expression : expression MINUS expression' p[0] = Minus(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_minus", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Minus", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ...
42.5
0.011561
def call(self, call_params): """REST Call Helper """ path = '/' + self.api_version + '/Call/' method = 'POST' return self.request(path, method, call_params)
[ "def", "call", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/Call/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")" ]
31.833333
0.010204
def populate_associations(self, metamodel): ''' Populate a *metamodel* with associations previously encountered from input. ''' for stmt in self.statements: if not isinstance(stmt, CreateAssociationStmt): continue ass = metamod...
[ "def", "populate_associations", "(", "self", ",", "metamodel", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "if", "not", "isinstance", "(", "stmt", ",", "CreateAssociationStmt", ")", ":", "continue", "ass", "=", "metamodel", ".", "define_as...
48.190476
0.012597
def _initiate_resumable_upload( self, client, stream, content_type, size, num_retries, predefined_acl=None, extra_headers=None, chunk_size=None, ): """Initiate a resumable upload. The content type of the upload will be determin...
[ "def", "_initiate_resumable_upload", "(", "self", ",", "client", ",", "stream", ",", "content_type", ",", "size", ",", "num_retries", ",", "predefined_acl", "=", "None", ",", "extra_headers", "=", "None", ",", "chunk_size", "=", "None", ",", ")", ":", "if", ...
33.705882
0.000848
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name Dat...
[ "def", "database_forwards", "(", "self", ",", "app_label", ",", "schema_editor", ",", "from_state", ",", "to_state", ")", ":", "from", "resolwe", ".", "flow", ".", "models", ".", "data", "import", "DataQuerySet", "# pylint: disable=protected-access", "Data", "=", ...
57.25
0.008602
def _write_crmod_file(filename): """Write a valid crmod configuration file to filename. TODO: Modify configuration according to, e.g., 2D """ crmod_lines = [ '***FILES***', '../grid/elem.dat', '../grid/elec.dat', '../rho/rho.dat', '../config/config.dat', ...
[ "def", "_write_crmod_file", "(", "filename", ")", ":", "crmod_lines", "=", "[", "'***FILES***'", ",", "'../grid/elem.dat'", ",", "'../grid/elec.dat'", ",", "'../rho/rho.dat'", ",", "'../config/config.dat'", ",", "'F ! potentials ?'", ",", "'../mod/pot/pot.dat...
32.777778
0.001098
def create(image_data): """ :param image_data: ImageMetadata :return: V1Pod, https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md """ # convert environment variables to Kubernetes objects env_variables = [] for key, value i...
[ "def", "create", "(", "image_data", ")", ":", "# convert environment variables to Kubernetes objects", "env_variables", "=", "[", "]", "for", "key", ",", "value", "in", "image_data", ".", "env_variables", ".", "items", "(", ")", ":", "env_variables", ".", "append"...
44.190476
0.002109
def to_XML(self, xml_declaration=True, xmlns=True): """ Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefix...
[ "def", "to_XML", "(", "self", ",", "xml_declaration", "=", "True", ",", "xmlns", "=", "True", ")", ":", "root_node", "=", "self", ".", "_to_DOM", "(", ")", "if", "xmlns", ":", "xmlutils", ".", "annotate_with_XMLNS", "(", "root_node", ",", "OZONE_XMLNS_PREF...
42.285714
0.002203
def read_json(fp, local_files, dir_files, name_bytes): """ Read json properties from the zip file :param fp: a file pointer :param local_files: the local files structure :param dir_files: the directory headers :param name: the name of the json file to read :return: t...
[ "def", "read_json", "(", "fp", ",", "local_files", ",", "dir_files", ",", "name_bytes", ")", ":", "if", "name_bytes", "in", "dir_files", ":", "json_pos", "=", "local_files", "[", "dir_files", "[", "name_bytes", "]", "[", "1", "]", "]", "[", "1", "]", "...
36.869565
0.001149
def typeCompileAst(ast): """Assign appropiate types to each node in the AST. Will convert opcodes and functions to appropiate upcast version, and add "cast" ops if needed. """ children = list(ast.children) if ast.astType == 'op': retsig = ast.typecode() basesig = ''.join(x.typec...
[ "def", "typeCompileAst", "(", "ast", ")", ":", "children", "=", "list", "(", "ast", ".", "children", ")", "if", "ast", ".", "astType", "==", "'op'", ":", "retsig", "=", "ast", ".", "typecode", "(", ")", "basesig", "=", "''", ".", "join", "(", "x", ...
44.365854
0.000538
def _precesion(date): """Precession in degrees """ t = date.change_scale('TT').julian_century zeta = (2306.2181 * t + 0.30188 * t ** 2 + 0.017998 * t ** 3) / 3600. theta = (2004.3109 * t - 0.42665 * t ** 2 - 0.041833 * t ** 3) / 3600. z = (2306.2181 * t + 1.09468 * t ** 2 + 0.018203 * t ** 3) ...
[ "def", "_precesion", "(", "date", ")", ":", "t", "=", "date", ".", "change_scale", "(", "'TT'", ")", ".", "julian_century", "zeta", "=", "(", "2306.2181", "*", "t", "+", "0.30188", "*", "t", "**", "2", "+", "0.017998", "*", "t", "**", "3", ")", "...
34.416667
0.002358
def poll_for_server_running(job_id): """ Poll for the job to start running and post the SERVER_READY_TAG. """ sys.stdout.write('Waiting for server in {0} to initialize ...'.format(job_id)) sys.stdout.flush() desc = dxpy.describe(job_id) # Keep checking until the server has begun or it has fa...
[ "def", "poll_for_server_running", "(", "job_id", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Waiting for server in {0} to initialize ...'", ".", "format", "(", "job_id", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "desc", "=", "dxpy", "....
39.9
0.002448
def set_value(obj, attrs, value, _copy=False): """ Allows set the same value to a list of attributes """ for attr in attrs: if _copy: value = copy(value) setattr(obj, attr, value)
[ "def", "set_value", "(", "obj", ",", "attrs", ",", "value", ",", "_copy", "=", "False", ")", ":", "for", "attr", "in", "attrs", ":", "if", "_copy", ":", "value", "=", "copy", "(", "value", ")", "setattr", "(", "obj", ",", "attr", ",", "value", ")...
27.125
0.008929
def chop(self, *args, at={}, parent=None, verbose=True) -> wt_collection.Collection: """Divide the dataset into its lower-dimensionality components. Parameters ---------- axis : str or int (args) Axes of the returned data objects. Strings refer to the names of ax...
[ "def", "chop", "(", "self", ",", "*", "args", ",", "at", "=", "{", "}", ",", "parent", "=", "None", ",", "verbose", "=", "True", ")", "->", "wt_collection", ".", "Collection", ":", "from", ".", "_axis", "import", "operators", ",", "operator_to_identifi...
38.78169
0.001593
def get_data_files(dname, ignore=None, parent=None): """ Get all the data files that should be included in this distutils Project. 'dname' should be the path to the package that you're distributing. 'ignore' is a list of sub-packages to ignore. This facilitates disparate package hierarchies. Tha...
[ "def", "get_data_files", "(", "dname", ",", "ignore", "=", "None", ",", "parent", "=", "None", ")", ":", "parent", "=", "parent", "or", "\".\"", "ignore", "=", "ignore", "or", "[", "]", "result", "=", "[", "]", "for", "directory", ",", "subdirectories"...
40.692308
0.000615
def checkseq(sequence: str=None, code="ATGC") -> bool: """ :param sequence: The input sequence. :type sequence: Seq :rtype: bool """ for base in sequence: if base not in code: return False return True
[ "def", "checkseq", "(", "sequence", ":", "str", "=", "None", ",", "code", "=", "\"ATGC\"", ")", "->", "bool", ":", "for", "base", "in", "sequence", ":", "if", "base", "not", "in", "code", ":", "return", "False", "return", "True" ]
24
0.012048
def _finish_frag_download(ffd_self, ctx): ''' We monkey-patch this youtube-dl internal method `_finish_frag_download()` because it gets called after downloading the last segment of a segmented video, which is a good time to upload the stitched-up video that youtube-dl creates for us to warcprox. We ...
[ "def", "_finish_frag_download", "(", "ffd_self", ",", "ctx", ")", ":", "result", "=", "_orig__finish_frag_download", "(", "ffd_self", ",", "ctx", ")", "if", "hasattr", "(", "thread_local", ",", "'finish_frag_download_callback'", ")", ":", "thread_local", ".", "fin...
52
0.001575
def for_compiler(self, compiler, platform): """Return a Linker object which is intended to be compatible with the given `compiler`.""" return (self.linker # TODO(#6143): describe why the compiler needs to be first on the PATH! .sequence(compiler, exclude_list_fields=['extra_args', 'path_...
[ "def", "for_compiler", "(", "self", ",", "compiler", ",", "platform", ")", ":", "return", "(", "self", ".", "linker", "# TODO(#6143): describe why the compiler needs to be first on the PATH!", ".", "sequence", "(", "compiler", ",", "exclude_list_fields", "=", "[", "'e...
63.571429
0.008869
def handle_data(self, ts, msg): """ Passes msg to responding data handler, determined by its channel id, which is expected at index 0. :param ts: timestamp, declares when data was received by the client :param msg: list or dict of websocket data :return: """ ...
[ "def", "handle_data", "(", "self", ",", "ts", ",", "msg", ")", ":", "try", ":", "chan_id", ",", "", "*", "data", "=", "msg", "except", "ValueError", "as", "e", ":", "# Too many or too few values", "raise", "FaultyPayloadError", "(", "\"handle_data(): %s - %s\"...
38.772727
0.002288
def get_canonical_combining_class_property(value, is_bytes=False): """Get `CANONICAL COMBINING CLASS` property.""" obj = unidata.ascii_canonical_combining_class if is_bytes else unidata.unicode_canonical_combining_class if value.startswith('^'): negated = value[1:] value = '^' + unidata.un...
[ "def", "get_canonical_combining_class_property", "(", "value", ",", "is_bytes", "=", "False", ")", ":", "obj", "=", "unidata", ".", "ascii_canonical_combining_class", "if", "is_bytes", "else", "unidata", ".", "unicode_canonical_combining_class", "if", "value", ".", "s...
40.416667
0.008065
def inspect_config(app): """Inspect the Sphinx configuration and update for slide-linking. If links from HTML to slides are enabled, make sure the sidebar configuration includes the template and add the necessary theme directory as a loader so the sidebar template can be located. If the sidebar co...
[ "def", "inspect_config", "(", "app", ")", ":", "# avoid import cycles :/", "from", "hieroglyph", "import", "writer", "# only reconfigure Sphinx if we're generating HTML", "if", "app", ".", "builder", ".", "name", "not", "in", "HTML_BUILDERS", ":", "return", "if", "app...
34.820513
0.000358
def query_variable(ncfile, name) -> netcdf4.Variable: """Return the variable with the given name from the given NetCDF file. Essentially, |query_variable| just performs a key assess via the used NetCDF library, but adds information to possible error messages: >>> from hydpy.core.netcdftools import que...
[ "def", "query_variable", "(", "ncfile", ",", "name", ")", "->", "netcdf4", ".", "Variable", ":", "try", ":", "return", "ncfile", "[", "name", "]", "except", "(", "IndexError", ",", "KeyError", ")", ":", "raise", "OSError", "(", "'NetCDF file `%s` does not co...
36.448276
0.000922
def aspirate(self, consonant) : ''' Aspirates a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +aspirated. ''' aspirated_consonant = deepcopy(consonant) aspirated_consonant[Aspirated] = Aspirated.pos return self._find_sound(aspirated_conson...
[ "def", "aspirate", "(", "self", ",", "consonant", ")", ":", "aspirated_consonant", "=", "deepcopy", "(", "consonant", ")", "aspirated_consonant", "[", "Aspirated", "]", "=", "Aspirated", ".", "pos", "return", "self", ".", "_find_sound", "(", "aspirated_consonant...
39.625
0.033951
def _clean_up_gene_id(geneid, sp, curie_map): """ A series of identifier rewriting to conform with standard gene identifiers. :param geneid: :param sp: :return: """ # special case for MGI geneid = re.sub(r'MGI:MGI:', 'MGI:', geneid) # rewr...
[ "def", "_clean_up_gene_id", "(", "geneid", ",", "sp", ",", "curie_map", ")", ":", "# special case for MGI", "geneid", "=", "re", ".", "sub", "(", "r'MGI:MGI:'", ",", "'MGI:'", ",", "geneid", ")", "# rewrite Ensembl --> ENSEMBL", "geneid", "=", "re", ".", "sub"...
36.6
0.000887
def configure_logging(info=False, debug=False): """Configure logging The function configures log messages. By default, log messages are sent to stderr. Set the parameter `debug` to activate the debug mode. :param debug: set the debug mode """ if info: logging.basicConfig(level=loggin...
[ "def", "configure_logging", "(", "info", "=", "False", ",", "debug", "=", "False", ")", ":", "if", "info", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "LOG_FORMAT", ")", "logging", ".", "getLogger", ...
44.136364
0.001008
def indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(ret)
[ "def", "indices_removed", "(", "lst", ",", "idxs", ")", ":", "ret", "=", "[", "item", "for", "k", ",", "item", "in", "enumerate", "(", "lst", ")", "if", "k", "not", "in", "idxs", "]", "return", "type", "(", "lst", ")", "(", "ret", ")" ]
45.5
0.010811
def getCovariance(self,normalize=True,i0=None,i1=None,pos0=None,pos1=None,chrom=None,center=True,unit=True,pos_cum0=None,pos_cum1=None,blocksize=None,X=None,**kw_args): """calculate the empirical genotype covariance in a region""" if X is not None: K=X.dot(X.T) Nsnp=X.shape[1] ...
[ "def", "getCovariance", "(", "self", ",", "normalize", "=", "True", ",", "i0", "=", "None", ",", "i1", "=", "None", ",", "pos0", "=", "None", ",", "pos1", "=", "None", ",", "chrom", "=", "None", ",", "center", "=", "True", ",", "unit", "=", "True...
40.96875
0.037258
def _add_ticks(xticks=True,yticks=True): """ NAME: _add_ticks PURPOSE: add minor axis ticks to a plot INPUT: (none; works on the current axes) OUTPUT: (none; works on the current axes) HISTORY: 2009-12-23 - Written - Bovy (NYU) """ ax=pyplot.g...
[ "def", "_add_ticks", "(", "xticks", "=", "True", ",", "yticks", "=", "True", ")", ":", "ax", "=", "pyplot", ".", "gca", "(", ")", "if", "xticks", ":", "xstep", "=", "ax", ".", "xaxis", ".", "get_majorticklocs", "(", ")", "xstep", "=", "xstep", "[",...
19.21875
0.010836
def get_atom_name(self, atom): """Look up the name of atom, returning it as a string. Will raise BadAtom if atom does not exist.""" r = request.GetAtomName(display = self.display, atom = atom) return r.name
[ "def", "get_atom_name", "(", "self", ",", "atom", ")", ":", "r", "=", "request", ".", "GetAtomName", "(", "display", "=", "self", ".", "display", ",", "atom", "=", "atom", ")", "return", "r", ".", "name" ]
44.166667
0.022222
def db_exists(name, **connection_args): ''' Checks if a database exists on the MySQL server. CLI Example: .. code-block:: bash salt '*' mysql.db_exists 'dbname' ''' dbc = _connect(**connection_args) if dbc is None: return False cur = dbc.cursor() # Warn: here db id...
[ "def", "db_exists", "(", "name", ",", "*", "*", "connection_args", ")", ":", "dbc", "=", "_connect", "(", "*", "*", "connection_args", ")", "if", "dbc", "is", "None", ":", "return", "False", "cur", "=", "dbc", ".", "cursor", "(", ")", "# Warn: here db ...
28.321429
0.00122
def index_collection(self, filenames): "Index a whole collection of files." for filename in filenames: self.index_document(open(filename).read(), filename)
[ "def", "index_collection", "(", "self", ",", "filenames", ")", ":", "for", "filename", "in", "filenames", ":", "self", ".", "index_document", "(", "open", "(", "filename", ")", ".", "read", "(", ")", ",", "filename", ")" ]
45
0.010929
def process(self, index=None): """ This will completely process a directory of elevation tiles (as supplied in the constructor). Both phases of the calculation, the single tile and edge resolution phases are run. Parameters ----------- index : int/slice (optional...
[ "def", "process", "(", "self", ",", "index", "=", "None", ")", ":", "# Round 0 of twi processing, process the magnitude and directions of", "# slopes", "print", "\"Starting slope calculation round\"", "self", ".", "process_twi", "(", "index", ",", "do_edges", "=", "False"...
34.311111
0.001259
def add_error(self, value, **kwargs): """Add an `Error` instance to this entry.""" kwargs.update({ERROR.VALUE: value}) self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs) return
[ "def", "add_error", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "ERROR", ".", "VALUE", ":", "value", "}", ")", "self", ".", "_add_cat_dict", "(", "Error", ",", "self", ".", "_KEYS", ".", "ERRORS"...
41.6
0.009434
def delete(ctx, slot, force): """ Deletes the configuration of a slot. """ controller = ctx.obj['controller'] if not force and not controller.slot_status[slot - 1]: ctx.fail('Not possible to delete an empty slot.') force or click.confirm( 'Do you really want to delete' ' ...
[ "def", "delete", "(", "ctx", ",", "slot", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "force", "and", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fa...
36.866667
0.001764
def _clear_done_waiters(self): """Remove waiters that are done (should only happen if they are cancelled)""" while self._waiters and self._waiters[0].done(): self._waiters.popleft() if not self._waiters: self._stop_listening()
[ "def", "_clear_done_waiters", "(", "self", ")", ":", "while", "self", ".", "_waiters", "and", "self", ".", "_waiters", "[", "0", "]", ".", "done", "(", ")", ":", "self", ".", "_waiters", ".", "popleft", "(", ")", "if", "not", "self", ".", "_waiters",...
44.833333
0.010949
def calc_avr_uvr_v1(self): """Calculate the flown through area and the wetted perimeter of both outer embankments. Note that each outer embankment lies beyond its foreland and that all water flowing exactly above the a embankment is added to |AVR|. The theoretical surface seperating water above the...
[ "def", "calc_avr_uvr_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".",...
33.381579
0.000383
def lookup_jid(jid, ext_source=None, returned=True, missing=False, display_progress=False): ''' Return the printout from a previously executed job jid The jid to look up. ext_source The external job cache to use. Default: `Non...
[ "def", "lookup_jid", "(", "jid", ",", "ext_source", "=", "None", ",", "returned", "=", "True", ",", "missing", "=", "False", ",", "display_progress", "=", "False", ")", ":", "ret", "=", "{", "}", "mminion", "=", "salt", ".", "minion", ".", "MasterMinio...
29.443182
0.000373
def sargasso_chart (self): """ Make the sargasso plot """ # Config for the plot config = { 'id': 'sargasso_assignment_plot', 'title': 'Sargasso: Assigned Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } #We ...
[ "def", "sargasso_chart", "(", "self", ")", ":", "# Config for the plot", "config", "=", "{", "'id'", ":", "'sargasso_assignment_plot'", ",", "'title'", ":", "'Sargasso: Assigned Reads'", ",", "'ylab'", ":", "'# Reads'", ",", "'cpswitch_counts_label'", ":", "'Number of...
35.692308
0.010504
def as_base_types(self): """Convert this measurement to a dict of basic types.""" if not self._cached: # Create the single cache file the first time this is called. self._cached = { 'name': self.name, 'outcome': self.outcome.name, } if self.validators: self._c...
[ "def", "as_base_types", "(", "self", ")", ":", "if", "not", "self", ".", "_cached", ":", "# Create the single cache file the first time this is called.", "self", ".", "_cached", "=", "{", "'name'", ":", "self", ".", "name", ",", "'outcome'", ":", "self", ".", ...
40.9
0.010753
def filter_host_by_tag(tpl): """Filter for host Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if tag in host.tags""" host = items["host"] if host is None: ...
[ "def", "filter_host_by_tag", "(", "tpl", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if tag in host.tags\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "retu...
22.111111
0.00241
def _rngs(self): """This is where we should also enforce evidence requirements""" outputs = [] if len(self._exon_groups)==1: return [self._exon_groups.consensus('single')] z = 0 #output count begin = 0 meeting_criteria = [i for i in range(0,len(self._exon_groups)) if len(se...
[ "def", "_rngs", "(", "self", ")", ":", "outputs", "=", "[", "]", "if", "len", "(", "self", ".", "_exon_groups", ")", "==", "1", ":", "return", "[", "self", ".", "_exon_groups", ".", "consensus", "(", "'single'", ")", "]", "z", "=", "0", "#output co...
40.192308
0.029907
def dump(args): """Load the build graph for a target and dump it to stdout.""" if len(args) != 1: log.error('One target required.') app.quit(1) try: bb = Butcher() bb.load_graph(args[0]) except error.BrokenGraph as lolno: log.fatal(lolno) app.quit(1) ...
[ "def", "dump", "(", "args", ")", ":", "if", "len", "(", "args", ")", "!=", "1", ":", "log", ".", "error", "(", "'One target required.'", ")", "app", ".", "quit", "(", "1", ")", "try", ":", "bb", "=", "Butcher", "(", ")", "bb", ".", "load_graph", ...
25.25
0.002387
def listPromise(*args): """ A special function that takes a bunch of promises and turns them into a promise for a vector of values. In other words, this turns an list of promises for values into a promise for a list of values. """ ret = Promise() def handleSuccess(v, ret): for a...
[ "def", "listPromise", "(", "*", "args", ")", ":", "ret", "=", "Promise", "(", ")", "def", "handleSuccess", "(", "v", ",", "ret", ")", ":", "for", "arg", "in", "args", ":", "if", "not", "arg", ".", "isFulfilled", "(", ")", ":", "return", "value", ...
27
0.001431
def copy(self, contents=True): '''Create a copy of this model, optionally without contents (i.e. just configuration)''' cp = connection(collection=self._db_coll, baseiri=self._baseiri) if contents: cp.add_many(self._relationships) return cp
[ "def", "copy", "(", "self", ",", "contents", "=", "True", ")", ":", "cp", "=", "connection", "(", "collection", "=", "self", ".", "_db_coll", ",", "baseiri", "=", "self", ".", "_baseiri", ")", "if", "contents", ":", "cp", ".", "add_many", "(", "self"...
53.6
0.014706
def setZValue(self, zValue): """ Sets the z-value for this layer to the inputed value. :param zValue | <int> :return <bool> changed """ if zValue == self._zValue: return False self._zValue = zValue self.sync(...
[ "def", "setZValue", "(", "self", ",", "zValue", ")", ":", "if", "zValue", "==", "self", ".", "_zValue", ":", "return", "False", "self", ".", "_zValue", "=", "zValue", "self", ".", "sync", "(", ")", "return", "True" ]
23.428571
0.014663
def resizeColumnToContents(self, column): """ Resizes the inputed column to the given contents. :param column | <int> """ self.header().blockSignals(True) self.setUpdatesEnabled(False) super(XTreeWidget, self).resizeColumnToContents...
[ "def", "resizeColumnToContents", "(", "self", ",", "column", ")", ":", "self", ".", "header", "(", ")", ".", "blockSignals", "(", "True", ")", "self", ".", "setUpdatesEnabled", "(", "False", ")", "super", "(", "XTreeWidget", ",", "self", ")", ".", "resiz...
32.333333
0.010017
def construct_codons_dict(alphabet_file = None): """Generate the sub_codons_right dictionary of codon suffixes. syntax of custom alphabet_files: char: list,of,amino,acids,or,codons,separated,by,commas Parameters ---------- alphabet_file : str File name for a custom al...
[ "def", "construct_codons_dict", "(", "alphabet_file", "=", "None", ")", ":", "#Some symbols can't be used in the CDR3 sequences in order to allow for", "#regular expression parsing and general manipulation.", "protected_symbols", "=", "[", "' '", ",", "'\\t'", ",", "'\\n'", ",", ...
49.8
0.020518
def join_tables(left, right, key_left, key_right, cols_right=None): """Perform a join of two tables. Parameters ---------- left : `~astropy.Table` Left table for join. right : `~astropy.Table` Right table for join. key_left : str Key used to match eleme...
[ "def", "join_tables", "(", "left", ",", "right", ",", "key_left", ",", "key_right", ",", "cols_right", "=", "None", ")", ":", "right", "=", "right", ".", "copy", "(", ")", "if", "cols_right", "is", "None", ":", "cols_right", "=", "right", ".", "colname...
24.458333
0.001638
def sound_touch(self, call_params): """REST Add soundtouch audio effects to a Call """ path = '/' + self.api_version + '/SoundTouch/' method = 'POST' return self.request(path, method, call_params)
[ "def", "sound_touch", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/SoundTouch/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")" ]
38.5
0.008475
def _cumulative_by_date(model, datefield): ''' Given a model and date field, generate monthly cumulative totals. ''' monthly_counts = defaultdict(int) for obj in model.objects.all().order_by(datefield): datevalue = getattr(obj, datefield) monthkey = (datevalue.year, datevalue.mon...
[ "def", "_cumulative_by_date", "(", "model", ",", "datefield", ")", ":", "monthly_counts", "=", "defaultdict", "(", "int", ")", "for", "obj", "in", "model", ".", "objects", ".", "all", "(", ")", ".", "order_by", "(", "datefield", ")", ":", "datevalue", "=...
34.625
0.002342
def Animation_setTiming(self, animationId, duration, delay): """ Function path: Animation.setTiming Domain: Animation Method name: setTiming Parameters: Required arguments: 'animationId' (type: string) -> Animation id. 'duration' (type: number) -> Duration of the animation. 'delay' (t...
[ "def", "Animation_setTiming", "(", "self", ",", "animationId", ",", "duration", ",", "delay", ")", ":", "assert", "isinstance", "(", "animationId", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'animationId' must be of type '['str']'. Received type: '%s'\"", "%", ...
37.518519
0.042348
async def insert_news(self, **params): """Inserts news for account Accepts: - event_type - cid - access_string (of buyer) - buyer_pubkey - buyer address - owner address - price - offer type - coin ID Returns: - dict with result """ logging.debug("\n\n [+] -- Setting news debuggin...
[ "async", "def", "insert_news", "(", "self", ",", "*", "*", "params", ")", ":", "logging", ".", "debug", "(", "\"\\n\\n [+] -- Setting news debugging. \"", ")", "if", "params", ".", "get", "(", "\"message\"", ")", ":", "params", "=", "json", ".", "loads", ...
25.539216
0.042129
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra): """ install the configured exception hook wrapping the old exception hook don't use it twice :oparam dialog: a different exception dialog class :oparam invoke_old_hook: should we invoke the old exception hook? """ ...
[ "def", "install_hook", "(", "dialog", "=", "SimpleExceptionDialog", ",", "invoke_old_hook", "=", "False", ",", "*", "*", "extra", ")", ":", "global", "_old_hook", "assert", "_old_hook", "is", "None", "def", "new_hook", "(", "etype", ",", "eval", ",", "trace"...
31.473684
0.001623
def to_camel_case(underscore_case, mixed=False): r""" Args: underscore_case (?): Returns: str: camel_case_str CommandLine: python -m utool.util_str --exec-to_camel_case References: https://en.wikipedia.org/wiki/CamelCase Example: >>> # ENABLE_DOCTEST ...
[ "def", "to_camel_case", "(", "underscore_case", ",", "mixed", "=", "False", ")", ":", "thresh", "=", "0", "if", "mixed", "else", "-", "1", "words", "=", "underscore_case", ".", "split", "(", "'_'", ")", "words2", "=", "[", "word", "[", "0", "]", ".",...
26.454545
0.001105
def _read_opt_ip_dff(self, code, *, desc): """Read HOPOPT IP_DFF option. Structure of HOPOPT IP_DFF option [RFC 6971]: 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-...
[ "def", "_read_opt_ip_dff", "(", "self", ",", "code", ",", "*", ",", "desc", ")", ":", "_type", "=", "self", ".", "_read_opt_type", "(", "code", ")", "_size", "=", "self", ".", "_read_unpack", "(", "1", ")", "if", "_size", "!=", "2", ":", "raise", "...
46
0.001388
def pyfs_storage_factory(fileinstance=None, default_location=None, default_storage_class=None, filestorage_class=PyFSFileStorage, fileurl=None, size=None, modified=None, clean_dir=True): """Get factory function for creating a PyFS file stora...
[ "def", "pyfs_storage_factory", "(", "fileinstance", "=", "None", ",", "default_location", "=", "None", ",", "default_storage_class", "=", "None", ",", "filestorage_class", "=", "PyFSFileStorage", ",", "fileurl", "=", "None", ",", "size", "=", "None", ",", "modif...
41.03125
0.000744
def try_import(module_name, names=None, default=ImportErrorModule, warn=True): """Try import module_name, except ImportError and return default, sometimes to be used for catch ImportError and lazy-import. """ try: module = importlib.import_module(module_name) except ImportError: ...
[ "def", "try_import", "(", "module_name", ",", "names", "=", "None", ",", "default", "=", "ImportErrorModule", ",", "warn", "=", "True", ")", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", ...
35.757576
0.00165
def set_data(self, pos=None, color=None, width=None, connect=None): """ Set the data used to draw this visual. Parameters ---------- pos : array Array of shape (..., 2) or (..., 3) specifying vertex coordinates. color : Color, tuple, or array The color to...
[ "def", "set_data", "(", "self", ",", "pos", "=", "None", ",", "color", "=", "None", ",", "width", "=", "None", ",", "connect", "=", "None", ")", ":", "if", "pos", "is", "not", "None", ":", "self", ".", "_bounds", "=", "None", "self", ".", "_pos",...
36.804878
0.001291
def load(self, name): """Loads and returns foreign library.""" name = ctypes.util.find_library(name) return ctypes.cdll.LoadLibrary(name)
[ "def", "load", "(", "self", ",", "name", ")", ":", "name", "=", "ctypes", ".", "util", ".", "find_library", "(", "name", ")", "return", "ctypes", ".", "cdll", ".", "LoadLibrary", "(", "name", ")" ]
39.5
0.012422
def mavlink_packet(self, m): '''handle REMOTE_LOG_DATA_BLOCK packets''' now = time.time() if m.get_type() == 'REMOTE_LOG_DATA_BLOCK': if self.stopped: # send a stop packet every second until the other end gets the idea: if now - self.time_last_stop_pac...
[ "def", "mavlink_packet", "(", "self", ",", "m", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "m", ".", "get_type", "(", ")", "==", "'REMOTE_LOG_DATA_BLOCK'", ":", "if", "self", ".", "stopped", ":", "# send a stop packet every second until the o...
53.712121
0.00831
def face_adjacency_unshared(mesh): """ Return the vertex index of the two vertices not in the shared edge between two adjacent faces Parameters ---------- mesh : Trimesh object Returns ----------- vid_unshared : (len(mesh.face_adjacency), 2) int Indexes of mesh.vertices ...
[ "def", "face_adjacency_unshared", "(", "mesh", ")", ":", "# the non- shared vertex index is the same shape as face_adjacnecy", "# just holding vertex indices rather than face indices", "vid_unshared", "=", "np", ".", "zeros_like", "(", "mesh", ".", "face_adjacency", ",", "dtype",...
35.428571
0.000981
def fetch_backpressure(self, cluster, metric, topology, component, instance, \ timerange, is_max, environ=None): ''' :param cluster: :param metric: :param topology: :param component: :param instance: :param timerange: :param is_max: :param environ: :return: ''' pass
[ "def", "fetch_backpressure", "(", "self", ",", "cluster", ",", "metric", ",", "topology", ",", "component", ",", "instance", ",", "timerange", ",", "is_max", ",", "environ", "=", "None", ")", ":", "pass" ]
21.785714
0.012579
def _run_dnb_normalization(self, dnb_data, sza_data): """Scale the DNB data using a histogram equalization method. Args: dnb_data (ndarray): Day/Night Band data array sza_data (ndarray): Solar Zenith Angle data array """ # convert dask arrays to DataArray object...
[ "def", "_run_dnb_normalization", "(", "self", ",", "dnb_data", ",", "sza_data", ")", ":", "# convert dask arrays to DataArray objects", "dnb_data", "=", "xr", ".", "DataArray", "(", "dnb_data", ",", "dims", "=", "(", "'y'", ",", "'x'", ")", ")", "sza_data", "=...
38.130435
0.001112
def check_perms(self, perms='0600,0400'): """Check and enforce the permissions of the config file. Enforce permission on a provided configuration file. This will check and see if the permission are set based on the permission octet as set in the ``perms`` value. ``perms`` is a comma sep...
[ "def", "check_perms", "(", "self", ",", "perms", "=", "'0600,0400'", ")", ":", "confpath", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "config_file", ")", "mode", "=", "stat", ".", "S_IMODE", "(", "os", ".", "stat", "(", "confpath", ")...
39.038462
0.001923
def formatted_description(self): """ Returns a formatted description string (%s* tokens replaced) or None if unavailable """ desc = self.description if desc: return desc.replace("%s1", self.formatted_value) else: return None
[ "def", "formatted_description", "(", "self", ")", ":", "desc", "=", "self", ".", "description", "if", "desc", ":", "return", "desc", ".", "replace", "(", "\"%s1\"", ",", "self", ".", "formatted_value", ")", "else", ":", "return", "None" ]
34.25
0.010676
def Refresh(self): """Reloads the group object to synchronize with cloud representation. >>> clc.v2.Group("wa-1234").Refresh() """ self.dirty = False self.data = clc.v2.API.Call('GET','groups/%s/%s' % (self.alias,self.id), session=self.session) self.data['changeInfo']['createdDate'] = clc.v2.time_utils....
[ "def", "Refresh", "(", "self", ")", ":", "self", ".", "dirty", "=", "False", "self", ".", "data", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'GET'", ",", "'groups/%s/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ...
40.25
0.02834
def _group_batches_shared(xs, caller_batch_fn, prep_data_fn): """Shared functionality for grouping by batches for variant calling and joint calling. """ singles = [] batch_groups = collections.defaultdict(list) for args in xs: data = utils.to_single_data(args) caller, batch = caller_...
[ "def", "_group_batches_shared", "(", "xs", ",", "caller_batch_fn", ",", "prep_data_fn", ")", ":", "singles", "=", "[", "]", "batch_groups", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "args", "in", "xs", ":", "data", "=", "utils", ".",...
45.071429
0.002327
def main(): """ Main entrypoint for the command-line app. """ args = app.parse_args(sys.argv[1:]) params = args.__dict__ params.update(**load_config(args.config_file)) if params['debug']: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig() try: ...
[ "def", "main", "(", ")", ":", "args", "=", "app", ".", "parse_args", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "params", "=", "args", ".", "__dict__", "params", ".", "update", "(", "*", "*", "load_config", "(", "args", ".", "config_file", ...
28
0.001279
def seqToKV(seq, strict=False): """Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: bytes """ def...
[ "def", "seqToKV", "(", "seq", ",", "strict", "=", "False", ")", ":", "def", "err", "(", "msg", ")", ":", "formatted", "=", "'seqToKV warning: %s: %r'", "%", "(", "msg", ",", "seq", ")", "if", "strict", ":", "raise", "KVFormError", "(", "formatted", ")"...
28.666667
0.000625
def full_analysis(self, analysis_set, output_directory, verbose = True, compile_pdf = True, quick_plots = False): '''Combines calculate_metrics, write_dataframe_to_csv, and plot''' if not os.path.isdir(output_directory): os.makedirs(output_directory) self.analysis_directory = output_...
[ "def", "full_analysis", "(", "self", ",", "analysis_set", ",", "output_directory", ",", "verbose", "=", "True", ",", "compile_pdf", "=", "True", ",", "quick_plots", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "output_director...
74.2
0.04261
def read_videos(self, begtime=None, endtime=None): """Return list of videos with start and end times for a period. Parameters ---------- begtime : int or datedelta or datetime or list start of the data to read; if it's int, it's assumed it's s; if it'...
[ "def", "read_videos", "(", "self", ",", "begtime", "=", "None", ",", "endtime", "=", "None", ")", ":", "if", "isinstance", "(", "begtime", ",", "datetime", ")", ":", "begtime", "=", "begtime", "-", "self", ".", "header", "[", "'start_time'", "]", "if",...
36.648148
0.000984
def _memoize_function(f, name, cache_scope=_CS_FOREVER): """ Wraps a function for memoization and ties it's cache into the Orca cacheing system. Parameters ---------- f : function name : str Name of injectable. cache_scope : {'step', 'iteration', 'forever'}, optional Sco...
[ "def", "_memoize_function", "(", "f", ",", "name", ",", "cache_scope", "=", "_CS_FOREVER", ")", ":", "cache", "=", "{", "}", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "cache_key"...
29.52381
0.000781
def capture_ratio(self, benchmark, threshold=0.0, compare_op=("ge", "lt")): """Capture ratio--ratio of upside to downside capture. Upside capture ratio divided by the downside capture ratio. Parameters ---------- benchmark : {pd.Series, TSeries, 1d np.ndarray} The b...
[ "def", "capture_ratio", "(", "self", ",", "benchmark", ",", "threshold", "=", "0.0", ",", "compare_op", "=", "(", "\"ge\"", ",", "\"lt\"", ")", ")", ":", "if", "isinstance", "(", "compare_op", "(", "tuple", ",", "list", ")", ")", ":", "op1", ",", "op...
37.833333
0.001432
def get_kvlayer_stream_item(client, stream_id): '''Retrieve a :class:`streamcorpus.StreamItem` from :mod:`kvlayer`. This function requires that `client` already be set up properly:: client = kvlayer.client() client.setup_namespace(STREAM_ITEM_TABLE_DEFS, STREAM_I...
[ "def", "get_kvlayer_stream_item", "(", "client", ",", "stream_id", ")", ":", "if", "client", "is", "None", ":", "client", "=", "kvlayer", ".", "client", "(", ")", "client", ".", "setup_namespace", "(", "STREAM_ITEM_TABLE_DEFS", ",", "STREAM_ITEM_VALUE_DEFS", ")"...
40
0.000763
def interventions(self): """ Dictionary of interventions in /scenario/interventions/vectorPop section """ interventions = {} if self.et is None: return interventions for intervention in self.et.findall("intervention"): interventions[intervention.attrib['name']] = ...
[ "def", "interventions", "(", "self", ")", ":", "interventions", "=", "{", "}", "if", "self", ".", "et", "is", "None", ":", "return", "interventions", "for", "intervention", "in", "self", ".", "et", ".", "findall", "(", "\"intervention\"", ")", ":", "inte...
47.125
0.010417
def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale) F = np.array(((-1.0/lengthscale,),)) L = np.array(((1.0,),)) Qc = np.array( ((2.0*variance/lengt...
[ "def", "sde", "(", "self", ")", ":", "variance", "=", "float", "(", "self", ".", "variance", ".", "values", ")", "lengthscale", "=", "float", "(", "self", ".", "lengthscale", ")", "F", "=", "np", ".", "array", "(", "(", "(", "-", "1.0", "/", "len...
26.566667
0.032688
def simple2data(text): """ Convert a simple table to data (the kind used by DashTable) Parameters ---------- text : str A valid simple rst table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a [row, column] pair that de...
[ "def", "simple2data", "(", "text", ")", ":", "try", ":", "import", "docutils", ".", "statemachine", "import", "docutils", ".", "parsers", ".", "rst", ".", "tableparser", "except", "ImportError", ":", "print", "(", "\"ERROR: You must install the docutils library to u...
29.964602
0.000858
def get_python_symbol_icons(oedata): """Return a list of icons for oedata of a python file.""" class_icon = ima.icon('class') method_icon = ima.icon('method') function_icon = ima.icon('function') private_icon = ima.icon('private1') super_private_icon = ima.icon('private2') symbols = process...
[ "def", "get_python_symbol_icons", "(", "oedata", ")", ":", "class_icon", "=", "ima", ".", "icon", "(", "'class'", ")", "method_icon", "=", "ima", ".", "icon", "(", "'method'", ")", "function_icon", "=", "ima", ".", "icon", "(", "'function'", ")", "private_...
30.734694
0.000644
def track(cls, obj, ptr): """ Track an object which needs destruction when it is garbage collected. """ cls._objects.add(cls(obj, ptr))
[ "def", "track", "(", "cls", ",", "obj", ",", "ptr", ")", ":", "cls", ".", "_objects", ".", "add", "(", "cls", "(", "obj", ",", "ptr", ")", ")" ]
32.6
0.011976
def restart_policy(val, **kwargs): # pylint: disable=unused-argument ''' CLI input is in the format NAME[:RETRY_COUNT] but the API expects {'Name': name, 'MaximumRetryCount': retry_count}. We will use the 'fill' kwarg here to make sure the mapped result uses '0' for the count if this optional value...
[ "def", "restart_policy", "(", "val", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "val", "=", "helpers", ".", "map_vals", "(", "val", ",", "'Name'", ",", "'MaximumRetryCount'", ",", "fill", "=", "'0'", ")", "# map_vals() converts the i...
40.37931
0.001668