text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def merge(self, other, merge_body=True): """ Default merge method. Args: other: another MujocoXML instance raises XML error if @other is not a MujocoXML instance. merges <worldbody/>, <actuator/> and <asset/> of @other into @self merge_bod...
[ "def", "merge", "(", "self", ",", "other", ",", "merge_body", "=", "True", ")", ":", "if", "not", "isinstance", "(", "other", ",", "MujocoXML", ")", ":", "raise", "XMLError", "(", "\"{} is not a MujocoXML instance.\"", ".", "format", "(", "type", "(", "oth...
41.333333
12.5
def _subspan(self, s, span, nextspan): """Recursively subdivide spans based on a series of rules.""" text = s[span[0]:span[1]] lowertext = text.lower() # Skip if only a single character or a split sequence if span[1] - span[0] < 2 or text in self.SPLIT or text in self.SPLIT_END_...
[ "def", "_subspan", "(", "self", ",", "s", ",", "span", ",", "nextspan", ")", ":", "text", "=", "s", "[", "span", "[", "0", "]", ":", "span", "[", "1", "]", "]", "lowertext", "=", "text", ".", "lower", "(", ")", "# Skip if only a single character or a...
47.177419
24.16129
def CHOLESKY(A, B, method='scipy'): """Solve linear system `AX=B` using CHOLESKY method. :param A: an input Hermitian matrix :param B: an array :param str method: a choice of method in [numpy, scipy, numpy_solver] * `numpy_solver` relies entirely on numpy.solver (no cholesky decomposition) ...
[ "def", "CHOLESKY", "(", "A", ",", "B", ",", "method", "=", "'scipy'", ")", ":", "if", "method", "==", "'numpy_solver'", ":", "X", "=", "_numpy_solver", "(", "A", ",", "B", ")", "return", "X", "elif", "method", "==", "'numpy'", ":", "X", ",", "_L", ...
33.315789
22.701754
def load(abspath, default=None, enable_verbose=True): """Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: defa...
[ "def", "load", "(", "abspath", ",", "default", "=", "None", ",", "enable_verbose", "=", "True", ")", ":", "if", "default", "is", "None", ":", "default", "=", "dict", "(", ")", "prt", "(", "\"\\nLoad from '%s' ...\"", "%", "abspath", ",", "enable_verbose", ...
29.236364
23.654545
def fix_grpc_import(): ''' Snippet to fix the gRPC import path ''' with open(GARUDA_GRPC_PATH, 'r') as f: filedata = f.read() filedata = filedata.replace( 'import garuda_pb2 as garuda__pb2', f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2') with open(GARUDA_GRPC_PATH, 'w'...
[ "def", "fix_grpc_import", "(", ")", ":", "with", "open", "(", "GARUDA_GRPC_PATH", ",", "'r'", ")", "as", "f", ":", "filedata", "=", "f", ".", "read", "(", ")", "filedata", "=", "filedata", ".", "replace", "(", "'import garuda_pb2 as garuda__pb2'", ",", "f'...
31.181818
13.181818
def move_tab(self, index_from, index_to): """Move tab.""" client = self.clients.pop(index_from) self.clients.insert(index_to, client)
[ "def", "move_tab", "(", "self", ",", "index_from", ",", "index_to", ")", ":", "client", "=", "self", ".", "clients", ".", "pop", "(", "index_from", ")", "self", ".", "clients", ".", "insert", "(", "index_to", ",", "client", ")" ]
39.25
3.25
def _send_ack(self, transaction): """ Sends an ACK message for the request. :param transaction: the transaction that owns the request """ ack = Message() ack.type = defines.Types['ACK'] # TODO handle mutex on transaction if not transaction.request.acknow...
[ "def", "_send_ack", "(", "self", ",", "transaction", ")", ":", "ack", "=", "Message", "(", ")", "ack", ".", "type", "=", "defines", ".", "Types", "[", "'ACK'", "]", "# TODO handle mutex on transaction", "if", "not", "transaction", ".", "request", ".", "ack...
37.769231
19.153846
def handle(self, *args, **options): """ Lists all the items in a container to stdout. """ self._connection = Auth()._get_connection() if len(args) == 0: containers = self._connection.list_containers() if not containers: print("No container...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "self", ".", "_connection", "=", "Auth", "(", ")", ".", "_get_connection", "(", ")", "if", "len", "(", "args", ")", "==", "0", ":", "containers", "=", "self", "."...
36.631579
18
def ancestors(self): """Returns list of ancestor task specs based on inputs""" results = [] def recursive_find_ancestors(task, stack): for input in task.inputs: if input not in stack: stack.append(input) recursive_find_ancestor...
[ "def", "ancestors", "(", "self", ")", ":", "results", "=", "[", "]", "def", "recursive_find_ancestors", "(", "task", ",", "stack", ")", ":", "for", "input", "in", "task", ".", "inputs", ":", "if", "input", "not", "in", "stack", ":", "stack", ".", "ap...
33
14.916667
def run_genesippr(self): """ Run GeneSippr on each of the samples """ from pathlib import Path home = str(Path.home()) logging.info('GeneSippr') # These unfortunate hard coded paths appear to be necessary miniconda_path = os.path.join(home, 'miniconda3') ...
[ "def", "run_genesippr", "(", "self", ")", ":", "from", "pathlib", "import", "Path", "home", "=", "str", "(", "Path", ".", "home", "(", ")", ")", "logging", ".", "info", "(", "'GeneSippr'", ")", "# These unfortunate hard coded paths appear to be necessary", "mini...
56.485714
24.428571
def save(self, f): """Save pickled model to file.""" return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)
[ "def", "save", "(", "self", ",", "f", ")", ":", "return", "pickle", ".", "dump", "(", "(", "self", ".", "perceptron", ".", "weights", ",", "self", ".", "tagdict", ",", "self", ".", "classes", ",", "self", ".", "clusters", ")", ",", "f", ",", "pro...
64
38.333333
def make_bands(self, ax): """Draw shaded horizontal bands for each plotter.""" y_vals, y_prev, is_zero = [0], None, False prev_color_index = 0 for plotter in self.plotters.values(): for y, *_, color in plotter.iterator(): if self.colors.index(color) < prev_col...
[ "def", "make_bands", "(", "self", ",", "ax", ")", ":", "y_vals", ",", "y_prev", ",", "is_zero", "=", "[", "0", "]", ",", "None", ",", "False", "prev_color_index", "=", "0", "for", "plotter", "in", "self", ".", "plotters", ".", "values", "(", ")", "...
42.428571
17.857143
def get(self, floating_ip_id): """Fetches the floating IP. :returns: FloatingIp object corresponding to floating_ip_id """ fip = self.client.show_floatingip(floating_ip_id).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip)
[ "def", "get", "(", "self", ",", "floating_ip_id", ")", ":", "fip", "=", "self", ".", "client", ".", "show_floatingip", "(", "floating_ip_id", ")", ".", "get", "(", "'floatingip'", ")", "self", ".", "_set_instance_info", "(", "fip", ")", "return", "Floating...
35.5
15.75
def env_string(name, required=False, default=empty): """Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: ...
[ "def", "env_string", "(", "name", ",", "required", "=", "False", ",", "default", "=", "empty", ")", ":", "value", "=", "get_env_value", "(", "name", ",", "default", "=", "default", ",", "required", "=", "required", ")", "if", "value", "is", "empty", ":...
38.52381
23.857143
def prefetch(self, bucket, key): """镜像回源预取文件: 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源,具体规格参考 http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html Args: bucket: 待获取资源所在的空间 key: 代获取资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg...
[ "def", "prefetch", "(", "self", ",", "bucket", ",", "key", ")", ":", "resource", "=", "entry", "(", "bucket", ",", "key", ")", "return", "self", ".", "__io_do", "(", "bucket", ",", "'prefetch'", ",", "resource", ")" ]
28.25
18.3125
def tune(runner, kernel_options, device_options, tuning_options): """ Tune a random sample of sample_fraction fraction in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :t...
[ "def", "tune", "(", "runner", ",", "kernel_options", ",", "device_options", ",", "tuning_options", ")", ":", "tune_params", "=", "tuning_options", ".", "tune_params", "#compute cartesian product of all tunable parameters", "parameter_space", "=", "itertools", ".", "produc...
42.808511
26.553191
def parse_atom_site(self, name, attributes): '''Parse the atom tag attributes. Most atom tags do not have attributes.''' if name == "PDBx:pdbx_PDB_ins_code": assert(not(self.current_atom_site.ATOMResidueiCodeIsNull)) if attributes.get('xsi:nil') == 'true': self.cu...
[ "def", "parse_atom_site", "(", "self", ",", "name", ",", "attributes", ")", ":", "if", "name", "==", "\"PDBx:pdbx_PDB_ins_code\"", ":", "assert", "(", "not", "(", "self", ".", "current_atom_site", ".", "ATOMResidueiCodeIsNull", ")", ")", "if", "attributes", "....
57.6
17.8
def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): """Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given. """ return _generat...
[ "def", "generate_anchors", "(", "stride", "=", "16", ",", "sizes", "=", "(", "32", ",", "64", ",", "128", ",", "256", ",", "512", ")", ",", "aspect_ratios", "=", "(", "0.5", ",", "1", ",", "2", ")", ")", ":", "return", "_generate_anchors", "(", "...
36.666667
18
def characterize_psf(self): """ Get support size and drift polynomial for current set of params """ # there may be an issue with the support and characterization-- # it might be best to do the characterization with the same support # as the calculated psf. l,u = max(self.zrange[0...
[ "def", "characterize_psf", "(", "self", ")", ":", "# there may be an issue with the support and characterization--", "# it might be best to do the characterization with the same support", "# as the calculated psf.", "l", ",", "u", "=", "max", "(", "self", ".", "zrange", "[", "0...
51.35
27.7
def freeze(proto_dataset_uri): """Convert a proto dataset into a dataset. This step is carried out after all files have been added to the dataset. Freezing a dataset finalizes it with a stamp marking it as frozen. """ proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri, ...
[ "def", "freeze", "(", "proto_dataset_uri", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "proto_dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "num_items", "=", "len", "(", "list", "(", "proto_d...
35.851852
21.055556
def _exit_session(self): """ Exits session to Hetzner account and returns. """ api = self.api[self.account] response = self._get(api['exit']['GET']['url']) if not Provider._filter_dom(response.text, api['filter']): LOGGER.info('Hetzner => Exit session') ...
[ "def", "_exit_session", "(", "self", ")", ":", "api", "=", "self", ".", "api", "[", "self", ".", "account", "]", "response", "=", "self", ".", "_get", "(", "api", "[", "'exit'", "]", "[", "'GET'", "]", "[", "'url'", "]", ")", "if", "not", "Provid...
35.666667
14
def sample_dynamic_posterior(self, inputs, samples, static_sample=None): """Sample the static latent posterior. Args: inputs: A batch of intermediate representations of image frames across all timesteps, of shape [..., batch_size, timesteps, hidden_size]. samples: Number of samples ...
[ "def", "sample_dynamic_posterior", "(", "self", ",", "inputs", ",", "samples", ",", "static_sample", "=", "None", ")", ":", "if", "self", ".", "latent_posterior", "==", "\"factorized\"", ":", "dist", "=", "self", ".", "dynamic_encoder", "(", "inputs", ")", "...
43.5
22
def get_params(job_inis, **kw): """ Parse one or more INI-style config files. :param job_inis: List of configuration files (or list containing a single zip archive) :param kw: Optionally override some parameters :returns: A dictionary of parameters """ input_zip = No...
[ "def", "get_params", "(", "job_inis", ",", "*", "*", "kw", ")", ":", "input_zip", "=", "None", "if", "len", "(", "job_inis", ")", "==", "1", "and", "job_inis", "[", "0", "]", ".", "endswith", "(", "'.zip'", ")", ":", "input_zip", "=", "job_inis", "...
34.625
18.475
def set_group_name(group, old_name, new_name): """ Group was renamed. """ for datastore in _get_datastores(): datastore.set_group_name(group, old_name, new_name)
[ "def", "set_group_name", "(", "group", ",", "old_name", ",", "new_name", ")", ":", "for", "datastore", "in", "_get_datastores", "(", ")", ":", "datastore", ".", "set_group_name", "(", "group", ",", "old_name", ",", "new_name", ")" ]
43.5
6.5
def false_positives(links_true, links_pred): """Count the number of False Positives. Returns the number of incorrect predictions of true non-links. (true non- links, but predicted as links). This value is known as the number of False Positives (FP). Parameters ---------- links_true: pandas...
[ "def", "false_positives", "(", "links_true", ",", "links_pred", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "return", "len", "(", "links_pred", ".", "difference", "(", "lin...
27.8
22.84
def build_tree(self): """Bulids the tree with all the fields converted to Elements """ if self.built: return self.doc_root = self.root.element() for key in self.sorted_fields(): if key not in self._fields: continue field = self....
[ "def", "build_tree", "(", "self", ")", ":", "if", "self", ".", "built", ":", "return", "self", ".", "doc_root", "=", "self", ".", "root", ".", "element", "(", ")", "for", "key", "in", "self", ".", "sorted_fields", "(", ")", ":", "if", "key", "not",...
47.392157
14.196078
def process_request(self, request): """ Lazy set user and token """ request.token = get_token(request) request.user = SimpleLazyObject(lambda: get_user(request)) request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request)
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "request", ".", "token", "=", "get_token", "(", "request", ")", "request", ".", "user", "=", "SimpleLazyObject", "(", "lambda", ":", "get_user", "(", "request", ")", ")", "request", ".", "_...
39
11.285714
def resources_availability(self): """Return the percentage of availability for resources.""" # Flatten the list. availabilities = list( chain( *[org.check_availability() for org in self.organizations] ) ) # Filter out the unknown av...
[ "def", "resources_availability", "(", "self", ")", ":", "# Flatten the list.", "availabilities", "=", "list", "(", "chain", "(", "*", "[", "org", ".", "check_availability", "(", ")", "for", "org", "in", "self", ".", "organizations", "]", ")", ")", "# Filter ...
41.333333
20.133333
def get_logs(self): """Gets the log list resulting from a search. return: (osid.logging.LogList) - the log list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: raise errors.Ille...
[ "def", "get_logs", "(", "self", ")", ":", "if", "self", ".", "retrieved", ":", "raise", "errors", ".", "IllegalState", "(", "'List has already been retrieved.'", ")", "self", ".", "retrieved", "=", "True", "return", "objects", ".", "LogList", "(", "self", "....
37.666667
20
def parse_job_files(self): """Check for job definitions in known zuul files.""" repo_jobs = [] for rel_job_file_path, job_info in self.job_files.items(): LOGGER.debug("Checking for job definitions in %s", rel_job_file_path) jobs = self.parse_job_definitions(rel_job_file_p...
[ "def", "parse_job_files", "(", "self", ")", ":", "repo_jobs", "=", "[", "]", "for", "rel_job_file_path", ",", "job_info", "in", "self", ".", "job_files", ".", "items", "(", ")", ":", "LOGGER", ".", "debug", "(", "\"Checking for job definitions in %s\"", ",", ...
47.875
24
def _find_usage_instances(self): """find usage for DB Instances and related limits""" paginator = self.conn.get_paginator('describe_db_instances') for page in paginator.paginate(): for instance in page['DBInstances']: self.limits['Read replicas per master']._add_curre...
[ "def", "_find_usage_instances", "(", "self", ")", ":", "paginator", "=", "self", ".", "conn", ".", "get_paginator", "(", "'describe_db_instances'", ")", "for", "page", "in", "paginator", ".", "paginate", "(", ")", ":", "for", "instance", "in", "page", "[", ...
52.7
16.9
def from_body(self, param_name, schema): """ A decorator that converts the request body into a function parameter based on the specified schema. :param param_name: The parameter which receives the argument. :param schema: The schema class or instance used to deserialize the request body...
[ "def", "from_body", "(", "self", ",", "param_name", ",", "schema", ")", ":", "schema", "=", "schema", "(", ")", "if", "isclass", "(", "schema", ")", "else", "schema", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "fu...
38.166667
21.5
def update_after_verification(self, user): """ Updates a job's state after being verified by a sheriff """ if not self.is_fully_verified(): return classification = 'autoclassified intermittent' already_classified = (JobNote.objects.filter(job=self) ...
[ "def", "update_after_verification", "(", "self", ",", "user", ")", ":", "if", "not", "self", ".", "is_fully_verified", "(", ")", ":", "return", "classification", "=", "'autoclassified intermittent'", "already_classified", "=", "(", "JobNote", ".", "objects", ".", ...
37.222222
20.444444
def _merge_layout_objs(obj, subobj): """ Merge layout objects recursively Note: This function mutates the input obj dict, but it does not mutate the subobj dict Parameters ---------- obj: dict dict into which the sub-figure dict will be merged subobj: dict dict that sil...
[ "def", "_merge_layout_objs", "(", "obj", ",", "subobj", ")", ":", "for", "prop", ",", "val", "in", "subobj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", "and", "prop", "in", "obj", ":", "# recursion", "_merge_layout_o...
28.148148
16
def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided,...
[ "def", "create", "(", "cidr_block", ",", "instance_tenancy", "=", "None", ",", "vpc_name", "=", "None", ",", "enable_dns_support", "=", "None", ",", "enable_dns_hostnames", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=",...
35.904762
23.47619
def line_print(self): """ Return the message as a one-line string. :return: the string representing the message """ inv_types = {v: k for k, v in defines.Types.items()} if self._code is None: self._code = defines.Codes.EMPTY.number msg = "From {sour...
[ "def", "line_print", "(", "self", ")", ":", "inv_types", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "defines", ".", "Types", ".", "items", "(", ")", "}", "if", "self", ".", "_code", "is", "None", ":", "self", ".", "_code", "=", "defin...
40.038462
22.423077
def _add_metadata_element(self, md, subsection, mdtype, mode="mdwrap", **kwargs): """ :param md: Value to pass to the MDWrap/MDRef :param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS` :param str mdtype: Value for mdWrap/mdRef @MDTYPE :param ...
[ "def", "_add_metadata_element", "(", "self", ",", "md", ",", "subsection", ",", "mdtype", ",", "mode", "=", "\"mdwrap\"", ",", "*", "*", "kwargs", ")", ":", "# HELP how handle multiple amdSecs?", "# When adding *MD which amdSec to add to?", "if", "mode", ".", "lower...
44.575758
14.272727
def _handle_recv(self, msg): """callback for stream.on_recv unpacks message, and calls handlers with it. """ ident,smsg = self.session.feed_identities(msg) self.call_handlers(self.session.unserialize(smsg))
[ "def", "_handle_recv", "(", "self", ",", "msg", ")", ":", "ident", ",", "smsg", "=", "self", ".", "session", ".", "feed_identities", "(", "msg", ")", "self", ".", "call_handlers", "(", "self", ".", "session", ".", "unserialize", "(", "smsg", ")", ")" ]
35.571429
12.571429
def bpMagnitudeErrorEoM(G, vmini, nobs=70): """ Calculate the end-of-mission photometric standard error in the BP band as a function of G and (V-I). Note: this refers to the integrated flux from the BP spectrophotometer. A margin of 20% is included. Parameters ---------- G - Value(s) of G-band magnitu...
[ "def", "bpMagnitudeErrorEoM", "(", "G", ",", "vmini", ",", "nobs", "=", "70", ")", ":", "return", "sqrt", "(", "(", "power", "(", "bpMagnitudeError", "(", "G", ",", "vmini", ")", "/", "_scienceMargin", ",", "2", ")", "+", "_eomCalibrationFloorBP", "*", ...
28.521739
28.434783
def create_page(self, build_dir, filepath, context={}, content=None, template=None, markup=None, layout=None): """ To dynamically create a page and save it in the build_dir :param build_dir: (path) The base directory that will hold the created page :param filepath: (string) the name of t...
[ "def", "create_page", "(", "self", ",", "build_dir", ",", "filepath", ",", "context", "=", "{", "}", ",", "content", "=", "None", ",", "template", "=", "None", ",", "markup", "=", "None", ",", "layout", "=", "None", ")", ":", "build_dir", "=", "build...
50.864865
24.027027
def boolean(name=None): """ Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Boolean Field' # Basic field field = pp.Regex('[YN]') # Parse action fie...
[ "def", "boolean", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Boolean Field'", "# Basic field", "field", "=", "pp", ".", "Regex", "(", "'[YN]'", ")", "# Parse action", "field", ".", "setParseAction", "(", "lambda", ...
19.047619
22.285714
def verify_realms(self, token, realms, request): """Verify if the realms match the requested realms.""" log.debug('Verify realms %r', realms) tok = request.request_token or self._grantgetter(token=token) if not tok: return False request.request_token = tok if...
[ "def", "verify_realms", "(", "self", ",", "token", ",", "realms", ",", "request", ")", ":", "log", ".", "debug", "(", "'Verify realms %r'", ",", "realms", ")", "tok", "=", "request", ".", "request_token", "or", "self", ".", "_grantgetter", "(", "token", ...
36.666667
13
def _add_post_data(self, request: Request): '''Add data to the payload.''' if self._item_session.url_record.post_data: data = wpull.string.to_bytes(self._item_session.url_record.post_data) else: data = wpull.string.to_bytes( self._processor.fetch_params.po...
[ "def", "_add_post_data", "(", "self", ",", "request", ":", "Request", ")", ":", "if", "self", ".", "_item_session", ".", "url_record", ".", "post_data", ":", "data", "=", "wpull", ".", "string", ".", "to_bytes", "(", "self", ".", "_item_session", ".", "u...
35.8
19.9
def client_side(func): """ Decorator to designate an API method applicable only to client-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion. """ def inner(*args, **kwargs): if args and hasat...
[ "def", "client_side", "(", "func", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "hasattr", "(", "args", "[", "0", "]", ",", "'is_server'", ")", "and", "voltron", ".", "debugger", ":", "raise", ...
39.230769
22.923077
def bash_checker(code, working_directory): """Return checker.""" run = run_in_subprocess(code, '.bash', ['bash', '-n'], working_directory=working_directory) def run_check(): """Yield errors.""" result = run() if result: (output, filename) = re...
[ "def", "bash_checker", "(", "code", ",", "working_directory", ")", ":", "run", "=", "run_in_subprocess", "(", "code", ",", "'.bash'", ",", "[", "'bash'", ",", "'-n'", "]", ",", "working_directory", "=", "working_directory", ")", "def", "run_check", "(", ")",...
36.263158
11.736842
def get_member_profile(self, member_id): ''' a method to retrieve member profile details :param member_id: integer with member id from member profile :return: dictionary with member profile details inside [json] key profile_details = self.objects.profile.schema ''' ...
[ "def", "get_member_profile", "(", "self", ",", "member_id", ")", ":", "# https://www.meetup.com/meetup_api/docs/members/:member_id/#get\r", "title", "=", "'%s.get_member_profile'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs\r", "input_fields", "=", "...
33.658537
26.682927
def equipable_classes(self): """ Returns a list of classes that _can_ use the item. """ sitem = self._schema_item return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c]
[ "def", "equipable_classes", "(", "self", ")", ":", "sitem", "=", "self", ".", "_schema_item", "return", "[", "c", "for", "c", "in", "sitem", ".", "get", "(", "\"used_by_classes\"", ",", "self", ".", "equipped", ".", "keys", "(", ")", ")", "if", "c", ...
42
20.4
def load_colormap(self, name=None): """ Loads a colormap of the supplied name. None means used the internal name. (See self.get_name()) """ if name == None: name = self.get_name() if name == "" or not type(name)==str: return "Error: Bad name." # assemble the pat...
[ "def", "load_colormap", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "==", "None", ":", "name", "=", "self", ".", "get_name", "(", ")", "if", "name", "==", "\"\"", "or", "not", "type", "(", "name", ")", "==", "str", ":", "return...
28.575758
19.969697
def _propagate_glyph_anchors(self, ufo, parent, processed): """Propagate anchors for a single parent glyph.""" if parent.name in processed: return processed.add(parent.name) base_components = [] mark_components = [] anchor_names = set() to_add = {} for component in parent.compo...
[ "def", "_propagate_glyph_anchors", "(", "self", ",", "ufo", ",", "parent", ",", "processed", ")", ":", "if", "parent", ".", "name", "in", "processed", ":", "return", "processed", ".", "add", "(", "parent", ".", "name", ")", "base_components", "=", "[", "...
37.926829
20.853659
def create_transcripts_xml(video_id, video_el, resource_fs, static_dir): """ Creates xml for transcripts. For each transcript element, an associated transcript file is also created in course OLX. Arguments: video_id (str): Video id of the video. video_el (Element): lxml Element object ...
[ "def", "create_transcripts_xml", "(", "video_id", ",", "video_el", ",", "resource_fs", ",", "static_dir", ")", ":", "video_transcripts", "=", "VideoTranscript", ".", "objects", ".", "filter", "(", "video__edx_video_id", "=", "video_id", ")", ".", "order_by", "(", ...
40.897959
24.040816
def create_config_tree(config, modules, prefix=''): '''Cause every possible configuration sub-dictionary to exist. This is intended to be called very early in the configuration sequence. For each module, it checks that the corresponding configuration item exists in `config` and creates it as an empty ...
[ "def", "create_config_tree", "(", "config", ",", "modules", ",", "prefix", "=", "''", ")", ":", "def", "work_in", "(", "parent_config", ",", "config_name", ",", "prefix", ",", "module", ")", ":", "if", "config_name", "not", "in", "parent_config", ":", "# t...
43.5
22.566667
def get_single_key(d): """Get a key from a dict which contains just one item.""" assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.iterkeys(d))
[ "def", "get_single_key", "(", "d", ")", ":", "assert", "len", "(", "d", ")", "==", "1", ",", "'Single-item dict must have just one item, not %d.'", "%", "len", "(", "d", ")", "return", "next", "(", "six", ".", "iterkeys", "(", "d", ")", ")" ]
49.75
17.5
def parse(argv, rules=None, config=None, **kwargs): """Parse the given arg vector with the default Splunk command rules.""" parser_ = parser(rules, **kwargs) if config is not None: parser_.loadrc(config) return parser_.parse(argv).result
[ "def", "parse", "(", "argv", ",", "rules", "=", "None", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "parser_", "=", "parser", "(", "rules", ",", "*", "*", "kwargs", ")", "if", "config", "is", "not", "None", ":", "parser_", ".",...
49.8
5.2
def settings(self): """Return batch job settings.""" _settings = { 'action': self._action, # not supported in v2 batch # 'attributeWriteType': self._attribute_write_type, 'attributeWriteType': 'Replace', 'haltOnError': str(self._halt_on_error)....
[ "def", "settings", "(", "self", ")", ":", "_settings", "=", "{", "'action'", ":", "self", ".", "_action", ",", "# not supported in v2 batch", "# 'attributeWriteType': self._attribute_write_type,", "'attributeWriteType'", ":", "'Replace'", ",", "'haltOnError'", ":", "str...
43.944444
16.388889
def rssi_bars(self) -> int: """Received Signal Strength Indication, from 0 to 4 bars.""" rssi_db = self.rssi_db if rssi_db < 45: return 0 elif rssi_db < 60: return 1 elif rssi_db < 75: return 2 elif rssi_db < 90: return 3 ...
[ "def", "rssi_bars", "(", "self", ")", "->", "int", ":", "rssi_db", "=", "self", ".", "rssi_db", "if", "rssi_db", "<", "45", ":", "return", "0", "elif", "rssi_db", "<", "60", ":", "return", "1", "elif", "rssi_db", "<", "75", ":", "return", "2", "eli...
26.916667
15.416667
def make_non_negative_axis(axis, rank): """Make (possibly negatively indexed) `axis` argument non-negative.""" axis = tf.convert_to_tensor(value=axis, name="axis") rank = tf.convert_to_tensor(value=rank, name="rank") axis_ = tf.get_static_value(axis) rank_ = tf.get_static_value(rank) # Static case. if ax...
[ "def", "make_non_negative_axis", "(", "axis", ",", "rank", ")", ":", "axis", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "axis", ",", "name", "=", "\"axis\"", ")", "rank", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "rank", ",", ...
32.24
16
def curve(self): """ Returns information about the curve used for an EC key :raises: ValueError - when the key is not an EC key :return: A two-element tuple, with the first element being a unicode string of "implicit_ca", "specified" or "named". If t...
[ "def", "curve", "(", "self", ")", ":", "if", "self", ".", "algorithm", "!=", "'ec'", ":", "raise", "ValueError", "(", "unwrap", "(", "'''\n Only EC keys have a curve, this key is %s\n '''", ",", "self", ".", "algorithm", ".", "upper", "...
31.4375
21.75
def _parse_float_vec(vec): """ Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats. """ dtype = np.dtype('>u4,>u4') vec1 = vec.view(dtype=dtype) xport1 = vec1['f0'] xport2 = vec1['f1'] # Start by setting first half of ieee number to first half of...
[ "def", "_parse_float_vec", "(", "vec", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "'>u4,>u4'", ")", "vec1", "=", "vec", ".", "view", "(", "dtype", "=", "dtype", ")", "xport1", "=", "vec1", "[", "'f0'", "]", "xport2", "=", "vec1", "[", "'f1'",...
39.218182
21.072727
def delay(self, key): """Sleep only if elapsed time since `self.last[key]` < `self.delay[key]`.""" last_action, target_delay = self.last[key], self.delays[key] elapsed_time = time.time() - last_action if elapsed_time < target_delay: t_remaining = target_delay - elapsed_time ...
[ "def", "delay", "(", "self", ",", "key", ")", ":", "last_action", ",", "target_delay", "=", "self", ".", "last", "[", "key", "]", ",", "self", ".", "delays", "[", "key", "]", "elapsed_time", "=", "time", ".", "time", "(", ")", "-", "last_action", "...
51.625
12.125
def get_proficiency_query_session(self, proxy): """Gets the ``OsidSession`` associated with the proficiency query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``ProficiencyQuerySession`` :rtype: ``osid.learning.ProficiencyQuerySession`` :ra...
[ "def", "get_proficiency_query_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_proficiency_query", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":",...
40.461538
19.269231
def hil_actuator_controls_send(self, time_usec, controls, mode, flags, force_mavlink1=False): ''' Sent from autopilot to simulation. Hardware in the loop control outputs (replacement for HIL_CONTROLS) time_usec : Timestamp (microseconds si...
[ "def", "hil_actuator_controls_send", "(", "self", ",", "time_usec", ",", "controls", ",", "mode", ",", "flags", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "hil_actuator_controls_encode", "(", "time_usec", ",...
71.166667
51.5
def err(format_msg, *args, **kwargs): '''print format_msg to stderr''' exc_info = kwargs.pop("exc_info", False) stderr.warning(str(format_msg).format(*args, **kwargs), exc_info=exc_info)
[ "def", "err", "(", "format_msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exc_info", "=", "kwargs", ".", "pop", "(", "\"exc_info\"", ",", "False", ")", "stderr", ".", "warning", "(", "str", "(", "format_msg", ")", ".", "format", "(", "...
48.75
12.25
def geom(self): """Geometry information. :class:`_Geometry` instance holding geometry information. It is issued from binary files holding field information. It is set to None if not available for this time step. """ if self._header is UNDETERMINED: binfiles =...
[ "def", "geom", "(", "self", ")", ":", "if", "self", ".", "_header", "is", "UNDETERMINED", ":", "binfiles", "=", "self", ".", "step", ".", "sdat", ".", "binfiles_set", "(", "self", ".", "step", ".", "isnap", ")", "if", "binfiles", ":", "self", ".", ...
42.625
17.75
def _smooth_epsf(self, epsf_data): """ Smooth the ePSF array by convolving it with a kernel. Parameters ---------- epsf_data : 2D `~numpy.ndarray` A 2D array containing the ePSF image. Returns ------- result : 2D `~numpy.ndarray` ...
[ "def", "_smooth_epsf", "(", "self", ",", "epsf_data", ")", ":", "from", "scipy", ".", "ndimage", "import", "convolve", "if", "self", ".", "smoothing_kernel", "is", "None", ":", "return", "epsf_data", "elif", "self", ".", "smoothing_kernel", "==", "'quartic'", ...
39.95082
19.885246
def qtrim_back(self, name, size=1): """ Sets the list element at ``index`` to ``value``. An error is returned for out of range indexes. :param string name: the queue name :param int size: the max length of removed elements :return: the length of removed elements ...
[ "def", "qtrim_back", "(", "self", ",", "name", ",", "size", "=", "1", ")", ":", "size", "=", "get_positive_integer", "(", "\"size\"", ",", "size", ")", "return", "self", ".", "execute_command", "(", "'qtrim_back'", ",", "name", ",", "size", ")" ]
35.384615
17.692308
async def query(self, path, method='get', **params): """ Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data """ if ...
[ "async", "def", "query", "(", "self", ",", "path", ",", "method", "=", "'get'", ",", "*", "*", "params", ")", ":", "if", "method", "in", "(", "'get'", ",", "'post'", ",", "'patch'", ",", "'delete'", ",", "'put'", ")", ":", "full_path", "=", "self",...
42.8125
18
def _populate_from_list_blobs(self, creds, options, dry_run): # type: (SourcePath, StorageCredentials, Any, bool) -> StorageEntity """Internal generator for Azure remote blobs :param SourcePath self: this :param StorageCredentials creds: storage creds :param object options: downl...
[ "def", "_populate_from_list_blobs", "(", "self", ",", "creds", ",", "options", ",", "dry_run", ")", ":", "# type: (SourcePath, StorageCredentials, Any, bool) -> StorageEntity", "is_synccopy", "=", "isinstance", "(", "options", ",", "blobxfer", ".", "models", ".", "optio...
48.375
14.640625
def get_from_layer(self, name, layer=None): """Get a configuration value from the named layer. Parameters ---------- name : str The name of the value to retrieve layer: str The name of the layer to retrieve the value from. If it is not supplied ...
[ "def", "get_from_layer", "(", "self", ",", "name", ",", "layer", "=", "None", ")", ":", "if", "name", "not", "in", "self", ".", "_children", ":", "if", "self", ".", "_frozen", ":", "raise", "KeyError", "(", "name", ")", "self", ".", "_children", "[",...
35.65
15.5
def trt_pmf(matrices): """ Fold full disaggregation matrix to tectonic region type PMF. :param matrices: a matrix with T submatrices :returns: an array of T probabilities one per each tectonic region type """ ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape pmf = nu...
[ "def", "trt_pmf", "(", "matrices", ")", ":", "ntrts", ",", "nmags", ",", "ndists", ",", "nlons", ",", "nlats", ",", "neps", "=", "matrices", ".", "shape", "pmf", "=", "numpy", ".", "zeros", "(", "ntrts", ")", "for", "t", "in", "range", "(", "ntrts"...
30.75
13.75
def call(self, obj, name, method, args, kwargs): """Trigger a method along with its beforebacks and afterbacks. Parameters ---------- name: str The name of the method that will be called args: tuple The arguments that will be passed to the base method ...
[ "def", "call", "(", "self", ",", "obj", ",", "name", ",", "method", ",", "args", ",", "kwargs", ")", ":", "if", "name", "in", "self", ".", "_callback_registry", ":", "beforebacks", ",", "afterbacks", "=", "zip", "(", "*", "self", ".", "_callback_regist...
34.833333
17.75
def consume_value(self, ctx, opts): """ Retrieve default value and display it when prompt is disabled. """ value = click.Option.consume_value(self, ctx, opts) if not value: # value not found by click on command line # now check using our context helper in order into ...
[ "def", "consume_value", "(", "self", ",", "ctx", ",", "opts", ")", ":", "value", "=", "click", ".", "Option", ".", "consume_value", "(", "self", ",", "ctx", ",", "opts", ")", "if", "not", "value", ":", "# value not found by click on command line", "# now che...
43.857143
12.52381
def read_eager(self): """Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() while self.cooke...
[ "def", "read_eager", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "while", "self", ".", "cookedq", ".", "tell", "(", ")", "==", "0", "and", "not", "self", ".", "eof", "and", "self", ".", "sock_avail", "(", ")", ":", "self", ".", ...
35.384615
18.769231
def getElementById(self, _id, root='root', useIndex=True): ''' getElementById - Searches and returns the first (should only be one) element with the given ID. @param id <str> - A string of the id attribute. @param root <AdvancedTag/'root'> - Search sta...
[ "def", "getElementById", "(", "self", ",", "_id", ",", "root", "=", "'root'", ",", "useIndex", "=", "True", ")", ":", "(", "root", ",", "isFromRoot", ")", "=", "self", ".", "_handleRootArg", "(", "root", ")", "if", "self", ".", "useIndex", "is", "Tru...
44.347826
35.913043
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element...
[ "def", "encode", "(", "self", ")", ":", "element", "=", "ElementTree", ".", "Element", "(", "self", ".", "name", ")", "element", "=", "self", ".", "_set_nil", "(", "element", ",", "lambda", "value", ":", "str", "(", "value", ")", ")", "return", "elem...
34.909091
14.909091
def add_item(self, item, field_name=None): """ Add the item to the specified section. Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL. Behavior on other items is undefined. """ field_name = self._choose_field_name(field_name) related_manager ...
[ "def", "add_item", "(", "self", ",", "item", ",", "field_name", "=", "None", ")", ":", "field_name", "=", "self", ".", "_choose_field_name", "(", "field_name", ")", "related_manager", "=", "getattr", "(", "item", ",", "field_name", ")", "related_manager", "....
37.2
12.4
def status(self): ''' :returns: A dictionary with the following: * 'num': Total number of hosts already probed * 'up': Number of hosts up * 'down': Number of hosts down * 'ratio': Ratio between 'up'/'down' as float Ratio: * ``100%`` up == `1...
[ "def", "status", "(", "self", ")", ":", "num", "=", "len", "(", "self", ".", "probe", ")", "up", "=", "len", "(", "[", "h", "for", "h", "in", "self", ".", "probe", "if", "self", ".", "probe", "[", "h", "]", "[", "'up'", "]", "]", ")", "rati...
26.727273
21.454545
def get_interfaces(self, socket_connection=None): """Returns the a list of Interface objects the service implements.""" if not socket_connection: socket_connection = self.open_connection() close_socket = True else: close_socket = False # noinspection ...
[ "def", "get_interfaces", "(", "self", ",", "socket_connection", "=", "None", ")", ":", "if", "not", "socket_connection", ":", "socket_connection", "=", "self", ".", "open_connection", "(", ")", "close_socket", "=", "True", "else", ":", "close_socket", "=", "Fa...
35.125
17.0625
def cleanup(self): """ Cleanup resources used during execution """ if self.local_port is not None: logger.debug(("Stopping ssh tunnel {0}:{1}:{2} for " "{3}@{4}".format(self.local_port, self.remote_address, ...
[ "def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "local_port", "is", "not", "None", ":", "logger", ".", "debug", "(", "(", "\"Stopping ssh tunnel {0}:{1}:{2} for \"", "\"{3}@{4}\"", ".", "format", "(", "self", ".", "local_port", ",", "self", ".", ...
42.3125
10.3125
def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise Type...
[ "def", "check_include_exclude", "(", "attributes", ")", ":", "include", "=", "attributes", ".", "get", "(", "'__include__'", ",", "tuple", "(", ")", ")", "exclude", "=", "attributes", ".", "get", "(", "'__exclude__'", ",", "tuple", "(", ")", ")", "if", "...
35.45
19.5
def dprintx(passeditem, special=False): """Print Text if DEBUGALL set, optionally with PrettyPrint. Args: passeditem (str): item to print special (bool): determines if item prints with PrettyPrint or regular print. """ if DEBUGALL: if special: ...
[ "def", "dprintx", "(", "passeditem", ",", "special", "=", "False", ")", ":", "if", "DEBUGALL", ":", "if", "special", ":", "from", "pprint", "import", "pprint", "pprint", "(", "passeditem", ")", "else", ":", "print", "(", "\"%s%s%s\"", "%", "(", "C_TI", ...
29
16.066667
def _set_show_bare_metal_state(self, v, load=False): """ Setter method for show_bare_metal_state, mapped from YANG variable /brocade_preprovision_rpc/show_bare_metal_state (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_bare_metal_state is considered as a priv...
[ "def", "_set_show_bare_metal_state", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
83.727273
39.863636
def message_with_placeholders(message): """ Return an ASGI message, with any body-type content omitted and replaced with a placeholder. """ new_message = message.copy() for attr in PLACEHOLDER_FORMAT.keys(): if message.get(attr) is not None: content = message[attr] ...
[ "def", "message_with_placeholders", "(", "message", ")", ":", "new_message", "=", "message", ".", "copy", "(", ")", "for", "attr", "in", "PLACEHOLDER_FORMAT", ".", "keys", "(", ")", ":", "if", "message", ".", "get", "(", "attr", ")", "is", "not", "None",...
37
10.666667
def _bit_is_one(self, n, hash_bytes): """ Check if the n (index) of hash_bytes is 1 or 0. """ scale = 16 # hexadecimal if not hash_bytes[int(n / (scale / 2))] >> int( (scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1: return False return True
[ "def", "_bit_is_one", "(", "self", ",", "n", ",", "hash_bytes", ")", ":", "scale", "=", "16", "# hexadecimal", "if", "not", "hash_bytes", "[", "int", "(", "n", "/", "(", "scale", "/", "2", ")", ")", "]", ">>", "int", "(", "(", "scale", "/", "2", ...
28.090909
16.454545
def set(name, data, **kwargs): ''' Set debconf selections .. code-block:: yaml <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} <s...
[ "def", "set", "(", "name", ",", "data", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "current", "=", "__salt__", "[", ...
32.415584
24.025974
def evaluate(self, verbose=True, passes=None): """Summary Returns: TYPE: Description """ if self.is_pivot: index, pivot, columns = LazyOpResult( self.expr, self.weld_type, 0 ).evaluate(verbose=verbose, p...
[ "def", "evaluate", "(", "self", ",", "verbose", "=", "True", ",", "passes", "=", "None", ")", ":", "if", "self", ".", "is_pivot", ":", "index", ",", "pivot", ",", "columns", "=", "LazyOpResult", "(", "self", ".", "expr", ",", "self", ".", "weld_type"...
32.057143
14.771429
async def async_open(self) -> None: """Opens connection to the LifeSOS ethernet interface.""" await self._loop.create_connection( lambda: self, self._host, self._port)
[ "async", "def", "async_open", "(", "self", ")", "->", "None", ":", "await", "self", ".", "_loop", ".", "create_connection", "(", "lambda", ":", "self", ",", "self", ".", "_host", ",", "self", ".", "_port", ")" ]
30.571429
13.857143
def from_optional_dict(cls, d: Optional[dict], force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T]: """From dict to optional instance. :param d: Dict :param force_snake_case: Keys are transformed to snake case in order to compliant P...
[ "def", "from_optional_dict", "(", "cls", ",", "d", ":", "Optional", "[", "dict", "]", ",", "force_snake_case", ":", "bool", "=", "True", ",", "force_cast", ":", "bool", "=", "False", ",", "restrict", ":", "bool", "=", "True", ")", "->", "TOption", "[",...
42.351351
21.243243
def is_revoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL an...
[ "def", "is_revoked", "(", "self", ",", "crl_list", ")", ":", "for", "c", "in", "crl_list", ":", "if", "(", "self", ".", "authorityKeyID", "is", "not", "None", "and", "c", ".", "authorityKeyID", "is", "not", "None", "and", "self", ".", "authorityKeyID", ...
47.75
22.416667
def sqllab(self): """SQL Editor""" d = { 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'), 'common': self.common_bootsrap_payload(), } return self.render_template( 'superset/basic.html', entry='sqllab', bootstrap_data=json.dumps...
[ "def", "sqllab", "(", "self", ")", ":", "d", "=", "{", "'defaultDbId'", ":", "config", ".", "get", "(", "'SQLLAB_DEFAULT_DBID'", ")", ",", "'common'", ":", "self", ".", "common_bootsrap_payload", "(", ")", ",", "}", "return", "self", ".", "render_template"...
32.454545
18.454545
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False): """ Low level child management. Send given HTTP method with given nurest_object to given ressource of current object Args: nurest_obje...
[ "def", "_manage_child_object", "(", "self", ",", "nurest_object", ",", "method", "=", "HTTP_METHOD_GET", ",", "async", "=", "False", ",", "callback", "=", "None", ",", "handler", "=", "None", ",", "response_choice", "=", "None", ",", "commit", "=", "False", ...
44.371429
30.457143
def _add_default_options(self) -> None: """Add default command line options to the parser. """ # Updating the trust stores update_stores_group = OptionGroup(self._parser, 'Trust stores options', '') update_stores_group.add_option( '--update_trust_stores', ...
[ "def", "_add_default_options", "(", "self", ")", "->", "None", ":", "# Updating the trust stores", "update_stores_group", "=", "OptionGroup", "(", "self", ".", "_parser", ",", "'Trust stores options'", ",", "''", ")", "update_stores_group", ".", "add_option", "(", "...
43.68254
25.373016
def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.op...
[ "def", "optional_else", "(", "self", ",", "node", ",", "last", ")", ":", "if", "node", ".", "orelse", ":", "min_first_max_last", "(", "node", ",", "node", ".", "orelse", "[", "-", "1", "]", ")", "if", "'else'", "in", "self", ".", "operators", ":", ...
54.2
17.7
def fun_en_complete_func(self, client, findstart_and_base, base=None): """Invokable function from vim and neovim to perform completion.""" if isinstance(findstart_and_base, list): # Invoked by neovim findstart = findstart_and_base[0] base = findstart_and_base[1] ...
[ "def", "fun_en_complete_func", "(", "self", ",", "client", ",", "findstart_and_base", ",", "base", "=", "None", ")", ":", "if", "isinstance", "(", "findstart_and_base", ",", "list", ")", ":", "# Invoked by neovim", "findstart", "=", "findstart_and_base", "[", "0...
44.4
10.5
def _genprop(converter, *apipaths, **kwargs): """ This internal helper method returns a property (similar to the @property decorator). In additional to a simple Python property, this also adds a type validator (`converter`) and most importantly, specifies the path within a dictionary where the value...
[ "def", "_genprop", "(", "converter", ",", "*", "apipaths", ",", "*", "*", "kwargs", ")", ":", "if", "not", "apipaths", ":", "raise", "TypeError", "(", "'Must have at least one API path'", ")", "def", "fget", "(", "self", ")", ":", "d", "=", "self", ".", ...
29.244898
20.387755
def as_iso8601(self): """ example: 00:38:05.210Z """ if self.__time is None: return None return "%s:%s:%s0Z" % (self.__time[:2], self.__time[2:4], self.__time[4:])
[ "def", "as_iso8601", "(", "self", ")", ":", "if", "self", ".", "__time", "is", "None", ":", "return", "None", "return", "\"%s:%s:%s0Z\"", "%", "(", "self", ".", "__time", "[", ":", "2", "]", ",", "self", ".", "__time", "[", "2", ":", "4", "]", ",...
26.125
17.125
def control_change(self, channel, control, value): """Send a control change message. See the MIDI specification for more information. """ if control < 0 or control > 128: return False if value < 0 or value > 128: return False self.cc_event(channel...
[ "def", "control_change", "(", "self", ",", "channel", ",", "control", ",", "value", ")", ":", "if", "control", "<", "0", "or", "control", ">", "128", ":", "return", "False", "if", "value", "<", "0", "or", "value", ">", "128", ":", "return", "False", ...
36.384615
13.461538
def prepend_elements(self, elements): """ Prepends more elements to the contained internal elements. """ self._elements = list(elements) + self._elements self._on_element_change()
[ "def", "prepend_elements", "(", "self", ",", "elements", ")", ":", "self", ".", "_elements", "=", "list", "(", "elements", ")", "+", "self", ".", "_elements", "self", ".", "_on_element_change", "(", ")" ]
35.666667
8.666667
def DOM_copyTo(self, nodeId, targetNodeId, **kwargs): """ Function path: DOM.copyTo Domain: DOM Method name: copyTo WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'nodeId' (type: NodeId) -> Id of the node to copy. 'targetNodeId' (type: NodeId) -> Id ...
[ "def", "DOM_copyTo", "(", "self", ",", "nodeId", ",", "targetNodeId", ",", "*", "*", "kwargs", ")", ":", "expected", "=", "[", "'insertBeforeNodeId'", "]", "passed_keys", "=", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "assert", "all", "(", "["...
40.5
25.423077
def daemonize(): """ Forks and daemonizes the current process. Does not automatically track the process id; to do this, use :class:`Exscript.util.pidutil`. """ sys.stdout.flush() sys.stderr.flush() # UNIX double-fork magic. We need to fork before any threads are # created. pid = os....
[ "def", "daemonize", "(", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "# UNIX double-fork magic. We need to fork before any threads are", "# created.", "pid", "=", "os", ".", "fork", "(", ")", "if", "p...
22.185185
21.962963
def __float(value): '''validate a float''' valid, _value = False, value try: _value = float(value) valid = True except ValueError: pass return (valid, _value, 'float')
[ "def", "__float", "(", "value", ")", ":", "valid", ",", "_value", "=", "False", ",", "value", "try", ":", "_value", "=", "float", "(", "value", ")", "valid", "=", "True", "except", "ValueError", ":", "pass", "return", "(", "valid", ",", "_value", ","...
22.555556
17.444444