text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def on_save_interpretation_button(self, event): """ save the current interpretation temporarily (not to a file) """ if "specimen_int_uT" not in self.Data[self.s]['pars']: return if 'deleted' in self.Data[self.s]['pars']: self.Data[self.s]['pars'].pop('dele...
[ "def", "on_save_interpretation_button", "(", "self", ",", "event", ")", ":", "if", "\"specimen_int_uT\"", "not", "in", "self", ".", "Data", "[", "self", ".", "s", "]", "[", "'pars'", "]", ":", "return", "if", "'deleted'", "in", "self", ".", "Data", "[", ...
44.451613
17.225806
def _set_cspf_group_subnet(self, v, load=False): """ Setter method for cspf_group_subnet, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/cspf_group/cspf_group_subnet (list) If this variable is read-only (config: false) in the source YANG file, then _set_cspf_group_subnet is consider...
[ "def", "_set_cspf_group_subnet", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",",...
129.272727
63.090909
def bind_bottom_up(lower, upper, __fval=None, **fval): """Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer, if ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501 layers, the last one will be used as default....
[ "def", "bind_bottom_up", "(", "lower", ",", "upper", ",", "__fval", "=", "None", ",", "*", "*", "fval", ")", ":", "if", "__fval", "is", "not", "None", ":", "fval", ".", "update", "(", "__fval", ")", "lower", ".", "payload_guess", "=", "lower", ".", ...
49.666667
25.466667
def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None, cert_contents=None, key_path=None, key_contents=None): """ returns a list of NetJSON extra files for automatically generated clients produces side effects in ``client`` dictionary ...
[ "def", "_auto_client_files", "(", "cls", ",", "client", ",", "ca_path", "=", "None", ",", "ca_contents", "=", "None", ",", "cert_path", "=", "None", ",", "cert_contents", "=", "None", ",", "key_path", "=", "None", ",", "key_contents", "=", "None", ")", "...
44.73913
12.73913
def delete_unit(unit_id, **kwargs): """ Delete a unit from the DB. Raises and exception if the unit does not exist """ try: db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() db.DBSession.delete(db_unit) db.DBSession.flush() return True ex...
[ "def", "delete_unit", "(", "unit_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "db_unit", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "filter", "(", "Unit", ".", "id", "==", "unit_id", ")", ".", "one", "(", ")", "db", ...
28.785714
18.5
def validate_config(self, organization, config, actor=None): """ ``` if config['foo'] and not config['bar']: raise PluginError('You cannot configure foo with bar') return config ``` """ if config.get('name'): client = self.get_client(actor)...
[ "def", "validate_config", "(", "self", ",", "organization", ",", "config", ",", "actor", "=", "None", ")", ":", "if", "config", ".", "get", "(", "'name'", ")", ":", "client", "=", "self", ".", "get_client", "(", "actor", ")", "try", ":", "repo", "=",...
32.529412
15.235294
def get_all_stations(self, station_type=None): """Returns information of all stations. @param<optional> station_type: ['mainline', 'suburban', 'dart'] """ params = None if station_type and station_type in STATION_TYPE_TO_CODE_DICT: url = self.api_base_url + 'getAllSta...
[ "def", "get_all_stations", "(", "self", ",", "station_type", "=", "None", ")", ":", "params", "=", "None", "if", "station_type", "and", "station_type", "in", "STATION_TYPE_TO_CODE_DICT", ":", "url", "=", "self", ".", "api_base_url", "+", "'getAllStationsXML_WithSt...
35.3
20.3
def data_from_dataset(dataset, X_indexing=None, y_indexing=None): """Try to access X and y attribute from dataset. Also works when dataset is a subset. Parameters ---------- dataset : skorch.dataset.Dataset or torch.utils.data.Subset The incoming dataset should be a ``skorch.dataset.Dataset`...
[ "def", "data_from_dataset", "(", "dataset", ",", "X_indexing", "=", "None", ",", "y_indexing", "=", "None", ")", ":", "X", ",", "y", "=", "_none", ",", "_none", "if", "isinstance", "(", "dataset", ",", "Subset", ")", ":", "X", ",", "y", "=", "data_fr...
37.705882
22.088235
def _loop(self, reader): """Main execution loop of the scheduler. The loop runs every second. Between iterations, the loop listens for schedule or cancel requests coming from Flask via over the gipc pipe (reader) and modifies the queue accordingly. When a task completes, it is rescheduled """ ...
[ "def", "_loop", "(", "self", ",", "reader", ")", ":", "results", "=", "set", "(", ")", "while", "True", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "self", ".", "_task_queue", "and", "self", ".", "_task_queue", "[", "0...
35.942308
14.769231
def initUi(self): """Initalizes the Uuser Interface with all sub widgets. """ self.gridLayout = QtGui.QGridLayout(self) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.buttonFrame = QtGui.QFrame(self) #self.buttonFrame.setMinimumSize(QtCore.QSize(250, 50)) #...
[ "def", "initUi", "(", "self", ")", ":", "self", ".", "gridLayout", "=", "QtGui", ".", "QGridLayout", "(", "self", ")", "self", ".", "gridLayout", ".", "setContentsMargins", "(", "0", ",", "0", ",", "0", ",", "0", ")", "self", ".", "buttonFrame", "=",...
45.756098
25.02439
def get_absolute_url(self): """Returns the default URL for this panel. The default URL is defined as the URL pattern with ``name="index"`` in the URLconf for this panel. """ try: return reverse('horizon:%s:%s:%s' % (self._registered_with.slug, ...
[ "def", "get_absolute_url", "(", "self", ")", ":", "try", ":", "return", "reverse", "(", "'horizon:%s:%s:%s'", "%", "(", "self", ".", "_registered_with", ".", "slug", ",", "self", ".", "slug", ",", "self", ".", "index_url_name", ")", ")", "except", "Excepti...
44.4375
20.25
def upload_sync(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and...
[ "def", "upload_sync", "(", "self", ",", "remote_path", ",", "local_path", ",", "callback", "=", "None", ")", ":", "self", ".", "upload", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ")", "if", "callback", ":", "callback", "...
50.333333
29.583333
def setconf(self, conf, rscpath, logger=None): """Set input conf in input path. :param Configuration conf: conf to write to path. :param str rscpath: specific resource path to use. :param Logger logger: used to log info/errors. :param bool error: raise catched errors. :r...
[ "def", "setconf", "(", "self", ",", "conf", ",", "rscpath", ",", "logger", "=", "None", ")", ":", "resource", "=", "self", ".", "pathresource", "(", "rscpath", "=", "rscpath", ",", "logger", "=", "logger", ")", "if", "resource", "is", "None", ":", "r...
37.375
20.166667
def check_dependencies(self): "Checks if the test program is available in the python environnement" if self.test_program == 'nose': try: import nose except ImportError: sys.exit('Nosetests is not available on your system. Please install it and try ...
[ "def", "check_dependencies", "(", "self", ")", ":", "if", "self", ".", "test_program", "==", "'nose'", ":", "try", ":", "import", "nose", "except", "ImportError", ":", "sys", ".", "exit", "(", "'Nosetests is not available on your system. Please install it and try to r...
45.518519
25.592593
def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None): """ Helper function for element-wise operation. The function will perform numpy-like broadcasting if needed and call different functions. Parameters -------- lhs : NDArray or numeric value Left-hand side operand....
[ "def", "_ufunc_helper", "(", "lhs", ",", "rhs", ",", "fn_array", ",", "fn_scalar", ",", "lfn_scalar", ",", "rfn_scalar", "=", "None", ")", ":", "if", "isinstance", "(", "lhs", ",", "numeric_types", ")", ":", "if", "isinstance", "(", "rhs", ",", "numeric_...
32.755556
21.822222
def create_nve_member(self, nexus_host, nve_int_num, vni, mcast_group): """Add a member configuration to the NVE interface.""" # Do CLI [no] member vni %s mcast-group %s # beneath int nve1 starttime = time.time() path = snipp.PATH_VNI_UPDATE % (nve_int_num, vni) body =...
[ "def", "create_nve_member", "(", "self", ",", "nexus_host", ",", "nve_int_num", ",", "vni", ",", "mcast_group", ")", ":", "# Do CLI [no] member vni %s mcast-group %s", "# beneath int nve1", "starttime", "=", "time", ".", "time", "(", ")", "path", "=", "snipp", "."...
34.866667
19.666667
def calculate_relative_url(url, filename=None, baseurl=None, subpath=None): """ Calculate the relative path for a URL relative to a base URL, possibly also injecting in a subpath prefix. """ # ensure the provided subpath is a list if isinstance(subpath, str): subpath = subpath.strip("/").sp...
[ "def", "calculate_relative_url", "(", "url", ",", "filename", "=", "None", ",", "baseurl", "=", "None", ",", "subpath", "=", "None", ")", ":", "# ensure the provided subpath is a list", "if", "isinstance", "(", "subpath", ",", "str", ")", ":", "subpath", "=", ...
41.64
27.32
def filtered_context(context): """Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.""" ctx = Context(context.opt) for resource in context.resources(): if resource.child:...
[ "def", "filtered_context", "(", "context", ")", ":", "ctx", "=", "Context", "(", "context", ".", "opt", ")", "for", "resource", "in", "context", ".", "resources", "(", ")", ":", "if", "resource", ".", "child", ":", "continue", "if", "resource", ".", "f...
27.066667
17.666667
def get_property_names(self, is_allprop): """Return list of supported property names in Clark Notation. Note that 'allprop', despite its name, which remains for backward-compatibility, does not return every property, but only dead properties and the live properties defined in RFC4918. ...
[ "def", "get_property_names", "(", "self", ",", "is_allprop", ")", ":", "# Live properties", "propNameList", "=", "[", "]", "propNameList", ".", "append", "(", "\"{DAV:}resourcetype\"", ")", "if", "self", ".", "get_creation_date", "(", ")", "is", "not", "None", ...
39.04
19.6
def alternative_titles(self, **kwargs): """ Get the alternative titles for a specific movie id. Args: country: (optional) ISO 3166-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON re...
[ "def", "alternative_titles", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_id_path", "(", "'alternative_titles'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_valu...
31.5
18.75
def set_naming_params(self, autonaming=None, prefix=None, suffix=None, name=None): """Setups processes naming parameters. :param bool autonaming: Automatically set process name to something meaningful. Generated process names may be 'uWSGI Master', 'uWSGI Worker #', etc. :param str...
[ "def", "set_naming_params", "(", "self", ",", "autonaming", "=", "None", ",", "prefix", "=", "None", ",", "suffix", "=", "None", ",", "name", "=", "None", ")", ":", "self", ".", "_set", "(", "'auto-procname'", ",", "autonaming", ",", "cast", "=", "bool...
40.842105
29.105263
def crossover(cross): """Return an inspyred crossover function based on the given function. This function generator takes a function that operates on only two parent candidates to produce an iterable sequence of offspring (typically two). The generator handles the pairing of selected parents and co...
[ "def", "crossover", "(", "cross", ")", ":", "@", "functools", ".", "wraps", "(", "cross", ")", "def", "inspyred_crossover", "(", "random", ",", "candidates", ",", "args", ")", ":", "if", "len", "(", "candidates", ")", "%", "2", "==", "1", ":", "candi...
36.347826
19.782609
def on_post_delete(sender, **kwargs): """Expire ultracache cache keys affected by this object """ if not invalidate: return if kwargs.get("raw", False): return if sender is MigrationRecorder.Migration: return if issubclass(sender, Model): obj = kwargs["instance"] ...
[ "def", "on_post_delete", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "invalidate", ":", "return", "if", "kwargs", ".", "get", "(", "\"raw\"", ",", "False", ")", ":", "return", "if", "sender", "is", "MigrationRecorder", ".", "Migration"...
33.972973
12.513514
def check(wants, has): """ Check if a desired scope ``wants`` is part of an available scope ``has``. Returns ``False`` if not, return ``True`` if yes. :example: If a list of scopes such as :: READ = 1 << 1 WRITE = 1 << 2 READ_WRITE = READ | WRITE SCOPES = ( ...
[ "def", "check", "(", "wants", ",", "has", ")", ":", "if", "wants", "&", "has", "==", "0", ":", "return", "False", "if", "wants", "&", "has", "<", "wants", ":", "return", "False", "return", "True" ]
20.217391
21.73913
def format_tasks(tasks): """Converts a list of tasks to a list of string representations. Args: tasks: A list of the tasks to convert. Returns: A list of string formatted tasks. """ return ['%d : %s (%s)' % (task.key.id(), task.description, ('do...
[ "def", "format_tasks", "(", "tasks", ")", ":", "return", "[", "'%d : %s (%s)'", "%", "(", "task", ".", "key", ".", "id", "(", ")", ",", "task", ".", "description", ",", "(", "'done'", "if", "task", ".", "done", "else", "'created %s'", "%", "task", "....
32.076923
13.384615
def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project...
[ "def", "get_cmdclass", "(", ")", ":", "if", "\"versioneer\"", "in", "sys", ".", "modules", ":", "del", "sys", ".", "modules", "[", "\"versioneer\"", "]", "# this fixes the \"python setup.py develop\" case (also 'install' and", "# 'easy_install .'), in which subdependencies of...
42.054688
20.132813
def parse_table(fq_table: str) -> Tuple[str, str]: """Parse a tablename into tuple(<schema>, <table>). Schema defaults to doc if the table name doesn't contain a schema. >>> parse_table('x.users') ('x', 'users') >>> parse_table('users') ('doc', 'users') """ parts = fq_table.split('.')...
[ "def", "parse_table", "(", "fq_table", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "parts", "=", "fq_table", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "return", "'doc'", ",", "parts", "["...
25.166667
18.277778
def read_root(self, fid): """Read the root node from an acclaim skeleton file stream.""" lin = self.read_line(fid) while lin[0] != ':': parts = lin.split() if parts[0]=='order': order = [] for i in range(1, len(parts)): ...
[ "def", "read_root", "(", "self", ",", "fid", ")", ":", "lin", "=", "self", ".", "read_line", "(", "fid", ")", "while", "lin", "[", "0", "]", "!=", "':'", ":", "parts", "=", "lin", ".", "split", "(", ")", "if", "parts", "[", "0", "]", "==", "'...
45.404762
10.928571
def translate(env, func, *args, **kwargs): """ Given a shellcode environment, a function and its parameters, translate the function to a list of shellcode operations ready to be compiled or assembled using :meth:`~pwnypack.shellcode.base.BaseEnvironment.compile` or :meth:`~pwnypack.shellcode.base.Ba...
[ "def", "translate", "(", "env", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func_code", "=", "six", ".", "get_function_code", "(", "func", ")", "func_globals", "=", "dict", "(", "__builtins__", ")", "func_globals", ".", "update", ...
32.791367
18.402878
def is_file(package): """Determine if a package name is for a File dependency.""" if hasattr(package, "keys"): return any(key for key in package.keys() if key in ["file", "path"]) if os.path.exists(str(package)): return True for start in SCHEME_LIST: if str(package).startswith(...
[ "def", "is_file", "(", "package", ")", ":", "if", "hasattr", "(", "package", ",", "\"keys\"", ")", ":", "return", "any", "(", "key", "for", "key", "in", "package", ".", "keys", "(", ")", "if", "key", "in", "[", "\"file\"", ",", "\"path\"", "]", ")"...
27.461538
20.153846
def data(): """Data providing function: Make sure to have every relevant import statement included here and return data as used in model function below. This function is separated from model() so that hyperopt won't reload data for each evaluation run. """ from keras.datasets import mnist f...
[ "def", "data", "(", ")", ":", "from", "keras", ".", "datasets", "import", "mnist", "from", "keras", ".", "utils", "import", "np_utils", "(", "x_train", ",", "y_train", ")", ",", "(", "x_test", ",", "y_test", ")", "=", "mnist", ".", "load_data", "(", ...
38.5
15.4
def _async_poll(self, poller, async_seconds, async_poll_interval): ''' launch an async job, if poll_interval is set, wait for completion ''' results = poller.wait(async_seconds, async_poll_interval) # mark any hosts that are still listed as started as failed # since these likely got ki...
[ "def", "_async_poll", "(", "self", ",", "poller", ",", "async_seconds", ",", "async_poll_interval", ")", ":", "results", "=", "poller", ".", "wait", "(", "async_seconds", ",", "async_poll_interval", ")", "# mark any hosts that are still listed as started as failed", "# ...
44.076923
25.307692
def get_team_push_restrictions(self): """ :calls: `GET /repos/:owner/:repo/branches/:branch/protection/restrictions/teams <https://developer.github.com/v3/repos/branches>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team` """ return github.Paginate...
[ "def", "get_team_push_restrictions", "(", "self", ")", ":", "return", "github", ".", "PaginatedList", ".", "PaginatedList", "(", "github", ".", "Team", ".", "Team", ",", "self", ".", "_requester", ",", "self", ".", "protection_url", "+", "\"/restrictions/teams\"...
43
23
def fmap(self, f: 'WrappedFunction') -> 'WrappedFunction': ''' function map for Wrapped Function. A forced transfermation to WrappedFunction would be applied.async def fmap(self, f: 'WrappedFunction') -> 'WrappedFunction' ''' if not isinstance(f, WrappedFunction): ...
[ "def", "fmap", "(", "self", ",", "f", ":", "'WrappedFunction'", ")", "->", "'WrappedFunction'", ":", "if", "not", "isinstance", "(", "f", ",", "WrappedFunction", ")", ":", "f", "=", "WrappedFunction", "(", "f", ")", "return", "WrappedFunction", "(", "lambd...
50.555556
33.666667
def bipartition_indices(N): """Return indices for undirected bipartitions of a sequence. Args: N (int): The length of the sequence. Returns: list: A list of tuples containing the indices for each of the two parts. Example: >>> N = 3 >>> bipartition_indices(N) ...
[ "def", "bipartition_indices", "(", "N", ")", ":", "result", "=", "[", "]", "if", "N", "<=", "0", ":", "return", "result", "for", "i", "in", "range", "(", "2", "**", "(", "N", "-", "1", ")", ")", ":", "part", "=", "[", "[", "]", ",", "[", "]...
24.961538
21.230769
def identifiers(dataset_uri): """List the item identifiers in the dataset.""" dataset = dtoolcore.DataSet.from_uri(dataset_uri) for i in dataset.identifiers: click.secho(i)
[ "def", "identifiers", "(", "dataset_uri", ")", ":", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "dataset_uri", ")", "for", "i", "in", "dataset", ".", "identifiers", ":", "click", ".", "secho", "(", "i", ")" ]
37.6
9.8
def _fix_dynamic_class_lookup(cls, pstfx): """Fix name lookup problem that prevents pickling of dynamically defined classes. Parameters ---------- cls : class Dynamically generated class to which fix is to be applied pstfx : string Postfix that can be used to identify dynamically ge...
[ "def", "_fix_dynamic_class_lookup", "(", "cls", ",", "pstfx", ")", ":", "# Extended name for the class that will be added to the module namespace", "extnm", "=", "'_'", "+", "cls", ".", "__name__", "+", "'_'", "+", "pstfx", "# Get the module in which the dynamic class is defi...
35.6
18.68
def log_weight(probs, weights, name='log_weight'): """Log weight. Parameters ----------- probs : tensor If it is a network output, usually we should scale it to [0, 1] via softmax. weights : tensor The weights. Returns -------- Tensor The Tensor after appling th...
[ "def", "log_weight", "(", "probs", ",", "weights", ",", "name", "=", "'log_weight'", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "exp_v", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "log", "(", "probs", ")", "*", "weights...
23.578947
23
def search_indicators(self, search_term=None, enclave_ids=None, from_time=None, to_time=None, indicator_types=None, tags=None, excluded_tags=None): """ ...
[ "def", "search_indicators", "(", "self", ",", "search_term", "=", "None", ",", "enclave_ids", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ",", "indicator_types", "=", "None", ",", "tags", "=", "None", ",", "excluded_tags", "=",...
66.37037
35.703704
def _on_entry(self, event): """ Callback for the Entry widget, sets the Scale variable to the appropriate value. :param event: Tkinter event """ contents = self._entry.get() if contents == "": return try: value = self._variable.set...
[ "def", "_on_entry", "(", "self", ",", "event", ")", ":", "contents", "=", "self", ".", "_entry", ".", "get", "(", ")", "if", "contents", "==", "\"\"", ":", "return", "try", ":", "value", "=", "self", ".", "_variable", ".", "set", "(", "int", "(", ...
28.533333
15.733333
def only_trashed(cls): """ Get a new query builder that only includes soft deletes :type cls: orator.orm.model.Model :rtype: orator.orm.builder.Builder """ instance = cls() column = instance.get_qualified_deleted_at_column() return instance.new_query_w...
[ "def", "only_trashed", "(", "cls", ")", ":", "instance", "=", "cls", "(", ")", "column", "=", "instance", ".", "get_qualified_deleted_at_column", "(", ")", "return", "instance", ".", "new_query_without_scope", "(", "SoftDeletingScope", "(", ")", ")", ".", "whe...
25.6
22.4
def set_name(self, new_name): """ Renames this router. :param new_name: new name string """ # change the hostname in the startup-config if os.path.isfile(self.startup_config_path): try: with open(self.startup_config_path, "r+", encoding="utf-...
[ "def", "set_name", "(", "self", ",", "new_name", ")", ":", "# change the hostname in the startup-config", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "startup_config_path", ")", ":", "try", ":", "with", "open", "(", "self", ".", "startup_config_p...
47.5625
27
def slice_by_size(seq, size): """Slice a sequence into chunks, return as a generation of chunks with `size`.""" filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: it = tuple(i for i in it if i is not filling) if it: yiel...
[ "def", "slice_by_size", "(", "seq", ",", "size", ")", ":", "filling", "=", "null", "for", "it", "in", "zip", "(", "*", "(", "itertools_chain", "(", "seq", ",", "[", "filling", "]", "*", "size", ")", ",", ")", "*", "size", ")", ":", "if", "filling...
39.625
17.5
def _handle_value(self, value): """ Given a value string, unquote, remove comment, handle lists. (including empty and single member lists) """ if self._inspec: # Parsing a configspec so don't handle comments return (value, '') # do we look for list...
[ "def", "_handle_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_inspec", ":", "# Parsing a configspec so don't handle comments", "return", "(", "value", ",", "''", ")", "# do we look for lists in values ?", "if", "not", "self", ".", "list_values", ...
40.234043
12.489362
def get_citation_by_reference(self, type: str, reference: str) -> Optional[Citation]: """Get a citation object by its type and reference.""" citation_hash = hash_citation(type=type, reference=reference) return self.get_citation_by_hash(citation_hash)
[ "def", "get_citation_by_reference", "(", "self", ",", "type", ":", "str", ",", "reference", ":", "str", ")", "->", "Optional", "[", "Citation", "]", ":", "citation_hash", "=", "hash_citation", "(", "type", "=", "type", ",", "reference", "=", "reference", "...
67.75
22.25
def get_abbr_impl(): """Return abbreviated implementation name.""" impl = platform.python_implementation() if impl == 'PyPy': return 'pp' elif impl == 'Jython': return 'jy' elif impl == 'IronPython': return 'ip' elif impl == 'CPython': return 'cp' raise Looku...
[ "def", "get_abbr_impl", "(", ")", ":", "impl", "=", "platform", ".", "python_implementation", "(", ")", "if", "impl", "==", "'PyPy'", ":", "return", "'pp'", "elif", "impl", "==", "'Jython'", ":", "return", "'jy'", "elif", "impl", "==", "'IronPython'", ":",...
27.384615
17.307692
def _twofilter_smoothing_ON(self, t, ti, info, phi, lwinfo, return_ess, modif_forward, modif_info): """O(N) version of two-filter smoothing. This method should not be called directly, see twofilter_smoothing. """ if modif_info is not None: lwin...
[ "def", "_twofilter_smoothing_ON", "(", "self", ",", "t", ",", "ti", ",", "info", ",", "phi", ",", "lwinfo", ",", "return_ess", ",", "modif_forward", ",", "modif_info", ")", ":", "if", "modif_info", "is", "not", "None", ":", "lwinfo", "+=", "modif_info", ...
38.571429
12.964286
def expr2dimacssat(ex): """Convert an expression into an equivalent DIMACS SAT string.""" if not ex.simple: raise ValueError("expected ex to be simplified") litmap, nvars = ex.encode_inputs() formula = _expr2sat(ex, litmap) if 'xor' in formula: if '=' in formula: fmt = ...
[ "def", "expr2dimacssat", "(", "ex", ")", ":", "if", "not", "ex", ".", "simple", ":", "raise", "ValueError", "(", "\"expected ex to be simplified\"", ")", "litmap", ",", "nvars", "=", "ex", ".", "encode_inputs", "(", ")", "formula", "=", "_expr2sat", "(", "...
25.157895
19.315789
def replace_666(meta_df, convert_neg_666): """ Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df """ if convert_neg_666: out_df = meta_df.replace([-666, "-666", -666.0], np.nan)...
[ "def", "replace_666", "(", "meta_df", ",", "convert_neg_666", ")", ":", "if", "convert_neg_666", ":", "out_df", "=", "meta_df", ".", "replace", "(", "[", "-", "666", ",", "\"-666\"", ",", "-", "666.0", "]", ",", "np", ".", "nan", ")", "else", ":", "o...
30.230769
15.076923
def click_nowait(self, pattern, action='click', desc=None, **match_kwargs): """ Return immediately if no image found Args: - pattern (str or Pattern): filename or an opencv image object. - action (str): click or long_click Returns: Click point or None ...
[ "def", "click_nowait", "(", "self", ",", "pattern", ",", "action", "=", "'click'", ",", "desc", "=", "None", ",", "*", "*", "match_kwargs", ")", ":", "point", "=", "self", ".", "match", "(", "pattern", ",", "*", "*", "match_kwargs", ")", "if", "not",...
30.117647
19.235294
def stem_plural_word(self, plural): """Stem a plural word to its common stem form. Asian J. (2007) "Effective Techniques for Indonesian Text Retrieval" page 76-77. @link http://researchbank.rmit.edu.au/eserv/rmit:6312/Asian.pdf """ matches = re.match(r'^(.*)-(.*)$', plural) ...
[ "def", "stem_plural_word", "(", "self", ",", "plural", ")", ":", "matches", "=", "re", ".", "match", "(", "r'^(.*)-(.*)$'", ",", "plural", ")", "#translated from PHP conditional check:", "#if (!isset($words[1]) || !isset($words[2]))", "if", "not", "matches", ":", "ret...
38
18.333333
def send_error_explain(self, code, message=None, headers=None, content_type=None): "do not use directly" if headers is None: headers = {} if code in self.responses: if message is None: message = self.responses[code][0] explain = self.response...
[ "def", "send_error_explain", "(", "self", ",", "code", ",", "message", "=", "None", ",", "headers", "=", "None", ",", "content_type", "=", "None", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if", "code", "in", "self", "."...
29.2
21.714286
def authorized_keys(mode='r'): """ Open the authorized_keys file. Separate function for mocking. :param mode: As :py:meth:`open` """ path = '/var/home/.ssh/authorized_keys' if not os.path.exists(path): os.makedirs(os.path.dirname(path)) open(path, 'w').close() with open(path, mo...
[ "def", "authorized_keys", "(", "mode", "=", "'r'", ")", ":", "path", "=", "'/var/home/.ssh/authorized_keys'", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "pat...
30.636364
9.909091
def getParent(self, returned_properties=None): """Get the parent workitem of this workitem If no parent, None will be returned. :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :...
[ "def", "getParent", "(", "self", ",", "returned_properties", "=", "None", ")", ":", "parent_tag", "=", "(", "\"rtc_cm:com.ibm.team.workitem.linktype.\"", "\"parentworkitem.parent\"", ")", "rp", "=", "returned_properties", "parent", "=", "(", "self", ".", "rtc_obj", ...
39.576923
19.5
def parse_function(fn): """Get the source of a function and return its AST.""" try: return parse_string(inspect.getsource(fn)) except (IOError, OSError) as e: raise ValueError( 'Cannot differentiate function: %s. Tangent must be able to access the ' 'source code of the function. Functions ...
[ "def", "parse_function", "(", "fn", ")", ":", "try", ":", "return", "parse_string", "(", "inspect", ".", "getsource", "(", "fn", ")", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "e", ":", "raise", "ValueError", "(", "'Cannot differentiate fun...
45
18.8
def is_valid(self, data): """ Check if data is valid. Audio data will be converted into an array (of signed values) of which the log energy is computed. Log energy is computed as follows: .. code:: python arr = AudioEnergyValidator._convert(signal, sample_width) ...
[ "def", "is_valid", "(", "self", ",", "data", ")", ":", "signal", "=", "AudioEnergyValidator", ".", "_convert", "(", "data", ",", "self", ".", "sample_width", ")", "return", "AudioEnergyValidator", ".", "_signal_log_energy", "(", "signal", ")", ">=", "self", ...
33.115385
27.5
def total_border_pixels_from_mask_and_edge_pixels(mask, edge_pixels, masked_grid_index_to_pixel): """Compute the total number of borders-pixels in a masks.""" border_pixel_total = 0 for i in range(edge_pixels.shape[0]): if check_if_border_pixel(mask, edge_pixels[i], masked_grid_index_to_pixel): ...
[ "def", "total_border_pixels_from_mask_and_edge_pixels", "(", "mask", ",", "edge_pixels", ",", "masked_grid_index_to_pixel", ")", ":", "border_pixel_total", "=", "0", "for", "i", "in", "range", "(", "edge_pixels", ".", "shape", "[", "0", "]", ")", ":", "if", "che...
34.090909
26.454545
def run(self): """ function called when thread is started """ global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.idx, self.min_file_size, self.max...
[ "def", "run", "(", "self", ")", ":", "global", "parallel", "if", "parallel", ":", "download_parallel", "(", "self", ".", "url", ",", "self", ".", "directory", ",", "self", ".", "idx", ",", "self", ".", "min_file_size", ",", "self", ".", "max_file_size", ...
28.25
18.75
def _modify(self, paths: Union[str, List[str]], metadata_for_paths: Union[IrodsMetadata, List[IrodsMetadata]], operation: str): """ Modifies the metadata of the entity or entities in iRODS with the given path. :param path: the paths of the entity or entities to modify :pa...
[ "def", "_modify", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "metadata_for_paths", ":", "Union", "[", "IrodsMetadata", ",", "List", "[", "IrodsMetadata", "]", "]", ",", "operation", ":", "str", ")", "...
59.96
28.76
def copy_node(node): """Copy a node but keep its annotations intact.""" if not isinstance(node, gast.AST): return [copy_node(n) for n in node] new_node = copy.deepcopy(node) setattr(new_node, anno.ANNOTATION_FIELD, getattr(node, anno.ANNOTATION_FIELD, {}).copy()) return new_node
[ "def", "copy_node", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "gast", ".", "AST", ")", ":", "return", "[", "copy_node", "(", "n", ")", "for", "n", "in", "node", "]", "new_node", "=", "copy", ".", "deepcopy", "(", "node", ...
37
9.5
def parse_mim2gene(lines): """Parse the file called mim2gene This file describes what type(s) the different mim numbers have. The different entry types are: 'gene', 'gene/phenotype', 'moved/removed', 'phenotype', 'predominantly phenotypes' Where: gene: Is a gene entry gene/pheno...
[ "def", "parse_mim2gene", "(", "lines", ")", ":", "LOG", ".", "info", "(", "\"Parsing mim2gene\"", ")", "header", "=", "[", "\"mim_number\"", ",", "\"entry_type\"", ",", "\"entrez_gene_id\"", ",", "\"hgnc_symbol\"", ",", "\"ensembl_gene_id\"", "]", "for", "i", ",...
34.178571
20.285714
def get_value(self, name, data): """ Get the value of this field from the data. If there is a problem with the data, raise ValidationError. :param name: Name of this field (to retrieve from data). :param data: Dictionary of data for all fields. :raises: ValidationError ...
[ "def", "get_value", "(", "self", ",", "name", ",", "data", ")", ":", "if", "name", "in", "data", ":", "return", "data", ".", "get", "(", "name", ")", "if", "self", ".", "default", ":", "if", "callable", "(", "self", ".", "default", ")", ":", "ret...
32.666667
12.666667
def _make_eof_intr(): """Set constants _EOF and _INTR. This avoids doing potentially costly operations on module load. """ global _EOF, _INTR if (_EOF is not None) and (_INTR is not None): return # inherit EOF and INTR definitions from controlling process. try: from ter...
[ "def", "_make_eof_intr", "(", ")", ":", "global", "_EOF", ",", "_INTR", "if", "(", "_EOF", "is", "not", "None", ")", "and", "(", "_INTR", "is", "not", "None", ")", ":", "return", "# inherit EOF and INTR definitions from controlling process.", "try", ":", "from...
35.205128
17.025641
def dump(cls, obj, file, protocol=0): """ Equivalent to pickle.dump except that the HoloViews option tree is saved appropriately. """ cls.save_option_state = True pickle.dump(obj, file, protocol=protocol) cls.save_option_state = False
[ "def", "dump", "(", "cls", ",", "obj", ",", "file", ",", "protocol", "=", "0", ")", ":", "cls", ".", "save_option_state", "=", "True", "pickle", ".", "dump", "(", "obj", ",", "file", ",", "protocol", "=", "protocol", ")", "cls", ".", "save_option_sta...
35.375
6.125
def get_install_value(self, value_name, wanted_type=None): ''' For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match ...
[ "def", "get_install_value", "(", "self", ",", "value_name", ",", "wanted_type", "=", "None", ")", ":", "try", ":", "item_value", ",", "item_type", "=", "self", ".", "__reg_query_value", "(", "self", ".", "__reg_uninstall_handle", ",", "value_name", ")", "excep...
36
25.384615
def _import_component(name): """ Returns a class, function, or class method specified by the fully qualified name. """ for f in (_get_from_module, _get_from_class): try: return f(name) except: pass log.debug("Couldn't load %s" % name)
[ "def", "_import_component", "(", "name", ")", ":", "for", "f", "in", "(", "_get_from_module", ",", "_get_from_class", ")", ":", "try", ":", "return", "f", "(", "name", ")", "except", ":", "pass", "log", ".", "debug", "(", "\"Couldn't load %s\"", "%", "na...
26.181818
16.545455
def error(self, msg): ''' error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. This keeps option parsing exit status uniform for all parsing errors. ''' self.print_usage(sys.stderr) self.exit(salt.defaults.exitcodes.EX_USAGE, '{0}: er...
[ "def", "error", "(", "self", ",", "msg", ")", ":", "self", ".", "print_usage", "(", "sys", ".", "stderr", ")", "self", ".", "exit", "(", "salt", ".", "defaults", ".", "exitcodes", ".", "EX_USAGE", ",", "'{0}: error: {1}\\n'", ".", "format", "(", "self"...
39.777778
29.555556
def ajax_recalculate_records(self): """Recalculate all AR records and dependencies - samples - templates - profiles - services - dependecies XXX: This function has grown too much and needs refactoring! """ out = {} # ...
[ "def", "ajax_recalculate_records", "(", "self", ")", ":", "out", "=", "{", "}", "# The sorted records from the request", "records", "=", "self", ".", "get_records", "(", ")", "for", "n", ",", "record", "in", "enumerate", "(", "records", ")", ":", "# Mapping of...
45.155963
17.655963
def verification_events(self): """ Events related to command verification. :type: List[:class:`.CommandHistoryEvent`] """ queued = self._assemble_event('Verifier_Queued') started = self._assemble_event('Verifier_Started') return [x for x in [queued, started] if x...
[ "def", "verification_events", "(", "self", ")", ":", "queued", "=", "self", ".", "_assemble_event", "(", "'Verifier_Queued'", ")", "started", "=", "self", ".", "_assemble_event", "(", "'Verifier_Started'", ")", "return", "[", "x", "for", "x", "in", "[", "que...
34.777778
12.333333
def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """ cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no...
[ "def", "main", "(", ")", ":", "cmd_args", "=", "TagCubeCLI", ".", "parse_args", "(", ")", "try", ":", "tagcube_cli", "=", "TagCubeCLI", ".", "from_cmd_args", "(", "cmd_args", ")", "except", "ValueError", ",", "ve", ":", "# We get here when there are no credentia...
30.666667
20.857143
def setup(self, **kwargs): ''' This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param tuple cdpp_range: If :py:obj:`parent_model` is set, \ neighbors are selected only if \ their de-trended CDPPs fall wit...
[ "def", "setup", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Get neighbors", "self", ".", "parent_model", "=", "kwargs", ".", "get", "(", "'parent_model'", ",", "None", ")", "neighbors", "=", "kwargs", ".", "get", "(", "'neighbors'", ",", "10", "...
55.739837
23.512195
def refresh_token(self): """ Refreshes access token using refresh token. Returns true if successful, false otherwise. """ try: if self.token: self.token = self.request().refresh_token(self.refresh_url, self.token['refresh_token']) return True except ...
[ "def", "refresh_token", "(", "self", ")", ":", "try", ":", "if", "self", ".", "token", ":", "self", ".", "token", "=", "self", ".", "request", "(", ")", ".", "refresh_token", "(", "self", ".", "refresh_url", ",", "self", ".", "token", "[", "'refresh_...
40.153846
21.461538
def sameSegment(seg1, seg2): """Return True if seg1 and seg2 are identical, ignoring order of synapses""" result = True # check sequence segment, total activations etc. In case any are floats, # check that they are within 0.001. for field in [1, 2, 3, 4, 5, 6]: if abs(seg1[0][field] - seg2[0][field]) > 0...
[ "def", "sameSegment", "(", "seg1", ",", "seg2", ")", ":", "result", "=", "True", "# check sequence segment, total activations etc. In case any are floats,", "# check that they are within 0.001.", "for", "field", "in", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5"...
28.724138
18.931034
def main(): """ NAME di_eq.py DESCRIPTION converts dec, inc pairs to x,y pairs using equal area projection NB: do only upper or lower hemisphere at a time: does not distinguish between up and down. SYNTAX di_eq.py [command line options] [< filename] OPTIO...
[ "def", "main", "(", ")", ":", "out", "=", "\"\"", "UP", "=", "0", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-f'", "in", "sys", ".", "argv", ":", "ind", "=", ...
26.583333
20.027778
async def _on_event(self, event_): """Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance """ conv_id = event_.conversation_id.id try: conv = await self._get_or_fetch_conversation(conv_id) except ex...
[ "async", "def", "_on_event", "(", "self", ",", "event_", ")", ":", "conv_id", "=", "event_", ".", "conversation_id", ".", "id", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "...
38.714286
16.619048
def lint_file(file_path): """ Validate & lint `file_path` and return a LintResult. :param file_path: YAML filename :type file_path: str :return: LintResult object """ with open(file_path, 'r') as yaml: try: return lint(yaml) except Exception as e: lr...
[ "def", "lint_file", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "yaml", ":", "try", ":", "return", "lint", "(", "yaml", ")", "except", "Exception", "as", "e", ":", "lr", "=", "LintResult", "(", ")", "lr", "....
25.75
15.75
def aer2ned(az: float, elev: float, slantRange: float, deg: bool = True) -> Tuple[float, float, float]: """ converts azimuth, elevation, range to target from observer to North, East, Down Parameters ----------- az : float or numpy.ndarray of float azimuth elev : float or n...
[ "def", "aer2ned", "(", "az", ":", "float", ",", "elev", ":", "float", ",", "slantRange", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "e", ",", "n", ",", "u", "=", ...
28.655172
16.931034
def make_fileitem_fileextension(extension, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/FileExtension :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FileExtension' content_type = 'string' con...
[ "def", "make_fileitem_fileextension", "(", "extension", ",", "condition", "=", "'is'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'FileItem'", "search", "=", "'FileItem/FileExtension'", "content_type", "=", "'strin...
40.846154
22.230769
def submission_post_save(sender, instance, **kwargs): ''' Several sanity checks after we got a valid submission object.''' logger.debug("Running post-processing for submission") # Make the submitter an author if instance.submitter not in instance.authors.all(): instance.authors.add(instance.subm...
[ "def", "submission_post_save", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"Running post-processing for submission\"", ")", "# Make the submitter an author", "if", "instance", ".", "submitter", "not", "in", "inst...
66.684211
30.473684
def remove_post_data_parameters(request, post_data_parameters_to_remove): """ Wrap replace_post_data_parameters() for API backward compatibility. """ replacements = [(k, None) for k in post_data_parameters_to_remove] return replace_post_data_parameters(request, replacements)
[ "def", "remove_post_data_parameters", "(", "request", ",", "post_data_parameters_to_remove", ")", ":", "replacements", "=", "[", "(", "k", ",", "None", ")", "for", "k", "in", "post_data_parameters_to_remove", "]", "return", "replace_post_data_parameters", "(", "reques...
48.333333
19.333333
def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion, claDescriptionTemplateFile): """ Parses and validates the --descriptionFromFile option and executes the request Parameters: ----------------------------------------------------------------------- filena...
[ "def", "_handleDescriptionFromFileOption", "(", "filename", ",", "outDir", ",", "usageStr", ",", "hsVersion", ",", "claDescriptionTemplateFile", ")", ":", "try", ":", "fileHandle", "=", "open", "(", "filename", ",", "'r'", ")", "JSONStringFromFile", "=", "fileHand...
36.71875
21.96875
def read_entity(self, entity_id, mount_point=DEFAULT_MOUNT_POINT): """Query an entity by its identifier. Supported methods: GET: /auth/{mount_point}/entity/id/{id}. Produces: 200 application/json :param entity_id: Identifier of the entity. :type entity_id: str :para...
[ "def", "read_entity", "(", "self", ",", "entity_id", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "api_path", "=", "'/v1/{mount_point}/entity/id/{id}'", ".", "format", "(", "mount_point", "=", "mount_point", ",", "id", "=", "entity_id", ",", ")", "r...
37
17.842105
def mutable_record_transform(cls): """Transform mutable records usage by updating locals.""" if not (len(cls.bases) > 0 and isinstance(cls.bases[0], astroid.Call) and cls.bases[0].func.as_string() == 'mutablerecords.Record'): return try: # Add required attributes. if len(cls.bases...
[ "def", "mutable_record_transform", "(", "cls", ")", ":", "if", "not", "(", "len", "(", "cls", ".", "bases", ")", ">", "0", "and", "isinstance", "(", "cls", ".", "bases", "[", "0", "]", ",", "astroid", ".", "Call", ")", "and", "cls", ".", "bases", ...
30.25
17
def post_processor_population_displacement_function( hazard=None, classification=None, hazard_class=None, population=None): """Private function used in the displacement postprocessor. :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. ...
[ "def", "post_processor_population_displacement_function", "(", "hazard", "=", "None", ",", "classification", "=", "None", ",", "hazard_class", "=", "None", ",", "population", "=", "None", ")", ":", "_", "=", "population", "# NOQA", "return", "get_displacement_rate",...
32.826087
22.043478
def get_instance_mem_histogram(cluster, environ, topology, instance, role=None): ''' :param cluster: :param environ: :param topology: :param instance: :param role: :return: ''' params = dict( cluster=cluster, environ=environ, topology=topology, instance=instance) if role is ...
[ "def", "get_instance_mem_histogram", "(", "cluster", ",", "environ", ",", "topology", ",", "instance", ",", "role", "=", "None", ")", ":", "params", "=", "dict", "(", "cluster", "=", "cluster", ",", "environ", "=", "environ", ",", "topology", "=", "topolog...
22.409091
24.318182
def cq_to_chroma(n_input, bins_per_octave=12, n_chroma=12, fmin=None, window=None, base_c=True, dtype=np.float32): '''Convert a Constant-Q basis to Chroma. Parameters ---------- n_input : int > 0 [scalar] Number of input components (CQT bins) bins_per_octave : int > 0 [sc...
[ "def", "cq_to_chroma", "(", "n_input", ",", "bins_per_octave", "=", "12", ",", "n_chroma", "=", "12", ",", "fmin", "=", "None", ",", "window", "=", "None", ",", "base_c", "=", "True", ",", "dtype", "=", "np", ".", "float32", ")", ":", "# How many fract...
30.064
21.552
def generate_binary(outputfname, format_, progname='', binary_files=None, headless_binary_files=None): """ Outputs the memory binary to the output filename using one of the given formats: tap, tzx or bin """ global AUTORUN_ADDR org, binary = MEMORY.dump() if gl.has_errors: return ...
[ "def", "generate_binary", "(", "outputfname", ",", "format_", ",", "progname", "=", "''", ",", "binary_files", "=", "None", ",", "headless_binary_files", "=", "None", ")", ":", "global", "AUTORUN_ADDR", "org", ",", "binary", "=", "MEMORY", ".", "dump", "(", ...
30.571429
20.460317
def strings_to_list_string(strings): '''Takes a list of strings presumably containing words and phrases, and returns a "list" form of those strings, like: >>> strings_to_list_string(('cats', 'dogs')) >>> 'cats and dogs' or >>> strings_to_list_string(('pizza', 'pop', 'chips')) ...
[ "def", "strings_to_list_string", "(", "strings", ")", ":", "if", "isinstance", "(", "strings", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'strings must be an iterable of strings, not a string '", "'itself'", ")", "if", "len", "(", "string...
33.192308
19.807692
def vm_update(name, kwargs=None, call=None): ''' Replaces the user template contents. .. versionadded:: 2016.3.0 name The name of the VM to update. path The path to a file containing new user template contents. Syntax within the file can be the usual attribute=value or XML...
[ "def", "vm_update", "(", "name", ",", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The vm_update action must be called with -a or --action.'", ")", "if", "kwargs", "is", "N...
28.258824
23.929412
def make_funcs(dataset, setdir, store): """Functions available for listing columns and filters.""" return { 'cat': lambda *lists: [x for lst in lists for x in lst], 'comments': lambda: None, 'detail_route': detail_route, 'format': lambda fmt, *args: fmt.format(*args), 'ge...
[ "def", "make_funcs", "(", "dataset", ",", "setdir", ",", "store", ")", ":", "return", "{", "'cat'", ":", "lambda", "*", "lists", ":", "[", "x", "for", "lst", "in", "lists", "for", "x", "in", "lst", "]", ",", "'comments'", ":", "lambda", ":", "None"...
38.772727
14.045455
def run_script(self, script_id, params=None): """ Runs a stored script. script_id:= id of stored script. params:= up to 10 parameters required by the script. ... s = pi.run_script(sid, [par1, par2]) s = pi.run_script(sid) s = pi.run_script(sid, [1, 2,...
[ "def", "run_script", "(", "self", ",", "script_id", ",", "params", "=", "None", ")", ":", "# I p1 script id", "# I p2 0", "# I p3 params * 4 (0-10 params)", "# (optional) extension", "# I[] params", "if", "params", "is", "not", "None", ":", "ext", "=", "bytearray", ...
28.46875
18.09375
def _flush_index(self): """Writes the current list of file paths in the index to the json file and then sets self.__index = None. """ data = {'version': self.version, 'index': self._index} with open(self._get_path('index.json'), 'w') as f: json.dump(data, f) s...
[ "def", "_flush_index", "(", "self", ")", ":", "data", "=", "{", "'version'", ":", "self", ".", "version", ",", "'index'", ":", "self", ".", "_index", "}", "with", "open", "(", "self", ".", "_get_path", "(", "'index.json'", ")", ",", "'w'", ")", "as",...
41.375
10.25
def __process_by_python(self): """! @brief Performs processing using python code. """ for index_cluster in range(len(self.__clusters)): for index_point in self.__clusters[index_cluster]: self.__score[index_point] = self.__calculate_score(index_point, i...
[ "def", "__process_by_python", "(", "self", ")", ":", "for", "index_cluster", "in", "range", "(", "len", "(", "self", ".", "__clusters", ")", ")", ":", "for", "index_point", "in", "self", ".", "__clusters", "[", "index_cluster", "]", ":", "self", ".", "__...
40.75
19.625
def filter(self, table, keypairs, filter_string): """Naive case-insensitive search.""" query = filter_string.lower() return [keypair for keypair in keypairs if query in keypair.name.lower()]
[ "def", "filter", "(", "self", ",", "table", ",", "keypairs", ",", "filter_string", ")", ":", "query", "=", "filter_string", ".", "lower", "(", ")", "return", "[", "keypair", "for", "keypair", "in", "keypairs", "if", "query", "in", "keypair", ".", "name",...
45.2
5.6
def install_global_objects(self): """ Process [GLOBAL_OBJECTS], and inject all object to uliweb module, so user can import from uliweb """ import uliweb for k, v in settings.GLOBAL_OBJECTS.items(): setattr(uliweb, k, import_attr(v))
[ "def", "install_global_objects", "(", "self", ")", ":", "import", "uliweb", "for", "k", ",", "v", "in", "settings", ".", "GLOBAL_OBJECTS", ".", "items", "(", ")", ":", "setattr", "(", "uliweb", ",", "k", ",", "import_attr", "(", "v", ")", ")" ]
35.625
10.625
def calculate_timeout(http_date): """Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: ...
[ "def", "calculate_timeout", "(", "http_date", ")", ":", "try", ":", "return", "int", "(", "http_date", ")", "except", "ValueError", ":", "date_after", "=", "parse", "(", "http_date", ")", "utc_now", "=", "datetime", ".", "now", "(", "tz", "=", "timezone", ...
31.571429
19.333333
def __StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True): """Helper function for StreamMedia / StreamInChunks.""" if self.strategy != RESUMABLE_UPLOAD: raise exceptions.InvalidUserInputError( 'Cannot stream n...
[ "def", "__StreamMedia", "(", "self", ",", "callback", "=", "None", ",", "finish_callback", "=", "None", ",", "additional_headers", "=", "None", ",", "use_chunks", "=", "True", ")", ":", "if", "self", ".", "strategy", "!=", "RESUMABLE_UPLOAD", ":", "raise", ...
47.569231
16.846154
def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0): """Generate an instance of the report format from a list of readings and a uuid. The signed list report is creat...
[ "def", "FromReadings", "(", "cls", ",", "uuid", ",", "readings", ",", "root_key", "=", "AuthProvider", ".", "NoKey", ",", "signer", "=", "None", ",", "report_id", "=", "IOTileReading", ".", "InvalidReadingID", ",", "selector", "=", "0xFFFF", ",", "streamer",...
52.333333
33.333333
def create_component(tag_name, allow_children=True): """ Create a component for an HTML Tag Examples: >>> marquee = create_component('marquee') >>> marquee('woohoo') <marquee>woohoo</marquee> """ def _component(*children, **kwargs): if 'children' in kwargs: ...
[ "def", "create_component", "(", "tag_name", ",", "allow_children", "=", "True", ")", ":", "def", "_component", "(", "*", "children", ",", "*", "*", "kwargs", ")", ":", "if", "'children'", "in", "kwargs", ":", "children", "=", "kwargs", ".", "pop", "(", ...
37.139535
15.790698
def get_worksheet(self, id_or_name): """ Gets a specific worksheet by id or name """ url = self.build_url(self._endpoints.get('get_worksheet').format(id=quote(id_or_name))) response = self.session.get(url) if not response: return None return self.worksheet_constructor...
[ "def", "get_worksheet", "(", "self", ",", "id_or_name", ")", ":", "url", "=", "self", ".", "build_url", "(", "self", ".", "_endpoints", ".", "get", "(", "'get_worksheet'", ")", ".", "format", "(", "id", "=", "quote", "(", "id_or_name", ")", ")", ")", ...
52.857143
21.285714