text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def gaussian(data, mean, covariance): """! @brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case multi-dimensional data. @param[in] data (list): Data that is used for gaussian calculation. @param[in] mean (float|n...
[ "def", "gaussian", "(", "data", ",", "mean", ",", "covariance", ")", ":", "dimension", "=", "float", "(", "len", "(", "data", "[", "0", "]", ")", ")", "if", "dimension", "!=", "1.0", ":", "inv_variance", "=", "numpy", ".", "linalg", ".", "pinv", "(...
36
26.151515
def display_outputs(self, groupby="type"): """republish the outputs of the computation Parameters ---------- groupby : str [default: type] if 'type': Group outputs by type (show all stdout, then all stderr, etc.): ...
[ "def", "display_outputs", "(", "self", ",", "groupby", "=", "\"type\"", ")", ":", "if", "self", ".", "_single_result", ":", "self", ".", "_display_single_result", "(", ")", "return", "stdouts", "=", "self", ".", "stdout", "stderrs", "=", "self", ".", "stde...
37.306931
18.29703
def bootstrap_datapackage(repo, force=False, options=None, noinput=False): """ Create the datapackage file.. """ print("Bootstrapping datapackage") # get the directory tsprefix = datetime.now().date().isoformat() # Initial data package json package = OrderedD...
[ "def", "bootstrap_datapackage", "(", "repo", ",", "force", "=", "False", ",", "options", "=", "None", ",", "noinput", "=", "False", ")", ":", "print", "(", "\"Bootstrapping datapackage\"", ")", "# get the directory", "tsprefix", "=", "datetime", ".", "now", "(...
27.884615
17.730769
def update(cls, whitelist_sdd_id, monetary_account_paying_id=None, maximum_amount_per_month=None, custom_headers=None): """ :type user_id: int :type whitelist_sdd_id: int :param monetary_account_paying_id: ID of the monetary account of which you want to pay from. ...
[ "def", "update", "(", "cls", ",", "whitelist_sdd_id", ",", "monetary_account_paying_id", "=", "None", ",", "maximum_amount_per_month", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{...
40.891892
22.621622
def format_level_1_memory(memory): """ Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 c...
[ "def", "format_level_1_memory", "(", "memory", ")", ":", "formatted_memory", "=", "_list_to_complex_array", "(", "memory", ")", "# infer meas_return from shape of returned data.", "if", "not", "1", "<=", "len", "(", "formatted_memory", ".", "shape", ")", "<=", "2", ...
37.052632
22.894737
def handle_import_tags(userdata, import_root): """Handle @import(filepath)@ tags in a UserData script. :param import_root: Location for imports. :type import_root: str :param userdata: UserData script content. :type userdata: str :return: UserData script with the content...
[ "def", "handle_import_tags", "(", "userdata", ",", "import_root", ")", ":", "imports", "=", "re", ".", "findall", "(", "'@import\\((.*?)\\)@'", ",", "userdata", ")", "# pylint: disable=anomalous-backslash-in-string", "if", "not", "imports", ":", "return", "userdata", ...
40.44
20.44
def generate_PID_name(self, prefix=None): ''' Generate a unique random Handle name (random UUID). The Handle is not registered. If a prefix is specified, the PID name has the syntax <prefix>/<generatedname>, otherwise it just returns the generated random name (suffix for the Hand...
[ "def", "generate_PID_name", "(", "self", ",", "prefix", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "'generate_PID_name...'", ")", "randomuuid", "=", "uuid", ".", "uuid4", "(", ")", "if", "prefix", "is", "not", "None", ":", "return", "prefix", "+...
37.473684
22.526316
def new(cls, num_id, abstractNum_id): """ Return a new ``<w:num>`` element having numId of *num_id* and having a ``<w:abstractNumId>`` child with val attribute set to *abstractNum_id*. """ num = OxmlElement('w:num') num.numId = num_id abstractNumId = CT_De...
[ "def", "new", "(", "cls", ",", "num_id", ",", "abstractNum_id", ")", ":", "num", "=", "OxmlElement", "(", "'w:num'", ")", "num", ".", "numId", "=", "num_id", "abstractNumId", "=", "CT_DecimalNumber", ".", "new", "(", "'w:abstractNumId'", ",", "abstractNum_id...
33.307692
12.846154
def serialize_wrapped_key(key_provider, wrapping_algorithm, wrapping_key_id, encrypted_wrapped_key): """Serializes EncryptedData into a Wrapped EncryptedDataKey. :param key_provider: Info for Wrapping MasterKey :type key_provider: aws_encryption_sdk.structures.MasterKeyInfo :param wrapping_algorithm: W...
[ "def", "serialize_wrapped_key", "(", "key_provider", ",", "wrapping_algorithm", ",", "wrapping_key_id", ",", "encrypted_wrapped_key", ")", ":", "if", "encrypted_wrapped_key", ".", "iv", "is", "None", ":", "key_info", "=", "wrapping_key_id", "key_ciphertext", "=", "enc...
49.903226
22.903226
def uri_unsplit_tree(uri_tree): """ Unsplit a coded URI tree, which must also be coalesced by uri_tree_normalize(). """ scheme, authority, path, query, fragment = uri_tree if authority: user, passwd, host, port = authority if user and passwd: userinfo = user + ':' + p...
[ "def", "uri_unsplit_tree", "(", "uri_tree", ")", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "uri_tree", "if", "authority", ":", "user", ",", "passwd", ",", "host", ",", "port", "=", "authority", "if", "user", "and",...
25.9375
15.1875
def string_to_locale(value, strict=True): """ Return an instance ``Locale`` corresponding to the string representation of a locale. @param value: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash character ``-`` and a IS...
[ "def", "string_to_locale", "(", "value", ",", "strict", "=", "True", ")", ":", "try", ":", "return", "None", "if", "is_undefined", "(", "value", ")", "else", "Locale", ".", "from_string", "(", "value", ",", "strict", "=", "strict", ")", "except", "Locale...
39.2
22.5
def options(self, **kwds): """ Change options for interactive functions. Returns ------- A new :class:`_InteractFactory` which will apply the options when called. """ opts = dict(self.opts) for k in kwds: try: # Ensure ...
[ "def", "options", "(", "self", ",", "*", "*", "kwds", ")", ":", "opts", "=", "dict", "(", "self", ".", "opts", ")", "for", "k", "in", "kwds", ":", "try", ":", "# Ensure that the key exists because we want to change", "# existing options, not add new ones.", "_",...
32.052632
16.578947
def get_masked_cnv_manifest(tcga_id): """Get manifest for masked TCGA copy-number variation data. Params ------ tcga_id : str The TCGA project ID. download_file : str The path of the download file. Returns ------- `pandas.DataFrame` The manifest. ...
[ "def", "get_masked_cnv_manifest", "(", "tcga_id", ")", ":", "payload", "=", "{", "\"filters\"", ":", "json", ".", "dumps", "(", "{", "\"op\"", ":", "\"and\"", ",", "\"content\"", ":", "[", "{", "\"op\"", ":", "\"in\"", ",", "\"content\"", ":", "{", "\"fi...
29.875
18
def jobUpdateResults(self, jobID, results): """ Update the results string and last-update-time fields of a model. Parameters: ---------------------------------------------------------------- jobID: job ID of model to modify results: new results (json dict string) """ with Connection...
[ "def", "jobUpdateResults", "(", "self", ",", "jobID", ",", "results", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), '", "' results=%%s '", "' WHE...
43.461538
13.461538
def write_line_list(argname, cmd, basename, filename): """ Write out the retrieved value as list of lines. """ values = getattr(cmd.distribution, argname, None) if isinstance(values, list): values = '\n'.join(values) cmd.write_or_delete_file(argname, filename, values, force=True)
[ "def", "write_line_list", "(", "argname", ",", "cmd", ",", "basename", ",", "filename", ")", ":", "values", "=", "getattr", "(", "cmd", ".", "distribution", ",", "argname", ",", "None", ")", "if", "isinstance", "(", "values", ",", "list", ")", ":", "va...
33.888889
13.222222
def remove_update_callback(self, group, name=None, cb=None): """Remove the supplied callback for a group or a group.name""" if not cb: return if not name: if group in self.group_update_callbacks: self.group_update_callbacks[group].remove_callback(cb) ...
[ "def", "remove_update_callback", "(", "self", ",", "group", ",", "name", "=", "None", ",", "cb", "=", "None", ")", ":", "if", "not", "cb", ":", "return", "if", "not", "name", ":", "if", "group", "in", "self", ".", "group_update_callbacks", ":", "self",...
41.833333
21.166667
def name(self, filetype, **kwargs): """Return the directory containing a file of a given type. Parameters ---------- filetype : str File type parameter. Returns ------- name : str Name of a file with no directory information. """ ...
[ "def", "name", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "full", "=", "kwargs", ".", "get", "(", "'full'", ",", "None", ")", "if", "not", "full", ":", "full", "=", "self", ".", "full", "(", "filetype", ",", "*", "*", "kwa...
23.736842
18.736842
async def post(self, public_key, coinid): """Writes content to blockchain Accepts: Query string args: - "public_key" - str - "coin id" - str Request body arguments: - message (signed dict as json): - "cus" (content) - str - "description" - str - "read_access" (price for read access...
[ "async", "def", "post", "(", "self", ",", "public_key", ",", "coinid", ")", ":", "logging", ".", "debug", "(", "\"[+] -- Post content debugging. \"", ")", "#if settings.SIGNATURE_VERIFICATION:", "#\tsuper().verify()", "# Define genesis variables", "if", "coinid", "in", ...
28.261682
19.233645
def decrypt(*args, **kwargs): """ Decrypts legacy or spec-compliant JOSE token. First attempts to decrypt the token in a legacy mode (https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-19). If it is not a valid legacy token then attempts to decrypt it in a spec-compliant way (http://tools.i...
[ "def", "decrypt", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "legacy_decrypt", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "NotYetValid", ",", "Expired", ")", "as", "e", ":", "# these should be raised ...
44.875
15.25
def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
[ "def", "clean_honeypot", "(", "self", ")", ":", "value", "=", "self", ".", "cleaned_data", "[", "\"honeypot\"", "]", "if", "value", ":", "raise", "forms", ".", "ValidationError", "(", "self", ".", "fields", "[", "\"honeypot\"", "]", ".", "label", ")", "r...
40.5
15.5
def record_markdown(text, cellid): """Records the specified markdown text to the acorn database. Args: text (str): the *raw* markdown text entered into the cell in the ipython notebook. """ from acorn.logging.database import record from time import time ekey = "nb-{}".format(c...
[ "def", "record_markdown", "(", "text", ",", "cellid", ")", ":", "from", "acorn", ".", "logging", ".", "database", "import", "record", "from", "time", "import", "time", "ekey", "=", "\"nb-{}\"", ".", "format", "(", "cellid", ")", "global", "_cellid_map", "i...
33.787234
16.808511
def _try_run(self, run_func: Callable[[], None]) -> None: """ Try running the given function (training/prediction). Calls - :py:meth:`cxflow.hooks.AbstractHook.before_training` - :py:meth:`cxflow.hooks.AbstractHook.after_training` :param run_func: function to be...
[ "def", "_try_run", "(", "self", ",", "run_func", ":", "Callable", "[", "[", "]", ",", "None", "]", ")", "->", "None", ":", "# Initialization: before_training", "for", "hook", "in", "self", ".", "_hooks", ":", "hook", ".", "before_training", "(", ")", "tr...
30.363636
16.818182
def register_previewer(self, name, previewer): """Register a previewer in the system.""" if name in self.previewers: assert name not in self.previewers, \ "Previewer with same name already registered" self.previewers[name] = previewer if hasattr(previewer, 'pr...
[ "def", "register_previewer", "(", "self", ",", "name", ",", "previewer", ")", ":", "if", "name", "in", "self", ".", "previewers", ":", "assert", "name", "not", "in", "self", ".", "previewers", ",", "\"Previewer with same name already registered\"", "self", ".", ...
48.222222
8.333333
def get_genomic_seq_for_transcript(self, transcript_id, expand): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/sequence/id/{0}?type=genomic;expand_3prime={1};expand_5prime={1}".f...
[ "def", "get_genomic_seq_for_transcript", "(", "self", ",", "transcript_id", ",", "expand", ")", ":", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", "}", "self", ".", "attempt", "=", "0", "ext", "=", "\"/sequence/id/{0}?type=genomic;expand_3prime...
31.103448
18.758621
def get_shard_by_key_id(self, key_id): """ get_shard_by_key_id returns the Redis shard given a key id. Keyword arguments: key_id -- the key id (e.g. '12345') This is similar to get_shard_by_key(key) except that it will not search for a key id within the curly braces. ...
[ "def", "get_shard_by_key_id", "(", "self", ",", "key_id", ")", ":", "shard_num", "=", "self", ".", "get_shard_num_by_key_id", "(", "key_id", ")", "return", "self", ".", "get_shard_by_num", "(", "shard_num", ")" ]
39.083333
13.25
def execute_reliabledictionary(client, application_name, service_name, input_file): """Execute create, update, delete operations on existing reliable dictionaries. carry out create, update and delete operations on existing reliable dictionaries for given application and service. :param application_name: N...
[ "def", "execute_reliabledictionary", "(", "client", ",", "application_name", ",", "service_name", ",", "input_file", ")", ":", "cluster", "=", "Cluster", ".", "from_sfclient", "(", "client", ")", "service", "=", "cluster", ".", "get_application", "(", "application...
42.85
24.25
def run_script(self, script_id, params=None): """ Runs a stored script. script_id:= id of stored script. params:= up to 10 parameters required by the script. ... s = pi.run_script(sid, [par1, par2]) s = pi.run_script(sid) s = pi.run_script(sid, [1, 2,...
[ "def", "run_script", "(", "self", ",", "script_id", ",", "params", "=", "None", ")", ":", "# I p1 script id", "# I p2 0", "# I p3 params * 4 (0-10 params)", "# (optional) extension", "# I[] params", "if", "params", "is", "not", "None", ":", "ext", "=", "bytearray", ...
28.46875
18.09375
def str_to_inet(address): """Convert an a string IP address to a inet struct Args: address (str): String representation of address Returns: inet: Inet network address """ # First try ipv4 and then ipv6 try: return socket.inet_pton(socket.AF_INET, address)...
[ "def", "str_to_inet", "(", "address", ")", ":", "# First try ipv4 and then ipv6", "try", ":", "return", "socket", ".", "inet_pton", "(", "socket", ".", "AF_INET", ",", "address", ")", "except", "socket", ".", "error", ":", "return", "socket", ".", "inet_pton",...
30.076923
16.461538
def ReadHuntObject(self, hunt_id): """Reads a hunt object from the database.""" try: return self._DeepCopy(self.hunts[hunt_id]) except KeyError: raise db.UnknownHuntError(hunt_id)
[ "def", "ReadHuntObject", "(", "self", ",", "hunt_id", ")", ":", "try", ":", "return", "self", ".", "_DeepCopy", "(", "self", ".", "hunts", "[", "hunt_id", "]", ")", "except", "KeyError", ":", "raise", "db", ".", "UnknownHuntError", "(", "hunt_id", ")" ]
33
11
def _sanitize(cls, message): """ Sanitize the given message, dealing with multiple arguments and/or string formatting. :param message: the log message to be sanitized :type message: string or list of strings :rtype: string """ if isinstance(messa...
[ "def", "_sanitize", "(", "cls", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "list", ")", ":", "if", "len", "(", "message", ")", "==", "0", ":", "sanitized", "=", "u\"Empty log message\"", "elif", "len", "(", "message", ")", "==",...
33.363636
11.909091
def addRelationships( self, data: list, LIMIT: int = 20, _print: bool = True, crawl: bool = False, ) -> list: """ data = [{ "term1_id", "term2_id", "relationship_tid", "term1_version", "term2_version", "relationship_term...
[ "def", "addRelationships", "(", "self", ",", "data", ":", "list", ",", "LIMIT", ":", "int", "=", "20", ",", "_print", ":", "bool", "=", "True", ",", "crawl", ":", "bool", "=", "False", ",", ")", "->", "list", ":", "url_base", "=", "self", ".", "b...
33
16.103448
def colum_avg(self, state): """Toggle backgroundcolor""" self.colum_avg_enabled = state > 0 if self.colum_avg_enabled: self.return_max = lambda col_vals, index: col_vals[index] else: self.return_max = global_max self.reset()
[ "def", "colum_avg", "(", "self", ",", "state", ")", ":", "self", ".", "colum_avg_enabled", "=", "state", ">", "0", "if", "self", ".", "colum_avg_enabled", ":", "self", ".", "return_max", "=", "lambda", "col_vals", ",", "index", ":", "col_vals", "[", "ind...
36
12.125
def export_dist(self, args): """Copies a created dist to an output dir. This makes it easy to navigate to the dist to investigate it or call build.py, though you do not in general need to do this and can use the apk command instead. """ ctx = self.ctx dist = dist...
[ "def", "export_dist", "(", "self", ",", "args", ")", ":", "ctx", "=", "self", ".", "ctx", "dist", "=", "dist_from_args", "(", "ctx", ",", "args", ")", "if", "dist", ".", "needs_build", ":", "raise", "BuildInterruptingException", "(", "'You asked to export a ...
42.722222
17.666667
def nifti_out(f): """ Picks a function whose first argument is an `img`, processes its data and returns a numpy array. This decorator wraps this numpy array into a nibabel.Nifti1Image.""" @wraps(f) def wrapped(*args, **kwargs): r = f(*args, **kwargs) img = read_img(args[0]) ...
[ "def", "nifti_out", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "r", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "img", "=", "read_img", "(", "args", ...
33.166667
20.666667
def do_blame(self, subcmd, opts, *args): """Output the content of specified files or URLs with revision and author information in-line. usage: blame TARGET... ${cmd_option_list} """ print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' a...
[ "def", "do_blame", "(", "self", ",", "subcmd", ",", "opts", ",", "*", "args", ")", ":", "print", "\"'svn %s' opts: %s\"", "%", "(", "subcmd", ",", "opts", ")", "print", "\"'svn %s' args: %s\"", "%", "(", "subcmd", ",", "args", ")" ]
30.454545
14.818182
def merge(self, merge_func=None, merge_key=None, stash='active'): """ Merge the states in a given stash. :param stash: The stash (default: 'active') :param merge_func: If provided, instead of using state.merge, call this function with the states as the...
[ "def", "merge", "(", "self", ",", "merge_func", "=", "None", ",", "merge_key", "=", "None", ",", "stash", "=", "'active'", ")", ":", "self", ".", "prune", "(", "from_stash", "=", "stash", ")", "to_merge", "=", "self", ".", "_fetch_states", "(", "stash"...
43.358974
23.461538
def score( self, X_test, Y_test, b=0.5, pos_label=1, set_unlabeled_as_neg=True, beta=1 ): """ Returns the summary scores: * For binary: precision, recall, F-beta score, ROC-AUC score * For categorical: accuracy :param X_test: The input test candidates. ...
[ "def", "score", "(", "self", ",", "X_test", ",", "Y_test", ",", "b", "=", "0.5", ",", "pos_label", "=", "1", ",", "set_unlabeled_as_neg", "=", "True", ",", "beta", "=", "1", ")", ":", "if", "self", ".", "_check_input", "(", "X_test", ")", ":", "X_t...
36.337838
19.851351
def search(self, search_content, search_type, limit=9): """Search entrance. :params search_content: search content. :params search_type: search type. :params limit: result count returned by weapi. :return: a dict. """ url = 'http://music.163.com/weapi/cloudsearc...
[ "def", "search", "(", "self", ",", "search_content", ",", "search_type", ",", "limit", "=", "9", ")", ":", "url", "=", "'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='", "params", "=", "{", "'s'", ":", "search_content", ",", "'type'", ":", "search_typ...
37.285714
16.714286
def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a formset instance with the passed POST variables and then checked for validity. """ formset = self.construct_formset() if formset.is_valid(): return self.formset_valid(formset)...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "formset", "=", "self", ".", "construct_formset", "(", ")", "if", "formset", ".", "is_valid", "(", ")", ":", "return", "self", ".", "formset_valid", "(",...
37.4
10.6
def all_experiments(self): """ Similar to experiments, but uses the default manager to return archived experiments as well. """ from db.models.experiments import Experiment return Experiment.all.filter(experiment_group=self)
[ "def", "all_experiments", "(", "self", ")", ":", "from", "db", ".", "models", ".", "experiments", "import", "Experiment", "return", "Experiment", ".", "all", ".", "filter", "(", "experiment_group", "=", "self", ")" ]
33.25
16.25
def push_not_registered_user_data_task(data): """ Async: push_not_registered_user_data_task.apply_async(args=[data], countdown=100) """ lock_id = "%s-push-not-registered-user-data-task-%s" % (settings.ENV_PREFIX, data["email"]) acquire_lock = lambda: cache.add(lock_id, "true", LOCK_EXPIRE) # noqa: ...
[ "def", "push_not_registered_user_data_task", "(", "data", ")", ":", "lock_id", "=", "\"%s-push-not-registered-user-data-task-%s\"", "%", "(", "settings", ".", "ENV_PREFIX", ",", "data", "[", "\"email\"", "]", ")", "acquire_lock", "=", "lambda", ":", "cache", ".", ...
40.266667
23.466667
def _fixupRandomEncoderParams(params, minVal, maxVal, minResolution): """ Given model params, figure out the correct parameters for the RandomDistributed encoder. Modifies params in place. """ encodersDict = ( params["modelConfig"]["modelParams"]["sensorParams"]["encoders"] ) for encoder in encodersD...
[ "def", "_fixupRandomEncoderParams", "(", "params", ",", "minVal", ",", "maxVal", ",", "minResolution", ")", ":", "encodersDict", "=", "(", "params", "[", "\"modelConfig\"", "]", "[", "\"modelParams\"", "]", "[", "\"sensorParams\"", "]", "[", "\"encoders\"", "]",...
37.6875
18.0625
def _formatEvidence(self, elements): """ Formats elements passed into parts of a query for filtering """ elementClause = None filters = [] for evidence in elements: if evidence.description: elementClause = 'regex(?{}, "{}")'.format( ...
[ "def", "_formatEvidence", "(", "self", ",", "elements", ")", ":", "elementClause", "=", "None", "filters", "=", "[", "]", "for", "evidence", "in", "elements", ":", "if", "evidence", ".", "description", ":", "elementClause", "=", "'regex(?{}, \"{}\")'", ".", ...
46.5
15.5
def delete_buckets(cls, record): """Delete the bucket.""" files = record.get('_files', []) buckets = set() for f in files: buckets.add(f.get('bucket')) for b_id in buckets: b = Bucket.get(b_id) b.deleted = True
[ "def", "delete_buckets", "(", "cls", ",", "record", ")", ":", "files", "=", "record", ".", "get", "(", "'_files'", ",", "[", "]", ")", "buckets", "=", "set", "(", ")", "for", "f", "in", "files", ":", "buckets", ".", "add", "(", "f", ".", "get", ...
30.888889
8.222222
def validate_schema_dict(schema): # type: (Dict[str, Any]) -> None """ Validate the schema. This raises iff either the schema or the master schema are invalid. If it's successful, it returns nothing. :param schema: The schema to validate, as parsed by `json`. :raises SchemaErro...
[ "def", "validate_schema_dict", "(", "schema", ")", ":", "# type: (Dict[str, Any]) -> None", "if", "not", "isinstance", "(", "schema", ",", "dict", ")", ":", "msg", "=", "(", "'The top level of the schema file is a {}, whereas a dict is '", "'expected.'", ".", "format", ...
41.589744
20.282051
async def hmset(self, name, mapping): """ Set key to value within hash ``name`` for each corresponding key and value from the ``mapping`` dict. """ if not mapping: raise DataError("'hmset' with 'mapping' of length 0") items = [] for pair in iteritems(m...
[ "async", "def", "hmset", "(", "self", ",", "name", ",", "mapping", ")", ":", "if", "not", "mapping", ":", "raise", "DataError", "(", "\"'hmset' with 'mapping' of length 0\"", ")", "items", "=", "[", "]", "for", "pair", "in", "iteritems", "(", "mapping", ")...
37.636364
12.545455
def generate_key_pair(size=512, number=2, rnd=default_crypto_random, k=DEFAULT_ITERATION, primality_algorithm=None, strict_size=True, e=0x10001): '''Generates an RSA key pair. size: the bit size of the modulus, default to 512. number: ...
[ "def", "generate_key_pair", "(", "size", "=", "512", ",", "number", "=", "2", ",", "rnd", "=", "default_crypto_random", ",", "k", "=", "DEFAULT_ITERATION", ",", "primality_algorithm", "=", "None", ",", "strict_size", "=", "True", ",", "e", "=", "0x10001", ...
32.903846
20.25
def modify_snapshot_attribute(self, snapshot_id, attribute='createVolumePermission', operation='add', user_ids=None, groups=None): """ Changes an attribute of an image. :type snapshot_id: string :param snapshot_id: The ...
[ "def", "modify_snapshot_attribute", "(", "self", ",", "snapshot_id", ",", "attribute", "=", "'createVolumePermission'", ",", "operation", "=", "'add'", ",", "user_ids", "=", "None", ",", "groups", "=", "None", ")", ":", "params", "=", "{", "'SnapshotId'", ":",...
39.151515
21.090909
def pkcs_mgf1(mgfSeed, maskLen, h): """ Implements generic MGF1 Mask Generation function as described in Appendix B.2.1 of RFC 3447. The hash function is passed by name. valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256', 'sha384' and 'sha512'. Returns None on error. Input: mgf...
[ "def", "pkcs_mgf1", "(", "mgfSeed", ",", "maskLen", ",", "h", ")", ":", "# steps are those of Appendix B.2.1", "if", "not", "h", "in", "_hashFuncParams", ":", "warning", "(", "\"pkcs_mgf1: invalid hash (%s) provided\"", ")", "return", "None", "hLen", "=", "_hashFunc...
37.75
18.75
def _handle_dl_term(self): """Handle the term in a description list (``foo`` in ``;foo:bar``).""" self._context ^= contexts.DL_TERM if self._read() == ":": self._handle_list_marker() else: self._emit_text("\n")
[ "def", "_handle_dl_term", "(", "self", ")", ":", "self", ".", "_context", "^=", "contexts", ".", "DL_TERM", "if", "self", ".", "_read", "(", ")", "==", "\":\"", ":", "self", ".", "_handle_list_marker", "(", ")", "else", ":", "self", ".", "_emit_text", ...
37.142857
8.571429
def __validate_decode_msg(self, message): # noqa (complexity) pylint: disable=too-many-return-statements,too-many-branches """Decodes wrapper, check hash & seq, decodes body. Returns body or None, if validation / unpack failed""" try: if not _CONTENT_TYPE_PATTERN.match(message.content_type)...
[ "def", "__validate_decode_msg", "(", "self", ",", "message", ")", ":", "# noqa (complexity) pylint: disable=too-many-return-statements,too-many-branches", "try", ":", "if", "not", "_CONTENT_TYPE_PATTERN", ".", "match", "(", "message", ".", "content_type", ")", ":", "logge...
43.5
26.535714
def sendImage( self, image_id, message=None, thread_id=None, thread_type=ThreadType.USER, is_gif=False, ): """ Deprecated. Use :func:`fbchat.Client._sendFiles` instead """ if is_gif: mimetype = "image/gif" else: ...
[ "def", "sendImage", "(", "self", ",", "image_id", ",", "message", "=", "None", ",", "thread_id", "=", "None", ",", "thread_type", "=", "ThreadType", ".", "USER", ",", "is_gif", "=", "False", ",", ")", ":", "if", "is_gif", ":", "mimetype", "=", "\"image...
24.428571
15.190476
def setup_users_page(self, ): """Create and set the model on the users page :returns: None :rtype: None :raises: None """ self.users_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) log.debug("Loading users for users page.") roo...
[ "def", "setup_users_page", "(", "self", ",", ")", ":", "self", ".", "users_tablev", ".", "horizontalHeader", "(", ")", ".", "setResizeMode", "(", "QtGui", ".", "QHeaderView", ".", "ResizeToContents", ")", "log", ".", "debug", "(", "\"Loading users for users page...
41
16.764706
def get_absolute_url(self): """produces a url to link directly to this instance, given the URL config :return: `str` """ try: url = reverse("content-detail-view", kwargs={"pk": self.pk, "slug": self.slug}) except NoReverseMatch: url = None return ...
[ "def", "get_absolute_url", "(", "self", ")", ":", "try", ":", "url", "=", "reverse", "(", "\"content-detail-view\"", ",", "kwargs", "=", "{", "\"pk\"", ":", "self", ".", "pk", ",", "\"slug\"", ":", "self", ".", "slug", "}", ")", "except", "NoReverseMatch...
31.4
20
def authenticate_search_bind(self, username, password): """ Performs a search bind to authenticate a user. This is required when a the login attribute is not the same as the RDN, since we cannot string together their DN on the fly, instead we have to find it in the LDAP, then att...
[ "def", "authenticate_search_bind", "(", "self", ",", "username", ",", "password", ")", ":", "connection", "=", "self", ".", "_make_connection", "(", "bind_user", "=", "self", ".", "config", ".", "get", "(", "'LDAP_BIND_USER_DN'", ")", ",", "bind_password", "="...
39.396552
21.327586
def on_send(self, frame): """ :param Frame frame: """ print('on_send %s %s %s' % (frame.cmd, frame.headers, frame.body))
[ "def", "on_send", "(", "self", ",", "frame", ")", ":", "print", "(", "'on_send %s %s %s'", "%", "(", "frame", ".", "cmd", ",", "frame", ".", "headers", ",", "frame", ".", "body", ")", ")" ]
29.6
12.4
def delete(self): """Delete this experiment and all its data.""" for alternative in self.alternatives: alternative.delete() self.reset_winner() self.redis.srem('experiments', self.name) self.redis.delete(self.name) self.increment_version()
[ "def", "delete", "(", "self", ")", ":", "for", "alternative", "in", "self", ".", "alternatives", ":", "alternative", ".", "delete", "(", ")", "self", ".", "reset_winner", "(", ")", "self", ".", "redis", ".", "srem", "(", "'experiments'", ",", "self", "...
36.5
8.75
def cmd(send, msg, args): """Slap somebody. Syntax: {command} <nick> [for <reason>] """ implements = ['the golden gate bridge', 'a large trout', 'a clue-by-four', 'a fresh haddock', 'moon', 'an Itanium', 'fwilson', 'a wombat'] methods = ['around a bit', 'upside the head'] if not msg: c...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "implements", "=", "[", "'the golden gate bridge'", ",", "'a large trout'", ",", "'a clue-by-four'", ",", "'a fresh haddock'", ",", "'moon'", ",", "'an Itanium'", ",", "'fwilson'", ",", "'a wombat'", ...
34.836066
17.52459
def match_host(host, pattern): ''' Match a host string against a pattern Args: host (str) A hostname to compare to the given pattern pattern (str) A string representing a hostname pattern, possibly including wildcards for ip address octets or ports. Thi...
[ "def", "match_host", "(", "host", ",", "pattern", ")", ":", "if", "':'", "in", "host", ":", "host", ",", "host_port", "=", "host", ".", "rsplit", "(", "':'", ",", "1", ")", "else", ":", "host_port", "=", "None", "if", "':'", "in", "pattern", ":", ...
25.571429
21.857143
def check_rollout(edits_service, package_name, days): """Check if package_name has a release on staged rollout for too long""" edit = edits_service.insert(body={}, packageName=package_name).execute() response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execu...
[ "def", "check_rollout", "(", "edits_service", ",", "package_name", ",", "days", ")", ":", "edit", "=", "edits_service", ".", "insert", "(", "body", "=", "{", "}", ",", "packageName", "=", "package_name", ")", ".", "execute", "(", ")", "response", "=", "e...
60.0625
24.0625
def calculate_power_output(weather, example_farm, example_cluster): r""" Calculates power output of wind farms and clusters using the :class:`~.turbine_cluster_modelchain.TurbineClusterModelChain`. The :class:`~.turbine_cluster_modelchain.TurbineClusterModelChain` is a class that provides all neces...
[ "def", "calculate_power_output", "(", "weather", ",", "example_farm", ",", "example_cluster", ")", ":", "# set efficiency of example_farm to apply wake losses", "example_farm", ".", "efficiency", "=", "0.9", "# power output calculation for example_farm", "# initialize TurbineCluste...
51.029412
23.779412
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element): """ Adds to graph the new element that represents BPMN parallel gateway. Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability. :param diagram...
[ "def", "import_parallel_gateway_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "element", ")", ":", "BpmnDiagramGraphImport", ".", "import_gateway_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "ele...
66.083333
39.083333
def _process_execs(self, contents, modulename, atype, mode="insert"): """Extracts all the executable methods that belong to the type.""" #We only want to look at text after the contains statement match = self.RE_CONTAINS.search(contents) #It is possible for the type to not have any exec...
[ "def", "_process_execs", "(", "self", ",", "contents", ",", "modulename", ",", "atype", ",", "mode", "=", "\"insert\"", ")", ":", "#We only want to look at text after the contains statement", "match", "=", "self", ".", "RE_CONTAINS", ".", "search", "(", "contents", ...
52.555556
20.111111
def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3, as_list=False): """Random paragraphs.""" if html: wrap_start = '<p>' wrap_end = '</p>' separator = '\n\n' result = [] for i in xrange(0, quantity): r...
[ "def", "paragraphs", "(", "quantity", "=", "2", ",", "separator", "=", "'\\n\\n'", ",", "wrap_start", "=", "''", ",", "wrap_end", "=", "''", ",", "html", "=", "False", ",", "sentences_quantity", "=", "3", ",", "as_list", "=", "False", ")", ":", "if", ...
28.6875
22.0625
def forward(self, address, types=None, lon=None, lat=None, country=None, bbox=None, limit=None, languages=None): """Returns a Requests response object that contains a GeoJSON collection of places matching the given address. `response.geojson()` returns the geocoding result as Ge...
[ "def", "forward", "(", "self", ",", "address", ",", "types", "=", "None", ",", "lon", "=", "None", ",", "lat", "=", "None", ",", "country", "=", "None", ",", "bbox", "=", "None", ",", "limit", "=", "None", ",", "languages", "=", "None", ")", ":",...
42.789474
20.578947
def download_ncbi_associations(gene2go="gene2go", prt=sys.stdout, loading_bar=True): """Download associations from NCBI, if necessary""" # Download: ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz gzip_file = "{GENE2GO}.gz".format(GENE2GO=gene2go) if not os.path.isfile(gene2go): file_remote = "f...
[ "def", "download_ncbi_associations", "(", "gene2go", "=", "\"gene2go\"", ",", "prt", "=", "sys", ".", "stdout", ",", "loading_bar", "=", "True", ")", ":", "# Download: ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz", "gzip_file", "=", "\"{GENE2GO}.gz\"", ".", "format",...
48.5
19.083333
def on_parallel_port_change(self, parallel_port): """Triggered when settings of a parallel port of the associated virtual machine have changed. in parallel_port of type :class:`IParallelPort` raises :class:`VBoxErrorInvalidVmState` Session state prevents operation. ...
[ "def", "on_parallel_port_change", "(", "self", ",", "parallel_port", ")", ":", "if", "not", "isinstance", "(", "parallel_port", ",", "IParallelPort", ")", ":", "raise", "TypeError", "(", "\"parallel_port can only be an instance of type IParallelPort\"", ")", "self", "."...
38.588235
16.058824
def potential_physical_input(method): """Decorator to convert inputs to Potential functions from physical to internal coordinates""" @wraps(method) def wrapper(*args,**kwargs): from galpy.potential import flatten as flatten_potential Pot= flatten_potential(args[0]) ro= kwargs.ge...
[ "def", "potential_physical_input", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "galpy", ".", "potential", "import", "flatten", "as", "flatten_potential", "Pot", ...
45.114286
12.114286
def is_full_mxid(user_string): """Returns True if a string is a valid mxid.""" if not user_string[0] == "@": return False parts = user_string[1:].split(":") localpart_chars = ascii_lowercase + digits + "._-=" if not (len(parts) == 2 and all([i in localpart_chars for i in parts[0]])): ...
[ "def", "is_full_mxid", "(", "user_string", ")", ":", "if", "not", "user_string", "[", "0", "]", "==", "\"@\"", ":", "return", "False", "parts", "=", "user_string", "[", "1", ":", "]", ".", "split", "(", "\":\"", ")", "localpart_chars", "=", "ascii_lowerc...
37.888889
15.333333
def kde_histogram(events_x, events_y, xout=None, yout=None, bins=None): """ Histogram-based Kernel Density Estimation Parameters ---------- events_x, events_y: 1D ndarray The input points for kernel density estimation. Input is flattened automatically. xout, yout: ndarray Th...
[ "def", "kde_histogram", "(", "events_x", ",", "events_y", ",", "xout", "=", "None", ",", "yout", "=", "None", ",", "bins", "=", "None", ")", ":", "valid_combi", "=", "(", "(", "xout", "is", "None", "and", "yout", "is", "None", ")", "or", "(", "xout...
31.745098
18.254902
def _ctypes_regular(parameter): """Returns the code lines to define a *local* variable with the fortran types that has a matching signature to the wrapped executable. """ if ("pointer" in parameter.modifiers or "allocatable" in parameter.modifiers or "target" in parameter.modifiers or parameter....
[ "def", "_ctypes_regular", "(", "parameter", ")", ":", "if", "(", "\"pointer\"", "in", "parameter", ".", "modifiers", "or", "\"allocatable\"", "in", "parameter", ".", "modifiers", "or", "\"target\"", "in", "parameter", ".", "modifiers", "or", "parameter", ".", ...
55.857143
17.285714
def validate(self, value): """Validate field value.""" if value is not None and not isinstance(value, str): raise ValidationError("field must be a string") super().validate(value)
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "ValidationError", "(", "\"field must be a string\"", ")", "super", "(", ")", ".", "valid...
35.166667
17
async def delete(self, request, resource=None, **kwargs): """Delete a resource. Supports batch delete. """ if resource: resources = [resource] else: data = await self.parse(request) if data: resources = list(self.collection.whe...
[ "async", "def", "delete", "(", "self", ",", "request", ",", "resource", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "resource", ":", "resources", "=", "[", "resource", "]", "else", ":", "data", "=", "await", "self", ".", "parse", "(", "re...
29.235294
18.176471
def xml(self, attribs = None,elements = None, skipchildren = False): """See :meth:`AbstractElement.xml`""" if not attribs: attribs = {} if self.idref: attribs['id'] = self.idref return super(AbstractTextMarkup,self).xml(attribs,elements, skipchildren)
[ "def", "xml", "(", "self", ",", "attribs", "=", "None", ",", "elements", "=", "None", ",", "skipchildren", "=", "False", ")", ":", "if", "not", "attribs", ":", "attribs", "=", "{", "}", "if", "self", ".", "idref", ":", "attribs", "[", "'id'", "]", ...
48.333333
15.5
def inv_entry_to_path(data): """ Determine the path from the intersphinx inventory entry Discard the anchors between head and tail to make it compatible with situations where extra meta information is encoded. """ path_tuple = data[2].split("#") if len(path_tuple) > 1: path_str = "#...
[ "def", "inv_entry_to_path", "(", "data", ")", ":", "path_tuple", "=", "data", "[", "2", "]", ".", "split", "(", "\"#\"", ")", "if", "len", "(", "path_tuple", ")", ">", "1", ":", "path_str", "=", "\"#\"", ".", "join", "(", "(", "path_tuple", "[", "0...
31.076923
17.076923
def send_last_message(self, msg, connection_id=None): """ Should be used instead of send_message, when you want to close the connection once the message is sent. :param msg: protobuf validator_pb2.Message """ zmq_identity = None if connection_id is not None and s...
[ "def", "send_last_message", "(", "self", ",", "msg", ",", "connection_id", "=", "None", ")", ":", "zmq_identity", "=", "None", "if", "connection_id", "is", "not", "None", "and", "self", ".", "_connections", "is", "not", "None", ":", "if", "connection_id", ...
38.258065
19.419355
def goback(self,days = 1): """ Go back days 刪除最新天數資料數據 days 代表刪除多少天數(倒退幾天) """ for i in xrange(days): self.raw_data.pop() self.data_date.pop() self.stock_range.pop() self.stock_vol.pop() self.stock_open.pop() self.stock_h.pop() self.stock_l.pop()
[ "def", "goback", "(", "self", ",", "days", "=", "1", ")", ":", "for", "i", "in", "xrange", "(", "days", ")", ":", "self", ".", "raw_data", ".", "pop", "(", ")", "self", ".", "data_date", ".", "pop", "(", ")", "self", ".", "stock_range", ".", "p...
23.384615
12.538462
def norm(self): """Return a Scalar object with the norm of this vector""" result = Scalar(self.size, self.deriv) result.v = np.sqrt(self.x.v**2 + self.y.v**2 + self.z.v**2) if self.deriv > 0: result.d += self.x.v*self.x.d result.d += self.y.v*self.y.d ...
[ "def", "norm", "(", "self", ")", ":", "result", "=", "Scalar", "(", "self", ".", "size", ",", "self", ".", "deriv", ")", "result", ".", "v", "=", "np", ".", "sqrt", "(", "self", ".", "x", ".", "v", "**", "2", "+", "self", ".", "y", ".", "v"...
47.6
14.28
def get_enclosingmethod(self): """ the class.method or class (if the definition is not from within a method) that encloses the definition of this class. Returns None if this was not an inner class. reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7...
[ "def", "get_enclosingmethod", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"EnclosingMethod\"", ")", "# TODO:", "# Running across classes with data in this attribute like", "# 00 06 00 00", "# which would be the 6th const for the class name, ...
30.027778
22.361111
def _at_dump_imports(self, calculator, rule, scope, block): """ Implements @dump_imports """ sys.stderr.write("%s\n" % repr(rule.namespace._imports))
[ "def", "_at_dump_imports", "(", "self", ",", "calculator", ",", "rule", ",", "scope", ",", "block", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"%s\\n\"", "%", "repr", "(", "rule", ".", "namespace", ".", "_imports", ")", ")" ]
35.4
10.2
def get_template_path(self, content=None): """ Find template. :return string: remplate path """ if isinstance(content, Paginator): return op.join('api', 'paginator.%s' % self.format) if isinstance(content, UpdatedList): return op.join('api', 'updated.%s...
[ "def", "get_template_path", "(", "self", ",", "content", "=", "None", ")", ":", "if", "isinstance", "(", "content", ",", "Paginator", ")", ":", "return", "op", ".", "join", "(", "'api'", ",", "'paginator.%s'", "%", "self", ".", "format", ")", "if", "is...
27.7
19.133333
def fullStats(a, b): """Performs several stats on a against b, typically a is the predictions array, and b the observations array Returns: A dataFrame of stat name, stat description, result """ stats = [ ['bias', 'Bias', bias(a, b)], ['stderr', 'Standard Deviation Error', s...
[ "def", "fullStats", "(", "a", ",", "b", ")", ":", "stats", "=", "[", "[", "'bias'", ",", "'Bias'", ",", "bias", "(", "a", ",", "b", ")", "]", ",", "[", "'stderr'", ",", "'Standard Deviation Error'", ",", "stderr", "(", "a", ",", "b", ")", "]", ...
42.192308
19.076923
def MigrateInstance(r, instance, mode=None, cleanup=None): """ Migrates an instance. @type instance: string @param instance: Instance name @type mode: string @param mode: Migration mode @type cleanup: bool @param cleanup: Whether to clean up a previously failed migration """ bo...
[ "def", "MigrateInstance", "(", "r", ",", "instance", ",", "mode", "=", "None", ",", "cleanup", "=", "None", ")", ":", "body", "=", "{", "}", "if", "mode", "is", "not", "None", ":", "body", "[", "\"mode\"", "]", "=", "mode", "if", "cleanup", "is", ...
23.863636
19.681818
def get_dataframe(self, sort_key="wall_time", **kwargs): """ Return a pandas DataFrame with entries sorted according to `sort_key`. """ import pandas as pd frame = pd.DataFrame(columns=AbinitTimerSection.FIELDS) for osect in self.order_sections(sort_key): fra...
[ "def", "get_dataframe", "(", "self", ",", "sort_key", "=", "\"wall_time\"", ",", "*", "*", "kwargs", ")", ":", "import", "pandas", "as", "pd", "frame", "=", "pd", ".", "DataFrame", "(", "columns", "=", "AbinitTimerSection", ".", "FIELDS", ")", "for", "os...
34
15.8
def str_arg_to_bool(value): """ Convert string argument into a boolean values. :param value: str value to convert. Allowed values are y, yes, true, 1, t, n, no, false, 0, f. The implementation is case insensitive. :raises: argparse.ArgumentTypeError if value is not recognized as a boolean. :retu...
[ "def", "str_arg_to_bool", "(", "value", ")", ":", "if", "value", ".", "lower", "(", ")", "in", "[", "\"y\"", ",", "\"yes\"", ",", "\"true\"", ",", "\"1\"", ",", "\"t\"", "]", ":", "return", "True", "elif", "value", ".", "lower", "(", ")", "in", "["...
39.928571
19.642857
def relabel_non_zero(label_image, start = 1): r""" Relabel the regions of a label image. Re-processes the labels to make them consecutively and starting from start. Keeps all zero (0) labels, as they are considered background. Parameters ---------- label_image : array_like A nD...
[ "def", "relabel_non_zero", "(", "label_image", ",", "start", "=", "1", ")", ":", "if", "start", "<=", "0", ":", "raise", "ArgumentError", "(", "'The starting value can not be 0 or lower.'", ")", "l", "=", "list", "(", "scipy", ".", "unique", "(", "label_image"...
26.53125
20.46875
def create_scans(urls_file): """ This method is rather simple, it will group the urls to be scanner together based on (protocol, domain and port). :param urls_file: The filename with all the URLs :return: A list of scans to be run """ cli_logger.debug('Starting to process batch input file')...
[ "def", "create_scans", "(", "urls_file", ")", ":", "cli_logger", ".", "debug", "(", "'Starting to process batch input file'", ")", "created_scans", "=", "[", "]", "for", "line", "in", "urls_file", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line...
29.897436
19.435897
def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ buf = tarfile.fileobj.read(self._block(self.size)) # Fetch the next header and process it. try: next = self.fromtarfile(tarfile) except HeaderE...
[ "def", "_proc_gnulong", "(", "self", ",", "tarfile", ")", ":", "buf", "=", "tarfile", ".", "fileobj", ".", "read", "(", "self", ".", "_block", "(", "self", ".", "size", ")", ")", "# Fetch the next header and process it.", "try", ":", "next", "=", "self", ...
36.095238
16.904762
def token_clean(self, length, numbers=True): """ Strip out non-alphanumeric tokens. length: remove tokens of length "length" or less. numbers: strip out non-alpha tokens. """ def clean1(tokens): return [t for t in tokens if t.isalpha() == 1 and len(t) > leng...
[ "def", "token_clean", "(", "self", ",", "length", ",", "numbers", "=", "True", ")", ":", "def", "clean1", "(", "tokens", ")", ":", "return", "[", "t", "for", "t", "in", "tokens", "if", "t", ".", "isalpha", "(", ")", "==", "1", "and", "len", "(", ...
31.277778
20.5
def update(self, duration): """Add a recorded duration.""" if duration >= 0: self.histogram.update(duration) self.meter.mark()
[ "def", "update", "(", "self", ",", "duration", ")", ":", "if", "duration", ">=", "0", ":", "self", ".", "histogram", ".", "update", "(", "duration", ")", "self", ".", "meter", ".", "mark", "(", ")" ]
32.4
8.4
def latitude_from_cross_section(cross): """Calculate the latitude of points in a cross-section. Parameters ---------- cross : `xarray.DataArray` The input DataArray of a cross-section from which to obtain latitudes. Returns ------- latitude : `xarray.DataArray` Latitude of ...
[ "def", "latitude_from_cross_section", "(", "cross", ")", ":", "y", "=", "cross", ".", "metpy", ".", "y", "if", "CFConventionHandler", ".", "check_axis", "(", "y", ",", "'lat'", ")", ":", "return", "y", "else", ":", "import", "cartopy", ".", "crs", "as", ...
33.08
22.36
def btemp_threshold(img, min_in, max_in, threshold, threshold_out=None, **kwargs): """Scale data linearly in two separate regions. This enhancement scales the input data linearly by splitting the data into two regions; min_in to threshold and threshold to max_in. These regions are mapped to 1 to thresh...
[ "def", "btemp_threshold", "(", "img", ",", "min_in", ",", "max_in", ",", "threshold", ",", "threshold_out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "threshold_out", "=", "threshold_out", "if", "threshold_out", "is", "not", "None", "else", "(", "176...
46.272727
22.575758
def assert_selector(self, *args, **kwargs): """ Asserts that a given selector is on the page or a descendant of the current node. :: page.assert_selector("p#foo") By default it will check if the expression occurs at least once, but a different number can be specified. :: ...
[ "def", "assert_selector", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "SelectorQuery", "(", "*", "args", ",", "*", "*", "kwargs", ")", "@", "self", ".", "synchronize", "(", "wait", "=", "query", ".", "wait", ")",...
32.264151
27.886792
def copy_to(self, destination): """ Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File or Folder object. """ target = self.__get_destination__(destination) logger.info("Copying %s to %s" % ...
[ "def", "copy_to", "(", "self", ",", "destination", ")", ":", "target", "=", "self", ".", "__get_destination__", "(", "destination", ")", "logger", ".", "info", "(", "\"Copying %s to %s\"", "%", "(", "self", ",", "target", ")", ")", "shutil", ".", "copy", ...
40.1
12.5
def _on_timeout(self, _attempts=0): """ Called when the request associated with this ResponseFuture times out. This function may reschedule itself. The ``_attempts`` parameter tracks the number of times this has happened. This parameter should only be set in those cases, where `...
[ "def", "_on_timeout", "(", "self", ",", "_attempts", "=", "0", ")", ":", "# PYTHON-853: for short timeouts, we sometimes race with our __init__", "if", "self", ".", "_connection", "is", "None", "and", "_attempts", "<", "3", ":", "self", ".", "_timer", "=", "self",...
46.860465
27.837209
def gload(smatch, gpaths=None, glabels=None, filt=None, reducel=False, remove_underscore=True, clear=True, single=True, reshape=RESHAPE_DEFAULT, idxlower=True, returnfirst=False, lowercase=True, lamb=None, verbose=True, idval=None): """ Loads into global namespace the symbols l...
[ "def", "gload", "(", "smatch", ",", "gpaths", "=", "None", ",", "glabels", "=", "None", ",", "filt", "=", "None", ",", "reducel", "=", "False", ",", "remove_underscore", "=", "True", ",", "clear", "=", "True", ",", "single", "=", "True", ",", "reshap...
41.77037
16.407407
def _ReloadArtifacts(self): """Load artifacts from all sources.""" self._artifacts = {} self._LoadArtifactsFromFiles(self._sources.GetAllFiles()) self.ReloadDatastoreArtifacts()
[ "def", "_ReloadArtifacts", "(", "self", ")", ":", "self", ".", "_artifacts", "=", "{", "}", "self", ".", "_LoadArtifactsFromFiles", "(", "self", ".", "_sources", ".", "GetAllFiles", "(", ")", ")", "self", ".", "ReloadDatastoreArtifacts", "(", ")" ]
37.8
11
def fingerprints(self, keyhalf='any', keytype='any'): """ List loaded fingerprints with some optional filtering. :param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the the other type will not be included i...
[ "def", "fingerprints", "(", "self", ",", "keyhalf", "=", "'any'", ",", "keytype", "=", "'any'", ")", ":", "return", "{", "pk", ".", "fingerprint", "for", "pk", "in", "self", ".", "_keys", ".", "values", "(", ")", "if", "pk", ".", "is_primary", "in", ...
67.666667
36.866667
def colored_noise(psd, start_time, end_time, seed=0, low_frequency_cutoff=1.0): """ Create noise from a PSD Return noise from the chosen PSD. Note that if unique noise is desired a unique seed should be provided. Parameters ---------- psd : pycbc.types.FrequencySeries PSD to color the ...
[ "def", "colored_noise", "(", "psd", ",", "start_time", ",", "end_time", ",", "seed", "=", "0", ",", "low_frequency_cutoff", "=", "1.0", ")", ":", "psd", "=", "psd", ".", "copy", "(", ")", "flen", "=", "int", "(", "SAMPLE_RATE", "/", "psd", ".", "delt...
39.135802
20.395062
def clear_thumbnails(self): '''clear all thumbnails from the map''' state = self.state for l in state.layers: keys = state.layers[l].keys()[:] for key in keys: if (isinstance(state.layers[l][key], SlipThumbnail) and not isinstance(state...
[ "def", "clear_thumbnails", "(", "self", ")", ":", "state", "=", "self", ".", "state", "for", "l", "in", "state", ".", "layers", ":", "keys", "=", "state", ".", "layers", "[", "l", "]", ".", "keys", "(", ")", "[", ":", "]", "for", "key", "in", "...
42.777778
13.666667