text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def prior_H0(self, H0, H0_min=0, H0_max=200): """ checks whether the parameter vector has left its bound, if so, adds a big number """ if H0 < H0_min or H0 > H0_max: penalty = -10**15 return penalty, False else: return 0, True
[ "def", "prior_H0", "(", "self", ",", "H0", ",", "H0_min", "=", "0", ",", "H0_max", "=", "200", ")", ":", "if", "H0", "<", "H0_min", "or", "H0", ">", "H0_max", ":", "penalty", "=", "-", "10", "**", "15", "return", "penalty", ",", "False", "else", ...
32.666667
12.666667
def validate_units(self, value): """Validate units, assuming that it was called by _validate_type_*.""" self.validate_quantity(value) self.units_type = inspect.stack()[1][3].split('_')[-1] assert self.units_type, ("`validate_units` should not be called " ...
[ "def", "validate_units", "(", "self", ",", "value", ")", ":", "self", ".", "validate_quantity", "(", "value", ")", "self", ".", "units_type", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "3", "]", ".", "split", "(", "'_'", ")", "[", ...
54.230769
16.692308
def refresh(self): """Re-pulls the data from redis""" redis_key = EXPERIMENT_REDIS_KEY_TEMPLATE % self.experiment.name self.plays = int(self.experiment.redis.hget(redis_key, "%s:plays" % self.name) or 0) self.rewards = int(self.experiment.redis.hget(redis_key, "%s:rewards" % self.name) ...
[ "def", "refresh", "(", "self", ")", ":", "redis_key", "=", "EXPERIMENT_REDIS_KEY_TEMPLATE", "%", "self", ".", "experiment", ".", "name", "self", ".", "plays", "=", "int", "(", "self", ".", "experiment", ".", "redis", ".", "hget", "(", "redis_key", ",", "...
55.285714
32.714286
def fi_iban_load_map(filename: str) -> dict: """ Loads Finnish monetary institution codes and BICs in CSV format. Map which is based on 3 digits as in FIXX<3 digits>. Can be used to map Finnish IBAN number to bank information. Format: dict('<3 digits': (BIC, name), ...) :param filename: CSV file...
[ "def", "fi_iban_load_map", "(", "filename", ":", "str", ")", "->", "dict", ":", "out", "=", "{", "}", "with", "open", "(", "filename", ",", "'rt'", ")", "as", "fp", ":", "lines", "=", "[", "line", ".", "strip", "(", ")", ".", "split", "(", "','",...
44.681818
16.863636
def _from_dict(cls, _dict): """Initialize a Log object from a json dictionary.""" args = {} if 'request' in _dict: args['request'] = MessageRequest._from_dict(_dict.get('request')) else: raise ValueError( 'Required property \'request\' not present ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'request'", "in", "_dict", ":", "args", "[", "'request'", "]", "=", "MessageRequest", ".", "_from_dict", "(", "_dict", ".", "get", "(", "'request'", ")", ")", "els...
40.878049
20.560976
def sls(name, mods=None, **kwargs): ''' Apply the states defined by the specified SLS modules to the running container .. versionadded:: 2016.11.0 The container does not need to have Salt installed, but Python is required. name Container name or ID mods : None A string co...
[ "def", "sls", "(", "name", ",", "mods", "=", "None", ",", "*", "*", "kwargs", ")", ":", "mods", "=", "[", "item", ".", "strip", "(", ")", "for", "item", "in", "mods", ".", "split", "(", "','", ")", "]", "if", "mods", "else", "[", "]", "# Figu...
31.886957
22.078261
def linkage_group_ordering(linkage_records): """Convert degenerate linkage records into ordered info_frags-like records for comparison purposes. Simple example: >>> linkage_records = [ ... ['linkage_group_1', 31842, 94039, 'sctg_207'], ... ['linkage_group_1', 95303, 95303, 'sctg_20...
[ "def", "linkage_group_ordering", "(", "linkage_records", ")", ":", "new_records", "=", "dict", "(", ")", "for", "lg_name", ",", "linkage_group", "in", "itertools", ".", "groupby", "(", "linkage_records", ",", "operator", ".", "itemgetter", "(", "0", ")", ")", ...
34.254545
22.672727
def combine_calls_parallel(samples, run_parallel): """Combine calls using batched Ensemble approach. """ batch_groups, extras = _group_by_batches(samples, _has_ensemble) out = [] if batch_groups: processed = run_parallel("combine_calls", ((b, xs, xs[0]) for b, xs in batch_groups.items())) ...
[ "def", "combine_calls_parallel", "(", "samples", ",", "run_parallel", ")", ":", "batch_groups", ",", "extras", "=", "_group_by_batches", "(", "samples", ",", "_has_ensemble", ")", "out", "=", "[", "]", "if", "batch_groups", ":", "processed", "=", "run_parallel",...
42.583333
16.083333
def fobj_to_tempfile(f, suffix=''): """Context manager which copies a file object to disk and return its name. When done the file is deleted. """ with tempfile.NamedTemporaryFile( dir=TEMPDIR, suffix=suffix, delete=False) as t: shutil.copyfileobj(f, t) try: yield t.name ...
[ "def", "fobj_to_tempfile", "(", "f", ",", "suffix", "=", "''", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "dir", "=", "TEMPDIR", ",", "suffix", "=", "suffix", ",", "delete", "=", "False", ")", "as", "t", ":", "shutil", ".", "copyfile...
31.545455
11.818182
def enable_model_triggers(self, state): """ Enables Model Nodes and attributes triggers. :param state: Inform model state. :type state: bool :return: Method success. :rtype: bool """ for node in foundations.walkers.nodes_walker(self.root_node): ...
[ "def", "enable_model_triggers", "(", "self", ",", "state", ")", ":", "for", "node", "in", "foundations", ".", "walkers", ".", "nodes_walker", "(", "self", ".", "root_node", ")", ":", "node", ".", "trigger_model", "=", "state", "for", "attribute", "in", "no...
29.066667
15.066667
def extract(self, item): """Creates an instance of Article without a Download and returns an ArticleCandidate with the results of parsing the HTML-Code. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ article_...
[ "def", "extract", "(", "self", ",", "item", ")", ":", "article_candidate", "=", "ArticleCandidate", "(", ")", "article_candidate", ".", "extractor", "=", "self", ".", "_name", "(", ")", "article", "=", "Article", "(", "''", ")", "article", ".", "set_html",...
45.148148
18.814815
def via_scan(): """ IP scan - now implemented """ import socket import ipaddress import httpfind bridges_from_scan = [] hosts = socket.gethostbyname_ex(socket.gethostname())[2] for host in hosts: bridges_from_scan += httpfind.survey( # TODO: how do we determine subnet con...
[ "def", "via_scan", "(", ")", ":", "import", "socket", "import", "ipaddress", "import", "httpfind", "bridges_from_scan", "=", "[", "]", "hosts", "=", "socket", ".", "gethostbyname_ex", "(", "socket", ".", "gethostname", "(", ")", ")", "[", "2", "]", "for", ...
37.107143
17.357143
def handle_wsgi_error(environ, exc): '''The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse` ''' if isinstance(exc, tuple): exc_info = exc exc = exc[1] else: exc_info...
[ "def", "handle_wsgi_error", "(", "environ", ",", "exc", ")", ":", "if", "isinstance", "(", "exc", ",", "tuple", ")", ":", "exc_info", "=", "exc", "exc", "=", "exc", "[", "1", "]", "else", ":", "exc_info", "=", "True", "request", "=", "wsgi_request", ...
36.152174
16.934783
def select_action(self, q_values): """Return the selected action The selected action follows the BoltzmannQPolicy with probability epsilon or return the Greedy Policy with probability (1 - epsilon) # Arguments q_values (np.ndarray): List of the estimations of Q for each acti...
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "assert", "q_values", ".", "ndim", "==", "1", "q_values", "=", "q_values", ".", "astype", "(", "'float64'", ")", "nb_actions", "=", "q_values", ".", "shape", "[", "0", "]", "if", "np", "."...
36.772727
19.772727
def __expect(self, exp='> ', timeout=None): """will wait for exp to be returned from nodemcu or timeout""" timeout_before = self._port.timeout timeout = timeout or self._timeout #do NOT set timeout on Windows if SYSTEM != 'Windows': # Checking for new data every 100us...
[ "def", "__expect", "(", "self", ",", "exp", "=", "'> '", ",", "timeout", "=", "None", ")", ":", "timeout_before", "=", "self", ".", "_port", ".", "timeout", "timeout", "=", "timeout", "or", "self", ".", "_timeout", "#do NOT set timeout on Windows", "if", "...
37.928571
19.928571
def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls per...
[ "def", "setup_mappings", "(", "cls", ",", "force", "=", "False", ")", ":", "if", "getattr", "(", "cls", ",", "'_mappings_setup'", ",", "False", ")", "and", "not", "force", ":", "log", ".", "debug", "(", "'ES mappings have been already set up for currently '", ...
45.88
19.28
def ensure_one_opt_multi_ifo(opt, parser, ifo, opt_list): """ Check that one and only one in the opt_list is defined in opt Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings """ the_one = None ...
[ "def", "ensure_one_opt_multi_ifo", "(", "opt", ",", "parser", ",", "ifo", ",", "opt_list", ")", ":", "the_one", "=", "None", "for", "name", "in", "opt_list", ":", "attr", "=", "name", "[", "2", ":", "]", ".", "replace", "(", "'-'", ",", "'_'", ")", ...
27.966667
17.8
def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file...
[ "def", "keygen", "(", "sk_file", "=", "None", ",", "pk_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'opts'", "]", "=", "__opts__", "return", "salt", ".", "utils", ".", "nacl", ".", "keygen", "(", "sk_file", ",", "pk_file", ...
32.863636
28.136364
def export(self): """Returns XUnit XML.""" top = self._top_element() properties = self._properties_element(top) testsuite = self._testsuite_element(top) self._fill_tests_results(testsuite) self._fill_lookup_prop(properties) return utils.prettify_xml(top)
[ "def", "export", "(", "self", ")", ":", "top", "=", "self", ".", "_top_element", "(", ")", "properties", "=", "self", ".", "_properties_element", "(", "top", ")", "testsuite", "=", "self", ".", "_testsuite_element", "(", "top", ")", "self", ".", "_fill_t...
37.875
6.875
def kl_divergence(p, q): """Compute the Kullback-Leibler (KL) divergence for discrete distributions. Parameters ---------- p : np.array "Ideal"/"true" Probability distribution q : np.array Approximation of probability distribution p Returns ------- kl : float KL...
[ "def", "kl_divergence", "(", "p", ",", "q", ")", ":", "# make sure numpy arrays are floats", "p", "=", "p", ".", "astype", "(", "float", ")", "q", "=", "q", ".", "astype", "(", "float", ")", "# compute kl divergence", "kl", "=", "np", ".", "sum", "(", ...
24.681818
20.318182
def either(*funcs): """ A utility function for selecting the first non-null query. Parameters: funcs: One or more functions Returns: A function that, when called with a :class:`Node`, will pass the input to each `func`, and return the first non-Falsey result. Examples...
[ "def", "either", "(", "*", "funcs", ")", ":", "def", "either", "(", "val", ")", ":", "for", "func", "in", "funcs", ":", "result", "=", "val", ".", "apply", "(", "func", ")", "if", "result", ":", "return", "result", "return", "Null", "(", ")", "re...
21.214286
22.857143
def get_locations(self): """ Returns a list of locations. http://dev.wheniwork.com/#listing-locations """ url = "/2/locations" data = self._get_resource(url) locations = [] for entry in data['locations']: locations.append(self.location_from_j...
[ "def", "get_locations", "(", "self", ")", ":", "url", "=", "\"/2/locations\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "locations", "=", "[", "]", "for", "entry", "in", "data", "[", "'locations'", "]", ":", "locations", ".", "append",...
24.571429
15.714286
def memset(self, allocation, value, size): """set the memory in allocation to the value in value :param allocation: An Argument for some memory allocation unit :type allocation: Argument :param value: The value to set the memory to :type value: a single 8-bit unsigned int ...
[ "def", "memset", "(", "self", ",", "allocation", ",", "value", ",", "size", ")", ":", "C", ".", "memset", "(", "allocation", ".", "ctypes", ",", "value", ",", "size", ")" ]
34.846154
17.461538
def get_token(self, user_id): """ Get user token Checks if a custom token implementation is registered and uses that. Otherwise falls back to default token implementation. Returns a string token on success. :param user_id: int, user id :return: str """ ...
[ "def", "get_token", "(", "self", ",", "user_id", ")", ":", "if", "not", "self", ".", "jwt_implementation", ":", "return", "self", ".", "default_token_implementation", "(", "user_id", ")", "try", ":", "implementation", "=", "import_string", "(", "self", ".", ...
35.681818
20.409091
def percentile(values=None, percentile=None): """Calculates a simplified weighted average percentile """ if values in [None, tuple(), []] or len(values) < 1: raise InsufficientData( "Expected a sequence of at least 1 integers, got {0!r}".format(values)) if percentile is None: ...
[ "def", "percentile", "(", "values", "=", "None", ",", "percentile", "=", "None", ")", ":", "if", "values", "in", "[", "None", ",", "tuple", "(", ")", ",", "[", "]", "]", "or", "len", "(", "values", ")", "<", "1", ":", "raise", "InsufficientData", ...
32.037037
16.666667
def peak_load_generation_at_node(nodes): """ Get maximum occuring load and generation at a certain node Summarizes peak loads and nominal generation power of descendant nodes of a branch Parameters ---------- nodes : :any:`list` Any LV grid Ding0 node object that is part of the gri...
[ "def", "peak_load_generation_at_node", "(", "nodes", ")", ":", "loads", "=", "[", "node", ".", "peak_load", "for", "node", "in", "nodes", "if", "isinstance", "(", "node", ",", "LVLoadDing0", ")", "]", "peak_load", "=", "sum", "(", "loads", ")", "generation...
27.758621
21.896552
def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)): """Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_ """ if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() ppoints1 = vtk.v...
[ "def", "Ribbon", "(", "line1", ",", "line2", ",", "c", "=", "\"m\"", ",", "alpha", "=", "1", ",", "res", "=", "(", "200", ",", "5", ")", ")", ":", "if", "isinstance", "(", "line1", ",", "Actor", ")", ":", "line1", "=", "line1", ".", "coordinate...
30.634921
13.52381
def _select1(data, field, depth, output): """ SELECT A SINGLE FIELD """ for d in data: for i, f in enumerate(field[depth:]): d = d[f] if d == None: output.append(None) break elif is_list(d): _select1(d, field, i ...
[ "def", "_select1", "(", "data", ",", "field", ",", "depth", ",", "output", ")", ":", "for", "d", "in", "data", ":", "for", "i", ",", "f", "in", "enumerate", "(", "field", "[", "depth", ":", "]", ")", ":", "d", "=", "d", "[", "f", "]", "if", ...
25.533333
12.066667
def destroy_sg(app='', env='', region='', **_): """Destroy Security Group. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): Region name, e.g. us-east-1. Returns: True upon successful completion. """ vpc = get_vpc_id(accou...
[ "def", "destroy_sg", "(", "app", "=", "''", ",", "env", "=", "''", ",", "region", "=", "''", ",", "*", "*", "_", ")", ":", "vpc", "=", "get_vpc_id", "(", "account", "=", "env", ",", "region", "=", "region", ")", "url", "=", "'{api}/securityGroups/{...
33.884615
25.153846
def delete(self, ids): """ Method to delete ipv4's by their ids :param ids: Identifiers of ipv4's :return: None """ url = build_uri_with_ids('api/v3/ipv4/%s/', ids) return super(ApiIPv4, self).delete(url)
[ "def", "delete", "(", "self", ",", "ids", ")", ":", "url", "=", "build_uri_with_ids", "(", "'api/v3/ipv4/%s/'", ",", "ids", ")", "return", "super", "(", "ApiIPv4", ",", "self", ")", ".", "delete", "(", "url", ")" ]
25.3
14.5
def stop(self): """ Restore the TTY to its original state. """ _curses.nocbreak() self.window.keypad(0) _curses.echo() _curses.resetty() _curses.endwin() self.running = False
[ "def", "stop", "(", "self", ")", ":", "_curses", ".", "nocbreak", "(", ")", "self", ".", "window", ".", "keypad", "(", "0", ")", "_curses", ".", "echo", "(", ")", "_curses", ".", "resetty", "(", ")", "_curses", ".", "endwin", "(", ")", "self", "....
23.7
11.7
def cleanup_codra_edus(self): """Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes.""" for leafpos in self.tree.treepositions('leaves'): edu_str = self.tree[leafpos] edu_str = EDU_START_RE.sub("", edu_str) edu_str = TRIPLE_ESCAPE_RE.sub('"',...
[ "def", "cleanup_codra_edus", "(", "self", ")", ":", "for", "leafpos", "in", "self", ".", "tree", ".", "treepositions", "(", "'leaves'", ")", ":", "edu_str", "=", "self", ".", "tree", "[", "leafpos", "]", "edu_str", "=", "EDU_START_RE", ".", "sub", "(", ...
41.2
14.4
def ensure_dir(path): """ :param path: path to directory to be created Create a directory if it does not already exist. """ if not os.path.exists(path): # path does not exist, create the directory os.mkdir(path) else: # The path exists, check that it is not a file ...
[ "def", "ensure_dir", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "# path does not exist, create the directory", "os", ".", "mkdir", "(", "path", ")", "else", ":", "# The path exists, check that it is not a file", ...
33.076923
17.230769
def _sort(self): """ Sort versions by their version number """ self.versions = OrderedDict(sorted(self.versions.items(), key=lambda v: v[0]))
[ "def", "_sort", "(", "self", ")", ":", "self", ".", "versions", "=", "OrderedDict", "(", "sorted", "(", "self", ".", "versions", ".", "items", "(", ")", ",", "key", "=", "lambda", "v", ":", "v", "[", "0", "]", ")", ")" ]
33.8
15
def get_abi3_suffix(): """Return the file extension for an abi3-compliant Extension()""" for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION): if '.abi3' in suffix: # Unix return suffix elif suffix == '.pyd': # Windows return suffix
[ "def", "get_abi3_suffix", "(", ")", ":", "for", "suffix", ",", "_", ",", "_", "in", "(", "s", "for", "s", "in", "imp", ".", "get_suffixes", "(", ")", "if", "s", "[", "2", "]", "==", "imp", ".", "C_EXTENSION", ")", ":", "if", "'.abi3'", "in", "s...
43.142857
13.571429
def rescan_hba(kwargs=None, call=None): ''' To rescan a specified HBA or all the HBAs on the Host System CLI Example: .. code-block:: bash salt-cloud -f rescan_hba my-vmware-config host="hostSystemName" salt-cloud -f rescan_hba my-vmware-config hba="hbaDeviceName" host="hostSystemName...
[ "def", "rescan_hba", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The rescan_hba function must be called with '", "'-f or --function.'", ")", "hba", "=", "kwargs", "."...
33.478261
24.782609
def _file_lists(load, form): ''' Return a dict containing the file lists for files, dirs, emtydirs and symlinks ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') saltenv = load['saltenv'] if saltenv not in __opts__['file_roots']: if '__env__'...
[ "def", "_file_lists", "(", "load", ",", "form", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "saltenv", "=", "load", "[", "'saltenv'", "]", "if", "saltenv", "not", "in", ...
40.575758
19.333333
def largest_loop(self): """ Return the boundaries for the largest loop segment. This is just meant to be a reasonable default for various selectors and filters to work with, in the case that more than one loop is being modeled. If you want to be more precise, you'll h...
[ "def", "largest_loop", "(", "self", ")", ":", "from", "collections", "import", "namedtuple", "Loop", "=", "namedtuple", "(", "'Loop'", ",", "'start end'", ")", "largest_segment", "=", "sorted", "(", "self", ".", "loop_segments", ",", "key", "=", "lambda", "x...
40
15
def get_config(self, ): """Return the user config for this plugin You have to provide a configspec, put the configspec file in the same folder as your plugin. Name it like your class and put 'ini' as extension. """ # get the module of the plugin class mod = sys.m...
[ "def", "get_config", "(", "self", ",", ")", ":", "# get the module of the plugin class", "mod", "=", "sys", ".", "modules", "[", "self", ".", "__module__", "]", "# get the file from where it was imported", "modfile", "=", "mod", ".", "__file__", "# get the module dire...
37.217391
11.73913
def _preprocess(self, data): """ Internal function to perform fit_transform() on all but last step. """ transformed_data = _copy(data) for name, step in self._transformers[:-1]: transformed_data = step.fit_transform(transformed_data) if type(transformed_da...
[ "def", "_preprocess", "(", "self", ",", "data", ")", ":", "transformed_data", "=", "_copy", "(", "data", ")", "for", "name", ",", "step", "in", "self", ".", "_transformers", "[", ":", "-", "1", "]", ":", "transformed_data", "=", "step", ".", "fit_trans...
48.75
17.416667
def witnessError(sp, inputVectors, activeColumnsCurrentEpoch): """ Computes a variation of a reconstruction error. It measures the average hamming distance of an active column's connected synapses vector and its witnesses. An input vector is called witness for a column, iff the column is among the active c...
[ "def", "witnessError", "(", "sp", ",", "inputVectors", ",", "activeColumnsCurrentEpoch", ")", ":", "connectionMatrix", "=", "getConnectedSyns", "(", "sp", ")", "batchSize", "=", "inputVectors", ".", "shape", "[", "0", "]", "# 1st sum... over each input in batch", "E...
37.885714
22.914286
def monitor_exit(self): """ Ask YubiHSM to exit to configuration mode (requires 'debug' mode enabled). @returns: None @rtype: NoneType @see: L{pyhsm.debug_cmd.YHSM_Cmd_Monitor_Exit} """ return pyhsm.debug_cmd.YHSM_Cmd_Monitor_Exit(self.stick).execute(read_respon...
[ "def", "monitor_exit", "(", "self", ")", ":", "return", "pyhsm", ".", "debug_cmd", ".", "YHSM_Cmd_Monitor_Exit", "(", "self", ".", "stick", ")", ".", "execute", "(", "read_response", "=", "False", ")" ]
32
24
def splitalleles(consensus): """ takes diploid consensus alleles with phase data stored as a mixture of upper and lower case characters and splits it into 2 alleles """ ## store two alleles, allele1 will start with bigbase allele1 = list(consensus) allele2 = list(consensus) hidx = [i for (i, j)...
[ "def", "splitalleles", "(", "consensus", ")", ":", "## store two alleles, allele1 will start with bigbase", "allele1", "=", "list", "(", "consensus", ")", "allele2", "=", "list", "(", "consensus", ")", "hidx", "=", "[", "i", "for", "(", "i", ",", "j", ")", "...
32.208333
16.208333
def sanitize_version(version): """ Take parse_version() output and standardize output from older setuptools' parse_version() to match current setuptools. """ if hasattr(version, 'base_version'): if version.base_version: parts = version.base_version.split('.') else: ...
[ "def", "sanitize_version", "(", "version", ")", ":", "if", "hasattr", "(", "version", ",", "'base_version'", ")", ":", "if", "version", ".", "base_version", ":", "parts", "=", "version", ".", "base_version", ".", "split", "(", "'.'", ")", "else", ":", "p...
29.416667
14.166667
def write_by_name(self, data_name, value, plc_datatype): # type: (str, Any, Type) -> None """Send data synchronous to an ADS-device from data name. :param string data_name: PLC storage address :param value: value to write to the storage address of the PLC :param int plc_da...
[ "def", "write_by_name", "(", "self", ",", "data_name", ",", "value", ",", "plc_datatype", ")", ":", "# type: (str, Any, Type) -> None\r", "if", "self", ".", "_port", ":", "return", "adsSyncWriteByNameEx", "(", "self", ".", "_port", ",", "self", ".", "_adr", ",...
40
17.571429
def require_user(self, *users, user=None): """A decorator to protect views with Negotiate authentication.""" # accept old-style single user keyword-argument as well if user: users = (*users, user) def _require_auth(view_func): @wraps(view_func) def w...
[ "def", "require_user", "(", "self", ",", "*", "users", ",", "user", "=", "None", ")", ":", "# accept old-style single user keyword-argument as well", "if", "user", ":", "users", "=", "(", "*", "users", ",", "user", ")", "def", "_require_auth", "(", "view_func"...
41.966667
17.5
def stage_in(self, file, executor): """Transport the file from the input source to the executor. This function returns a DataFuture. Args: - self - file (File) : file to stage in - executor (str) : an executor the file is going to be staged in to. ...
[ "def", "stage_in", "(", "self", ",", "file", ",", "executor", ")", ":", "if", "file", ".", "scheme", "==", "'ftp'", ":", "working_dir", "=", "self", ".", "dfk", ".", "executors", "[", "executor", "]", ".", "working_dir", "stage_in_app", "=", "self", "....
48.258065
22.354839
def regexNamer(regex, usePageUrl=False): """Get name from regular expression.""" @classmethod def _namer(cls, imageUrl, pageUrl): """Get first regular expression group.""" url = pageUrl if usePageUrl else imageUrl mo = regex.search(url) if mo: return mo.group(1) ...
[ "def", "regexNamer", "(", "regex", ",", "usePageUrl", "=", "False", ")", ":", "@", "classmethod", "def", "_namer", "(", "cls", ",", "imageUrl", ",", "pageUrl", ")", ":", "\"\"\"Get first regular expression group.\"\"\"", "url", "=", "pageUrl", "if", "usePageUrl"...
32.7
10.3
def get_gears_cache_size(): """ :return: the Ariane gears cache size defined by InjectorCachedGearService.cache_id """ LOGGER.debug("InjectorCachedGearService.get_gears_cache_size") ret = None args = {'properties': {'OPERATION': 'COUNT_GEARS_CACHE', ...
[ "def", "get_gears_cache_size", "(", ")", ":", "LOGGER", ".", "debug", "(", "\"InjectorCachedGearService.get_gears_cache_size\"", ")", "ret", "=", "None", "args", "=", "{", "'properties'", ":", "{", "'OPERATION'", ":", "'COUNT_GEARS_CACHE'", ",", "'CACHE_ID'", ":", ...
46.777778
25.888889
def get_max(self, field=None): """ Create a max aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be aggregated :returns: self, which allows the method to be chainable with the other methods """ if not field: ...
[ "def", "get_max", "(", "self", ",", "field", "=", "None", ")", ":", "if", "not", "field", ":", "raise", "AttributeError", "(", "\"Please provide field to apply aggregation to!\"", ")", "agg", "=", "A", "(", "\"max\"", ",", "field", "=", "field", ")", "self",...
37.846154
23.076923
def add(self, name: str, sig: Tuple, obj: object) -> None: """ Add a file to the cache :param name: name of the object to be pickled :param sig: signature for object :param obj: object to pickle """ if self._cache_directory is not None: if name in self...
[ "def", "add", "(", "self", ",", "name", ":", "str", ",", "sig", ":", "Tuple", ",", "obj", ":", "object", ")", "->", "None", ":", "if", "self", ".", "_cache_directory", "is", "not", "None", ":", "if", "name", "in", "self", ".", "_cache", ":", "os"...
43
11.8
def render_head(self, ctx, data): """ Put liveglue content into the header of this page to activate it, but otherwise delegate to my parent's renderer for <head>. """ ctx.tag[tags.invisible(render=tags.directive('liveglue'))] return _PublicPageMixin.render_head(self, ctx,...
[ "def", "render_head", "(", "self", ",", "ctx", ",", "data", ")", ":", "ctx", ".", "tag", "[", "tags", ".", "invisible", "(", "render", "=", "tags", ".", "directive", "(", "'liveglue'", ")", ")", "]", "return", "_PublicPageMixin", ".", "render_head", "(...
45.714286
16
def updateRPYText(self): 'Updates the displayed Roll, Pitch, Yaw Text' self.rollText.set_text('Roll: %.2f' % self.roll) self.pitchText.set_text('Pitch: %.2f' % self.pitch) self.yawText.set_text('Yaw: %.2f' % self.yaw)
[ "def", "updateRPYText", "(", "self", ")", ":", "self", ".", "rollText", ".", "set_text", "(", "'Roll: %.2f'", "%", "self", ".", "roll", ")", "self", ".", "pitchText", ".", "set_text", "(", "'Pitch: %.2f'", "%", "self", ".", "pitch", ")", "self", ".", ...
49.8
16.2
def render_fetch_maven_artifacts(self): """Configure fetch_maven_artifacts plugin""" phase = 'prebuild_plugins' plugin = 'fetch_maven_artifacts' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return koji_hub = self.spec.kojihub.value koji_root = sel...
[ "def", "render_fetch_maven_artifacts", "(", "self", ")", ":", "phase", "=", "'prebuild_plugins'", "plugin", "=", "'fetch_maven_artifacts'", "if", "not", "self", ".", "dj", ".", "dock_json_has_plugin_conf", "(", "phase", ",", "plugin", ")", ":", "return", "koji_hub...
41.952381
21.47619
def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, autoraise=True, text_beside_icon=False): """Create a QToolButton""" button = QToolButton(parent) if text is not None: button.setText(text) ...
[ "def", "create_toolbutton", "(", "parent", ",", "text", "=", "None", ",", "shortcut", "=", "None", ",", "icon", "=", "None", ",", "tip", "=", "None", ",", "toggled", "=", "None", ",", "triggered", "=", "None", ",", "autoraise", "=", "True", ",", "tex...
37.958333
11.416667
def embed(parent_locals=None, parent_globals=None, exec_lines=None, remove_pyqt_hook=True, N=0): """ Starts interactive session. Similar to keyboard command in matlab. Wrapper around IPython.embed """ import utool as ut from functools import partial import IPython if parent_g...
[ "def", "embed", "(", "parent_locals", "=", "None", ",", "parent_globals", "=", "None", ",", "exec_lines", "=", "None", ",", "remove_pyqt_hook", "=", "True", ",", "N", "=", "0", ")", ":", "import", "utool", "as", "ut", "from", "functools", "import", "part...
35.306931
15.821782
def _read_packet(self): """ Reads and decodes a single packet Reads a single packet from the device and stores the data from it in the current Command object """ # Grab command, send it and decode response cmd = self._commands_to_read.popleft() tr...
[ "def", "_read_packet", "(", "self", ")", ":", "# Grab command, send it and decode response", "cmd", "=", "self", ".", "_commands_to_read", ".", "popleft", "(", ")", "try", ":", "raw_data", "=", "self", ".", "_interface", ".", "read", "(", ")", "raw_data", "=",...
33.547619
16.02381
def run(self): """Execute events until the queue is empty. When there is a positive delay until the first event, the delay function is called and the event is left in the queue; otherwise, the event is removed from the queue and executed (its action function is called, passing it...
[ "def", "run", "(", "self", ")", ":", "# localize variable access to minimize overhead", "# and to improve thread safety", "q", "=", "self", ".", "_queue", "delayfunc", "=", "self", ".", "delayfunc", "timefunc", "=", "self", ".", "timefunc", "pop", "=", "heapq", "....
44.410256
16.820513
def run_process(workflow, *, n_processes, registry, verbose=False, jobdirs=False, init=None, finish=None, deref=False): """Run the workflow using a number of new python processes. Use this runner to test the workflow in a situation where data serial is needed. :param wor...
[ "def", "run_process", "(", "workflow", ",", "*", ",", "n_processes", ",", "registry", ",", "verbose", "=", "False", ",", "jobdirs", "=", "False", ",", "init", "=", "None", ",", "finish", "=", "None", ",", "deref", "=", "False", ")", ":", "workers", "...
29.292308
23.061538
async def set_conversation_notification_level( self, set_conversation_notification_level_request ): """Set the notification level of a conversation.""" response = hangouts_pb2.SetConversationNotificationLevelResponse() await self._pb_request( 'conversations/setconvers...
[ "async", "def", "set_conversation_notification_level", "(", "self", ",", "set_conversation_notification_level_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SetConversationNotificationLevelResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversa...
43.5
19.8
def seriesflow(self, dae): """ Compute the flow through the line after solving PF. Compute terminal injections, line losses """ # Vm = dae.y[self.v] # Va = dae.y[self.a] # V1 = polar(Vm[self.a1], Va[self.a1]) # V2 = polar(Vm[self.a2], Va[self.a2]) ...
[ "def", "seriesflow", "(", "self", ",", "dae", ")", ":", "# Vm = dae.y[self.v]", "# Va = dae.y[self.a]", "# V1 = polar(Vm[self.a1], Va[self.a1])", "# V2 = polar(Vm[self.a2], Va[self.a2])", "I1", "=", "mul", "(", "self", ".", "v1", ",", "div", "(", "self", ".", "y12", ...
31.52381
17.380952
def update(self, dt): """ Tasks that occur over time should be handled here """ self.group.update(dt) # check if the sprite's feet are colliding with wall # sprite must have a rect called feet, and move_back method, # otherwise this will fail for sprite in self.g...
[ "def", "update", "(", "self", ",", "dt", ")", ":", "self", ".", "group", ".", "update", "(", "dt", ")", "# check if the sprite's feet are colliding with wall", "# sprite must have a rect called feet, and move_back method,", "# otherwise this will fail", "for", "sprite", "in...
38.090909
13.363636
def disco(version, co, out=None, is_pypy=False): """ diassembles and deparses a given code block 'co' """ assert iscode(co) # store final output stream for case of error real_out = out or sys.stdout print('# Python %s' % version, file=real_out) if co.co_filename: print('# Embed...
[ "def", "disco", "(", "version", ",", "co", ",", "out", "=", "None", ",", "is_pypy", "=", "False", ")", ":", "assert", "iscode", "(", "co", ")", "# store final output stream for case of error", "real_out", "=", "out", "or", "sys", ".", "stdout", "print", "(...
27.444444
17.111111
def log(name, data=None): """Entry point for the event lib that starts the logging process This function uses the `name` param to find the event class that will be processed to log stuff. This name must provide two informations separated by a dot: the app name and the event class name. Like this: ...
[ "def", "log", "(", "name", ",", "data", "=", "None", ")", ":", "data", "=", "data", "or", "{", "}", "data", ".", "update", "(", "core", ".", "get_default_values", "(", "data", ")", ")", "# InvalidEventNameError, EventNotFoundError", "event_cls", "=", "core...
38.194444
19.444444
def _parse_script(list, line, line_iter): """ Eliminate any bash script contained in the grub v2 configuration """ ifIdx = 0 while (True): line = next(line_iter) if line.startswith("fi"): if ifIdx == 0: return ifIdx -= 1 elif line.start...
[ "def", "_parse_script", "(", "list", ",", "line", ",", "line_iter", ")", ":", "ifIdx", "=", "0", "while", "(", "True", ")", ":", "line", "=", "next", "(", "line_iter", ")", "if", "line", ".", "startswith", "(", "\"fi\"", ")", ":", "if", "ifIdx", "=...
26.384615
13
def _run_flake8_internal(filename): """Run flake8.""" from flake8.engine import get_style_guide from pep8 import BaseReport from prospector.message import Message, Location return_dict = dict() cwd = os.getcwd() class Flake8MergeReporter(BaseReport): """An implementation of pep8.B...
[ "def", "_run_flake8_internal", "(", "filename", ")", ":", "from", "flake8", ".", "engine", "import", "get_style_guide", "from", "pep8", "import", "BaseReport", "from", "prospector", ".", "message", "import", "Message", ",", "Location", "return_dict", "=", "dict", ...
40.444444
19.555556
def check_permission(cls, fine=True): """ Returns a future that returns a boolean indicating if permission is currently granted or denied. If permission is denied, you can request using `LocationManager.request_permission()` below. """ app = AndroidApplication.instance() ...
[ "def", "check_permission", "(", "cls", ",", "fine", "=", "True", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "permission", "=", "(", "cls", ".", "ACCESS_FINE_PERMISSION", "if", "fine", "else", "cls", ".", "ACCESS_COARSE_PERMISSION", ...
46.5
14.3
def gettrace(self, burn=0, thin=1, chain=-1, slicing=None): """Return the trace (last by default). :Parameters: burn : integer The number of transient steps to skip. thin : integer Keep one in thin. chain : integer The index of the chain to fetch. I...
[ "def", "gettrace", "(", "self", ",", "burn", "=", "0", ",", "thin", "=", "1", ",", "chain", "=", "-", "1", ",", "slicing", "=", "None", ")", ":", "if", "chain", "is", "not", "None", ":", "tables", "=", "[", "self", ".", "db", ".", "_gettables",...
33.6875
17.46875
def get_encrpyted_path(original_path, surfix=default_surfix): """ Find the output encrypted file /dir path (by adding a surfix). Example: - file: ``${home}/test.txt`` -> ``${home}/test-encrypted.txt`` - dir: ``${home}/Documents`` -> ``${home}/Documents-encrypted`` """ p = Path(original_pat...
[ "def", "get_encrpyted_path", "(", "original_path", ",", "surfix", "=", "default_surfix", ")", ":", "p", "=", "Path", "(", "original_path", ")", ".", "absolute", "(", ")", "encrypted_p", "=", "p", ".", "change", "(", "new_fname", "=", "p", ".", "fname", "...
34
19.5
def shadow_normal_module(cls, mod_name=None): """ Shadow a module with an instance of LazyModule :param mod_name: Name of the module to shadow. By default this is the module that is making the call into this method. This is not hard-coded as that module might...
[ "def", "shadow_normal_module", "(", "cls", ",", "mod_name", "=", "None", ")", ":", "if", "mod_name", "is", "None", ":", "frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "mod_name", "=", "frame", ".", "f_back", ".", "f_locals", "[", "...
39.347826
16.913043
def assoc_host(self, hostname, env): """ Associate a host with an environment. hostname is opaque to Jones. Any string which uniquely identifies a host is acceptable. """ dest = self._get_view_path(env) self.associations.set(hostname, dest)
[ "def", "assoc_host", "(", "self", ",", "hostname", ",", "env", ")", ":", "dest", "=", "self", ".", "_get_view_path", "(", "env", ")", "self", ".", "associations", ".", "set", "(", "hostname", ",", "dest", ")" ]
28.9
12.5
def summary(self): '''Compute the execution summary''' out = {} for bench in self.runner.runned: key = self.key(bench) runs = {} for method, results in bench.results.items(): mean = results.total / bench.times name = bench.label...
[ "def", "summary", "(", "self", ")", ":", "out", "=", "{", "}", "for", "bench", "in", "self", ".", "runner", ".", "runned", ":", "key", "=", "self", ".", "key", "(", "bench", ")", "runs", "=", "{", "}", "for", "method", ",", "results", "in", "be...
31.85
12.05
def new_filehandler_instances(self, filetype_info, filename_items, fh_kwargs=None): """Generate new filehandler instances.""" requirements = filetype_info.get('requires') filetype_cls = filetype_info['file_reader'] if fh_kwargs is None: fh_kwargs = {} for filename, ...
[ "def", "new_filehandler_instances", "(", "self", ",", "filetype_info", ",", "filename_items", ",", "fh_kwargs", "=", "None", ")", ":", "requirements", "=", "filetype_info", ".", "get", "(", "'requires'", ")", "filetype_cls", "=", "filetype_info", "[", "'file_reade...
42.136364
21.636364
def _put_bucket_versioning(self): """Adds bucket versioning policy to bucket""" status = 'Suspended' if self.s3props['versioning']['enabled']: status = 'Enabled' versioning_config = { 'MFADelete': self.s3props['versioning']['mfa_delete'], 'Status': st...
[ "def", "_put_bucket_versioning", "(", "self", ")", ":", "status", "=", "'Suspended'", "if", "self", ".", "s3props", "[", "'versioning'", "]", "[", "'enabled'", "]", ":", "status", "=", "'Enabled'", "versioning_config", "=", "{", "'MFADelete'", ":", "self", "...
40.5
22.857143
def vrrp_vip(self, **kwargs): """Set VRRP VIP. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc). name (str): Name of interface. (1/0/5, 1/0/10, etc). vrid (str): VRRPv3 ID. vip (str): IPv4/IPv6 Virtual IP ...
[ "def", "vrrp_vip", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "vrid", "=", "kwargs", ".", "pop", "(...
51.018692
18.747664
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None): """ Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parame...
[ "def", "send_media_group", "(", "self", ",", "chat_id", ",", "media", ",", "disable_notification", "=", "None", ",", "reply_to_message_id", "=", "None", ")", ":", "from", "pytgbot", ".", "api_types", ".", "sendable", ".", "input_media", "import", "InputMediaPhot...
48.792453
34.641509
def to_lower(self, string): "Helper function to transform strings to lower case" value = None try: value = string.lower() except AttributeError: value = "" finally: return value
[ "def", "to_lower", "(", "self", ",", "string", ")", ":", "value", "=", "None", "try", ":", "value", "=", "string", ".", "lower", "(", ")", "except", "AttributeError", ":", "value", "=", "\"\"", "finally", ":", "return", "value" ]
27.222222
17.222222
def getAvgBySweep(abf,feature,T0=None,T1=None): """return average of a feature divided by sweep.""" if T1 is None: T1=abf.sweepLength if T0 is None: T0=0 data = [np.empty((0))]*abf.sweeps for AP in cm.dictFlat(cm.matrixToDicts(abf.APs)): if T0<AP['sweepT']<T1: val...
[ "def", "getAvgBySweep", "(", "abf", ",", "feature", ",", "T0", "=", "None", ",", "T1", "=", "None", ")", ":", "if", "T1", "is", "None", ":", "T1", "=", "abf", ".", "sweepLength", "if", "T0", "is", "None", ":", "T0", "=", "0", "data", "=", "[", ...
35.210526
14.210526
def clear(self) -> None: """ Treat as if the *underlying* database will also be cleared by some other mechanism. We build a special empty changeset just for marking that all previous data should be ignored. """ # these internal records are used as a way to tell the differ...
[ "def", "clear", "(", "self", ")", "->", "None", ":", "# these internal records are used as a way to tell the difference between", "# changes that came before and after the clear", "self", ".", "record_changeset", "(", ")", "self", ".", "_clears_at", ".", "add", "(", "self",...
44.090909
19.363636
def permlink(self, identifier): ''' Deconstructs an identifier into an account name and permlink ''' temp = identifier.split("@") temp2 = temp[1].split("/") return [temp2[0], temp2[1]]
[ "def", "permlink", "(", "self", ",", "identifier", ")", ":", "temp", "=", "identifier", ".", "split", "(", "\"@\"", ")", "temp2", "=", "temp", "[", "1", "]", ".", "split", "(", "\"/\"", ")", "return", "[", "temp2", "[", "0", "]", ",", "temp2", "[...
32.285714
8.571429
def delete_vnic_template_for_vlan(self, vlan_id): """Deletes VNIC Template for a vlan_id and physnet if it exists.""" with self.session.begin(subtransactions=True): try: self.session.query(ucsm_model.VnicTemplate).filter_by( vlan_id=vlan_id).delete() ...
[ "def", "delete_vnic_template_for_vlan", "(", "self", ",", "vlan_id", ")", ":", "with", "self", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "try", ":", "self", ".", "session", ".", "query", "(", "ucsm_model", ".", "VnicTempl...
46.5
12.625
def parse_cli_configuration(arguments: List[str]) -> CliConfiguration: """ Parses the configuration passed in via command line arguments. :param arguments: CLI arguments :return: the configuration """ try: parsed_arguments = {x.replace("_", "-"): y for x, y in vars(_argument_parser.parse...
[ "def", "parse_cli_configuration", "(", "arguments", ":", "List", "[", "str", "]", ")", "->", "CliConfiguration", ":", "try", ":", "parsed_arguments", "=", "{", "x", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ":", "y", "for", "x", ",", "y", "in", ...
44.32
23.4
def get_buildenv_graph(self): """Return a graph induced by buildenv nodes""" # This implementation first obtains all subsets of nodes that all # buildenvs depend on, and then builds a subgraph induced by the union # of these subsets. This can be very non-optimal. # TODO(itamar): ...
[ "def", "get_buildenv_graph", "(", "self", ")", ":", "# This implementation first obtains all subsets of nodes that all", "# buildenvs depend on, and then builds a subgraph induced by the union", "# of these subsets. This can be very non-optimal.", "# TODO(itamar): Reimplement efficient algo, or re...
57.333333
18.666667
def cmy(self): """ CMY: returned in range 0.0 - 1.0 CMY is subtractive, e.g. black: (1, 1, 1), white (0, 0, 0) """ r, g, b = self.color c = 1 - r m = 1 - g y = 1 - b return (c, m, y)
[ "def", "cmy", "(", "self", ")", ":", "r", ",", "g", ",", "b", "=", "self", ".", "color", "c", "=", "1", "-", "r", "m", "=", "1", "-", "g", "y", "=", "1", "-", "b", "return", "(", "c", ",", "m", ",", "y", ")" ]
22.272727
17.181818
def fetch(self, link, into=None): """Fetch the binary content associated with the link and write to a file. :param link: The :class:`Link` to fetch. :keyword into: If specified, write into the directory ``into``. If ``None``, creates a new temporary directory that persists for the duration of the in...
[ "def", "fetch", "(", "self", ",", "link", ",", "into", "=", "None", ")", ":", "target", "=", "os", ".", "path", ".", "join", "(", "into", "or", "safe_mkdtemp", "(", ")", ",", "link", ".", "filename", ")", "if", "os", ".", "path", ".", "exists", ...
39.095238
20.619048
def every_minute(dt=datetime.datetime.utcnow(), fmt=None): """ Just pass on the given date. """ date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, 1, 0, dt.tzinfo) if fmt is not None: return date.strftime(fmt) return date
[ "def", "every_minute", "(", "dt", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ",", "fmt", "=", "None", ")", ":", "date", "=", "datetime", ".", "datetime", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ".", "day", ",",...
33.375
15.875
def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': ...
[ "def", "_parse_caps_guest", "(", "guest", ")", ":", "arch_node", "=", "guest", ".", "find", "(", "'arch'", ")", "result", "=", "{", "'os_type'", ":", "guest", ".", "find", "(", "'os_type'", ")", ".", "text", ",", "'arch'", ":", "{", "'name'", ":", "a...
38.644444
19.355556
def average_repetitions(df, keys_mean): """average duplicate measurements. This requires that IDs and norrec labels were assigned using the *assign_norrec_to_df* function. Parameters ---------- df DataFrame keys_mean: list list of keys to average. For all other keys the first en...
[ "def", "average_repetitions", "(", "df", ",", "keys_mean", ")", ":", "if", "'norrec'", "not", "in", "df", ".", "columns", ":", "raise", "Exception", "(", "'The \"norrec\" column is required for this function to work!'", ")", "# Get column order to restore later", "cols", ...
33.382353
19.617647
def from_url(cls, url): "Construct a (possibly null) ContentChecker from a URL" fragment = urlparse(url)[-1] if not fragment: return ContentChecker() match = cls.pattern.search(fragment) if not match: return ContentChecker() return cls(**match.grou...
[ "def", "from_url", "(", "cls", ",", "url", ")", ":", "fragment", "=", "urlparse", "(", "url", ")", "[", "-", "1", "]", "if", "not", "fragment", ":", "return", "ContentChecker", "(", ")", "match", "=", "cls", ".", "pattern", ".", "search", "(", "fra...
35.555556
10.444444
def Rsync(url, tgt_name, tgt_root=None): """ RSync a folder. Args: url (str): The url of the SOURCE location. fname (str): The name of the TARGET. to (str): Path of the target location. Defaults to ``CFG["tmpdir"]``. """ if tgt_root is None: tgt_root = st...
[ "def", "Rsync", "(", "url", ",", "tgt_name", ",", "tgt_root", "=", "None", ")", ":", "if", "tgt_root", "is", "None", ":", "tgt_root", "=", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "rsy...
24.521739
15.130435
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Use schema_editor to apply any forward changes.""" self.truncate(app_label, schema_editor, self.truncate_forwards)
[ "def", "database_forwards", "(", "self", ",", "app_label", ",", "schema_editor", ",", "from_state", ",", "to_state", ")", ":", "self", ".", "truncate", "(", "app_label", ",", "schema_editor", ",", "self", ".", "truncate_forwards", ")" ]
69.333333
22.333333
def enabled(self): """ Check whether we're enabled (or if parent is). """ # Cache into ._enabled if self._enabled is None: if self.parent is not None and self.parent.enabled(): self._enabled = True else: # Default to Enabled if not otherwis...
[ "def", "enabled", "(", "self", ")", ":", "# Cache into ._enabled", "if", "self", ".", "_enabled", "is", "None", ":", "if", "self", ".", "parent", "is", "not", "None", "and", "self", ".", "parent", ".", "enabled", "(", ")", ":", "self", ".", "_enabled",...
42.1
15.5
def convert_boxed_text_elements(self): """ Textual material that is part of the body of text but outside the flow of the narrative text, for example, a sidebar, marginalia, text insert (whether enclosed in a box or not), caution, tip, note box, etc. <boxed-text> elements for PLo...
[ "def", "convert_boxed_text_elements", "(", "self", ")", ":", "for", "boxed_text", "in", "self", ".", "main", ".", "getroot", "(", ")", ".", "findall", "(", "'.//boxed-text'", ")", ":", "sec_el", "=", "boxed_text", ".", "find", "(", "'sec'", ")", "if", "s...
48.321429
16.678571
def exclude_from(l, containing = [], equal_to = []): """Exclude elements in list l containing any elements from list ex. Example: >>> l = ['bob', 'r', 'rob\r', '\r\nrobert'] >>> containing = ['\n', '\r'] >>> equal_to = ['r'] >>> exclude_from(l, containing, equal_to) ['bob...
[ "def", "exclude_from", "(", "l", ",", "containing", "=", "[", "]", ",", "equal_to", "=", "[", "]", ")", ":", "cont", "=", "lambda", "li", ":", "any", "(", "c", "in", "li", "for", "c", "in", "containing", ")", "eq", "=", "lambda", "li", ":", "an...
37.461538
13.307692
def sign_statement(self, statement, node_name, key_file, node_id, id_attr): """ Sign an XML statement. The parameters actually used in this CryptoBackend implementation are : :param statement: XML as string :param node_name: Name of the node to sign :param key_f...
[ "def", "sign_statement", "(", "self", ",", "statement", ",", "node_name", ",", "key_file", ",", "node_id", ",", "id_attr", ")", ":", "import", "xmlsec", "import", "lxml", ".", "etree", "xml", "=", "xmlsec", ".", "parse_xml", "(", "statement", ")", "signed"...
35.909091
16.272727
def submit_msql_object_query(object_query, client=None): """Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects. """ client = client or get_new_client(...
[ "def", "submit_msql_object_query", "(", "object_query", ",", "client", "=", "None", ")", ":", "client", "=", "client", "or", "get_new_client", "(", ")", "if", "not", "client", ".", "session_id", ":", "client", ".", "request_session", "(", ")", "result", "=",...
38.209302
21.488372
def install_tool(app, Cnt): ''' Install the requested software from the git 'repo' and check out the version given by 'sha1'. ''' # get the current working directory cwd = os.getcwd() # pick the target installation folder for tools if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='': ...
[ "def", "install_tool", "(", "app", ",", "Cnt", ")", ":", "# get the current working directory", "cwd", "=", "os", ".", "getcwd", "(", ")", "# pick the target installation folder for tools", "if", "'PATHTOOLS'", "in", "Cnt", "and", "Cnt", "[", "'PATHTOOLS'", "]", "...
39.206349
20.857143
def _set(self, obj, value): """Internal method to set state, called by meth:`StateTransition.__call__`""" if value not in self.lenum: raise ValueError("Not a valid value: %s" % value) type(obj).__dict__[self.propname].__set__(obj, value)
[ "def", "_set", "(", "self", ",", "obj", ",", "value", ")", ":", "if", "value", "not", "in", "self", ".", "lenum", ":", "raise", "ValueError", "(", "\"Not a valid value: %s\"", "%", "value", ")", "type", "(", "obj", ")", ".", "__dict__", "[", "self", ...
44.833333
16.666667
def _reset_page_refs(self): """Invalidate all pages in document dictionary.""" if self.isClosed: return for page in self._page_refs.values(): if page: page._erase() page = None self._page_refs.clear()
[ "def", "_reset_page_refs", "(", "self", ")", ":", "if", "self", ".", "isClosed", ":", "return", "for", "page", "in", "self", ".", "_page_refs", ".", "values", "(", ")", ":", "if", "page", ":", "page", ".", "_erase", "(", ")", "page", "=", "None", "...
31.111111
12
def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached']
[ "def", "is_target_temperature_reached", "(", "self", ",", "zone_name", ")", ":", "zone", "=", "self", ".", "get_zone", "(", "zone_name", ")", "if", "zone", "is", "None", ":", "raise", "RuntimeError", "(", "\"Unknown zone\"", ")", "return", "zone", "[", "'isT...
26.4
13