text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def create_pool(dsn=None, *, min_size=10, max_size=10, max_queries=50000, max_inactive_connection_lifetime=300.0, setup=None, init=None, loop=None, connection_class=connection.Connection, ...
[ "def", "create_pool", "(", "dsn", "=", "None", ",", "*", ",", "min_size", "=", "10", ",", "max_size", "=", "10", ",", "max_queries", "=", "50000", ",", "max_inactive_connection_lifetime", "=", "300.0", ",", "setup", "=", "None", ",", "init", "=", "None",...
37.553571
21.821429
def discard_local_changes(cwd, path='.', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2019.2.0 Runs a ``git checkout -- <path>`` ...
[ "def", "discard_local_changes", "(", "cwd", ",", "path", "=", "'.'", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", ...
32.553571
22.732143
def extend(func): """Allow to extend a bot: Create a module with some useful routine: .. literalinclude:: ../examples/myextends.py .. >>> import sys >>> sys.path.append('examples') >>> from irc3 import IrcBot >>> IrcBot.defaults.update(asynchronous=False, testing=True) ...
[ "def", "extend", "(", "func", ")", ":", "def", "callback", "(", "context", ",", "name", ",", "ob", ")", ":", "obj", "=", "context", ".", "context", "if", "info", ".", "scope", "==", "'class'", ":", "f", "=", "getattr", "(", "obj", ".", "get_plugin"...
29.419355
17.096774
def s3am_upload_job(job, file_id, file_name, s3_dir, s3_key_path=None): """Job version of s3am_upload""" work_dir = job.fileStore.getLocalTempDir() fpath = job.fileStore.readGlobalFile(file_id, os.path.join(work_dir, file_name)) s3am_upload(job=job, fpath=fpath, s3_dir=s3_dir, num_cores=job.cores, s3_ke...
[ "def", "s3am_upload_job", "(", "job", ",", "file_id", ",", "file_name", ",", "s3_dir", ",", "s3_key_path", "=", "None", ")", ":", "work_dir", "=", "job", ".", "fileStore", ".", "getLocalTempDir", "(", ")", "fpath", "=", "job", ".", "fileStore", ".", "rea...
67
27.8
def _apply_pipeline_and_get_build_instance(self, X_factory, mX_factory, category_idx_store, df, pars...
[ "def", "_apply_pipeline_and_get_build_instance", "(", "self", ",", "X_factory", ",", "mX_factory", ",", "category_idx_store", ",", "df", ",", "parse_pipeline", ",", "term_idx_store", ",", "metadata_idx_store", ",", "y", ")", ":", "df", ".", "apply", "(", "parse_pi...
27.638889
20.805556
def valid(self, instance, schema): """Validate schema.""" try: jsonschema.validate(instance, schema) except jsonschema.exceptions.ValidationError as ex: self.stderr.write(" VALIDATION ERROR: {}".format(instance['name'] if 'name' in instance else '')) self.s...
[ "def", "valid", "(", "self", ",", "instance", ",", "schema", ")", ":", "try", ":", "jsonschema", ".", "validate", "(", "instance", ",", "schema", ")", "except", "jsonschema", ".", "exceptions", ".", "ValidationError", "as", "ex", ":", "self", ".", "stder...
50.458333
27.875
def go(fn, *args, **kwargs): """Launch an operation on a thread and get a handle to its future result. >>> from time import sleep >>> def print_sleep_print(duration): ... sleep(duration) ... print('hello from background thread') ... sleep(duration) ... print('goodbye from ba...
[ "def", "go", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "callable", "(", "fn", ")", ":", "raise", "TypeError", "(", "'go() requires a function, not %r'", "%", "(", "fn", ",", ")", ")", "result", "=", "[", "None", "...
26.297872
17.489362
def update_catalog_extent(self, current_extent): # type: (int) -> None ''' A method to update the extent associated with this Boot Catalog. Parameters: current_extent - New extent to associate with this Boot Catalog Returns: Nothing. ''' if not ...
[ "def", "update_catalog_extent", "(", "self", ",", "current_extent", ")", ":", "# type: (int) -> None", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'El Torito Boot Catalog not yet initialized'", ")", "self"...
35.857143
27.857143
def bind(self, form): """Bind to filters form.""" field = self.field(default=self.default, **self.field_kwargs) form._fields[self.name] = field.bind(form, self.name, prefix=form._prefix)
[ "def", "bind", "(", "self", ",", "form", ")", ":", "field", "=", "self", ".", "field", "(", "default", "=", "self", ".", "default", ",", "*", "*", "self", ".", "field_kwargs", ")", "form", ".", "_fields", "[", "self", ".", "name", "]", "=", "fiel...
51.75
22.5
def fit(self, X, y=None): ''' Learn the linear transformation to flipped eigenvalues. Parameters ---------- X : array, shape [n, n] The *symmetric* input similarities. If X is asymmetric, it will be treated as if it were symmetric based on its lower-trian...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "n", "=", "X", ".", "shape", "[", "0", "]", "if", "X", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "raise", "TypeError", "(", "\"Input must be a square matrix.\"", ")", ...
34.318182
22.318182
def start_output (self): """ Write start of checking info as sql comment. """ super(SQLLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.flush()
[ "def", "start_output", "(", "self", ")", ":", "super", "(", "SQLLogger", ",", "self", ")", ".", "start_output", "(", ")", "if", "self", ".", "has_part", "(", "\"intro\"", ")", ":", "self", ".", "write_intro", "(", ")", "self", ".", "writeln", "(", ")...
28.555556
8.777778
def check_dimensionless_vertical_coordinate(self, ds): ''' Check the validity of dimensionless coordinates under CF CF §4.3.2 The units attribute is not required for dimensionless coordinates. The standard_name attribute associates a coordinate with its definition from ...
[ "def", "check_dimensionless_vertical_coordinate", "(", "self", ",", "ds", ")", ":", "ret_val", "=", "[", "]", "z_variables", "=", "cfutil", ".", "get_z_variables", "(", "ds", ")", "deprecated_units", "=", "[", "'level'", ",", "'layer'", ",", "'sigma_level'", "...
40.877551
25.408163
def _do_conjunction(self, _and=("and", "e", "en", "et", "und", "y")): """ Attach conjunctions. CC-words like "and" and "or" between two chunks indicate a conjunction. """ w = self.words if len(w) > 2 and w[-2].type == "CC" and w[-2].chunk is None: cc = w[-2].stri...
[ "def", "_do_conjunction", "(", "self", ",", "_and", "=", "(", "\"and\"", ",", "\"e\"", ",", "\"en\"", ",", "\"et\"", ",", "\"und\"", ",", "\"y\"", ")", ")", ":", "w", "=", "self", ".", "words", "if", "len", "(", "w", ")", ">", "2", "and", "w", ...
43.615385
14.615385
def recv(self, bufsize): """Buffers up to _chunk_size bytes when the internal buffer has less than `bufsize` bytes.""" assert bufsize > 0, 'a positive bufsize is required' if len(self._buffer) < bufsize: readable, _, _ = safe_select([self._socket], [], [], self._select_timeout) if readable: ...
[ "def", "recv", "(", "self", ",", "bufsize", ")", ":", "assert", "bufsize", ">", "0", ",", "'a positive bufsize is required'", "if", "len", "(", "self", ".", "_buffer", ")", "<", "bufsize", ":", "readable", ",", "_", ",", "_", "=", "safe_select", "(", "...
46.909091
20.272727
def print_matching_trees(arg_dict, tree_format, exact, verbose): """The `TreeRef` instance returned by the oti.find_trees(... wrap_response=True) can be used as an argument to the phylesystem_api.get call. If you pass in a string (instead of a TreeRef), the string will be interpreted as a study ID """ ...
[ "def", "print_matching_trees", "(", "arg_dict", ",", "tree_format", ",", "exact", ",", "verbose", ")", ":", "from", "peyotl", ".", "sugar", "import", "phylesystem_api", "tree_list", "=", "ot_find_tree", "(", "arg_dict", ",", "exact", "=", "exact", ",", "verbos...
54.3
18.6
def _validate_input_data(self, data, request): """ Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is performed and succeeds the data is converted into whatever format the validation uses (by default Django's ...
[ "def", "_validate_input_data", "(", "self", ",", "data", ",", "request", ")", ":", "validator", "=", "self", ".", "_get_input_validator", "(", "request", ")", "if", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "map"...
40.125
16.3125
def rg(self): """ Brazilian RG, return plain numbers. Check: https://www.ngmatematica.com/2014/02/como-determinar-o-digito-verificador-do.html """ digits = self.generator.random.sample(range(0, 9), 8) checksum = sum(i * digits[i - 2] for i in range(2, 10)) last_...
[ "def", "rg", "(", "self", ")", ":", "digits", "=", "self", ".", "generator", ".", "random", ".", "sample", "(", "range", "(", "0", ",", "9", ")", ",", "8", ")", "checksum", "=", "sum", "(", "i", "*", "digits", "[", "i", "-", "2", "]", "for", ...
30.333333
18.111111
def optimizer(name): """Get pre-registered optimizer keyed by name. `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and UpperCamelCase -> snake_case conversions included for legacy support. Args: name: name of optimizer used in registration. This should be a snake case identifier...
[ "def", "optimizer", "(", "name", ")", ":", "warn_msg", "=", "(", "\"Please update `registry.optimizer` callsite \"", "\"(likely due to a `HParams.optimizer` value)\"", ")", "if", "name", "==", "\"SGD\"", ":", "name", "=", "\"sgd\"", "tf", ".", "logging", ".", "warning...
34.448276
23.586207
def get_sdc_by_ip(self, ip): """ Get ScaleIO SDC object by its ip :param name: IP address of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified IP found :rtype: SDC object """ if self.conn.is_ip_addr(ip): for sdc in self.sdc...
[ "def", "get_sdc_by_ip", "(", "self", ",", "ip", ")", ":", "if", "self", ".", "conn", ".", "is_ip_addr", "(", "ip", ")", ":", "for", "sdc", "in", "self", ".", "sdc", ":", "if", "sdc", ".", "sdcIp", "==", "ip", ":", "return", "sdc", "raise", "KeyEr...
34.4
9.866667
def dmat(c,nocc): "Form the density matrix from the first nocc orbitals of c" return np.dot(c[:,:nocc],c[:,:nocc].T)
[ "def", "dmat", "(", "c", ",", "nocc", ")", ":", "return", "np", ".", "dot", "(", "c", "[", ":", ",", ":", "nocc", "]", ",", "c", "[", ":", ",", ":", "nocc", "]", ".", "T", ")" ]
40.666667
16
def set(self, key, value): """set key data""" if self._db: self._db.hset(self.index, key, value)
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_db", ":", "self", ".", "_db", ".", "hset", "(", "self", ".", "index", ",", "key", ",", "value", ")" ]
30.25
10.75
def delete_taskrun(taskrun_id): """Delete the given taskrun. :param task: PYBOSSA task """ try: res = _pybossa_req('delete', 'taskrun', taskrun_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
[ "def", "delete_taskrun", "(", "taskrun_id", ")", ":", "try", ":", "res", "=", "_pybossa_req", "(", "'delete'", ",", "'taskrun'", ",", "taskrun_id", ")", "if", "type", "(", "res", ")", ".", "__name__", "==", "'bool'", ":", "return", "True", "else", ":", ...
23.692308
16.076923
def run_with_gunicorn(self, **options): """Run with gunicorn.""" import gunicorn.app.base from gunicorn.six import iteritems import multiprocessing class GourdeApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): sel...
[ "def", "run_with_gunicorn", "(", "self", ",", "*", "*", "options", ")", ":", "import", "gunicorn", ".", "app", ".", "base", "from", "gunicorn", ".", "six", "import", "iteritems", "import", "multiprocessing", "class", "GourdeApplication", "(", "gunicorn", ".", ...
36.758621
19.034483
def routers_removed_from_hosting_device(self, context, router_ids, hosting_device): """Notify cfg agent that routers have been removed from hosting device. @param: context - information about tenant, user etc @param: router-ids - list of ids @p...
[ "def", "routers_removed_from_hosting_device", "(", "self", ",", "context", ",", "router_ids", ",", "hosting_device", ")", ":", "self", ".", "_agent_notification_bulk", "(", "context", ",", "'router_removed_from_hosting_device'", ",", "router_ids", ",", "hosting_device", ...
52.6
12
def get_state(self, force_update=False): """ Returns 0 if off and 1 if on. """ if force_update or self._state is None: return int(self.basicevent.GetBinaryState()['BinaryState']) return self._state
[ "def", "get_state", "(", "self", ",", "force_update", "=", "False", ")", ":", "if", "force_update", "or", "self", ".", "_state", "is", "None", ":", "return", "int", "(", "self", ".", "basicevent", ".", "GetBinaryState", "(", ")", "[", "'BinaryState'", "]...
34.714286
7.857143
def get_compass_raw(self): """ Magnetometer x y z raw data in uT (micro teslas) """ raw = self._get_raw_data('compassValid', 'compass') if raw is not None: self._last_compass_raw = raw return deepcopy(self._last_compass_raw)
[ "def", "get_compass_raw", "(", "self", ")", ":", "raw", "=", "self", ".", "_get_raw_data", "(", "'compassValid'", ",", "'compass'", ")", "if", "raw", "is", "not", "None", ":", "self", ".", "_last_compass_raw", "=", "raw", "return", "deepcopy", "(", "self",...
25.181818
17.181818
def read_header(headerlabels, options): """ read csv header, returns prop_indices dictionary, {'label' : index} where label is the csv column label, and index the column index """ # set input variables status_field = options.status_field # confirm that status_field exists status_field_matcher =...
[ "def", "read_header", "(", "headerlabels", ",", "options", ")", ":", "# set input variables", "status_field", "=", "options", ".", "status_field", "# confirm that status_field exists", "status_field_matcher", "=", "re", ".", "compile", "(", "status_field", ")", "if", ...
29.708333
20.916667
def join_host_port(host, port): """Joins a hostname and port together. This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port. """ if ':' in host and not ...
[ "def", "join_host_port", "(", "host", ",", "port", ")", ":", "if", "':'", "in", "host", "and", "not", "host", ".", "startswith", "(", "'['", ")", ":", "return", "'[%s]:%d'", "%", "(", "host", ",", "port", ")", "return", "'%s:%d'", "%", "(", "host", ...
28.714286
17.5
def get_local_client( c_path=os.path.join(syspaths.CONFIG_DIR, 'master'), mopts=None, skip_perm_errors=False, io_loop=None, auto_reconnect=False): ''' .. versionadded:: 2014.7.0 Read in the config and return the correct LocalClient object based on the configured ...
[ "def", "get_local_client", "(", "c_path", "=", "os", ".", "path", ".", "join", "(", "syspaths", ".", "CONFIG_DIR", ",", "'master'", ")", ",", "mopts", "=", "None", ",", "skip_perm_errors", "=", "False", ",", "io_loop", "=", "None", ",", "auto_reconnect", ...
31.967742
19.967742
def process_input_data(filename, imager, grid_data, grid_norm, grid_weights): """Reads visibility data from a Measurement Set. The visibility grid or weights grid is updated accordingly. Visibility data are read from disk in blocks of size num_baselines. Args: filename (str): ...
[ "def", "process_input_data", "(", "filename", ",", "imager", ",", "grid_data", ",", "grid_norm", ",", "grid_weights", ")", ":", "# Get data from the input Measurement Set.", "ms", "=", "oskar", ".", "MeasurementSet", ".", "open", "(", "filename", ")", "block_start",...
40.683333
22.5
def inferObjectWithRandomMovements(self, objectDescription, numSensations=None, randomLocation=False, checkFalseConvergence=True): """ Attempt to recognize the spec...
[ "def", "inferObjectWithRandomMovements", "(", "self", ",", "objectDescription", ",", "numSensations", "=", "None", ",", "randomLocation", "=", "False", ",", "checkFalseConvergence", "=", "True", ")", ":", "self", ".", "reset", "(", ")", "for", "monitor", "in", ...
36.433333
24.055556
def get_instances(name, lifecycle_state="InService", health_status="Healthy", attribute="private_ip_address", attributes=None, region=None, key=None, keyid=None, profile=None): ''' return attribute of all instances in the named autoscale group. CLI example:: sal...
[ "def", "get_instances", "(", "name", ",", "lifecycle_state", "=", "\"InService\"", ",", "health_status", "=", "\"Healthy\"", ",", "attribute", "=", "\"private_ip_address\"", ",", "attributes", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", "...
41.844444
27
def sils(T,f,c,d,h): """sils -- LP lotsizing for the single item lot sizing problem Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) - c[t]: variable costs - d[t]: demand values - h[t]: holding costs Returns a model, r...
[ "def", "sils", "(", "T", ",", "f", ",", "c", ",", "d", ",", "h", ")", ":", "model", "=", "Model", "(", "\"single item lotsizing\"", ")", "Ts", "=", "range", "(", "1", ",", "T", "+", "1", ")", "M", "=", "sum", "(", "d", "[", "t", "]", "for",...
30.193548
17.774194
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) ...
[ "def", "init_app", "(", "self", ",", "app", ",", "sessionstore", "=", "None", ",", "register_blueprint", "=", "True", ")", ":", "self", ".", "make_session_permanent", "(", "app", ")", "return", "super", "(", "InvenioAccountsUI", ",", "self", ")", ".", "ini...
42.666667
15
def _get_permutations(num_results, dims, seed=None): """Uniform iid sample from the space of permutations. Draws a sample of size `num_results` from the group of permutations of degrees specified by the `dims` tensor. These are packed together into one tensor such that each row is one sample from each of the d...
[ "def", "_get_permutations", "(", "num_results", ",", "dims", ",", "seed", "=", "None", ")", ":", "sample_range", "=", "tf", ".", "range", "(", "num_results", ")", "stream", "=", "distributions", ".", "SeedStream", "(", "seed", ",", "salt", "=", "'MCMCSampl...
45.272727
25.515152
def get_result(self): """ Build compiled SQL expression from the bottom up and return as a string """ translated = self.translate(self.expr) if self._needs_name(self.expr): # TODO: this could fail in various ways name = self.expr.get_name() tra...
[ "def", "get_result", "(", "self", ")", ":", "translated", "=", "self", ".", "translate", "(", "self", ".", "expr", ")", "if", "self", ".", "_needs_name", "(", "self", ".", "expr", ")", ":", "# TODO: this could fail in various ways", "name", "=", "self", "....
37.4
10.4
def bounding_boxes(self): """ A list of minimal bounding boxes (`~photutils.BoundingBox`), one for each position, enclosing the exact elliptical apertures. """ cos_theta = np.cos(self.theta) sin_theta = np.sin(self.theta) ax = self.a_out * cos_theta ay = ...
[ "def", "bounding_boxes", "(", "self", ")", ":", "cos_theta", "=", "np", ".", "cos", "(", "self", ".", "theta", ")", "sin_theta", "=", "np", ".", "sin", "(", "self", ".", "theta", ")", "ax", "=", "self", ".", "a_out", "*", "cos_theta", "ay", "=", ...
34.318182
12.227273
def _parse_query(self, source): """Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: ...
[ "def", "_parse_query", "(", "self", ",", "source", ")", ":", "if", "self", ".", "OBJECTFILTER_WORDS", ".", "search", "(", "source", ")", ":", "syntax_", "=", "\"objectfilter\"", "else", ":", "syntax_", "=", "None", "# Default it is.", "return", "query", ".",...
28.789474
17.947368
def get_attribute(self): """Gets the appropriate module attribute name for a collection corresponding to the context's element type.""" attributes = ['dependencies', 'publics', 'members', 'types', 'executables'] #Find the correct attribute based on the type of...
[ "def", "get_attribute", "(", "self", ")", ":", "attributes", "=", "[", "'dependencies'", ",", "'publics'", ",", "'members'", ",", "'types'", ",", "'executables'", "]", "#Find the correct attribute based on the type of the context", "if", "self", ".", "context", ".", ...
41.5
13.642857
def si_round(val): ''' round to a "scientific notation" tuple of (factor, exponent) such that 1 < factor < 1000, and factor * 10 ** exponent == val ''' if val < 0: neg = True val = -val elif val == 0: return 0, 0 else: neg = False exp = math.log(val) / mat...
[ "def", "si_round", "(", "val", ")", ":", "if", "val", "<", "0", ":", "neg", "=", "True", "val", "=", "-", "val", "elif", "val", "==", "0", ":", "return", "0", ",", "0", "else", ":", "neg", "=", "False", "exp", "=", "math", ".", "log", "(", ...
22.47619
22.380952
def collision_warning(self, item): """ Given a string, print a warning if this could collide with a Zappa core package module. Use for app functions and events. """ namespace_collisions = [ "zappa.", "wsgi.", "middleware.", "handler.", "util.", "letsencrypt....
[ "def", "collision_warning", "(", "self", ",", "item", ")", ":", "namespace_collisions", "=", "[", "\"zappa.\"", ",", "\"wsgi.\"", ",", "\"middleware.\"", ",", "\"handler.\"", ",", "\"util.\"", ",", "\"letsencrypt.\"", ",", "\"cli.\"", "]", "for", "namespace_collis...
42.894737
19.526316
def encryption(self): """ Property for accessing :class:`EncryptionManager` instance, which is used to manage encryption. :rtype: yagocd.resources.encryption.EncryptionManager """ if self._encryption_manager is None: self._encryption_manager = EncryptionManag...
[ "def", "encryption", "(", "self", ")", ":", "if", "self", ".", "_encryption_manager", "is", "None", ":", "self", ".", "_encryption_manager", "=", "EncryptionManager", "(", "session", "=", "self", ".", "_session", ")", "return", "self", ".", "_encryption_manage...
37.6
15.4
def revrank_dict(dict, key=lambda t: t[1], as_tuple=False): """ Reverse sorts a #dict by a given key, optionally returning it as a #tuple. By default, the @dict is sorted by it's value. @dict: the #dict you wish to sorts @key: the #sorted key to use @as_tuple: returns result as a #t...
[ "def", "revrank_dict", "(", "dict", ",", "key", "=", "lambda", "t", ":", "t", "[", "1", "]", ",", "as_tuple", "=", "False", ")", ":", "sorted_list", "=", "sorted", "(", "dict", ".", "items", "(", ")", ",", "key", "=", "key", ",", "reverse", "=", ...
42.75
16.833333
def get_matching_kwargs(func, kwargs): """Takes a function and keyword arguments and returns the ones that can be passed.""" args, uses_startstar = _get_argspec(func) if uses_startstar: return kwargs.copy() else: matching_kwargs = dict((k, kwargs[k]) for k in args if k in kwargs) ...
[ "def", "get_matching_kwargs", "(", "func", ",", "kwargs", ")", ":", "args", ",", "uses_startstar", "=", "_get_argspec", "(", "func", ")", "if", "uses_startstar", ":", "return", "kwargs", ".", "copy", "(", ")", "else", ":", "matching_kwargs", "=", "dict", "...
42
14.125
def _enable_notifications_failed(self, dbus_error): """ Called when notification enabling has failed. """ if ((dbus_error.get_dbus_name() == 'org.bluez.Error.Failed') and ((dbus_error.get_dbus_message() == "Already notifying") or (dbus_error.get_dbus_message() ==...
[ "def", "_enable_notifications_failed", "(", "self", ",", "dbus_error", ")", ":", "if", "(", "(", "dbus_error", ".", "get_dbus_name", "(", ")", "==", "'org.bluez.Error.Failed'", ")", "and", "(", "(", "dbus_error", ".", "get_dbus_message", "(", ")", "==", "\"Alr...
55.090909
24.363636
def get_available_columns(self, dataset_ids): """ Retrieves the set of columns from the combination of dataset ids given :param dataset_ids: The id of the dataset to retrieve columns from :type dataset_ids: list of int :return: A list of column names from the dataset ids given. ...
[ "def", "get_available_columns", "(", "self", ",", "dataset_ids", ")", ":", "if", "not", "isinstance", "(", "dataset_ids", ",", "list", ")", ":", "dataset_ids", "=", "[", "dataset_ids", "]", "data", "=", "{", "\"dataset_ids\"", ":", "dataset_ids", "}", "failu...
36.142857
23.47619
def create_bayesian_tear_sheet(returns, benchmark_rets=None, live_start_date=None, samples=2000, return_fig=False, stoch_vol=False, progressbar=True): """ Generate a number of Bayesian distributions and a Bayesian c...
[ "def", "create_bayesian_tear_sheet", "(", "returns", ",", "benchmark_rets", "=", "None", ",", "live_start_date", "=", "None", ",", "samples", "=", "2000", ",", "return_fig", "=", "False", ",", "stoch_vol", "=", "False", ",", "progressbar", "=", "True", ")", ...
37.559783
18.668478
def find_example_dir(): """ Find examples dir .. a little bit ugly.. """ # Replace %s with directory to check for shoebot menus. code_stub = textwrap.dedent(""" from pkg_resources import resource_filename, Requirement, DistributionNotFound try: print(resource_filename(Requirement.par...
[ "def", "find_example_dir", "(", ")", ":", "# Replace %s with directory to check for shoebot menus.", "code_stub", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n from pkg_resources import resource_filename, Requirement, DistributionNotFound\n try:\n print(resource_filename(Requir...
38.651163
21.697674
def check_reservation_rooms(self): ''' This method is used to validate the reservation_line. ----------------------------------------------------- @param self: object pointer @return: raise a warning depending on the validation ''' ctx = dict(self._context) or {} ...
[ "def", "check_reservation_rooms", "(", "self", ")", ":", "ctx", "=", "dict", "(", "self", ".", "_context", ")", "or", "{", "}", "for", "reservation", "in", "self", ":", "cap", "=", "0", "for", "rec", "in", "reservation", ".", "reservation_line", ":", "...
44.416667
12.75
def get_direction(self, direction, rev=False): """ Translate a direction in compass degrees into 'up' or 'down'. """ if (direction < 90.0) or (direction >= 270.0): if not rev: return 'up' else: return 'down' elif (90.0 <= di...
[ "def", "get_direction", "(", "self", ",", "direction", ",", "rev", "=", "False", ")", ":", "if", "(", "direction", "<", "90.0", ")", "or", "(", "direction", ">=", "270.0", ")", ":", "if", "not", "rev", ":", "return", "'up'", "else", ":", "return", ...
28.875
13.75
def project_meta(self, attributes): """ Projects the specified metadata attributes to new region fields :param attributes: a list of metadata attributes :return: a new GDataframe with additional region fields """ if not isinstance(attributes, list): raise TypeError('...
[ "def", "project_meta", "(", "self", ",", "attributes", ")", ":", "if", "not", "isinstance", "(", "attributes", ",", "list", ")", ":", "raise", "TypeError", "(", "'attributes must be a list'", ")", "meta_to_project", "=", "self", ".", "meta", "[", "attributes",...
51.090909
18.727273
def mse(mean, estimator): """ Description: Calculates the Mean Squared Error (MSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray) """ return np.mean((np.asarr...
[ "def", "mse", "(", "mean", ",", "estimator", ")", ":", "return", "np", ".", "mean", "(", "(", "np", ".", "asarray", "(", "estimator", ")", "-", "np", ".", "asarray", "(", "mean", ")", ")", "**", "2", ",", "axis", "=", "0", ")" ]
35.8
14.4
def find(soup, name=None, attrs=None, recursive=True, text=None, **kwargs): """Modified find method; see `find_all`, above. """ tags = find_all( soup, name, attrs or {}, recursive, text, 1, **kwargs ) if tags: return tags[0]
[ "def", "find", "(", "soup", ",", "name", "=", "None", ",", "attrs", "=", "None", ",", "recursive", "=", "True", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "tags", "=", "find_all", "(", "soup", ",", "name", ",", "attrs", "or", ...
28.111111
21.888889
async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. opti...
[ "async", "def", "rcpt", "(", "self", ",", "recipient", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "[", "]", "to_addr", "=", "\"TO:{}\"", ".", "format", "(", "quoteaddr", "(", "recipient", ")", ")", "cod...
34.806452
25.064516
def user(self, user): """ Sets the user of this WebCredentials. The name of the account to login to. :param user: The user of this WebCredentials. :type: str """ if user is None: raise ValueError("Invalid value for `user`, must not be `None`") ...
[ "def", "user", "(", "self", ",", "user", ")", ":", "if", "user", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `user`, must not be `None`\"", ")", "if", "user", "is", "not", "None", "and", "len", "(", "user", ")", ">", "1024", ":", ...
34.142857
20
def inject(): """Injects pout into the builtins module so it can be called from anywhere without having to be explicitely imported, this is really just for convenience when debugging https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable """ try: from .com...
[ "def", "inject", "(", ")", ":", "try", ":", "from", ".", "compat", "import", "builtins", "module", "=", "sys", ".", "modules", "[", "__name__", "]", "setattr", "(", "builtins", ",", "__name__", ",", "module", ")", "#builtins.pout = pout", "except", "Import...
29.75
22.4375
def drop(self, async_=False, if_exists=False, **kw): """ Drop this table. :param async_: run asynchronously if True :return: None """ async_ = kw.get('async', async_) return self.parent.delete(self, async_=async_, if_exists=if_exists)
[ "def", "drop", "(", "self", ",", "async_", "=", "False", ",", "if_exists", "=", "False", ",", "*", "*", "kw", ")", ":", "async_", "=", "kw", ".", "get", "(", "'async'", ",", "async_", ")", "return", "self", ".", "parent", ".", "delete", "(", "sel...
31.444444
14.555556
def wrap_in_ndarray(value): """Wraps the argument in a numpy.ndarray. If value is a scalar, it is converted in a list first. If value is array-like, the shape is conserved. """ if hasattr(value, "__len__"): return np.array(value) else: return np.array([value])
[ "def", "wrap_in_ndarray", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "\"__len__\"", ")", ":", "return", "np", ".", "array", "(", "value", ")", "else", ":", "return", "np", ".", "array", "(", "[", "value", "]", ")" ]
24.833333
18.666667
def to_vars_dict(self): """ Return local state which is relevant for the cluster setup process. """ return { 'aws_access_key_id': self._access_key, 'aws_secret_access_key': self._secret_key, 'aws_region': self._region_name, ...
[ "def", "to_vars_dict", "(", "self", ")", ":", "return", "{", "'aws_access_key_id'", ":", "self", ".", "_access_key", ",", "'aws_secret_access_key'", ":", "self", ".", "_secret_key", ",", "'aws_region'", ":", "self", ".", "_region_name", ",", "'aws_vpc_name'", ":...
38.727273
17.090909
def _from_dict(cls, _dict): """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'customer_id' in _dict: args['customer_id'] = _dict.get('customer_i...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'environment_id'", "in", "_dict", ":", "args", "[", "'environment_id'", "]", "=", "_dict", ".", "get", "(", "'environment_id'", ")", "if", "'customer_id'", "in", "_dic...
46.916667
12.972222
def log(self, n=None, template=None, **kwargs): """ Run the repository log command Returns: str: output of log command (``svn log -l <n> <--kwarg=value>``) """ cmd = ['svn', 'log'] if n: cmd.append('-l%d' % n) cmd.extend( (('--...
[ "def", "log", "(", "self", ",", "n", "=", "None", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cmd", "=", "[", "'svn'", ",", "'log'", "]", "if", "n", ":", "cmd", ".", "append", "(", "'-l%d'", "%", "n", ")", "cmd", ".", ...
28.857143
16.285714
def _instantiate_app(self, target_cls, kwargs): """For App targets, convert BundleAdaptor to BundleProps.""" parse_context = ParseContext(kwargs['address'].spec_path, dict()) bundleprops_factory = Bundle(parse_context) kwargs['bundles'] = [ bundleprops_factory.create_bundle_props(bundle) for...
[ "def", "_instantiate_app", "(", "self", ",", "target_cls", ",", "kwargs", ")", ":", "parse_context", "=", "ParseContext", "(", "kwargs", "[", "'address'", "]", ".", "spec_path", ",", "dict", "(", ")", ")", "bundleprops_factory", "=", "Bundle", "(", "parse_co...
39.6
15.8
def main(sample_id, fastq_pair, gsize, minimum_coverage, opts): """ Main executor of the integrity_coverage template. Parameters ---------- sample_id : str Sample Identification string. fastq_pair : list Two element list containing the paired FastQ files. gsize : float or int ...
[ "def", "main", "(", "sample_id", ",", "fastq_pair", ",", "gsize", ",", "minimum_coverage", ",", "opts", ")", ":", "logger", ".", "info", "(", "\"Starting integrity coverage main\"", ")", "# Check for runtime options", "if", "\"-e\"", "in", "opts", ":", "skip_encod...
39.868996
18.279476
def _replace_placeholder(sql_statement, variable): """ Return the string obtained by replacing the specified placeholders by its corresponding value. @param sql_statement: the string expression of a SQL statement to replace placeholders with their corresponding values. ...
[ "def", "_replace_placeholder", "(", "sql_statement", ",", "variable", ")", ":", "(", "variable_name", ",", "variable_type", ",", "variable_value", ")", "=", "variable", "sql_value", "=", "RdbmsConnection", ".", "_expand_placeholder_value", "(", "variable_value", ")", ...
44.1
33.233333
def _list_availability_zones(vm_=None): ''' List all availability zones in the current region ''' ret = {} params = {'Action': 'DescribeAvailabilityZones', 'Filter.0.Name': 'region-name', 'Filter.0.Value.0': get_location(vm_)} result = aws.query(params, ...
[ "def", "_list_availability_zones", "(", "vm_", "=", "None", ")", ":", "ret", "=", "{", "}", "params", "=", "{", "'Action'", ":", "'DescribeAvailabilityZones'", ",", "'Filter.0.Name'", ":", "'region-name'", ",", "'Filter.0.Value.0'", ":", "get_location", "(", "vm...
29
18.157895
def find_message_handler(self, handler_name, handler_type='primary'): """Returns the MessageHandler given its name and type for this class.""" ret = lib.EnvFindDefmessageHandler( self._env, self._cls, handler_name.encode(), handler_type.encode()) if ret == 0: raise CLIPSE...
[ "def", "find_message_handler", "(", "self", ",", "handler_name", ",", "handler_type", "=", "'primary'", ")", ":", "ret", "=", "lib", ".", "EnvFindDefmessageHandler", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "handler_name", ".", "encode", "(",...
48.25
18.5
async def connect(self, host, port=DEFAULT_PORT): """ :py:func:`asyncio.coroutine` Connect to server. :param host: host name for connection :type host: :py:class:`str` :param port: port number for connection :type port: :py:class:`int` """ await...
[ "async", "def", "connect", "(", "self", ",", "host", ",", "port", "=", "DEFAULT_PORT", ")", ":", "await", "super", "(", ")", ".", "connect", "(", "host", ",", "port", ")", "code", ",", "info", "=", "await", "self", ".", "command", "(", "None", ",",...
27.6
14
def parseLinkAttrs(html): """Find all link tags in a string representing a HTML document and return a list of their attributes. @param html: the text to parse @type html: str or unicode @return: A list of dictionaries of attributes, one for each link tag @rtype: [[(type(html), type(html))]] ...
[ "def", "parseLinkAttrs", "(", "html", ")", ":", "stripped", "=", "removed_re", ".", "sub", "(", "''", ",", "html", ")", "html_mo", "=", "html_find", ".", "search", "(", "stripped", ")", "if", "html_mo", "is", "None", "or", "html_mo", ".", "start", "(",...
32.904762
18.928571
def render(self, context, instance, placeholder): """ Update the context with plugin's data """ entries = Entry.published.search(instance.query) if instance.number_of_entries: entries = entries[:instance.number_of_entries] context = super(CMSQueryEntriesPlugi...
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "entries", "=", "Entry", ".", "published", ".", "search", "(", "instance", ".", "query", ")", "if", "instance", ".", "number_of_entries", ":", "entries", "=", "e...
35.75
11.25
def _read_holidays(self, filename): """ Read holidays from an iCalendar-format file. """ cal = Calendar.from_ical(open(filename, 'rb').read()) holidays = [] for component in cal.walk('VEVENT'): start = component.decoded('DTSTART') try: end = component.decoded('DTEND') except KeyError: # RF...
[ "def", "_read_holidays", "(", "self", ",", "filename", ")", ":", "cal", "=", "Calendar", ".", "from_ical", "(", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", ")", "holidays", "=", "[", "]", "for", "component", "in", "cal", ".", ...
35.891892
17.405405
def ULT(self, o): """ Unsigned less than. :param o: The other operand :return: TrueResult(), FalseResult(), or MaybeResult() """ unsigned_bounds_1 = self._unsigned_bounds() unsigned_bounds_2 = o._unsigned_bounds() ret = [] for lb_1, ub_1 in unsi...
[ "def", "ULT", "(", "self", ",", "o", ")", ":", "unsigned_bounds_1", "=", "self", ".", "_unsigned_bounds", "(", ")", "unsigned_bounds_2", "=", "o", ".", "_unsigned_bounds", "(", ")", "ret", "=", "[", "]", "for", "lb_1", ",", "ub_1", "in", "unsigned_bounds...
30.037037
15.222222
def get_pull_requests(self): "https://developer.github.com/v3/pulls/#list-pull-requests" g = self.github query = {'state': 'all'} if self.args.github_token: query['access_token'] = g['token'] def f(pull): if self.args.ignore_closed: return...
[ "def", "get_pull_requests", "(", "self", ")", ":", "g", "=", "self", ".", "github", "query", "=", "{", "'state'", ":", "'all'", "}", "if", "self", ".", "args", ".", "github_token", ":", "query", "[", "'access_token'", "]", "=", "g", "[", "'token'", "...
40.235294
18.470588
def detect_view_name(self, environ: Dict[str, Any]) -> str: """ get view name from routing args """ urlvars = environ.get('wsgiorg.routing_args', [(), {}])[1] return urlvars.get(self.action_var_name)
[ "def", "detect_view_name", "(", "self", ",", "environ", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "urlvars", "=", "environ", ".", "get", "(", "'wsgiorg.routing_args'", ",", "[", "(", ")", ",", "{", "}", "]", ")", "[", "1", ...
55
13.25
async def gather_candidates(self): """ Gather local candidates. You **must** call this coroutine before calling :meth:`connect`. """ if not self._local_candidates_start: self._local_candidates_start = True addresses = get_host_addresses(use_ipv4=self._use...
[ "async", "def", "gather_candidates", "(", "self", ")", ":", "if", "not", "self", ".", "_local_candidates_start", ":", "self", ".", "_local_candidates_start", "=", "True", "addresses", "=", "get_host_addresses", "(", "use_ipv4", "=", "self", ".", "_use_ipv4", ","...
42.285714
14.142857
def footrule_dist(params1, params2=None): r"""Compute Spearman's footrule distance between two models. This function computes Spearman's footrule distance between the rankings induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item ``i`` in the model described by ``params1``, and :ma...
[ "def", "footrule_dist", "(", "params1", ",", "params2", "=", "None", ")", ":", "assert", "params2", "is", "None", "or", "len", "(", "params1", ")", "==", "len", "(", "params2", ")", "ranks1", "=", "rankdata", "(", "params1", ",", "method", "=", "\"aver...
33.076923
22.846154
def eigh(a, eigvec=True, rcond=None): """ Eigenvalues and eigenvectors of symmetric matrix ``a``. Args: a: Two-dimensional, square Hermitian matrix/array of numbers and/or :class:`gvar.GVar`\s. Array elements must be real-valued if `gvar.GVar`\s are involved (i.e., symmetric ...
[ "def", "eigh", "(", "a", ",", "eigvec", "=", "True", ",", "rcond", "=", "None", ")", ":", "a", "=", "numpy", ".", "asarray", "(", "a", ")", "if", "a", ".", "dtype", "!=", "object", ":", "val", ",", "vec", "=", "numpy", ".", "linalg", ".", "ei...
42.403509
20.438596
def unary_operator(op): """ Factory function for making unary operator methods for Factors. """ # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(u...
[ "def", "unary_operator", "(", "op", ")", ":", "# Only negate is currently supported.", "valid_ops", "=", "{", "'-'", "}", "if", "op", "not", "in", "valid_ops", ":", "raise", "ValueError", "(", "\"Invalid unary operator %s.\"", "%", "op", ")", "@", "with_doc", "(...
34.25
15.7
def _is_local_filter(filter_block): """Return True if the Filter block references no non-local fields, and False otherwise.""" # We need the "result" value of this function to be mutated within the "visitor_fn". # Since we support both Python 2 and Python 3, we can't use the "nonlocal" keyword here: # h...
[ "def", "_is_local_filter", "(", "filter_block", ")", ":", "# We need the \"result\" value of this function to be mutated within the \"visitor_fn\".", "# Since we support both Python 2 and Python 3, we can't use the \"nonlocal\" keyword here:", "# https://www.python.org/dev/peps/pep-3104/", "# Inst...
43.846154
23.615385
def cloud_init_interface(name, vm_=None, **kwargs): ''' Interface between salt.cloud.lxc driver and lxc.init ``vm_`` is a mapping of vm opts in the salt.cloud format as documented for the lxc driver. This can be used either: - from the salt cloud driver - because you find the argument to g...
[ "def", "cloud_init_interface", "(", "name", ",", "vm_", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "vm_", "is", "None", ":", "vm_", "=", "{", "}", "vm_", "=", "copy", ".", "deepcopy", "(", "vm_", ")", "vm_", "=", "salt", ".", "utils", ...
36.3
15.796774
def yticksize(self, size, index=1): """Set the tick font size. Parameters ---------- size : int Returns ------- Chart """ self.layout['yaxis' + str(index)]['tickfont']['size'] = size return self
[ "def", "yticksize", "(", "self", ",", "size", ",", "index", "=", "1", ")", ":", "self", ".", "layout", "[", "'yaxis'", "+", "str", "(", "index", ")", "]", "[", "'tickfont'", "]", "[", "'size'", "]", "=", "size", "return", "self" ]
18.857143
22.642857
def calc_density(self, density_standard=None): """ Calculates the density of the SpectralColor. By default, Status T density is used, and the correct density distribution (Red, Green, or Blue) is chosen by comparing the Red, Green, and Blue components of the spectral sample (the ...
[ "def", "calc_density", "(", "self", ",", "density_standard", "=", "None", ")", ":", "if", "density_standard", "is", "not", "None", ":", "return", "density", ".", "ansi_density", "(", "self", ",", "density_standard", ")", "else", ":", "return", "density", "."...
47.454545
17.636364
def pixel_coords(self, latlon, reverse=False): '''return pixel coordinates in the map image for a (lat,lon) if reverse is set, then return lat/lon for a pixel coordinate ''' state = self.state if reverse: (x,y) = latlon return self.coordinates(x,y) ...
[ "def", "pixel_coords", "(", "self", ",", "latlon", ",", "reverse", "=", "False", ")", ":", "state", "=", "self", ".", "state", "if", "reverse", ":", "(", "x", ",", "y", ")", "=", "latlon", "return", "self", ".", "coordinates", "(", "x", ",", "y", ...
45
20.6
def get_waveset(model): """Get optimal wavelengths for sampling a given model. Parameters ---------- model : `~astropy.modeling.Model` Model. Returns ------- waveset : array-like or `None` Optimal wavelengths. `None` if undefined. Raises ------ synphot.exceptio...
[ "def", "get_waveset", "(", "model", ")", ":", "if", "not", "isinstance", "(", "model", ",", "Model", ")", ":", "raise", "SynphotError", "(", "'{0} is not a model.'", ".", "format", "(", "model", ")", ")", "if", "isinstance", "(", "model", ",", "_CompoundMo...
22.321429
21.642857
def optgroups(self, name, value, attrs=None): """Add empty option for clearable selects.""" if not self.is_required and not self.allow_multiple_selected: self.choices = list(chain([('', '')], self.choices)) return super(Select2Mixin, self).optgroups(name, value, attrs=attrs)
[ "def", "optgroups", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ")", ":", "if", "not", "self", ".", "is_required", "and", "not", "self", ".", "allow_multiple_selected", ":", "self", ".", "choices", "=", "list", "(", "chain", "(",...
61.4
18.8
def all_exist(filepaths): """Returns true if all files in the list exist.""" for fname in filepaths: if not tf.gfile.Exists(fname): return False return True
[ "def", "all_exist", "(", "filepaths", ")", ":", "for", "fname", "in", "filepaths", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "fname", ")", ":", "return", "False", "return", "True" ]
27.833333
14.166667
def append(self, item): """Append item to end of model""" self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self.items.append(item) self.endInsertRows()
[ "def", "append", "(", "self", ",", "item", ")", ":", "self", ".", "beginInsertRows", "(", "QtCore", ".", "QModelIndex", "(", ")", ",", "self", ".", "rowCount", "(", ")", ",", "self", ".", "rowCount", "(", ")", ")", "self", ".", "items", ".", "appen...
32.875
12.25
def build_list_regex(self): """Return the regex for the folder which contains the list of builds.""" regex = 'tinderbox-builds/%(BRANCH)s-%(PLATFORM)s%(L10N)s%(DEBUG)s/' return regex % { 'BRANCH': self.branch, 'PLATFORM': '' if self.locale_build else self.platform_regex,...
[ "def", "build_list_regex", "(", "self", ")", ":", "regex", "=", "'tinderbox-builds/%(BRANCH)s-%(PLATFORM)s%(L10N)s%(DEBUG)s/'", "return", "regex", "%", "{", "'BRANCH'", ":", "self", ".", "branch", ",", "'PLATFORM'", ":", "''", "if", "self", ".", "locale_build", "e...
47.555556
19.777778
def on_finished(self): """Finished signal handler""" self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully...
[ "def", "on_finished", "(", "self", ")", ":", "self", ".", "controller", ".", "is_running", "=", "False", "error", "=", "self", ".", "controller", ".", "current_error", "if", "error", "is", "not", "None", ":", "self", ".", "info", "(", "self", ".", "tr"...
35.111111
16.777778
def _write_with_fallback(s, write, fileobj): """Write the supplied string with the given write function like ``write(s)``, but use a writer for the locale's preferred encoding in case of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or 'latin-1'. """ if IPythonIOStream is no...
[ "def", "_write_with_fallback", "(", "s", ",", "write", ",", "fileobj", ")", ":", "if", "IPythonIOStream", "is", "not", "None", "and", "isinstance", "(", "fileobj", ",", "IPythonIOStream", ")", ":", "# If the output stream is an IPython.utils.io.IOStream object that's", ...
32.190476
22.904762
def sync_fetch(self, task): '''Synchronization fetch, usually used in xmlrpc thread''' if not self._running: return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True)) wait_result = threading.Condition() _result = {} def callback(ty...
[ "def", "sync_fetch", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "_running", ":", "return", "self", ".", "ioloop", ".", "run_sync", "(", "functools", ".", "partial", "(", "self", ".", "async_fetch", ",", "task", ",", "lambda", "t", ...
34.181818
16.181818
def add_sequence_flow_to_diagram(self, process_id, source_ref_id, target_ref_id, sequence_flow_name=""): """ Adds a SequenceFlow element to BPMN diagram. Requires that user passes a sourceRef and targetRef as parameters. User-defined attributes: - name :param proces...
[ "def", "add_sequence_flow_to_diagram", "(", "self", ",", "process_id", ",", "source_ref_id", ",", "target_ref_id", ",", "sequence_flow_name", "=", "\"\"", ")", ":", "sequence_flow_id", "=", "BpmnDiagramGraph", ".", "id_prefix", "+", "str", "(", "uuid", ".", "uuid4...
55.702703
27.702703
def sendhello(self): try: # send hello cli_hello_msg = "<hello>\n" +\ " <capabilities>\n" +\ " <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\ " </capabilities>\n" +\ ...
[ "def", "sendhello", "(", "self", ")", ":", "try", ":", "# send hello\r", "cli_hello_msg", "=", "\"<hello>\\n\"", "+", "\" <capabilities>\\n\"", "+", "\" <capability>urn:ietf:params:netconf:base:1.0</capability>\\n\"", "+", "\" </capabilities>\\n\"", "+", "\"</hello>\\n\"",...
37.631579
18.105263
def gc(): """Deletes old stellar tables that are not used anymore""" def after_delete(database): click.echo("Deleted table %s" % database) app = get_app() upgrade_from_old_version(app) app.delete_orphan_snapshots(after_delete)
[ "def", "gc", "(", ")", ":", "def", "after_delete", "(", "database", ")", ":", "click", ".", "echo", "(", "\"Deleted table %s\"", "%", "database", ")", "app", "=", "get_app", "(", ")", "upgrade_from_old_version", "(", "app", ")", "app", ".", "delete_orphan_...
31
15.25
def list_task_definitions(self): """ Filtering not implemented """ task_arns = [] for task_definition_list in self.task_definitions.values(): task_arns.extend( [task_definition.arn for task_definition in task_definition_list]) return task_arns
[ "def", "list_task_definitions", "(", "self", ")", ":", "task_arns", "=", "[", "]", "for", "task_definition_list", "in", "self", ".", "task_definitions", ".", "values", "(", ")", ":", "task_arns", ".", "extend", "(", "[", "task_definition", ".", "arn", "for",...
34.555556
14.333333
def _setup_segments(self): """ Parses the database file to determine what kind of database is being used and setup segment sizes and start points that will be used by the seek*() methods later. """ self._databaseType = const.COUNTRY_EDITION self._recordLength = co...
[ "def", "_setup_segments", "(", "self", ")", ":", "self", ".", "_databaseType", "=", "const", ".", "COUNTRY_EDITION", "self", ".", "_recordLength", "=", "const", ".", "STANDARD_RECORD_LENGTH", "self", ".", "_databaseSegments", "=", "const", ".", "COUNTRY_BEGIN", ...
40.984615
21.292308
def get_serializer_class(self): """gets the class type of the serializer :return: `rest_framework.Serializer` """ klass = None lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field if lookup_url_kwarg in self.kwargs: # Looks like this is a detail... ...
[ "def", "get_serializer_class", "(", "self", ")", ":", "klass", "=", "None", "lookup_url_kwarg", "=", "self", ".", "lookup_url_kwarg", "or", "self", ".", "lookup_field", "if", "lookup_url_kwarg", "in", "self", ".", "kwargs", ":", "# Looks like this is a detail...", ...
37.333333
17.875
def initialize(self, host): """ The EventProcessorHost can't pass itself to the AzureStorageCheckpointLeaseManager constructor because it is still being constructed. Do other initialization here also because it might throw and hence we don't want it in the constructor. """ ...
[ "def", "initialize", "(", "self", ",", "host", ")", ":", "self", ".", "host", "=", "host", "self", ".", "storage_client", "=", "BlockBlobService", "(", "account_name", "=", "self", ".", "storage_account_name", ",", "account_key", "=", "self", ".", "storage_a...
67.071429
35.357143
def convert_softmax_output(node, **kwargs): """Map MXNet's SoftmaxOutput operator attributes to onnx's Softmax operator and return the created node. """ name = node["name"] input1_idx = kwargs["index_lookup"][node["inputs"][0][0]] input1 = kwargs["proc_nodes"][input1_idx] softmax_node = on...
[ "def", "convert_softmax_output", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", "=", "node", "[", "\"name\"", "]", "input1_idx", "=", "kwargs", "[", "\"index_lookup\"", "]", "[", "node", "[", "\"inputs\"", "]", "[", "0", "]", "[", "0", "]", ...
24.888889
18.777778
def interpolate_delta_t(delta_t_table, tt): """Return interpolated Delta T values for the times in `tt`. The 2xN table should provide TT values as element 0 and corresponding Delta T values for element 1. For times outside the range of the table, a long-term formula is used instead. """ tt_ar...
[ "def", "interpolate_delta_t", "(", "delta_t_table", ",", "tt", ")", ":", "tt_array", ",", "delta_t_array", "=", "delta_t_table", "delta_t", "=", "_to_array", "(", "interp", "(", "tt", ",", "tt_array", ",", "delta_t_array", ",", "nan", ",", "nan", ")", ")", ...
38.5
21.65
def from_pydate(cls, pydate): """ Creates sql date object from Python date object. @param pydate: Python date @return: sql date """ return cls(days=(datetime.datetime.combine(pydate, datetime.time(0, 0, 0)) - _datetime2_base_date).days)
[ "def", "from_pydate", "(", "cls", ",", "pydate", ")", ":", "return", "cls", "(", "days", "=", "(", "datetime", ".", "datetime", ".", "combine", "(", "pydate", ",", "datetime", ".", "time", "(", "0", ",", "0", ",", "0", ")", ")", "-", "_datetime2_ba...
39.714286
17.142857