text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def receive(self, path, diff, showProgress=True): """ Return a context manager for stream that will store a diff. """ directory = os.path.dirname(path) cmd = ["btrfs", "receive", "-e", directory] if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd): return None ...
[ "def", "receive", "(", "self", ",", "path", ",", "diff", ",", "showProgress", "=", "True", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "cmd", "=", "[", "\"btrfs\"", ",", "\"receive\"", ",", "\"-e\"", ",", "directo...
30.333333
19.238095
def split(self, indice=None): """ Splits the Stack, either in half, or at the given indice, into two separate Stacks. :arg int indice: Optional. The indice to split the Stack at. Defaults to the middle of the ``Stack``. :returns: The two part...
[ "def", "split", "(", "self", ",", "indice", "=", "None", ")", ":", "self_size", "=", "self", ".", "size", "if", "self_size", ">", "1", ":", "if", "not", "indice", ":", "mid", "=", "self_size", "//", "2", "return", "Stack", "(", "cards", "=", "self"...
32.454545
21.545455
def collect_dirs(path, max_depth=1, followlinks=True): """Recursively find directories under the given path.""" if not os.path.isdir(path): return [] o = [path] if max_depth == 0: return o for subdir in os.listdir(path): subdir = os.path.join(path, subdir) if no...
[ "def", "collect_dirs", "(", "path", ",", "max_depth", "=", "1", ",", "followlinks", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "[", "]", "o", "=", "[", "path", "]", "if", "max_depth", "==...
20.518519
24.148148
def _show_annotation_box(self, event): """Update an existing box or create an annotation box for an event.""" ax = event.artist.axes # Get the pre-created annotation box for the axes or create a new one. if self.display != 'multiple': annotation = self.annotations[ax] ...
[ "def", "_show_annotation_box", "(", "self", ",", "event", ")", ":", "ax", "=", "event", ".", "artist", ".", "axes", "# Get the pre-created annotation box for the axes or create a new one.", "if", "self", ".", "display", "!=", "'multiple'", ":", "annotation", "=", "s...
44.4
15.4
def atom_fractions(self): r'''Dictionary of atom:fractional occurence of the elements in a chemical. Useful when performing element balances. For mass-fraction occurences, see :obj:`mass_fractions`. Examples -------- >>> Chemical('Ammonium aluminium sulfate').atom_fracti...
[ "def", "atom_fractions", "(", "self", ")", ":", "if", "self", ".", "__atom_fractions", ":", "return", "self", ".", "__atom_fractions", "else", ":", "self", ".", "__atom_fractions", "=", "atom_fractions", "(", "self", ".", "atoms", ")", "return", "self", ".",...
38.866667
21
def _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, log_only_last: bool = False): """ Adds a log message and creates a recursive parsing plan. :param desired_type: :param filesystem_object: :param...
[ "def", "_create_parsing_plan", "(", "self", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "filesystem_object", ":", "PersistedObject", ",", "logger", ":", "Logger", ",", "log_only_last", ":", "bool", "=", "False", ")", ":", "logger", ".", "debug", ...
51.428571
30
def yaml_conf_as_dict(file_path, encoding=None): """ 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 :param: * file_path: (string) 需要读入的 yaml 配置文件长文件名 * encoding: (string) 文件编码 * msg: (string) 读取配置信息 :return: * flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False * d: (dict) 如果读取配置文件正...
[ "def", "yaml_conf_as_dict", "(", "file_path", ",", "encoding", "=", "None", ")", ":", "if", "not", "pathlib", ".", "Path", "(", "file_path", ")", ".", "is_file", "(", ")", ":", "return", "False", ",", "{", "}", ",", "'File not exist'", "try", ":", "if"...
28.807692
18.153846
def discover(timeout=5, include_invisible=False, interface_addr=None, all_households=False): """ Discover Sonos zones on the local network. Return a set of `SoCo` instances for each zone found. Include invisible zones (bridges and slave zones in stereo pairs if ``...
[ "def", "discover", "(", "timeout", "=", "5", ",", "include_invisible", "=", "False", ",", "interface_addr", "=", "None", ",", "all_households", "=", "False", ")", ":", "found_zones", "=", "set", "(", ")", "first_response", "=", "None", "def", "callback", "...
36.137931
21.706897
def acquire (self, blocking=1): """Acquire lock.""" threadname = threading.currentThread().getName() log.debug(LOG_THREAD, "Acquire %s for %s", self.name, threadname) self.lock.acquire(blocking) log.debug(LOG_THREAD, "...acquired %s for %s", self.name, threadname)
[ "def", "acquire", "(", "self", ",", "blocking", "=", "1", ")", ":", "threadname", "=", "threading", ".", "currentThread", "(", ")", ".", "getName", "(", ")", "log", ".", "debug", "(", "LOG_THREAD", ",", "\"Acquire %s for %s\"", ",", "self", ".", "name", ...
49.833333
16.666667
def load_dependencies(req, history=None): """ Load the dependency tree as a Python object tree, suitable for JSON serialization. >>> deps = load_dependencies('jaraco.packaging') >>> import json >>> doc = json.dumps(deps) """ if history is None: history = set() dist = pkg_res...
[ "def", "load_dependencies", "(", "req", ",", "history", "=", "None", ")", ":", "if", "history", "is", "None", ":", "history", "=", "set", "(", ")", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "req", ")", "spec", "=", "dict", "(", "requi...
27.185185
14.37037
def set_headers(self) -> None: """Sets the content and caching headers on the response. .. versionadded:: 3.1 """ self.set_header("Accept-Ranges", "bytes") self.set_etag_header() if self.modified is not None: self.set_header("Last-Modified", self.modified) ...
[ "def", "set_headers", "(", "self", ")", "->", "None", ":", "self", ".", "set_header", "(", "\"Accept-Ranges\"", ",", "\"bytes\"", ")", "self", ".", "set_etag_header", "(", ")", "if", "self", ".", "modified", "is", "not", "None", ":", "self", ".", "set_he...
33.666667
20.291667
def load_truetype_font( path: str, tile_width: int, tile_height: int ) -> Tileset: """Return a new Tileset from a `.ttf` or `.otf` file. Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead. You can send this Tileset to :any:`set_default`. This function is provisional. The API m...
[ "def", "load_truetype_font", "(", "path", ":", "str", ",", "tile_width", ":", "int", ",", "tile_height", ":", "int", ")", "->", "Tileset", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "RuntimeError", "(", "\"File ...
36.466667
21.666667
def ToScriptHash(self, address): """ Retrieve the script_hash based from an address. Args: address (str): a base58 encoded address. Raises: ValuesError: if an invalid address is supplied or the coin version is incorrect Exception: if the address stri...
[ "def", "ToScriptHash", "(", "self", ",", "address", ")", ":", "if", "len", "(", "address", ")", "==", "34", ":", "if", "address", "[", "0", "]", "==", "'A'", ":", "data", "=", "b58decode", "(", "address", ")", "if", "data", "[", "0", "]", "!=", ...
35.75
20.535714
def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit): """ Constructs dict with URL params :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbo...
[ "def", "_prepare_url_params", "(", "tile_id", ",", "bbox", ",", "end_date", ",", "start_date", ",", "absolute_orbit", ")", ":", "url_params", "=", "{", "'identifier'", ":", "tile_id", ",", "'startDate'", ":", "start_date", ",", "'completionDate'", ":", "end_date...
41.32
21.8
def seek_end(fileobj, offset): """Like fileobj.seek(-offset, 2), but will not try to go beyond the start Needed since file objects from BytesIO will not raise IOError and file objects from open() will raise IOError if going to a negative offset. To make things easier for custom implementations, instead...
[ "def", "seek_end", "(", "fileobj", ",", "offset", ")", ":", "if", "offset", "<", "0", ":", "raise", "ValueError", "if", "get_size", "(", "fileobj", ")", "<", "offset", ":", "fileobj", ".", "seek", "(", "0", ",", "0", ")", "else", ":", "fileobj", "....
28.347826
23.565217
def send(self, data, room=None, skip_sid=None, namespace=None, callback=None): """Send a message to the server. The only difference with the :func:`socketio.Client.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is u...
[ "def", "send", "(", "self", ",", "data", ",", "room", "=", "None", ",", "skip_sid", "=", "None", ",", "namespace", "=", "None", ",", "callback", "=", "None", ")", ":", "return", "self", ".", "client", ".", "send", "(", "data", ",", "namespace", "="...
45.5
18.8
def get_msg_info(yaml_info, topics, parse_header=True): ''' Get info from all of the messages about what they contain and will be added to the dataframe ''' topic_info = yaml_info['topics'] msgs = {} classes = {} for topic in topics: base_key = get_key_name(topic) msg_pa...
[ "def", "get_msg_info", "(", "yaml_info", ",", "topics", ",", "parse_header", "=", "True", ")", ":", "topic_info", "=", "yaml_info", "[", "'topics'", "]", "msgs", "=", "{", "}", "classes", "=", "{", "}", "for", "topic", "in", "topics", ":", "base_key", ...
35.64
17.32
def vmx_path(self, vmx_path): """ Sets the path to the vmx file. :param vmx_path: VMware vmx file """ log.info("VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'".format(name=self.name, id=self.id, vmx=vmx_path)) self._vmx_path = vmx_path
[ "def", "vmx_path", "(", "self", ",", "vmx_path", ")", ":", "log", ".", "info", "(", "\"VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'\"", ".", "format", "(", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "vmx", "="...
32.555556
21.222222
def highpass(self, frequency, gpass=2, gstop=30, fstop=None, type='iir', filtfilt=True, **kwargs): """Filter this `TimeSeries` with a high-pass filter. Parameters ---------- frequency : `float` high-pass corner frequency gpass : `float` ...
[ "def", "highpass", "(", "self", ",", "frequency", ",", "gpass", "=", "2", ",", "gstop", "=", "30", ",", "fstop", "=", "None", ",", "type", "=", "'iir'", ",", "filtfilt", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# design filter", "filt", "="...
32.367347
22.510204
def adjoint(self): """Adjoint, given as scaling with the conjugate of the scalar. Examples -------- In the real case, the adjoint is the same as the operator: >>> r3 = odl.rn(3) >>> x = r3.element([1, 2, 3]) >>> op = ScalingOperator(r3, 2) >>> op(x) ...
[ "def", "adjoint", "(", "self", ")", ":", "if", "complex", "(", "self", ".", "scalar", ")", ".", "imag", "==", "0.0", ":", "return", "self", "else", ":", "return", "ScalingOperator", "(", "self", ".", "domain", ",", "self", ".", "scalar", ".", "conjug...
31.914286
16.914286
def format_numbers(number, prefix=""): """Formats number in the scientific notation for LaTeX. :param number: the number to format. :param prefix: a prefix to add before the number (e.g. "p < "). :type number: str :type prefix: str :returns: a string containing the scientific notation of the ...
[ "def", "format_numbers", "(", "number", ",", "prefix", "=", "\"\"", ")", ":", "# Matching", "r", "=", "re", ".", "match", "(", "r\"^([-+]?\\d*\\.\\d+|\\d+)e([-+]?\\d+)$\"", ",", "number", ")", "# Nothing matched", "if", "not", "r", ":", "if", "prefix", "!=", ...
26.357143
22.357143
def enumeration(*values, **kwargs): ''' Create an |Enumeration| object from a sequence of values. Call ``enumeration`` with a sequence of (unique) strings to create an Enumeration object: .. code-block:: python #: Specify the horizontal alignment for rendering text TextAlign = enumera...
[ "def", "enumeration", "(", "*", "values", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "values", "and", "all", "(", "isinstance", "(", "value", ",", "string_types", ")", "and", "value", "for", "value", "in", "values", ")", ")", ":", "raise", ...
33.3125
27.354167
def selection_sort(arr, simulation=False): """ Selection Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # "Select" the ...
[ "def", "selection_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "for", "i", "in", "range", "(", "len", ...
25.478261
15.086957
def _update_counters(self, ti_status): """ Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks :type ti_status: BackfillJob._DagRunTaskStatus """ ...
[ "def", "_update_counters", "(", "self", ",", "ti_status", ")", ":", "for", "key", ",", "ti", "in", "list", "(", "ti_status", ".", "running", ".", "items", "(", ")", ")", ":", "ti", ".", "refresh_from_db", "(", ")", "if", "ti", ".", "state", "==", "...
49
16.306122
def rel_paths(self, *args, **kwargs): """ Fix the paths in the given dictionary to get relative paths Parameters ---------- %(ExperimentsConfig.rel_paths.parameters)s Returns ------- %(ExperimentsConfig.rel_paths.returns)s Notes ----- ...
[ "def", "rel_paths", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "config", ".", "experiments", ".", "rel_paths", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
25.1875
21.25
def verifySignature(self, msg): """ Validate the signature of the request Note: Batch is whitelisted because the inner messages are checked :param msg: a message requiring signature verification :return: None; raises an exception if the signature is not valid """ ...
[ "def", "verifySignature", "(", "self", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "self", ".", "authnWhitelist", ")", ":", "return", "if", "isinstance", "(", "msg", ",", "Propagate", ")", ":", "typ", "=", "'propagate'", "req", "=", "Txn...
33.96875
20.90625
def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used. """ if not widget: wid...
[ "def", "as_widget", "(", "self", ",", "widget", "=", "None", ",", "attrs", "=", "None", ",", "only_initial", "=", "False", ")", ":", "if", "not", "widget", ":", "widget", "=", "self", ".", "field", ".", "widget", "attrs", "=", "attrs", "or", "{", "...
35.631579
17.631579
def _install_signal_handlers(self): """ Sets up signal handlers for safely stopping the worker. """ def request_stop(signum, frame): self._stop_requested = True self.log.info('stop requested, waiting for task to finish') signal.signal(signal.SIGINT, reques...
[ "def", "_install_signal_handlers", "(", "self", ")", ":", "def", "request_stop", "(", "signum", ",", "frame", ")", ":", "self", ".", "_stop_requested", "=", "True", "self", ".", "log", ".", "info", "(", "'stop requested, waiting for task to finish'", ")", "signa...
41.222222
9
def saveCopy(self) : "saves a copy of the object and become that copy. returns a tuple (old _key, new _key)" old_key = self._key self.reset(self.collection) self.save() return (old_key, self._key)
[ "def", "saveCopy", "(", "self", ")", ":", "old_key", "=", "self", ".", "_key", "self", ".", "reset", "(", "self", ".", "collection", ")", "self", ".", "save", "(", ")", "return", "(", "old_key", ",", "self", ".", "_key", ")" ]
38.5
19.833333
async def _make_request(self, method: str, url: str, url_vars: Dict[str, str], data: Any, accept: str, jwt: Opt[str] = None, oauth_token: Opt[str] = None, ) -> Tuple[bytes, Opt[str]]: """Construct and...
[ "async", "def", "_make_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", ",", "data", ":", "Any", ",", "accept", ":", "str", ",", "jwt", ":", "Opt", "[", "str", ...
48.303571
16.428571
def MeshLines(*inputobj, **options): """ Build the line segments between two lists of points `startPoints` and `endPoints`. `startPoints` can be also passed in the form ``[[point1, point2], ...]``. A dolfin ``Mesh`` that was deformed/modified by a function can be passed together as inputs. :pa...
[ "def", "MeshLines", "(", "*", "inputobj", ",", "*", "*", "options", ")", ":", "scale", "=", "options", ".", "pop", "(", "\"scale\"", ",", "1", ")", "lw", "=", "options", ".", "pop", "(", "\"lw\"", ",", "1", ")", "c", "=", "options", ".", "pop", ...
35.457143
20.771429
def get_scalar_value(self, name): """ Get scalar value by name """ if name not in self.scalars: raise InvalidServiceConfiguration( 'Invalid Service Argument Scalar "%s" (not found)' % name ) new_value = self.scalars.get(name) return new_value
[ "def", "get_scalar_value", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "scalars", ":", "raise", "InvalidServiceConfiguration", "(", "'Invalid Service Argument Scalar \"%s\" (not found)'", "%", "name", ")", "new_value", "=", "self", ...
38.375
11.875
def schemas_map(add_generics=False): """ Returns a dictionary of H₂O schemas, indexed by their name. """ m = {} for schema in schemas(): if schema["name"].startswith('AutoML'): continue # Generation code doesn't know how to deal with defaults for complex objects yet if schema["name"...
[ "def", "schemas_map", "(", "add_generics", "=", "False", ")", ":", "m", "=", "{", "}", "for", "schema", "in", "schemas", "(", ")", ":", "if", "schema", "[", "\"name\"", "]", ".", "startswith", "(", "'AutoML'", ")", ":", "continue", "# Generation code doe...
52.509091
25.836364
def filter_from_query(query, id_field="id", field_map={}): """This returns a filter which actually filters out everything, unlike the preview filter which includes excluded_ids for UI purposes. """ f = groups_filter_from_query(query, field_map=field_map) excluded_ids = query.get("excluded_ids") ...
[ "def", "filter_from_query", "(", "query", ",", "id_field", "=", "\"id\"", ",", "field_map", "=", "{", "}", ")", ":", "f", "=", "groups_filter_from_query", "(", "query", ",", "field_map", "=", "field_map", ")", "excluded_ids", "=", "query", ".", "get", "(",...
32.1
15.55
def request_add(self, req, x, y): """Add two numbers""" r = x + y self._add_result.set_value(r) return ("ok", r)
[ "def", "request_add", "(", "self", ",", "req", ",", "x", ",", "y", ")", ":", "r", "=", "x", "+", "y", "self", ".", "_add_result", ".", "set_value", "(", "r", ")", "return", "(", "\"ok\"", ",", "r", ")" ]
28
9.8
def getmessage(self) -> str: """ parse self into unicode string as message content """ image = {} for key, default in vars(self.__class__).items(): if not key.startswith('_') and key !='' and (not key in vars(QueueMessage).items()): ...
[ "def", "getmessage", "(", "self", ")", "->", "str", ":", "image", "=", "{", "}", "for", "key", ",", "default", "in", "vars", "(", "self", ".", "__class__", ")", ".", "items", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "'_'", ")", ...
63.416667
32.416667
def lpc(x, N=None): """Linear Predictor Coefficients. :param x: :param int N: default is length(X) - 1 :Details: Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order forward linear predictor that predicts the current value value of the real-valued time series x based ...
[ "def", "lpc", "(", "x", ",", "N", "=", "None", ")", ":", "m", "=", "len", "(", "x", ")", "if", "N", "is", "None", ":", "N", "=", "m", "-", "1", "#default value if N is not provided", "elif", "N", ">", "m", "-", "1", ":", "#disp('Warning: zero-paddi...
28.809524
27.063492
def get_answer_id_for_question(self, question): """Get the answer_id corresponding to the answer given for question by looking at this :class:`~.UserQuestion`'s answer_options. The given :class:`~.Question` instance must have the same id as this :class:`~.UserQuestion`. That thi...
[ "def", "get_answer_id_for_question", "(", "self", ",", "question", ")", ":", "assert", "question", ".", "id", "==", "self", ".", "id", "for", "answer_option", "in", "self", ".", "answer_options", ":", "if", "answer_option", ".", "text", "==", "question", "."...
48.769231
16.307692
def make_fields_unique(self, fields): """ iterates over the row and make each field unique """ for i in range(0, len(fields)): for j in range(i+1, len(fields)): if fields[i] == fields[j]: fields[j] += "'"
[ "def", "make_fields_unique", "(", "self", ",", "fields", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "fields", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "fields", ")", ")", ":", "if", "...
34.625
3.875
def commit(self): """Commit dirty records to the server. This method is automatically called when the `auto_commit` option is set to `True` (default). It can be useful to set the former option to `False` to get better performance by reducing the number of RPC requests generated. ...
[ "def", "commit", "(", "self", ")", ":", "# Iterate on a new set, as we remove record during iteration from the", "# original one", "for", "record", "in", "set", "(", "self", ".", "dirty", ")", ":", "values", "=", "{", "}", "for", "field", "in", "record", ".", "_...
43.270833
23.0625
def register(self, new_formulas, *args, **kwargs): """ Register formula and meta data. * ``islinear`` - ``True`` if formula is linear, ``False`` if non-linear. * ``args`` - position of arguments * ``units`` - units of returns and arguments as pair of tuples * ``isconstan...
[ "def", "register", "(", "self", ",", "new_formulas", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "zip", "(", "self", ".", "meta_names", ",", "args", ")", ")", "# call super method, meta must be passed as kwargs!", "supe...
43.785714
19.5
def decode(string, base): """ Given a string (string) and a numeric base (base), decode the string into an integer. Returns the integer """ base = int(base) code_string = get_code_string(base) result = 0 if base == 16: string = string.lower() while len(string) > 0: ...
[ "def", "decode", "(", "string", ",", "base", ")", ":", "base", "=", "int", "(", "base", ")", "code_string", "=", "get_code_string", "(", "base", ")", "result", "=", "0", "if", "base", "==", "16", ":", "string", "=", "string", ".", "lower", "(", ")"...
22.944444
15.5
def get_resource_form_for_create(self, resource_record_types): """Gets the resource form for creating new resources. A new form should be requested for each create transaction. arg: resource_record_types (osid.type.Type[]): array of resource record types return: (osi...
[ "def", "get_resource_form_for_create", "(", "self", ",", "resource_record_types", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.get_resource_form_for_create_template", "for", "arg", "in", "resource_record_types", ":", "if", "not", "isinstance", ...
46.138889
17.694444
def convert_windows_path_to_cygwin(path): """Convert a Windows path to a Cygwin path. Just handles the basic case.""" if len(path) > 2 and path[1] == ":" and path[2] == "\\": newpath = cygwin_full_path_prefix + "/" + path[0] if len(path) > 3: newpath += "/" + path[3:] path = newpath ...
[ "def", "convert_windows_path_to_cygwin", "(", "path", ")", ":", "if", "len", "(", "path", ")", ">", "2", "and", "path", "[", "1", "]", "==", "\":\"", "and", "path", "[", "2", "]", "==", "\"\\\\\"", ":", "newpath", "=", "cygwin_full_path_prefix", "+", "...
45
12.25
def search_images(q, start=1, count=10, wait=10, asynchronous=False, cached=False): """ Returns a Yahoo images query formatted as a YahooSearch list object. """ service = YAHOO_IMAGES return YahooSearch(q, start, count, service, None, wait, asynchronous, cached)
[ "def", "search_images", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_IMAGES", "return", "YahooSearch", "(", "q", ",...
40.285714
24.428571
def transform(self, attrs): """Perform all actions on a given attribute dict.""" self.collect(attrs) self.add_missing_implementations() self.fill_attrs(attrs)
[ "def", "transform", "(", "self", ",", "attrs", ")", ":", "self", ".", "collect", "(", "attrs", ")", "self", ".", "add_missing_implementations", "(", ")", "self", ".", "fill_attrs", "(", "attrs", ")" ]
37.2
7.6
def update_org(cls, module): """ Adds the `users` field to the organization model """ try: cls.module_registry[module]["OrgModel"]._meta.get_field("users") except FieldDoesNotExist: cls.module_registry[module]["OrgModel"].add_to_class( "use...
[ "def", "update_org", "(", "cls", ",", "module", ")", ":", "try", ":", "cls", ".", "module_registry", "[", "module", "]", "[", "\"OrgModel\"", "]", ".", "_meta", ".", "get_field", "(", "\"users\"", ")", "except", "FieldDoesNotExist", ":", "cls", ".", "mod...
33.761905
21
def is_population_germline(rec): """Identify a germline calls based on annoations with ExAC or other population databases. """ min_count = 50 for k in population_keys: if k in rec.info: val = rec.info.get(k) if "," in val: val = val.split(",")[0] ...
[ "def", "is_population_germline", "(", "rec", ")", ":", "min_count", "=", "50", "for", "k", "in", "population_keys", ":", "if", "k", "in", "rec", ".", "info", ":", "val", "=", "rec", ".", "info", ".", "get", "(", "k", ")", "if", "\",\"", "in", "val"...
32.642857
9.642857
def require_app(app_name, api_style=False): """ Request the application to be automatically loaded. If this is used for "api" style modules, which is imported by a client application, set api_style=True. If this is used for client application module, set api_style=False. """ iterable = (in...
[ "def", "require_app", "(", "app_name", ",", "api_style", "=", "False", ")", ":", "iterable", "=", "(", "inspect", ".", "getmodule", "(", "frame", "[", "0", "]", ")", "for", "frame", "in", "inspect", ".", "stack", "(", ")", ")", "modules", "=", "[", ...
38.722222
20.166667
def combinePlinkBinaryFiles(prefixes, outPrefix): """Combine Plink binary files. :param prefixes: a list of the prefix of the files that need to be combined. :param outPrefix: the prefix of the output file (the combined file). :type prefixes: list :type outPrefix: str It ...
[ "def", "combinePlinkBinaryFiles", "(", "prefixes", ",", "outPrefix", ")", ":", "# The first file is the bfile, the others are the ones to merge", "outputFile", "=", "None", "try", ":", "outputFile", "=", "open", "(", "outPrefix", "+", "\".files_to_merge\"", ",", "\"w\"", ...
32.416667
23.222222
def watch_async(self, limit=None, timeout=None): """Non-block method to watch the clipboard changing.""" return self.watch(limit=limit, timeout=timeout)
[ "def", "watch_async", "(", "self", ",", "limit", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "watch", "(", "limit", "=", "limit", ",", "timeout", "=", "timeout", ")" ]
55.333333
7.666667
def tag2id(self, xs): """Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s) """ if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for...
[ "def", "tag2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_tag2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self", ...
22.5
18.4375
def object(self, o_type, o_name=None): """Get a monitored object from the arbiter. Indeed, the arbiter requires the object from its schedulers. It will iterate in its schedulers list until a matching object is found. Else it will return a Json structure containing _status and _message p...
[ "def", "object", "(", "self", ",", "o_type", ",", "o_name", "=", "None", ")", ":", "for", "scheduler_link", "in", "self", ".", "app", ".", "conf", ".", "schedulers", ":", "sched_res", "=", "scheduler_link", ".", "con", ".", "get", "(", "'object'", ",",...
40.805556
19.222222
def find_point_bin(self, chi_coords): """ Given a set of coordinates in the chi parameter space, identify the indices of the chi1 and chi2 bins that the point occurs in. Returns these indices. Parameters ----------- chi_coords : numpy.array The positi...
[ "def", "find_point_bin", "(", "self", ",", "chi_coords", ")", ":", "# Identify bin", "chi1_bin", "=", "int", "(", "(", "chi_coords", "[", "0", "]", "-", "self", ".", "chi1_min", ")", "//", "self", ".", "bin_spacing", ")", "chi2_bin", "=", "int", "(", "...
33.173913
19.347826
def _colorize(output): """ Return `output` colorized with Pygments, if available. """ if not pygments: return output # Available styles # ['monokai', 'manni', 'rrt', 'perldoc', 'borland', 'colorful', 'default', # 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs', ...
[ "def", "_colorize", "(", "output", ")", ":", "if", "not", "pygments", ":", "return", "output", "# Available styles", "# ['monokai', 'manni', 'rrt', 'perldoc', 'borland', 'colorful', 'default',", "# 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs',", "# 'vim', 'pastie'...
35.785714
17.357143
def get_command(self, name): """ Gets a single command by its unique name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Command """ name = adapt_name_for_rest(name) url = '/mdb...
[ "def", "get_command", "(", "self", ",", "name", ")", ":", "name", "=", "adapt_name_for_rest", "(", "name", ")", "url", "=", "'/mdb/{}/commands{}'", ".", "format", "(", "self", ".", "_instance", ",", "name", ")", "response", "=", "self", ".", "_client", "...
37.142857
12.428571
def _b64_to_bstr(b64str): """Deserialize base64 encoded string into string. :param str b64str: response string to be deserialized. :rtype: bytearray :raises: TypeError if string format invalid. """ padding = '=' * (3 - (len(b64str) + 3) % 4) b64str = b64str + padding encoded = b64str.rep...
[ "def", "_b64_to_bstr", "(", "b64str", ")", ":", "padding", "=", "'='", "*", "(", "3", "-", "(", "len", "(", "b64str", ")", "+", "3", ")", "%", "4", ")", "b64str", "=", "b64str", "+", "padding", "encoded", "=", "b64str", ".", "replace", "(", "'-'"...
37.3
10.5
def allocate_sync_ensembles(dynamic, tolerance = 0.1, threshold = 1.0, ignore = None): """! @brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster. @param[in] dynamic (dynamic): Dynamic of each oscillato...
[ "def", "allocate_sync_ensembles", "(", "dynamic", ",", "tolerance", "=", "0.1", ",", "threshold", "=", "1.0", ",", "ignore", "=", "None", ")", ":", "descriptors", "=", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "dynamic", "[", "0", "]...
42.489362
24.414894
def from_point_record(cls, other_point_record, new_point_format): """ Construct a new PackedPointRecord from an existing one with the ability to change to point format while doing so """ array = np.zeros_like(other_point_record.array, dtype=new_point_format.dtype) new_record = c...
[ "def", "from_point_record", "(", "cls", ",", "other_point_record", ",", "new_point_format", ")", ":", "array", "=", "np", ".", "zeros_like", "(", "other_point_record", ".", "array", ",", "dtype", "=", "new_point_format", ".", "dtype", ")", "new_record", "=", "...
52.75
13.875
def export_agent(self, parent, agent_uri=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Exports the specified agent to a ZIP...
[ "def", "export_agent", "(", "self", ",", "parent", ",", "agent_uri", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method"...
42.858974
21.474359
def parse_docstring(self, content): """ Parse the given full docstring, and extract method description, arguments, and return documentation. This method try to find arguments description and types, and put the information in "args_doc" and "signature" members. Also parse return type and...
[ "def", "parse_docstring", "(", "self", ",", "content", ")", ":", "if", "not", "content", ":", "return", "raw_docstring", "=", "''", "# We use the helper defined in django admindocs app to remove indentation chars from docstring,", "# and parse it as title, body, metadata. We don't ...
36.279412
21.955882
def values(self): """Gets the user enter max and min values of where the raster points should appear on the y-axis :returns: (float, float) -- (min, max) y-values to bound the raster plot by """ lower = float(self.lowerSpnbx.value()) upper = float(self.upperSpnbx.value(...
[ "def", "values", "(", "self", ")", ":", "lower", "=", "float", "(", "self", ".", "lowerSpnbx", ".", "value", "(", ")", ")", "upper", "=", "float", "(", "self", ".", "upperSpnbx", ".", "value", "(", ")", ")", "return", "(", "lower", ",", "upper", ...
38.222222
15.333333
def _unpack(c, tmp, package, version, git_url=None): """ Download + unpack given package into temp dir ``tmp``. Return ``(real_version, source)`` where ``real_version`` is the "actual" version downloaded (e.g. if a Git master was indicated, it will be the SHA of master HEAD) and ``source`` is the s...
[ "def", "_unpack", "(", "c", ",", "tmp", ",", "package", ",", "version", ",", "git_url", "=", "None", ")", ":", "real_version", "=", "version", "[", ":", "]", "source", "=", "None", "if", "git_url", ":", "pass", "# git clone into tempdir", "# git checko...
37.791667
17.083333
def draw_best_fit(X, y, ax, estimator='linear', **kwargs): """ Uses Scikit-Learn to fit a model to X and y then uses the resulting model to predict the curve based on the X values. This curve is drawn to the ax (matplotlib axis) which must be passed as the third variable. The estimator function can...
[ "def", "draw_best_fit", "(", "X", ",", "y", ",", "ax", ",", "estimator", "=", "'linear'", ",", "*", "*", "kwargs", ")", ":", "# Estimators are the types of best fit lines that can be drawn.", "estimators", "=", "{", "LINEAR", ":", "fit_linear", ",", "# Uses OLS to...
35.752294
22.908257
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b...
[ "def", "silhouette_score", "(", "X", ",", "labels", ",", "metric", "=", "'euclidean'", ",", "sample_size", "=", "None", ",", "random_state", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "sample_size", "is", "not", "None", ":", "X", ",", "labels"...
45.25
26.4875
def run_autoapi(app): """ Load AutoAPI data from the filesystem. """ if not app.config.autoapi_dirs: raise ExtensionError("You must configure an autoapi_dirs setting") # Make sure the paths are full normalized_dirs = [] autoapi_dirs = app.config.autoapi_dirs if isinstance(autoa...
[ "def", "run_autoapi", "(", "app", ")", ":", "if", "not", "app", ".", "config", ".", "autoapi_dirs", ":", "raise", "ExtensionError", "(", "\"You must configure an autoapi_dirs setting\"", ")", "# Make sure the paths are full", "normalized_dirs", "=", "[", "]", "autoapi...
34.492537
20.641791
def patchURL(self, url, headers, body): """ Request a URL using the HTTP method PATCH. """ return self._load_resource("PATCH", url, headers, body)
[ "def", "patchURL", "(", "self", ",", "url", ",", "headers", ",", "body", ")", ":", "return", "self", ".", "_load_resource", "(", "\"PATCH\"", ",", "url", ",", "headers", ",", "body", ")" ]
34.8
6.8
def setData(self, index, value, role=Qt.EditRole): """ Reimplements the :meth:`QAbstractItemModel.setData` method. :param index: Index. :type index: QModelIndex :param value: Value. :type value: QVariant :param role: Role. :type role: int :return:...
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "False", "node", "=", "self", ".", "get_node", "(", "index", ")", "if", "...
30.972222
16.527778
def generate_words(files): """ Transform list of files to list of words, removing new line character and replace name entity '<NE>...</NE>' and abbreviation '<AB>...</AB>' symbol """ repls = {'<NE>' : '','</NE>' : '','<AB>': '','</AB>': ''} words_all = [] for i, file in enumerate(files...
[ "def", "generate_words", "(", "files", ")", ":", "repls", "=", "{", "'<NE>'", ":", "''", ",", "'</NE>'", ":", "''", ",", "'<AB>'", ":", "''", ",", "'</AB>'", ":", "''", "}", "words_all", "=", "[", "]", "for", "i", ",", "file", "in", "enumerate", ...
33.764706
18.470588
def check_venv(self): """ Ensure we're inside a virtualenv. """ if self.zappa: venv = self.zappa.get_current_venv() else: # Just for `init`, when we don't have settings yet. venv = Zappa.get_current_venv() if not venv: raise ClickException(...
[ "def", "check_venv", "(", "self", ")", ":", "if", "self", ".", "zappa", ":", "venv", "=", "self", ".", "zappa", ".", "get_current_venv", "(", ")", "else", ":", "# Just for `init`, when we don't have settings yet.", "venv", "=", "Zappa", ".", "get_current_venv", ...
55.545455
31.272727
def clearScreen(cls): """Clear the screen""" if "win32" in sys.platform: os.system('cls') elif "linux" in sys.platform: os.system('clear') elif 'darwin' in sys.platform: os.system('clear') else: cit.err("No clearScreen for " + sys.p...
[ "def", "clearScreen", "(", "cls", ")", ":", "if", "\"win32\"", "in", "sys", ".", "platform", ":", "os", ".", "system", "(", "'cls'", ")", "elif", "\"linux\"", "in", "sys", ".", "platform", ":", "os", ".", "system", "(", "'clear'", ")", "elif", "'darw...
31.9
10.5
def clone_scope(self, source_scope, name=None, status=None, start_date=None, due_date=None, description=None, tags=None, team=None, asynchronous=False): """ Clone a Scope. This will clone a scope if the client has the right to do so. Sufficient permissions to clone a scope a...
[ "def", "clone_scope", "(", "self", ",", "source_scope", ",", "name", "=", "None", ",", "status", "=", "None", ",", "start_date", "=", "None", ",", "due_date", "=", "None", ",", "description", "=", "None", ",", "tags", "=", "None", ",", "team", "=", "...
50.672727
27.218182
def weight_from_comm(self, v, comm): """ The total number of edges (or sum of weights) to node ``v`` from community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_to_comm` """ return _c_leiden._MutableVertexPartition_weight_from_comm(self._partition, v, co...
[ "def", "weight_from_comm", "(", "self", ",", "v", ",", "comm", ")", ":", "return", "_c_leiden", ".", "_MutableVertexPartition_weight_from_comm", "(", "self", ".", "_partition", ",", "v", ",", "comm", ")" ]
35
21.111111
def is_permitted(self, permission_s): """ :param permission_s: a collection of 1..N permissions :type permission_s: List of authz_abcs.Permission object(s) or String(s) :returns: a List of tuple(s), containing the authz_abcs.Permission and a Boolean indicating whether ...
[ "def", "is_permitted", "(", "self", ",", "permission_s", ")", ":", "if", "self", ".", "authorized", ":", "self", ".", "check_security_manager", "(", ")", "return", "(", "self", ".", "security_manager", ".", "is_permitted", "(", "self", ".", "identifiers", ",...
42.6
20.733333
def audit_1_1(self): """1.1 Avoid the use of the "root" account (Scored)""" for row in self.credential_report: if row["user"] == "<root_account>": for field in "password_last_used", "access_key_1_last_used_date", "access_key_2_last_used_date": if row[field...
[ "def", "audit_1_1", "(", "self", ")", ":", "for", "row", "in", "self", ".", "credential_report", ":", "if", "row", "[", "\"user\"", "]", "==", "\"<root_account>\"", ":", "for", "field", "in", "\"password_last_used\"", ",", "\"access_key_1_last_used_date\"", ",",...
72.285714
34.857143
def get_open_spaces(board): """Given a representation of the board, returns a list of open spaces.""" open_spaces = [] for i in range(3): for j in range(3): if board[i][j] == 0: open_spaces.append(encode_pos(i, j)) return open_spaces
[ "def", "get_open_spaces", "(", "board", ")", ":", "open_spaces", "=", "[", "]", "for", "i", "in", "range", "(", "3", ")", ":", "for", "j", "in", "range", "(", "3", ")", ":", "if", "board", "[", "i", "]", "[", "j", "]", "==", "0", ":", "open_s...
31.5
13.875
def find_minimum_spanning_tree_as_subgraph(graph): """Calculates a minimum spanning tree and returns a graph representation.""" edge_list = find_minimum_spanning_tree(graph) subgraph = get_subgraph_from_edge_list(graph, edge_list) return subgraph
[ "def", "find_minimum_spanning_tree_as_subgraph", "(", "graph", ")", ":", "edge_list", "=", "find_minimum_spanning_tree", "(", "graph", ")", "subgraph", "=", "get_subgraph_from_edge_list", "(", "graph", ",", "edge_list", ")", "return", "subgraph" ]
43
16.666667
def get_recently_played_games(self, steamID, count=0, format=None): """Request a list of recently played games by a given steam id. steamID: The users ID count: Number of games to return. (0 is all recent games.) format: Return format. None defaults to json. (json, xml, vdf) ""...
[ "def", "get_recently_played_games", "(", "self", ",", "steamID", ",", "count", "=", "0", ",", "format", "=", "None", ")", ":", "parameters", "=", "{", "'steamid'", ":", "steamID", ",", "'count'", ":", "count", "}", "if", "format", "is", "not", "None", ...
42.8
18.4
def get_parameter_definitions(self): """Get the parameter definitions to submit to CloudFormation. Any variable definition whose `type` is an instance of `CFNType` will be returned as a CloudFormation Parameter. Returns: dict: parameter definitions. Keys are parameter names...
[ "def", "get_parameter_definitions", "(", "self", ")", ":", "output", "=", "{", "}", "for", "var_name", ",", "attrs", "in", "self", ".", "defined_variables", "(", ")", ".", "items", "(", ")", ":", "var_type", "=", "attrs", ".", "get", "(", "\"type\"", "...
38.6
18.7
def remove(self, label): """Remove a label. Args: label (gkeepapi.node.Label): The Label object. """ if label.id in self._labels: self._labels[label.id] = None self._dirty = True
[ "def", "remove", "(", "self", ",", "label", ")", ":", "if", "label", ".", "id", "in", "self", ".", "_labels", ":", "self", ".", "_labels", "[", "label", ".", "id", "]", "=", "None", "self", ".", "_dirty", "=", "True" ]
26.111111
13.333333
def age(self, year, month=2, day=1): """Returns the age of the player on a given date. :year: int representing the year. :month: int representing the month (1-12). :day: int representing the day within the month (1-31). :returns: Age in years as a float. """ doc ...
[ "def", "age", "(", "self", ",", "year", ",", "month", "=", "2", ",", "day", "=", "1", ")", ":", "doc", "=", "self", ".", "get_main_doc", "(", ")", "date_string", "=", "doc", "(", "'span[itemprop=\"birthDate\"]'", ")", ".", "attr", "(", "'data-birth'", ...
42.058824
12.764706
def help(rest): """Help (this command)""" rs = rest.strip() if rs: # give help for matching commands for handler in Handler._registry: if handler.name == rs.lower(): yield '!%s: %s' % (handler.name, handler.doc) break else: yield "command not found" return # give help for all commands def mk...
[ "def", "help", "(", "rest", ")", ":", "rs", "=", "rest", ".", "strip", "(", ")", "if", "rs", ":", "# give help for matching commands", "for", "handler", "in", "Handler", ".", "_registry", ":", "if", "handler", ".", "name", "==", "rs", ".", "lower", "("...
24.212121
19.121212
def schema_key_for(self, seq_no: int) -> SchemaKey: """ Get schema key for schema by sequence number if known, None for no such schema in cache. :param seq_no: sequence number :return: corresponding schema key or None """ LOGGER.debug('SchemaCache.schema_key_for >>> seq...
[ "def", "schema_key_for", "(", "self", ",", "seq_no", ":", "int", ")", "->", "SchemaKey", ":", "LOGGER", ".", "debug", "(", "'SchemaCache.schema_key_for >>> seq_no: %s'", ",", "seq_no", ")", "rv", "=", "self", ".", "_seq_no2schema_key", ".", "get", "(", "seq_no...
32.928571
23.5
def resolve(self, dispatcher, node): """ For the given node, resolve it into the scope it was declared at, and if one was found, return its value. """ scope = self.identifiers.get(node) if not scope: return node.value return scope.resolve(node.value)
[ "def", "resolve", "(", "self", ",", "dispatcher", ",", "node", ")", ":", "scope", "=", "self", ".", "identifiers", ".", "get", "(", "node", ")", "if", "not", "scope", ":", "return", "node", ".", "value", "return", "scope", ".", "resolve", "(", "node"...
31
11.6
def __remove_dashboard_menu(self, kibiter_major): """Remove existing menu for dashboard, if any. Usually, we remove the menu before creating a new one. :param kibiter_major: major version of kibiter """ logger.info("Removing old dashboard menu, if any") if kibiter_major...
[ "def", "__remove_dashboard_menu", "(", "self", ",", "kibiter_major", ")", ":", "logger", ".", "info", "(", "\"Removing old dashboard menu, if any\"", ")", "if", "kibiter_major", "==", "\"6\"", ":", "metadashboard", "=", "\".kibana/doc/metadashboard\"", "else", ":", "m...
40.142857
17.642857
def _check_generic_pos(self, *tokens): """Check if the different tokens were logged in one record, any level.""" for record in self.records: if all(token in record.message for token in tokens): return # didn't exit, all tokens are not present in the same record ...
[ "def", "_check_generic_pos", "(", "self", ",", "*", "tokens", ")", ":", "for", "record", "in", "self", ".", "records", ":", "if", "all", "(", "token", "in", "record", ".", "message", "for", "token", "in", "tokens", ")", ":", "return", "# didn't exit, all...
49.818182
18.818182
def _xfer_file(self, source_file=None, source_config=None, dest_file=None, file_system=None, TransferClass=FileTransfer): """Transfer file to remote device. By default, this will use Secure Copy if self.inline_transfer is set, then will use Netmiko InlineTransfer method to tr...
[ "def", "_xfer_file", "(", "self", ",", "source_file", "=", "None", ",", "source_config", "=", "None", ",", "dest_file", "=", "None", ",", "file_system", "=", "None", ",", "TransferClass", "=", "FileTransfer", ")", ":", "if", "not", "source_file", "and", "n...
41.98
22.08
def wait(self): """Waits and returns received messages. If running in compatibility mode for older uWSGI versions, it also sends messages that have been queued by send(). A return value of None means that connection was closed. This must be called repeatedly. For uWSGI < 2.1.x it...
[ "def", "wait", "(", "self", ")", ":", "while", "True", ":", "if", "self", ".", "_req_ctx", "is", "not", "None", ":", "try", ":", "msg", "=", "uwsgi", ".", "websocket_recv", "(", "request_context", "=", "self", ".", "_req_ctx", ")", "except", "IOError",...
44.526316
14.026316
def privatekey_to_publickey(private_key_bin: bytes) -> bytes: """ Returns public key in bitcoins 'bin' encoding. """ if not ishash(private_key_bin): raise ValueError('private_key_bin format mismatch. maybe hex encoded?') return keys.PrivateKey(private_key_bin).public_key.to_bytes()
[ "def", "privatekey_to_publickey", "(", "private_key_bin", ":", "bytes", ")", "->", "bytes", ":", "if", "not", "ishash", "(", "private_key_bin", ")", ":", "raise", "ValueError", "(", "'private_key_bin format mismatch. maybe hex encoded?'", ")", "return", "keys", ".", ...
59.6
18
def source(source_id=None, **kwargs): """Get a source of economic data.""" if source_id is not None: kwargs['source_id'] = source_id elif 'id' in kwargs: source_id = kwargs.pop('id') kwargs['source_id'] = source_id if 'releases' in kwargs: kwargs.pop('releases') p...
[ "def", "source", "(", "source_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source_id", "is", "not", "None", ":", "kwargs", "[", "'source_id'", "]", "=", "source_id", "elif", "'id'", "in", "kwargs", ":", "source_id", "=", "kwargs", ".", ...
30.384615
9.615385
def push_external_commands_to_schedulers(self): # pragma: no cover - not used! """Send external commands to schedulers :return: None """ # Now get all external commands and push them to the schedulers for external_command in self.external_commands: self.external_com...
[ "def", "push_external_commands_to_schedulers", "(", "self", ")", ":", "# pragma: no cover - not used!", "# Now get all external commands and push them to the schedulers", "for", "external_command", "in", "self", ".", "external_commands", ":", "self", ".", "external_commands_manager...
47.136364
21.590909
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_video_note( # receiver, self.media, disable_notific...
[ "def", "send", "(", "self", ",", "sender", ":", "PytgbotApiBot", ")", ":", "return", "sender", ".", "send_video_note", "(", "# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id", "video_note", "=", "self", ".", "video_note", ...
47.538462
31.538462
def addGene( self, gene_id, gene_label, gene_type=None, gene_description=None ): ''' genes are classes ''' if gene_type is None: gene_type = self.globaltt['gene'] self.model.addClassToGraph(gene_id, gene_label, gene_type, gene_description) return
[ "def", "addGene", "(", "self", ",", "gene_id", ",", "gene_label", ",", "gene_type", "=", "None", ",", "gene_description", "=", "None", ")", ":", "if", "gene_type", "is", "None", ":", "gene_type", "=", "self", ".", "globaltt", "[", "'gene'", "]", "self", ...
33.222222
25.666667
def search(signal='', action='', signals=SIGNALS): """ Search the signals DB for signal named *signal*, and which action matches *action* in a case insensitive way. :param signal: Regex for signal name. :param action: Regex for default action. :param signals: Database of signals. """ ...
[ "def", "search", "(", "signal", "=", "''", ",", "action", "=", "''", ",", "signals", "=", "SIGNALS", ")", ":", "sig_re", "=", "re", ".", "compile", "(", "signal", ",", "re", ".", "IGNORECASE", ")", "act_re", "=", "re", ".", "compile", "(", "action"...
32.777778
11.444444
def title(self, value): """ Setter for **self.__title** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "title", v...
[ "def", "title", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"title\"", ",", "value", ")", ...
28.583333
17.25
def _write_new_tag_to_init(self): """ Write version to __init__.py by editing in place """ for line in fileinput.input(self.init_file, inplace=1): if line.strip().startswith("__version__"): line = "__version__ = \"" + self.tag + "\"" print(line.str...
[ "def", "_write_new_tag_to_init", "(", "self", ")", ":", "for", "line", "in", "fileinput", ".", "input", "(", "self", ".", "init_file", ",", "inplace", "=", "1", ")", ":", "if", "line", ".", "strip", "(", ")", ".", "startswith", "(", "\"__version__\"", ...
40.25
10.5
def shutdown(self): """Disconnect all connections and end the loop :returns: None :rtype: None :raises: None """ log.debug('Shutting down %s' % self) self.disconnect_all() self._looping.clear()
[ "def", "shutdown", "(", "self", ")", ":", "log", ".", "debug", "(", "'Shutting down %s'", "%", "self", ")", "self", ".", "disconnect_all", "(", ")", "self", ".", "_looping", ".", "clear", "(", ")" ]
24.9
14.4
def cli(ctx, **kwargs): """ A powerful spider system in python. """ if kwargs['add_sys_path']: sys.path.append(os.getcwd()) logging.config.fileConfig(kwargs['logging_config']) # get db from env for db in ('taskdb', 'projectdb', 'resultdb'): if kwargs[db] is not None: ...
[ "def", "cli", "(", "ctx", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'add_sys_path'", "]", ":", "sys", ".", "path", ".", "append", "(", "os", ".", "getcwd", "(", ")", ")", "logging", ".", "config", ".", "fileConfig", "(", "kwargs", ...
42.506024
20.554217
def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False, password=False): """Ask a question and get the input values. This method will validade the input values. Args: field_name(string): Field name used to ask for input value. pat...
[ "def", "ask_question", "(", "self", ",", "field_name", ",", "pattern", "=", "NAME_PATTERN", ",", "is_required", "=", "False", ",", "password", "=", "False", ")", ":", "input_value", "=", "\"\"", "question", "=", "(", "\"Insert the field using the pattern below:\""...
38.944444
22.833333
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
[ "def", "copyFile", "(", "input", ",", "output", ",", "replace", "=", "None", ")", ":", "_found", "=", "findFile", "(", "output", ")", "if", "not", "_found", "or", "(", "_found", "and", "replace", ")", ":", "shutil", ".", "copy2", "(", "input", ",", ...
32.833333
10