text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def expand_rmf_matrix(rmf): """Expand an RMF matrix stored in compressed form. *rmf* An RMF object as might be returned by ``sherpa.astro.ui.get_rmf()``. Returns: A non-sparse RMF matrix. The Response Matrix Function (RMF) of an X-ray telescope like Chandra can be stored in a sparse fo...
[ "def", "expand_rmf_matrix", "(", "rmf", ")", ":", "n_chan", "=", "rmf", ".", "e_min", ".", "size", "n_energy", "=", "rmf", ".", "n_grp", ".", "size", "expanded", "=", "np", ".", "zeros", "(", "(", "n_energy", ",", "n_chan", ")", ")", "mtx_ofs", "=", ...
31.939394
0.001842
def iptag_set(self, iptag, addr, port, x, y): """Set the value of an IPTag. Forward SDP packets with the specified IP tag sent by a SpiNNaker application to a given external IP address. A :ref:`tutorial example <scp-and-sdp-tutorial>` of the use of IP Tags to send and receive S...
[ "def", "iptag_set", "(", "self", ",", "iptag", ",", "addr", ",", "port", ",", "x", ",", "y", ")", ":", "# Format the IP address", "ip_addr", "=", "struct", ".", "pack", "(", "'!4B'", ",", "*", "map", "(", "int", ",", "socket", ".", "gethostbyname", "...
38.68
0.002018
def render_to_file(template, fn=None, extra=None, **kwargs): """ Returns a template to a local file. If no filename given, a temporary filename will be generated and returned. """ import tempfile dryrun = get_dryrun(kwargs.get('dryrun')) append_newline = kwargs.pop('append_newline', True) ...
[ "def", "render_to_file", "(", "template", ",", "fn", "=", "None", ",", "extra", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "tempfile", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")", ")", "append_newline", "...
28.377778
0.001514
def run_cli(self, cli, args=None, node_paths=None): """Returns a command that when executed will run an installed cli via package manager.""" cli_args = [cli] if args: cli_args.append('--') cli_args.extend(args) return self.run_command(args=cli_args, node_paths=node_paths)
[ "def", "run_cli", "(", "self", ",", "cli", ",", "args", "=", "None", ",", "node_paths", "=", "None", ")", ":", "cli_args", "=", "[", "cli", "]", "if", "args", ":", "cli_args", ".", "append", "(", "'--'", ")", "cli_args", ".", "extend", "(", "args",...
42.142857
0.013289
def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: """ Create explanation (as a list of header/content entries) for an answer """ output = [] nl_world = {} if wo...
[ "def", "get_explanation", "(", "logical_form", ":", "str", ",", "world_extractions", ":", "JsonDict", ",", "answer_index", ":", "int", ",", "world", ":", "QuarelWorld", ")", "->", "List", "[", "JsonDict", "]", ":", "output", "=", "[", "]", "nl_world", "=",...
38.368421
0.001783
def mutate(self, context, handler, args, kw): """Inspect and potentially mutate the given handler's arguments. The args list and kw dictionary may be freely modified, though invalid arguments to the handler will fail. """ def cast(arg, val): if arg not in annotations: return cast = annotations[...
[ "def", "mutate", "(", "self", ",", "context", ",", "handler", ",", "args", ",", "kw", ")", ":", "def", "cast", "(", "arg", ",", "val", ")", ":", "if", "arg", "not", "in", "annotations", ":", "return", "cast", "=", "annotations", "[", "key", "]", ...
25.325
0.04943
def _project(reference_sources, estimated_source, flen): """Least-squares projection of estimated source on the subspace spanned by delayed versions of reference sources, with delays between 0 and flen-1 """ nsrc = reference_sources.shape[0] nsampl = reference_sources.shape[1] # computing coeff...
[ "def", "_project", "(", "reference_sources", ",", "estimated_source", ",", "flen", ")", ":", "nsrc", "=", "reference_sources", ".", "shape", "[", "0", "]", "nsampl", "=", "reference_sources", ".", "shape", "[", "1", "]", "# computing coefficients of least squares ...
44.409091
0.000501
def get_temp_var(self): """Gets the next match_temp_var.""" tempvar = match_temp_var + "_" + str(self.var_index) self.var_index += 1 return tempvar
[ "def", "get_temp_var", "(", "self", ")", ":", "tempvar", "=", "match_temp_var", "+", "\"_\"", "+", "str", "(", "self", ".", "var_index", ")", "self", ".", "var_index", "+=", "1", "return", "tempvar" ]
35
0.011173
def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None): 'Perform the act of constructing a Dash instance taking into account state' ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id) return self.form_dash_instance(replacements, ndid,...
[ "def", "do_form_dash_instance", "(", "self", ",", "replacements", "=", "None", ",", "specific_identifier", "=", "None", ",", "cache_id", "=", "None", ")", ":", "ndid", ",", "base_pathname", "=", "self", ".", "get_base_pathname", "(", "specific_identifier", ",", ...
66.2
0.014925
def assign_taxonomy(dataPath, reference_sequences_fp, id_to_taxonomy_fp, read_1_seqs_fp, read_2_seqs_fp, single_ok=False, no_single_ok_generic=False, header_id_regex=None, read_id_regex = "\S+\s+(\S+)", amplicon_id_regex = "(\S+)\s+(\S+?)\/", output_fp=None, log_path=None, HALT_E...
[ "def", "assign_taxonomy", "(", "dataPath", ",", "reference_sequences_fp", ",", "id_to_taxonomy_fp", ",", "read_1_seqs_fp", ",", "read_2_seqs_fp", ",", "single_ok", "=", "False", ",", "no_single_ok_generic", "=", "False", ",", "header_id_regex", "=", "None", ",", "re...
41.167832
0.008127
def run_profilers(run_object, prof_config, verbose=False): """Runs profilers on run_object. Args: run_object: An object (string or tuple) for profiling. prof_config: A string with profilers configuration. verbose: True if info about running profilers should be shown. Returns: ...
[ "def", "run_profilers", "(", "run_object", ",", "prof_config", ",", "verbose", "=", "False", ")", ":", "if", "len", "(", "prof_config", ")", ">", "len", "(", "set", "(", "prof_config", ")", ")", ":", "raise", "AmbiguousConfigurationError", "(", "'Profiler co...
40.266667
0.000808
def initialise_site_lookup_table( self ): """ Create a lookup table allowing sites in this lattice to be queried using `self.site_lookup[n]` where `n` is the identifying site numbe. Args: None Returns: None """ self.site_lookup = {} for s...
[ "def", "initialise_site_lookup_table", "(", "self", ")", ":", "self", ".", "site_lookup", "=", "{", "}", "for", "site", "in", "self", ".", "sites", ":", "self", ".", "site_lookup", "[", "site", ".", "number", "]", "=", "site" ]
29
0.017995
def _autocomplete(ctx, shell): """Print the shell autocompletion code.""" if not shell: shell = os.environ.get("SHELL", "") shell = os.path.basename(shell).lower() if not shell: click.secho( "Your shell could not be detected, please pass its name " "as the arg...
[ "def", "_autocomplete", "(", "ctx", ",", "shell", ")", ":", "if", "not", "shell", ":", "shell", "=", "os", ".", "environ", ".", "get", "(", "\"SHELL\"", ",", "\"\"", ")", "shell", "=", "os", ".", "path", ".", "basename", "(", "shell", ")", ".", "...
29.346154
0.001269
def date_suggestions(): """ Returns a list of relative date that is presented to the user as auto complete suggestions. """ # don't use strftime, prevent locales to kick in days_of_week = { 0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Frid...
[ "def", "date_suggestions", "(", ")", ":", "# don't use strftime, prevent locales to kick in", "days_of_week", "=", "{", "0", ":", "\"Monday\"", ",", "1", ":", "\"Tuesday\"", ",", "2", ":", "\"Wednesday\"", ",", "3", ":", "\"Thursday\"", ",", "4", ":", "\"Friday\...
23.2
0.001379
def comment_sync(self, comment): """Update comments to host and notify subscribers""" self.host.update(key="comment", value=comment) self.host.emit("commented", comment=comment)
[ "def", "comment_sync", "(", "self", ",", "comment", ")", ":", "self", ".", "host", ".", "update", "(", "key", "=", "\"comment\"", ",", "value", "=", "comment", ")", "self", ".", "host", ".", "emit", "(", "\"commented\"", ",", "comment", "=", "comment",...
49.5
0.00995
def generate_noise(dimensions, stimfunction_tr, tr_duration, template, mask=None, noise_dict=None, temporal_proportion=0.5, iterations=None, fit_thresh=0.05, ...
[ "def", "generate_noise", "(", "dimensions", ",", "stimfunction_tr", ",", "tr_duration", ",", "template", ",", "mask", "=", "None", ",", "noise_dict", "=", "None", ",", "temporal_proportion", "=", "0.5", ",", "iterations", "=", "None", ",", "fit_thresh", "=", ...
38.926471
0.000123
def geometric_center(coords, periodic): '''Geometric center taking into account periodic boundaries''' max_vals = periodic theta = 2 * np.pi * (coords / max_vals) eps = np.cos(theta) * max_vals / (2 * np.pi) zeta = np.sin(theta) * max_vals / (2 * np.pi) eps_avg = eps.sum(axis=0) zeta_avg = ...
[ "def", "geometric_center", "(", "coords", ",", "periodic", ")", ":", "max_vals", "=", "periodic", "theta", "=", "2", "*", "np", ".", "pi", "*", "(", "coords", "/", "max_vals", ")", "eps", "=", "np", ".", "cos", "(", "theta", ")", "*", "max_vals", "...
35.666667
0.002278
def compute_chunk(self, graph, dates, symbols, initial_workspace): """ Compute the Pipeline terms in the graph for the requested start and end dates. Parameters ---------- graph : zipline.pipeline.graph.TermGraph dates : pd.DatetimeIndex Row labels fo...
[ "def", "compute_chunk", "(", "self", ",", "graph", ",", "dates", ",", "symbols", ",", "initial_workspace", ")", ":", "self", ".", "_validate_compute_chunk_params", "(", "dates", ",", "symbols", ",", "initial_workspace", ")", "# get_loader = self.get_loader", "# Copy...
38.375
0.000577
def setimdi(self, node): #OBSOLETE """OBSOLETE""" ns = {'imdi': 'http://www.mpi.nl/IMDI/Schema/IMDI'} self.metadatatype = MetaDataType.IMDI if LXE: self.metadata = ElementTree.tostring(node, xml_declaration=False, pretty_print=True, encoding='utf-8') else: ...
[ "def", "setimdi", "(", "self", ",", "node", ")", ":", "#OBSOLETE", "ns", "=", "{", "'imdi'", ":", "'http://www.mpi.nl/IMDI/Schema/IMDI'", "}", "self", ".", "metadatatype", "=", "MetaDataType", ".", "IMDI", "if", "LXE", ":", "self", ".", "metadata", "=", "E...
56
0.011707
def no_type_check(arg): """Decorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the...
[ "def", "no_type_check", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "type", ")", ":", "arg_attrs", "=", "arg", ".", "__dict__", ".", "copy", "(", ")", "for", "attr", ",", "val", "in", "arg", ".", "__dict__", ".", "items", "(", ")", ...
36
0.001127
def has_status(method=None, status='draft'): """Check that deposit has a defined status (default: draft). :param method: Function executed if record has a defined status. (Default: ``None``) :param status: Defined status to check. (Default: ``'draft'``) """ if method is None: return...
[ "def", "has_status", "(", "method", "=", "None", ",", "status", "=", "'draft'", ")", ":", "if", "method", "is", "None", ":", "return", "partial", "(", "has_status", ",", "status", "=", "status", ")", "@", "wraps", "(", "method", ")", "def", "wrapper", ...
32.111111
0.001681
def load_parameter_file(file_path, name = ''): """ Load parameters from a YAML file (or a directory containing YAML files). :returns: An instance of :any:`ParameterNode` or :any:`Scale` or :any:`Parameter`. """ if not os.path.exists(file_path): raise ValueError("{} doest not exist".format(f...
[ "def", "load_parameter_file", "(", "file_path", ",", "name", "=", "''", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "raise", "ValueError", "(", "\"{} doest not exist\"", ".", "format", "(", "file_path", ")", ")", ...
41.666667
0.011742
def import_classes(name, currmodule): # type: (unicode, unicode) -> Any """Import a class using its fully-qualified *name*.""" target = None # import class or module using currmodule if currmodule: target = try_import(currmodule + '.' + name) # import class or module without currmodule...
[ "def", "import_classes", "(", "name", ",", "currmodule", ")", ":", "# type: (unicode, unicode) -> Any", "target", "=", "None", "# import class or module using currmodule", "if", "currmodule", ":", "target", "=", "try_import", "(", "currmodule", "+", "'.'", "+", "name"...
35.7
0.000909
def command_getkeys(self, command, *args, encoding='utf-8'): """Extract keys given a full Redis command.""" return self.execute(b'COMMAND', b'GETKEYS', command, *args, encoding=encoding)
[ "def", "command_getkeys", "(", "self", ",", "command", ",", "*", "args", ",", "encoding", "=", "'utf-8'", ")", ":", "return", "self", ".", "execute", "(", "b'COMMAND'", ",", "b'GETKEYS'", ",", "command", ",", "*", "args", ",", "encoding", "=", "encoding"...
56.75
0.008696
def _compute_start_end(df, start, end): """ Compute two dataframes with value for start and end Args: totals(dataframe): Returns: Dataframe, Dataframe """ result = {} time_dict = {'start': start, 'end': end} totals = df.groupby('date').agg({'value': sum}).reset_index() for ...
[ "def", "_compute_start_end", "(", "df", ",", "start", ",", "end", ")", ":", "result", "=", "{", "}", "time_dict", "=", "{", "'start'", ":", "start", ",", "'end'", ":", "end", "}", "totals", "=", "df", ".", "groupby", "(", "'date'", ")", ".", "agg",...
29.44
0.001316
def generate_from_iterable(grm, data, **kwargs): """ Generate from each MRS in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): MRSs as SimpleMRS strings **kwargs: additional keyword arguments to pass to the AceGener...
[ "def", "generate_from_iterable", "(", "grm", ",", "data", ",", "*", "*", "kwargs", ")", ":", "with", "AceGenerator", "(", "grm", ",", "*", "*", "kwargs", ")", "as", "generator", ":", "for", "datum", "in", "data", ":", "yield", "generator", ".", "intera...
33.533333
0.001934
def claim_pep_node(self, node_namespace, *, register_feature=True, notify=False): """ Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` ...
[ "def", "claim_pep_node", "(", "self", ",", "node_namespace", ",", "*", ",", "register_feature", "=", "True", ",", "notify", "=", "False", ")", ":", "if", "node_namespace", "in", "self", ".", "_pep_node_claims", ":", "raise", "RuntimeError", "(", "\"claiming al...
35.631579
0.001437
def get_cantons(self): """ Return the list of unique cantons, sorted by name. """ return sorted(list(set([ location.canton for location in self.get_locations().values() ])))
[ "def", "get_cantons", "(", "self", ")", ":", "return", "sorted", "(", "list", "(", "set", "(", "[", "location", ".", "canton", "for", "location", "in", "self", ".", "get_locations", "(", ")", ".", "values", "(", ")", "]", ")", ")", ")" ]
31.285714
0.008889
def fetch(self): """Attempt to fetch the object from the Infoblox device. If successful the object will be updated and the method will return True. :rtype: bool :raises: infoblox.exceptions.ProtocolError """ LOGGER.debug('Fetching %s, %s', self._path, self._search_value...
[ "def", "fetch", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Fetching %s, %s'", ",", "self", ".", "_path", ",", "self", ".", "_search_values", ")", "response", "=", "self", ".", "_session", ".", "get", "(", "self", ".", "_path", ",", "self", ...
39.5
0.002247
def _extract_obo_relation(cls, rawterm): """Extract the relationships defined in the rawterm. """ relations = {} if 'subClassOf' in rawterm: relations[Relationship('is_a')] = l = [] l.extend(map(cls._get_id_from_url, rawterm.pop('subClassOf'))) return rela...
[ "def", "_extract_obo_relation", "(", "cls", ",", "rawterm", ")", ":", "relations", "=", "{", "}", "if", "'subClassOf'", "in", "rawterm", ":", "relations", "[", "Relationship", "(", "'is_a'", ")", "]", "=", "l", "=", "[", "]", "l", ".", "extend", "(", ...
39.75
0.009231
def infer_literal(self, args, diagnostic=None): """ Infer type from an LITERAL! Type of literal depend of language. We adopt a basic convention """ literal, t = args #self.type_node.add(EvalCtx.from_sig(Val(literal, t))) self.infer_node.scope_node.add(Eval...
[ "def", "infer_literal", "(", "self", ",", "args", ",", "diagnostic", "=", "None", ")", ":", "literal", ",", "t", "=", "args", "#self.type_node.add(EvalCtx.from_sig(Val(literal, t)))", "self", ".", "infer_node", ".", "scope_node", ".", "add", "(", "EvalCtx", ".",...
38
0.008571
def _extract_and_handle_mpbgp_new_paths(self, update_msg): """Extracts new paths advertised in the given update message's *MpReachNlri* attribute. Assumes MPBGP capability is enabled and message was validated. Parameters: - update_msg: (Update) is assumed to be checked for ...
[ "def", "_extract_and_handle_mpbgp_new_paths", "(", "self", ",", "update_msg", ")", ":", "umsg_pattrs", "=", "update_msg", ".", "pathattr_map", "mpreach_nlri_attr", "=", "umsg_pattrs", ".", "get", "(", "BGP_ATTR_TYPE_MP_REACH_NLRI", ")", "assert", "mpreach_nlri_attr", "m...
44.23
0.000442
def validate(self, data): """Validate the data against the schema. """ validator = self._schema.validator(self._id) validator.validate(data)
[ "def", "validate", "(", "self", ",", "data", ")", ":", "validator", "=", "self", ".", "_schema", ".", "validator", "(", "self", ".", "_id", ")", "validator", ".", "validate", "(", "data", ")" ]
28
0.011561
def from_Track(track, maxwidth=80, tuning=None): """Convert a mingus.containers.Track object to an ASCII tablature string. 'tuning' should be set to a StringTuning object or to None to use the Track's tuning (or alternatively the default if the Track hasn't got its own tuning). 'string' and 'fret'...
[ "def", "from_Track", "(", "track", ",", "maxwidth", "=", "80", ",", "tuning", "=", "None", ")", ":", "result", "=", "[", "]", "width", "=", "_get_width", "(", "maxwidth", ")", "if", "not", "tuning", ":", "tuning", "=", "track", ".", "get_tuning", "("...
36.12
0.001079
def transformer_revnet_big(): """Base hparams for TransformerRevnet.""" hparams = transformer_revnet_base() # The TransformerRevnet uses significantly less memory than the Transformer. # Increase batch size and model size. hparams.batch_size *= 2 hparams.hidden_size *= 2 hparams.num_heads *= 2 hparams....
[ "def", "transformer_revnet_big", "(", ")", ":", "hparams", "=", "transformer_revnet_base", "(", ")", "# The TransformerRevnet uses significantly less memory than the Transformer.", "# Increase batch size and model size.", "hparams", ".", "batch_size", "*=", "2", "hparams", ".", ...
31.727273
0.027855
def plot_tree(booster, num_trees=0, rankdir='UT', ax=None, **kwargs): """Plot specified tree. Parameters ---------- booster : Booster, XGBModel Booster or XGBModel instance num_trees : int, default 0 Specify the ordinal number of target tree rankdir : str, default "UT" P...
[ "def", "plot_tree", "(", "booster", ",", "num_trees", "=", "0", ",", "rankdir", "=", "'UT'", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "matplotlib", ".", "imag...
24.560976
0.000955
def get_route_to(self, destination='', protocol=''): """Return route details to a specific destination, learned from a certain protocol.""" # Note, it should be possible to query the FIB: # "<show><routing><fib></fib></routing></show>" # To add informations to this getter routes...
[ "def", "get_route_to", "(", "self", ",", "destination", "=", "''", ",", "protocol", "=", "''", ")", ":", "# Note, it should be possible to query the FIB:", "# \"<show><routing><fib></fib></routing></show>\"", "# To add informations to this getter", "routes", "=", "{", "}", ...
36.868421
0.001738
def snpsift(self): """SnpSift""" tstart = datetime.now() # command = 'python %s/snpsift.py -i sanity_check/checked.vcf 2>log/snpsift.log' % (scripts_dir) # self.shell(command) ss = snpsift.SnpSift(self.vcf_file) ss.run() tend = datetime.now() execution...
[ "def", "snpsift", "(", "self", ")", ":", "tstart", "=", "datetime", ".", "now", "(", ")", "# command = 'python %s/snpsift.py -i sanity_check/checked.vcf 2>log/snpsift.log' % (scripts_dir)", "# self.shell(command)", "ss", "=", "snpsift", ".", "SnpSift", "(", "self", ".", ...
25.307692
0.008798
def assign_rates(self, mu=1.0, pi=None, W=None): """ Overwrite the GTR model given the provided data Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibrium frequenc...
[ "def", "assign_rates", "(", "self", ",", "mu", "=", "1.0", ",", "pi", "=", "None", ",", "W", "=", "None", ")", ":", "n", "=", "len", "(", "self", ".", "alphabet", ")", "self", ".", "mu", "=", "mu", "if", "pi", "is", "not", "None", "and", "len...
29.363636
0.009738
def last_month(): """ Return start and end date of this month. """ since = TODAY + delta(day=1, months=-1) until = since + delta(months=1) return Date(since), Date(until)
[ "def", "last_month", "(", ")", ":", "since", "=", "TODAY", "+", "delta", "(", "day", "=", "1", ",", "months", "=", "-", "1", ")", "until", "=", "since", "+", "delta", "(", "months", "=", "1", ")", "return", "Date", "(", "since", ")", ",", "Date...
39.6
0.009901
def open_archive(fs_url, archive): """Open an archive on a filesystem. This function tries to mimick the behaviour of `fs.open_fs` as closely as possible: it accepts either a FS URL or a filesystem instance, and will close all resources it had to open. Arguments: fs_url (FS or text_type): ...
[ "def", "open_archive", "(", "fs_url", ",", "archive", ")", ":", "it", "=", "pkg_resources", ".", "iter_entry_points", "(", "'fs.archive.open_archive'", ")", "entry_point", "=", "next", "(", "(", "ep", "for", "ep", "in", "it", "if", "archive", ".", "endswith"...
33.680556
0.000801
def move_to(self, xpos, ypos): """ Move cursor to specified position """ self.stream.write(self.move(ypos, xpos))
[ "def", "move_to", "(", "self", ",", "xpos", ",", "ypos", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move", "(", "ypos", ",", "xpos", ")", ")" ]
23.5
0.013699
def length(value, min=None, max=None): """ Return whether or not the length of given string is within a specified range. Examples:: >>> length('something', min=2) True >>> length('something', min=9, max=9) True >>> length('something', max=5) Validation...
[ "def", "length", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "if", "(", "min", "is", "not", "None", "and", "min", "<", "0", ")", "or", "(", "max", "is", "not", "None", "and", "max", "<", "0", ")", ":", "raise", ...
27.09375
0.001114
def remove_exts(self, exts): """ Remove the files with the given extensions. Unlike rmtree, this function preserves the directory path. Return list with the absolute paths of the files that have been removed. """ paths = [] for ext in list_strings(exts): path...
[ "def", "remove_exts", "(", "self", ",", "exts", ")", ":", "paths", "=", "[", "]", "for", "ext", "in", "list_strings", "(", "exts", ")", ":", "path", "=", "self", ".", "has_abiext", "(", "ext", ")", "if", "not", "path", ":", "continue", "try", ":", ...
33.941176
0.010118
def format_int(n, singular=_Default, plural=_Default): """ Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If plural is not specified, then it is assumed to be same as singular but suffixed with an 's'. :param n: Integer which determines pluralness. :param singu...
[ "def", "format_int", "(", "n", ",", "singular", "=", "_Default", ",", "plural", "=", "_Default", ")", ":", "n", "=", "int", "(", "n", ")", "if", "singular", "in", "(", "None", ",", "_Default", ")", ":", "if", "plural", "is", "_Default", ":", "plura...
26.636364
0.000823
def merge_resources(resource_list): """Merge multiple resources to get a new resource. Resources earlier in the list take precedence: if multiple resources share a label key, use the value from the first resource in the list with that key. The combined resource's type will be the first non-null type in...
[ "def", "merge_resources", "(", "resource_list", ")", ":", "if", "not", "resource_list", ":", "raise", "ValueError", "rtype", "=", "None", "for", "rr", "in", "resource_list", ":", "if", "rr", ".", "type", ":", "rtype", "=", "rr", ".", "type", "break", "la...
31.4
0.001236
def addconstraint(self, x, y=0, fnct=None, fid=0): """Add constraint.""" self._checkid(fid) i = 0 if "constraint" in self._fitids[fid]: i = len(self._fitids[fid]["constraint"]) else: self._fitids[fid]["constraint"] = {} # dict key needs to be strin...
[ "def", "addconstraint", "(", "self", ",", "x", ",", "y", "=", "0", ",", "fnct", "=", "None", ",", "fid", "=", "0", ")", ":", "self", ".", "_checkid", "(", "fid", ")", "i", "=", "0", "if", "\"constraint\"", "in", "self", ".", "_fitids", "[", "fi...
41.631579
0.002472
def files_auth(request): """Display authentication for filecenter.""" if "password" in request.POST: """ Encrypt the password with AES mode CFB. Create a random 32 char key, stored in a CLIENT-side cookie. Create a random 32 char IV, stored in a SERVER-side session. ...
[ "def", "files_auth", "(", "request", ")", ":", "if", "\"password\"", "in", "request", ".", "POST", ":", "\"\"\"\n Encrypt the password with AES mode CFB.\n Create a random 32 char key, stored in a CLIENT-side cookie.\n Create a random 32 char IV, stored in ...
44.297297
0.001791
def route(regex, view, method, name): """ Route the given view. :param regex: A string describing a regular expression to which the request path will be matched. :param view: A string describing the name of the view to delegate the request to. :param method: A string describing the HTTP method ...
[ "def", "route", "(", "regex", ",", "view", ",", "method", ",", "name", ")", ":", "return", "_Route", "(", "regex", ",", "view", ",", "method", ",", "name", ")" ]
50
0.011043
def project_data(self): ''' Assign the sum of ``.integral``\* to each sensible point in the ``pyny.Space`` for the intervals that the points are visible to the Sun. The generated information is stored in: * **.proj_vor** (*ndarray*): ``.integral`` projected t...
[ "def", "project_data", "(", "self", ")", ":", "from", "pyny3d", ".", "utils", "import", "sort_numpy", "proj", "=", "self", ".", "light_vor", ".", "astype", "(", "float", ")", "map_", "=", "np", ".", "vstack", "(", "(", "self", ".", "t2vor_map", ",", ...
38.225806
0.009053
def prompt_4_mfa_serial(input = None): """ Prompt for an MFA serial number :param input: Used for unit testing :return: The MFA serial number """ return prompt_4_value('Enter your MFA serial:', required = False, regex = re_mfa_serial_format, reg...
[ "def", "prompt_4_mfa_serial", "(", "input", "=", "None", ")", ":", "return", "prompt_4_value", "(", "'Enter your MFA serial:'", ",", "required", "=", "False", ",", "regex", "=", "re_mfa_serial_format", ",", "regex_format", "=", "mfa_serial_format", ",", "input", "...
39.666667
0.032877
def query_by_id(self, id): """ Returns object with _id = id. :param id: Value for ID. If not a string will be coerced to string. :type id: ``string`` :return: Document with id :rtype: ``dict`` """ return json.loads(self._get(UrlEncoded(str(id))).body.rea...
[ "def", "query_by_id", "(", "self", ",", "id", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_get", "(", "UrlEncoded", "(", "str", "(", "id", ")", ")", ")", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "...
30
0.008824
def get_attribute(self, attribute, value=None, features=False): """This returns a list of GFF objects (or GFF Features) with the given attribute and if supplied, those attributes with the specified value :param attribute: The 'info' field attribute we are querying :param value: Optional...
[ "def", "get_attribute", "(", "self", ",", "attribute", ",", "value", "=", "None", ",", "features", "=", "False", ")", ":", "if", "attribute", "in", "self", ".", "filters", ":", "valid_gff_objects", "=", "self", ".", "fast_attributes", "[", "attribute", "]"...
63.607143
0.00885
def register_class(self, class_type, component_scope=scope.InstancePerDependency, register_as=None): """ Registers the given class for creation via its constructor. :param class_type: The class type. :param component_scope: The scope of the component, defaults to instance per dependency....
[ "def", "register_class", "(", "self", ",", "class_type", ",", "component_scope", "=", "scope", ".", "InstancePerDependency", ",", "register_as", "=", "None", ")", ":", "registration", "=", "_ConstructorRegistration", "(", "class_type", ",", "component_scope", "(", ...
62.555556
0.008757
def _parse_quit(client, command, actor, args): """Parse a QUIT and update channel states, then dispatch events. Note that two events are dispatched here: - QUIT, because a user quit the server - MEMBERS, for each channel the user is no longer in """ actor = User(actor) _, _, message...
[ "def", "_parse_quit", "(", "client", ",", "command", ",", "actor", ",", "args", ")", ":", "actor", "=", "User", "(", "actor", ")", "_", ",", "_", ",", "message", "=", "args", ".", "partition", "(", "':'", ")", "client", ".", "dispatch_event", "(", ...
39.857143
0.001751
def _ref_replacer(match, passage): """ Helper to replace xpath/scope/refsDecl on iteration with passage value :param match: A RegExp match :type match: re.SRE_MATCH :param passage: A list with subreference informations :type passage: iter :rtype: basestring :return: Replaced string """...
[ "def", "_ref_replacer", "(", "match", ",", "passage", ")", ":", "groups", "=", "match", ".", "groups", "(", ")", "ref", "=", "next", "(", "passage", ")", "if", "ref", "is", "None", ":", "return", "groups", "[", "0", "]", "else", ":", "return", "\"{...
27.117647
0.002096
def network_connect(self, value): """The network_connect property. Args: value (string). the property value. """ if value == self._defaults['networkConnect'] and 'networkConnect' in self._values: del self._values['networkConnect'] else: ...
[ "def", "network_connect", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'networkConnect'", "]", "and", "'networkConnect'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'networkConnect'", ...
35.1
0.011111
def init_weights(self, m): """ Initialize the weights. """ classname = m.__class__.__name__ if classname.find('Linear') != -1: if hasattr(m, 'weight') and m.weight is not None: self.init_weight(m.weight) if hasattr(m, 'bias') and m.bias is not None...
[ "def", "init_weights", "(", "self", ",", "m", ")", ":", "classname", "=", "m", ".", "__class__", ".", "__name__", "if", "classname", ".", "find", "(", "'Linear'", ")", "!=", "-", "1", ":", "if", "hasattr", "(", "m", ",", "'weight'", ")", "and", "m"...
47.65
0.002057
def init(sf2, driver=None, file=None): """Initialize the audio. Return True on success, False on failure. This function needs to be called before you can have any audio. The sf2 argument should be the location of a valid soundfont file. The optional driver argument can be any of 'alsa', 'oss', '...
[ "def", "init", "(", "sf2", ",", "driver", "=", "None", ",", "file", "=", "None", ")", ":", "global", "midi", ",", "initialized", "if", "not", "initialized", ":", "if", "file", "is", "not", "None", ":", "midi", ".", "start_recording", "(", "file", ")"...
31.846154
0.001172
def hist(P, edges, **kwargs): r''' Plot histogram. ''' from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # extract local options axis = kwargs.pop( 'axis' , plt.gca() ) cindex = kwargs.pop( 'cindex' , None ) autoscale = kwargs.pop( 'auto...
[ "def", "hist", "(", "P", ",", "edges", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", ".", "collections", "import", "PatchCollection", "from", "matplotlib", ".", "patches", "import", "Polygon", "# extract local options", "axis", "=", "kwargs", ".", ...
24.8
0.040341
def __ticker_midi_note(x, pos): '''A ticker function for midi notes. Inputs x are interpreted as midi numbers, and converted to [NOTE][OCTAVE]+[cents]. ''' NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] cents = float(np.mod(x, 1.0)) if cents >= 0.5: cent...
[ "def", "__ticker_midi_note", "(", "x", ",", "pos", ")", ":", "NOTES", "=", "[", "'C'", ",", "'C#'", ",", "'D'", ",", "'D#'", ",", "'E'", ",", "'F'", ",", "'F#'", ",", "'G'", ",", "'G#'", ",", "'A'", ",", "'A#'", ",", "'B'", "]", "cents", "=", ...
25.571429
0.001795
def set_stream_class_lists_url(self, session_id): """ this method returns the url to set the stream class list """ url = self.api_url + '/v2/project/' + self.api_key + '/session/' + session_id + '/stream' return url
[ "def", "set_stream_class_lists_url", "(", "self", ",", "session_id", ")", ":", "url", "=", "self", ".", "api_url", "+", "'/v2/project/'", "+", "self", ".", "api_key", "+", "'/session/'", "+", "session_id", "+", "'/stream'", "return", "url" ]
59
0.012552
def initialize_create_state_map(self): """This is a mapping of create result message string to state. """ self.fabric_state_map = { fw_const.INIT_STATE_STR: fw_const.OS_IN_NETWORK_STATE, fw_const.OS_IN_NETWORK_CREATE_FAIL: fw_const.OS_IN_NETWORK_STATE, ...
[ "def", "initialize_create_state_map", "(", "self", ")", ":", "self", ".", "fabric_state_map", "=", "{", "fw_const", ".", "INIT_STATE_STR", ":", "fw_const", ".", "OS_IN_NETWORK_STATE", ",", "fw_const", ".", "OS_IN_NETWORK_CREATE_FAIL", ":", "fw_const", ".", "OS_IN_NE...
48.805556
0.001116
def workspace_state_changed(ob, event): """ when a workspace is made 'open', we need to give all intranet users the 'Guest' role equally, when the workspace is not open, we need to remove the role again """ workspace = event.object roles = ['Guest', ] if event.new_state.id == 'open'...
[ "def", "workspace_state_changed", "(", "ob", ",", "event", ")", ":", "workspace", "=", "event", ".", "object", "roles", "=", "[", "'Guest'", ",", "]", "if", "event", ".", "new_state", ".", "id", "==", "'open'", ":", "api", ".", "group", ".", "grant_rol...
29.25
0.001379
def filename(cls, tag, schemas, ext='.rnc'): """given a tag and a list of schemas, return the filename of the schema. If schemas is a string, treat it as a comma-separated list. """ if type(schemas)==str: schemas = re.split("\s*,\s*", schemas) for schema in schemas: ...
[ "def", "filename", "(", "cls", ",", "tag", ",", "schemas", ",", "ext", "=", "'.rnc'", ")", ":", "if", "type", "(", "schemas", ")", "==", "str", ":", "schemas", "=", "re", ".", "split", "(", "\"\\s*,\\s*\"", ",", "schemas", ")", "for", "schema", "in...
45.5
0.017241
def check_positive(value, strict=False): """ Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed """ if not strict and value < 0: raise ValueError(...
[ "def", "check_positive", "(", "value", ",", "strict", "=", "False", ")", ":", "if", "not", "strict", "and", "value", "<", "0", ":", "raise", "ValueError", "(", "\"Value must be positive or zero, not %s\"", "%", "str", "(", "value", ")", ")", "if", "strict", ...
30.8
0.002101
def transform_32_33(inst, new_inst, i, n, offset, instructions, new_asm): """MAKEFUNCTION adds another const. probably MAKECLASS as well """ add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'): # Previous instruction should b...
[ "def", "transform_32_33", "(", "inst", ",", "new_inst", ",", "i", ",", "n", ",", "offset", ",", "instructions", ",", "new_asm", ")", ":", "add_size", "=", "xdis", ".", "op_size", "(", "new_inst", ".", "opcode", ",", "opcode_33", ")", "if", "inst", ".",...
43.285714
0.001291
def define_ppo_step(data_points, hparams, action_space, lr): """Define ppo step.""" observation, action, discounted_reward, norm_advantage, old_pdf = data_points obs_shape = common_layers.shape_list(observation) observation = tf.reshape( observation, [obs_shape[0] * obs_shape[1]] + obs_shape[2:] ) (l...
[ "def", "define_ppo_step", "(", "data_points", ",", "hparams", ",", "action_space", ",", "lr", ")", ":", "observation", ",", "action", ",", "discounted_reward", ",", "norm_advantage", ",", "old_pdf", "=", "data_points", "obs_shape", "=", "common_layers", ".", "sh...
40.055556
0.015572
def _is_pid_running_on_windows(pid): """Check if a process is running on windows systems based on the pid.""" pid = str(pid) # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(r'tasklis...
[ "def", "_is_pid_running_on_windows", "(", "pid", ")", ":", "pid", "=", "str", "(", "pid", ")", "# Hide flashing command prompt\r", "startupinfo", "=", "subprocess", ".", "STARTUPINFO", "(", ")", "startupinfo", ".", "dwFlags", "|=", "subprocess", ".", "STARTF_USESH...
37.444444
0.001447
def create_cube(): """ Generate vertices & indices for a filled and outlined cube Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. filled : array Indices to use to produce a filled cube. outline : array Indices to use to produce an o...
[ "def", "create_cube", "(", ")", ":", "vtype", "=", "[", "(", "'position'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'texcoord'", ",", "np", ".", "float32", ",", "2", ")", ",", "(", "'normal'", ",", "np", ".", "float32", ",", "3", ")...
29.972973
0.000436
def unique(iterable): """ Yield unique values in iterable, preserving order. """ seen = set() for value in iterable: if not value in seen: seen.add(value) yield value
[ "def", "unique", "(", "iterable", ")", ":", "seen", "=", "set", "(", ")", "for", "value", "in", "iterable", ":", "if", "not", "value", "in", "seen", ":", "seen", ".", "add", "(", "value", ")", "yield", "value" ]
23.333333
0.009174
def get_tag(self, name): """Return the tag as Tag object.""" res = self.get_request('/tag/' + name) return Tag(cloud_manager=self, **res['tag'])
[ "def", "get_tag", "(", "self", ",", "name", ")", ":", "res", "=", "self", ".", "get_request", "(", "'/tag/'", "+", "name", ")", "return", "Tag", "(", "cloud_manager", "=", "self", ",", "*", "*", "res", "[", "'tag'", "]", ")" ]
41.25
0.011905
def gff3_parse_attributes(attributes_string): """ Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary. """ attributes = dict() fields = attributes_string.split(';') for f in fields: if '=' in f: key, value = f.split('=')...
[ "def", "gff3_parse_attributes", "(", "attributes_string", ")", ":", "attributes", "=", "dict", "(", ")", "fields", "=", "attributes_string", ".", "split", "(", "';'", ")", "for", "f", "in", "fields", ":", "if", "'='", "in", "f", ":", "key", ",", "value",...
31.294118
0.009124
def random_split(valid_pct:float, *arrs:NPArrayableList)->SplitArrayList: "Randomly split `arrs` with `valid_pct` ratio. good for creating validation set." assert (valid_pct>=0 and valid_pct<=1), 'Validation set percentage should be between 0 and 1' is_train = np.random.uniform(size=(len(arrs[0]),)) > valid...
[ "def", "random_split", "(", "valid_pct", ":", "float", ",", "*", "arrs", ":", "NPArrayableList", ")", "->", "SplitArrayList", ":", "assert", "(", "valid_pct", ">=", "0", "and", "valid_pct", "<=", "1", ")", ",", "'Validation set percentage should be between 0 and 1...
72.2
0.021918
def dnd_endSnooze(self, **kwargs) -> SlackResponse: """Ends the current user's snooze mode immediately.""" self._validate_xoxp_token() return self.api_call("dnd.endSnooze", json=kwargs)
[ "def", "dnd_endSnooze", "(", "self", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "self", ".", "_validate_xoxp_token", "(", ")", "return", "self", ".", "api_call", "(", "\"dnd.endSnooze\"", ",", "json", "=", "kwargs", ")" ]
51.5
0.009569
def IsDevice(self): """Determines if the file entry is a device. Returns: bool: True if the file entry is a device. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entr...
[ "def", "IsDevice", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type",...
32.181818
0.008242
def entries(self): """Returns file meta-data entries one by one.""" self.meta.seek(self.file_list_start) for i in range(0, self.num_files): yield self._get_node()
[ "def", "entries", "(", "self", ")", ":", "self", ".", "meta", ".", "seek", "(", "self", ".", "file_list_start", ")", "for", "i", "in", "range", "(", "0", ",", "self", ".", "num_files", ")", ":", "yield", "self", ".", "_get_node", "(", ")" ]
38.8
0.010101
def _repeat_iter(input_iter): """Iterate over the input iter values. Then repeat the last value indefinitely. This is useful to repeat seed values when an insufficient number of seeds are provided. E.g. KISS(1) effectively becomes KISS(1, 1, 1, 1), rather than (if we just used default values) KISS(...
[ "def", "_repeat_iter", "(", "input_iter", ")", ":", "last_value", "=", "None", "for", "value", "in", "input_iter", ":", "last_value", "=", "value", "yield", "value", "if", "last_value", "is", "not", "None", ":", "while", "True", ":", "yield", "last_value" ]
42
0.001164
async def send_pages(self): """A helper utility to send the page output from :attr:`paginator` to the destination.""" destination = self.get_destination() for page in self.paginator.pages: await destination.send(page)
[ "async", "def", "send_pages", "(", "self", ")", ":", "destination", "=", "self", ".", "get_destination", "(", ")", "for", "page", "in", "self", ".", "paginator", ".", "pages", ":", "await", "destination", ".", "send", "(", "page", ")" ]
49.8
0.011858
def return_env(self, exists=True): """ Return environment dict. Parameters ---------- exists: bool It True, only return existing paths. """ env = dict( include=self._build_paths('include', [self.VCIncl...
[ "def", "return_env", "(", "self", ",", "exists", "=", "True", ")", ":", "env", "=", "dict", "(", "include", "=", "self", ".", "_build_paths", "(", "'include'", ",", "[", "self", ".", "VCIncludes", ",", "self", ".", "OSIncludes", ",", "self", ".", "UC...
42.886364
0.001036
def clique(graph, id): """ Returns the largest possible clique for the node with given id. """ clique = [id] for n in graph.nodes: friend = True for id in clique: if n.id == id or graph.edge(n.id, id) == None: friend = False break ...
[ "def", "clique", "(", "graph", ",", "id", ")", ":", "clique", "=", "[", "id", "]", "for", "n", "in", "graph", ".", "nodes", ":", "friend", "=", "True", "for", "id", "in", "clique", ":", "if", "n", ".", "id", "==", "id", "or", "graph", ".", "e...
23.4375
0.012821
def bovy_plot3d(*args,**kwargs): """ NAME: bovy_plot3d PURPOSE: plot in 3d much as in 2d INPUT: see http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed ylabel - (raw stri...
[ "def", "bovy_plot3d", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "overplot", "=", "kwargs", ".", "pop", "(", "'overplot'", ",", "False", ")", "if", "not", "overplot", ":", "pyplot", ".", "figure", "(", ")", "ax", "=", "pyplot", ".", "gca"...
25.964706
0.018333
def do_p(self, arg): """p expression Print the value of the expression. """ try: self.message(bdb.safe_repr(self._getval(arg))) except Exception: pass
[ "def", "do_p", "(", "self", ",", "arg", ")", ":", "try", ":", "self", ".", "message", "(", "bdb", ".", "safe_repr", "(", "self", ".", "_getval", "(", "arg", ")", ")", ")", "except", "Exception", ":", "pass" ]
25.875
0.009346
def addInput(self, key): """Add key to input : key, value or map """ if key not in self.inputs: self.inputs.append(key) root = self.etree t_inputs = root.find('inputs') if not t_inputs : t_inputs = ctree.SubElement(root, 'inputs') t_inpu...
[ "def", "addInput", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ".", "inputs", ":", "self", ".", "inputs", ".", "append", "(", "key", ")", "root", "=", "self", ".", "etree", "t_inputs", "=", "root", ".", "find", "(", "'inp...
23.133333
0.00831
def cluster_reduce(idx, snr, window_size): """ Reduce the events by clustering over a window Parameters ----------- indices: Array The list of indices of the SNR values snr: Array The list of SNR value window_size: int The size of the window in integer samples. Retu...
[ "def", "cluster_reduce", "(", "idx", ",", "snr", ",", "window_size", ")", ":", "ind", "=", "findchirp_cluster_over_window", "(", "idx", ",", "snr", ",", "window_size", ")", "return", "idx", ".", "take", "(", "ind", ")", ",", "snr", ".", "take", "(", "i...
25.571429
0.001795
def maybe_canonicalize_exe_path(exe_name, iocontext): '''There's a tricky interaction between exe paths and `dir`. Exe paths can be relative, and so we have to ask: Is an exe path interpreted relative to the parent's cwd, or the child's? The answer is that it's platform dependent! >.< (Windows uses the ...
[ "def", "maybe_canonicalize_exe_path", "(", "exe_name", ",", "iocontext", ")", ":", "has_sep", "=", "(", "os", ".", "path", ".", "sep", "in", "exe_name", "or", "(", "os", ".", "path", ".", "altsep", "is", "not", "None", "and", "os", ".", "path", ".", ...
59.205882
0.000489
def iterbyscore(self, min='-inf', max='+inf', start=None, num=None, withscores=False, reverse=None): """ Return a range of values from the sorted set name with scores between @min and @max. If @start and @num are specified, then return a slice of the rang...
[ "def", "iterbyscore", "(", "self", ",", "min", "=", "'-inf'", ",", "max", "=", "'+inf'", ",", "start", "=", "None", ",", "num", "=", "None", ",", "withscores", "=", "False", ",", "reverse", "=", "None", ")", ":", "reverse", "=", "reverse", "if", "r...
45
0.002251
def get_mst(points): """ Parameters ---------- points : list of points (geometry.Point) The first element of the list is the center of the bounding box of the first stroke, the second one belongs to the seconds stroke, ... Returns ------- mst : square matrix 0 nodes ...
[ "def", "get_mst", "(", "points", ")", ":", "graph", "=", "Graph", "(", ")", "for", "point", "in", "points", ":", "graph", ".", "add_node", "(", "point", ")", "graph", ".", "generate_euclidean_edges", "(", ")", "matrix", "=", "scipy", ".", "sparse", "."...
31.555556
0.001139
def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', cache=False): """ Convert argument to datetime. Parameters ---------- arg : integ...
[ "def", "to_datetime", "(", "arg", ",", "errors", "=", "'raise'", ",", "dayfirst", "=", "False", ",", "yearfirst", "=", "False", ",", "utc", "=", "None", ",", "box", "=", "True", ",", "format", "=", "None", ",", "exact", "=", "True", ",", "unit", "=...
38.277273
0.000116
def getKeywordList(self, kw): """ Return lists of all attribute values for all active chips in the ``imageObject``. """ kwlist = [] for chip in range(1,self._numchips+1,1): sci_chip = self._image[self.scienceExt,chip] if sci_chip.group_member: ...
[ "def", "getKeywordList", "(", "self", ",", "kw", ")", ":", "kwlist", "=", "[", "]", "for", "chip", "in", "range", "(", "1", ",", "self", ".", "_numchips", "+", "1", ",", "1", ")", ":", "sci_chip", "=", "self", ".", "_image", "[", "self", ".", "...
29.230769
0.012755
def save_callback(operation, graphdef): '''callback from save thread''' if operation == 'test': for e in graphdef.expressions: if expression_ok(e, msgs): graphdef.expression = e pipe_graph_input.send('graph ' + graphdef.expression) return ...
[ "def", "save_callback", "(", "operation", ",", "graphdef", ")", ":", "if", "operation", "==", "'test'", ":", "for", "e", "in", "graphdef", ".", "expressions", ":", "if", "expression_ok", "(", "e", ",", "msgs", ")", ":", "graphdef", ".", "expression", "="...
36.333333
0.002237
def focus(self): """ Call this to give this Widget the input focus. """ self._has_focus = True self._frame.move_to(self._x, self._y, self._h) if self._on_focus is not None: self._on_focus()
[ "def", "focus", "(", "self", ")", ":", "self", ".", "_has_focus", "=", "True", "self", ".", "_frame", ".", "move_to", "(", "self", ".", "_x", ",", "self", ".", "_y", ",", "self", ".", "_h", ")", "if", "self", ".", "_on_focus", "is", "not", "None"...
30.25
0.008032
def Diguilio_Teja(T, xs, sigmas_Tb, Tbs, Tcs): r'''Calculates surface tension of a liquid mixture according to mixing rules in [1]_. .. math:: \sigma = 1.002855(T^*)^{1.118091} \frac{T}{T_b} \sigma_r T^* = \frac{(T_c/T)-1}{(T_c/T_b)-1} \sigma_r = \sum x_i \sigma_i T_b = ...
[ "def", "Diguilio_Teja", "(", "T", ",", "xs", ",", "sigmas_Tb", ",", "Tbs", ",", "Tcs", ")", ":", "if", "not", "none_and_length_check", "(", "[", "xs", ",", "sigmas_Tb", ",", "Tbs", ",", "Tcs", "]", ")", ":", "raise", "Exception", "(", "'Function inputs...
32.75
0.00218
def _create_mappings(self, spec): """ Create property name map based on aliases. """ ret = dict(zip(set(spec.fields), set(spec.fields))) ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias])) return ret
[ "def", "_create_mappings", "(", "self", ",", "spec", ")", ":", "ret", "=", "dict", "(", "zip", "(", "set", "(", "spec", ".", "fields", ")", ",", "set", "(", "spec", ".", "fields", ")", ")", ")", "ret", ".", "update", "(", "dict", "(", "[", "(",...
50.2
0.011765
def get_families_by_ids(self, family_ids=None): """Gets a ``FamilyList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the families specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` ...
[ "def", "get_families_by_ids", "(", "self", ",", "family_ids", "=", "None", ")", ":", "if", "family_ids", "is", "None", ":", "raise", "NullArgument", "(", ")", "families", "=", "[", "]", "for", "i", "in", "family_ids", ":", "family", "=", "None", "url_pat...
41.775
0.00117
def insert(self, item): 'Insert a new item. If equal keys are found, add to the left' k = self._key(item) i = bisect_left(self._keys, k) self._keys.insert(i, k) self._items.insert(i, item)
[ "def", "insert", "(", "self", ",", "item", ")", ":", "k", "=", "self", ".", "_key", "(", "item", ")", "i", "=", "bisect_left", "(", "self", ".", "_keys", ",", "k", ")", "self", ".", "_keys", ".", "insert", "(", "i", ",", "k", ")", "self", "."...
37.333333
0.008734
def generate_IR(self): """Parses the text of each spec and returns an API description. Returns None if an error was encountered during parsing.""" raw_api = [] for partial_ast in self._partial_asts: namespace_ast_node = self._extract_namespace_ast_node(partial_ast) ...
[ "def", "generate_IR", "(", "self", ")", ":", "raw_api", "=", "[", "]", "for", "partial_ast", "in", "self", ".", "_partial_asts", ":", "namespace_ast_node", "=", "self", ".", "_extract_namespace_ast_node", "(", "partial_ast", ")", "namespace", "=", "self", ".",...
41.233333
0.00158
def get(self, hyp_lengths: Union[mx.nd.NDArray, int, float], reference_lengths: Optional[Union[mx.nd.NDArray, int, float]]) -> Union[mx.nd.NDArray, float]: """ Calculate the length penalty for the given vector of lengths. :param hyp_lengths: Hypotheses lengths. :...
[ "def", "get", "(", "self", ",", "hyp_lengths", ":", "Union", "[", "mx", ".", "nd", ".", "NDArray", ",", "int", ",", "float", "]", ",", "reference_lengths", ":", "Optional", "[", "Union", "[", "mx", ".", "nd", ".", "NDArray", ",", "int", ",", "float...
43.714286
0.0096
def handleDetailDblClick( self, item ): """ Handles when a detail item is double clicked on. :param item | <QTreeWidgetItem> """ if ( isinstance(item, XOrbRecordItem) ): self.emitRecordDoubleClicked(item.record())
[ "def", "handleDetailDblClick", "(", "self", ",", "item", ")", ":", "if", "(", "isinstance", "(", "item", ",", "XOrbRecordItem", ")", ")", ":", "self", ".", "emitRecordDoubleClicked", "(", "item", ".", "record", "(", ")", ")" ]
34.875
0.024476
def _parse_specs(specs, Ks): ''' Set up the different functions we need to call. Returns: - a dict mapping base estimator functions to _FuncInfo objects. If the function needs_alpha, then the alphas attribute is an array of alpha values and pos is a corresponding array of indice...
[ "def", "_parse_specs", "(", "specs", ",", "Ks", ")", ":", "funcs", "=", "{", "}", "metas", "=", "{", "}", "meta_deps", "=", "defaultdict", "(", "set", ")", "def", "add_func", "(", "func", ",", "alpha", "=", "None", ",", "pos", "=", "None", ")", "...
40.446927
0.00027