text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def capitalize(string): """Capitalize a sentence. Parameters ---------- string : `str` String to capitalize. Returns ------- `str` Capitalized string. Examples -------- >>> capitalize('worD WORD WoRd') 'Word word word' """ if not string: ret...
[ "def", "capitalize", "(", "string", ")", ":", "if", "not", "string", ":", "return", "string", "if", "len", "(", "string", ")", "==", "1", ":", "return", "string", ".", "upper", "(", ")", "return", "string", "[", "0", "]", ".", "upper", "(", ")", ...
17.956522
0.002299
def remove_objects(self, bucket_name, objects_iter): """ Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiD...
[ "def", "remove_objects", "(", "self", ",", "bucket_name", ",", "objects_iter", ")", ":", "is_valid_bucket_name", "(", "bucket_name", ")", "if", "isinstance", "(", "objects_iter", ",", "basestring", ")", ":", "raise", "TypeError", "(", "'objects_iter cannot be `str` ...
34.22449
0.001159
def generateSummary(self, extraLapse = TYPICAL_LAPSE): '''Generates a summary of the status of the expected scripts broken based on the log. This summary (a list of strings) is returned as well as a list with the dates (which can be used to index the log)of the most recent attempts at the failed jobs. ''' ...
[ "def", "generateSummary", "(", "self", ",", "extraLapse", "=", "TYPICAL_LAPSE", ")", ":", "scriptsRun", "=", "self", ".", "scriptsRun", "body", "=", "[", "]", "numberOfFailed", "=", "0", "numberWithWarnings", "=", "0", "failedList", "=", "[", "]", "successLi...
31.493151
0.040489
def __StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True): """Helper function for StreamMedia / StreamInChunks.""" if self.strategy != RESUMABLE_UPLOAD: raise exceptions.InvalidUserInputError( 'Cannot stream n...
[ "def", "__StreamMedia", "(", "self", ",", "callback", "=", "None", ",", "finish_callback", "=", "None", ",", "additional_headers", "=", "None", ",", "use_chunks", "=", "True", ")", ":", "if", "self", ".", "strategy", "!=", "RESUMABLE_UPLOAD", ":", "raise", ...
47.569231
0.000951
def set_canned_acl(self, acl_str, key_name='', headers=None, version_id=None): """sets or changes a bucket's acl to a predefined (canned) value. We include a version_id argument to support a polymorphic interface for callers, however, version_id is not relevant fo...
[ "def", "set_canned_acl", "(", "self", ",", "acl_str", ",", "key_name", "=", "''", ",", "headers", "=", "None", ",", "version_id", "=", "None", ")", ":", "return", "self", ".", "set_canned_acl_helper", "(", "acl_str", ",", "key_name", ",", "headers", ",", ...
64.625
0.017176
def _create_index_formula_lookup(formula_id2index, feature_folder, index2latex): """ Create a lookup file where the index is mapped to the formula id and the LaTeX command. Parameters ---------- formula_id2index : dict featur...
[ "def", "_create_index_formula_lookup", "(", "formula_id2index", ",", "feature_folder", ",", "index2latex", ")", ":", "index2formula_id", "=", "sorted", "(", "formula_id2index", ".", "items", "(", ")", ",", "key", "=", "lambda", "n", ":", "n", "[", "1", "]", ...
39.045455
0.001136
async def do_upload(context, files): """Upload artifacts and return status. Returns the integer status of the upload. args: context (scriptworker.context.Context): the scriptworker context. files (list of str): list of files to be uploaded as artifacts Raises: Exception: on un...
[ "async", "def", "do_upload", "(", "context", ",", "files", ")", ":", "status", "=", "0", "try", ":", "await", "upload_artifacts", "(", "context", ",", "files", ")", "except", "ScriptWorkerException", "as", "e", ":", "status", "=", "worst_level", "(", "stat...
30.206897
0.001106
def koji_instance(config, message, instance=None, *args, **kw): """ Particular koji instances You may not have even known it, but we have multiple instances of the koji build system. There is the **primary** buildsystem at `koji.fedoraproject.org <http://koji.fedoraproject.org>`_ and also secondar...
[ "def", "koji_instance", "(", "config", ",", "message", ",", "instance", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "instance", "=", "kw", ".", "get", "(", "'instance'", ",", "instance", ")", "if", "not", "instance", ":", "return", ...
44.384615
0.000848
def get_idcard_photo(self, regid, size="medium"): """ Returns a jpeg image, for the passed uwregid. Size is configured as: "small" (20w x 25h px), "medium" (120w x 150h px), "large" (240w x 300h px), {height in pixels} (custom height, default aspect ratio)...
[ "def", "get_idcard_photo", "(", "self", ",", "regid", ",", "size", "=", "\"medium\"", ")", ":", "if", "not", "self", ".", "valid_uwregid", "(", "regid", ")", ":", "raise", "InvalidRegID", "(", "regid", ")", "size", "=", "str", "(", "size", ")", "if", ...
34.451613
0.001821
def __parseParameters(self): """Parses the parameters of data.""" self.__parameters = [] for parameter in self.__data['parameters']: self.__parameters.append(Parameter(parameter))
[ "def", "__parseParameters", "(", "self", ")", ":", "self", ".", "__parameters", "=", "[", "]", "for", "parameter", "in", "self", ".", "__data", "[", "'parameters'", "]", ":", "self", ".", "__parameters", ".", "append", "(", "Parameter", "(", "parameter", ...
42.2
0.009302
def comments_nb_counts(): """Get number of comments for the record `recid`.""" recid = request.view_args.get('recid') if recid is None: return elif recid == 0: return 0 else: return CmtRECORDCOMMENT.count(*[ CmtRECORDCOMMENT.id_bibrec == recid, CmtREC...
[ "def", "comments_nb_counts", "(", ")", ":", "recid", "=", "request", ".", "view_args", ".", "get", "(", "'recid'", ")", "if", "recid", "is", "None", ":", "return", "elif", "recid", "==", "0", ":", "return", "0", "else", ":", "return", "CmtRECORDCOMMENT",...
28.714286
0.00241
def cmd_dns_lookup_reverse(ip_address, verbose): """Perform a reverse lookup of a given IP address. Example: \b $ $ habu.dns.lookup.reverse 8.8.8.8 { "hostname": "google-public-dns-a.google.com" } """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message...
[ "def", "cmd_dns_lookup_reverse", "(", "ip_address", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "print", "(", "\"Looking up %s...\"", "%", ...
24.434783
0.001712
def success(self): """Return boolean indicating whether a solution was found""" self._check_valid() return self._problem._p.get_status() == qsoptex.SolutionStatus.OPTIMAL
[ "def", "success", "(", "self", ")", ":", "self", ".", "_check_valid", "(", ")", "return", "self", ".", "_problem", ".", "_p", ".", "get_status", "(", ")", "==", "qsoptex", ".", "SolutionStatus", ".", "OPTIMAL" ]
47.75
0.010309
def _get_jenks_config(): """ retrieve the jenks configuration object """ config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, 'w').close() with open(config_file, 'r') as fh: ...
[ "def", "_get_jenks_config", "(", ")", ":", "config_file", "=", "(", "get_configuration_file", "(", ")", "or", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "CONFIG_FILE_NAME", ")", ")", ")", "if", "not", ...
34.076923
0.002198
def _publish_replset(self, data, base_prefix): """ Given a response to replSetGetStatus, publishes all numeric values of the instance, aggregate stats of healthy nodes vs total nodes, and the observed statuses of all nodes in the replica set. """ prefix = base_prefix + ['...
[ "def", "_publish_replset", "(", "self", ",", "data", ",", "base_prefix", ")", ":", "prefix", "=", "base_prefix", "+", "[", "'replset'", "]", "self", ".", "_publish_dict_with_prefix", "(", "data", ",", "prefix", ")", "total_nodes", "=", "len", "(", "data", ...
48.684211
0.002121
def push_subscription_generate_keys(self): """ Generates a private key, public key and shared secret for use in webpush subscriptions. Returns two dicts: One with the private key and shared secret and another with the public key and shared secret. """ push_key_p...
[ "def", "push_subscription_generate_keys", "(", "self", ")", ":", "push_key_pair", "=", "ec", ".", "generate_private_key", "(", "ec", ".", "SECP256R1", "(", ")", ",", "default_backend", "(", ")", ")", "push_key_priv", "=", "push_key_pair", ".", "private_numbers", ...
36.347826
0.013986
def remove_urls(text_string): ''' Removes all URLs within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or text_string == "...
[ "def", "remove_urls", "(", "text_string", ")", ":", "if", "text_string", "is", "None", "or", "text_string", "==", "\"\"", ":", "return", "\"\"", "elif", "isinstance", "(", "text_string", ",", "str", ")", ":", "return", "\" \"", ".", "join", "(", "re", "....
27.722222
0.001938
def cache_call_refresh(self, method, *options): """ Call a remote method and update the local cache with the result if it already existed. :param str method: The name of the remote procedure to execute. :return: The return value from the remote function. """ options_hash = self.encode(options) if len(o...
[ "def", "cache_call_refresh", "(", "self", ",", "method", ",", "*", "options", ")", ":", "options_hash", "=", "self", ".", "encode", "(", "options", ")", "if", "len", "(", "options_hash", ")", ">", "20", ":", "options_hash", "=", "hashlib", ".", "new", ...
40.565217
0.025131
def add_segment(self, name, model_expression=None, ytransform='default'): """ Add a new segment with its own model expression and ytransform. Parameters ---------- name : Segment name. Must match a segment in the groupby of the data. model_expression : str or...
[ "def", "add_segment", "(", "self", ",", "name", ",", "model_expression", "=", "None", ",", "ytransform", "=", "'default'", ")", ":", "if", "not", "model_expression", ":", "if", "self", ".", "default_model_expr", "is", "None", ":", "raise", "ValueError", "(",...
40.837838
0.001293
def list(self, **params): """ Retrieve text messages Returns Text Messages, according to the parameters provided :calls: ``get /text_messages`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which repres...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "text_messages", "=", "self", ".", "http_client", ".", "get", "(", "\"/text_messages\"", ",", "params", "=", "params", ")", "return", "text_messages" ]
34.642857
0.008032
def _get_features_string(self, features=None): """ Generates the extended newick string NHX with extra data about a node.""" string = "" if features is None: features = [] elif features == []: features = self.features for pr in features: if hasattr(self, pr): raw...
[ "def", "_get_features_string", "(", "self", ",", "features", "=", "None", ")", ":", "string", "=", "\"\"", "if", "features", "is", "None", ":", "features", "=", "[", "]", "elif", "features", "==", "[", "]", ":", "features", "=", "self", ".", "features"...
31.3
0.010331
def is_builtin_css_function(name): """Returns whether the given `name` looks like the name of a builtin CSS function. Unrecognized functions not in this list produce warnings. """ name = name.replace('_', '-') if name in BUILTIN_FUNCTIONS: return True # Vendor-specific functions (...
[ "def", "is_builtin_css_function", "(", "name", ")", ":", "name", "=", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "name", "in", "BUILTIN_FUNCTIONS", ":", "return", "True", "# Vendor-specific functions (-foo-bar) are always okay", "if", "name", "[", ...
25.6875
0.002347
def garbage_collection(time_limit=YEAR/12.0): """ Collect and remove all :class:`.RequestInfo` objects older than `time_limit` (in seconds). Args: time_limit (float, default YEAR / 2): Collect objects older than this limit. """ expired_request_infos = ( ri for ri in ...
[ "def", "garbage_collection", "(", "time_limit", "=", "YEAR", "/", "12.0", ")", ":", "expired_request_infos", "=", "(", "ri", "for", "ri", "in", "DATABASE", ".", "values", "(", ")", "if", "ri", ".", "creation_ts", "+", "time_limit", "<=", "time", ".", "ti...
28.0625
0.002155
def fill_zero( x=None, y=None, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', **kargs ): """Fill to zero. Parameters ---------- x : array-like, optional y : TODO, optional label : TODO, optional Returns ------- ...
[ "def", "fill_zero", "(", "x", "=", "None", ",", "y", "=", "None", ",", "label", "=", "None", ",", "color", "=", "None", ",", "width", "=", "None", ",", "dash", "=", "None", ",", "opacity", "=", "None", ",", "mode", "=", "'lines+markers'", ",", "*...
14.305556
0.001818
def vp(self): """Velocity at pericenter """ return np.sqrt(self.mu * (2 / (self.rp) - 1 / self.kep.a))
[ "def", "vp", "(", "self", ")", ":", "return", "np", ".", "sqrt", "(", "self", ".", "mu", "*", "(", "2", "/", "(", "self", ".", "rp", ")", "-", "1", "/", "self", ".", "kep", ".", "a", ")", ")" ]
30.75
0.015873
def _ReadN(self, n): """Reads n characters from the input stream, or until EOF. This is equivalent to the current CPython implementation of read(n), but not guaranteed by the docs. Args: n: int Returns: string """ ret = "" while True: chunk = self._read_file.read(n -...
[ "def", "_ReadN", "(", "self", ",", "n", ")", ":", "ret", "=", "\"\"", "while", "True", ":", "chunk", "=", "self", ".", "_read_file", ".", "read", "(", "n", "-", "len", "(", "ret", ")", ")", "ret", "+=", "chunk", "if", "len", "(", "ret", ")", ...
20.421053
0.009852
def cycle_data(self, verbose=False, result_cycle=None, result_size=None, result_edges=None,changelog=True): """Get data from JIRA for cycle/flow times and story points size change. Build a numerically indexed data frame with the following 'fixed' columns: `key`, 'url', 'issue_type', `summary`, ...
[ "def", "cycle_data", "(", "self", ",", "verbose", "=", "False", ",", "result_cycle", "=", "None", ",", "result_size", "=", "None", ",", "result_edges", "=", "None", ",", "changelog", "=", "True", ")", ":", "cycle_names", "=", "[", "s", "[", "'name'", "...
50.691176
0.008251
def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_...
[ "def", "suggest", "(", "query", ")", ":", "search_params", "=", "{", "'list'", ":", "'search'", ",", "'srinfo'", ":", "'suggestion'", ",", "'srprop'", ":", "''", ",", "}", "search_params", "[", "'srsearch'", "]", "=", "query", "raw_result", "=", "_wiki_req...
21.578947
0.016355
def v1_label_negative_inference(request, response, visid_to_dbid, dbid_to_visid, label_store, cid): '''Return inferred negative labels. The route for this endpoint is: ``/dossier/v1/label/<cid>/negative-inference``. Negative labels are in...
[ "def", "v1_label_negative_inference", "(", "request", ",", "response", ",", "visid_to_dbid", ",", "dbid_to_visid", ",", "label_store", ",", "cid", ")", ":", "# No subtopics yet? :-(", "lab_to_json", "=", "partial", "(", "label_to_json", ",", "dbid_to_visid", ")", "l...
43.434783
0.000979
def remove_users_from_user_group(self, id, **kwargs): # noqa: E501 """Remove multiple users from a specific user group # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thre...
[ "def", "remove_users_from_user_group", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", ...
46.045455
0.001934
def assign(self, var, val, assignment): "Add {var: val} to assignment; Discard the old value if any." assignment[var] = val self.nassigns += 1
[ "def", "assign", "(", "self", ",", "var", ",", "val", ",", "assignment", ")", ":", "assignment", "[", "var", "]", "=", "val", "self", ".", "nassigns", "+=", "1" ]
40.75
0.012048
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
[ "def", "memoize", "(", "f", ")", ":", "cache", "=", "{", "}", "def", "memf", "(", "*", "x", ")", ":", "if", "x", "not", "in", "cache", ":", "cache", "[", "x", "]", "=", "f", "(", "*", "x", ")", "return", "cache", "[", "x", "]", "return", ...
23.5
0.015385
def get(self, path): """ Get the content of a file, indentified by its path relative to the folder configured in PyGreen. If the file extension is one of the extensions that should be processed through Mako, it will be processed. """ data = self.app.test_client().get("/%s...
[ "def", "get", "(", "self", ",", "path", ")", ":", "data", "=", "self", ".", "app", ".", "test_client", "(", ")", ".", "get", "(", "\"/%s\"", "%", "path", ")", ".", "data", "return", "data" ]
43.375
0.011299
def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit: """Return only the non-Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: ...
[ "def", "pauli_string_half", "(", "circuit", ":", "circuits", ".", "Circuit", ")", "->", "circuits", ".", "Circuit", ":", "return", "circuits", ".", "Circuit", ".", "from_ops", "(", "_pull_non_clifford_before", "(", "circuit", ")", ",", "strategy", "=", "circui...
36.357143
0.001916
def translate_codon(codon, aa_pos): """Translate a single codon into a single amino acid or stop '*' Parameters ---------- codon : str Expected to be of length 3 aa_pos : int Codon/amino acid offset into the protein (starting from 0) """ # not handling rare Leucine or Valine...
[ "def", "translate_codon", "(", "codon", ",", "aa_pos", ")", ":", "# not handling rare Leucine or Valine starts!", "if", "aa_pos", "==", "0", "and", "codon", "in", "START_CODONS", ":", "return", "\"M\"", "elif", "codon", "in", "STOP_CODONS", ":", "return", "\"*\"",...
27.941176
0.002037
def _clear_screen(): """ http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell """ if platform.system() == "Windows": tmp = os.system('cls') #for window else: tmp = os.system('clear') #for Linux return True
[ "def", "_clear_screen", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "\"Windows\"", ":", "tmp", "=", "os", ".", "system", "(", "'cls'", ")", "#for window", "else", ":", "tmp", "=", "os", ".", "system", "(", "'clear'", ")", "#for Li...
36.142857
0.015444
async def _get_payload(self, user): """ Given a user object, create a payload and extend it as configured. """ payload = await utils.call(self.build_payload, user) if ( not isinstance(payload, dict) or self.config.user_id() not in payload ): ...
[ "async", "def", "_get_payload", "(", "self", ",", "user", ")", ":", "payload", "=", "await", "utils", ".", "call", "(", "self", ".", "build_payload", ",", "user", ")", "if", "(", "not", "isinstance", "(", "payload", ",", "dict", ")", "or", "self", "....
35.363636
0.001668
def ParseFileObject(self, parser_mediator, file_object): """Parses a MSIE Cache File (MSIECF) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. ...
[ "def", "ParseFileObject", "(", "self", ",", "parser_mediator", ",", "file_object", ")", ":", "msiecf_file", "=", "pymsiecf", ".", "file", "(", ")", "msiecf_file", ".", "set_ascii_codepage", "(", "parser_mediator", ".", "codepage", ")", "try", ":", "msiecf_file",...
32.727273
0.008097
async def delete(self): """Delete this Fabric.""" if self.id == self._origin.Fabric._default_fabric_id: raise CannotDelete("Default fabric cannot be deleted.") await self._handler.delete(id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "if", "self", ".", "id", "==", "self", ".", "_origin", ".", "Fabric", ".", "_default_fabric_id", ":", "raise", "CannotDelete", "(", "\"Default fabric cannot be deleted.\"", ")", "await", "self", ".", "_handler",...
46
0.008547
def reraise_as(new_exception_or_type): """ Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py >>> try: >>> do_something_crazy() >>> except Exception: >>> reraise_as(UnhandledException) """ __traceback_hide__ = True # NOQA e_type, e_value, e_tracebac...
[ "def", "reraise_as", "(", "new_exception_or_type", ")", ":", "__traceback_hide__", "=", "True", "# NOQA", "e_type", ",", "e_value", ",", "e_traceback", "=", "sys", ".", "exc_info", "(", ")", "if", "inspect", ".", "isclass", "(", "new_exception_or_type", ")", "...
27.92
0.001385
def quantile(image, q, nonzero=True): """ Get the quantile values from an ANTsImage """ img_arr = image.numpy() if isinstance(q, (list,tuple)): q = [qq*100. if qq <= 1. else qq for qq in q] if nonzero: img_arr = img_arr[img_arr>0] vals = [np.percentile(img_arr, qq...
[ "def", "quantile", "(", "image", ",", "q", ",", "nonzero", "=", "True", ")", ":", "img_arr", "=", "image", ".", "numpy", "(", ")", "if", "isinstance", "(", "q", ",", "(", "list", ",", "tuple", ")", ")", ":", "q", "=", "[", "qq", "*", "100.", ...
32.473684
0.009449
def from_shape(cls, shape): """Try to linearize a curve (or an already linearized curve). Args: shape (Union[SubdividedCurve, \ ~bezier._geometric_intersection.Linearization]): A curve or an already linearized curve. Returns: Union[Subdivided...
[ "def", "from_shape", "(", "cls", ",", "shape", ")", ":", "# NOTE: In the below we replace ``isinstance(a, B)`` with", "# ``a.__class__ is B``, which is a 3-3.5x speedup.", "if", "shape", ".", "__class__", "is", "cls", ":", "return", "shape", "else", ":", "error", "=...
32.538462
0.002296
def cmd_http_headers(server, verbose): """Retrieve the HTTP headers of a web server. Example: \b $ habu.http.headers http://duckduckgo.com { "Server": "nginx", "Date": "Sun, 14 Apr 2019 00:00:55 GMT", "Content-Type": "text/html", "Content-Length": "178", "Co...
[ "def", "cmd_http_headers", "(", "server", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "if", "verbose", ":", "print", "(", "\"[-] Retriev...
29.512195
0.0016
def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: ...
[ "def", "find_element", "(", "driver", ",", "elem_path", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "wait", "=", "WebDriverWait", "(", "driver", ",", "timeout", ",", "poll_frequency", ")", "return", ...
39.636364
0.00224
def _post_ppc_arima(a): """If there are no suitable models, raise a ValueError. Otherwise, return ``a``. In the case that ``a`` is an iterable (i.e., it made it to the end of the function), this method will filter out the None values and assess whether the list is empty. Parameters ---------- ...
[ "def", "_post_ppc_arima", "(", "a", ")", ":", "# if it's a result of making it to the end, it will", "# be a list of ARIMA models. Filter out the Nones", "# (the failed models)...", "if", "is_iterable", "(", "a", ")", ":", "a", "=", "[", "m", "for", "m", "in", "a", "if"...
42.423077
0.000887
def stdin_channel(self): """Get the REP socket channel object to handle stdin (raw_input).""" if self._stdin_channel is None: self._stdin_channel = self.stdin_channel_class(self.context, self.session, ...
[ "def", "stdin_channel", "(", "self", ")", ":", "if", "self", ".", "_stdin_channel", "is", "None", ":", "self", ".", "_stdin_channel", "=", "self", ".", "stdin_channel_class", "(", "self", ".", "context", ",", "self", ".", "session", ",", "(", "self", "."...
56.428571
0.012469
def classmethod(self, encoding): """Function decorator for class methods.""" # Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) d...
[ "def", "classmethod", "(", "self", ",", "encoding", ")", ":", "# Add encodings for hidden self and cmd arguments.", "encoding", "=", "ensure_bytes", "(", "encoding", ")", "typecodes", "=", "parse_type_encoding", "(", "encoding", ")", "typecodes", ".", "insert", "(", ...
42.434783
0.002004
def same_indexes(l1,l2): ''' from elist.elist import * l1 = [1,2,3,5] l2 = [0,2,3,4] same_indexes(l1,l2) ''' rslt = [] for i in range(0,l1.__len__()): if(l1[i]==l2[i]): rslt.append(i) return(rslt)
[ "def", "same_indexes", "(", "l1", ",", "l2", ")", ":", "rslt", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "l1", ".", "__len__", "(", ")", ")", ":", "if", "(", "l1", "[", "i", "]", "==", "l2", "[", "i", "]", ")", ":", "rslt",...
21.416667
0.014925
def receive( self, messagedata: bytes, host_port: Tuple[str, int], # pylint: disable=unused-argument ) -> bool: """ Handle an UDP packet. """ # pylint: disable=unidiomatic-typecheck if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE: self.log.wa...
[ "def", "receive", "(", "self", ",", "messagedata", ":", "bytes", ",", "host_port", ":", "Tuple", "[", "str", ",", "int", "]", ",", "# pylint: disable=unused-argument", ")", "->", "bool", ":", "# pylint: disable=unidiomatic-typecheck", "if", "len", "(", "messaged...
32.777778
0.001975
def comment_out_line(filename, line, comment='#', update_or_append_line=update_or_append_line): '''Comment line out by putting a comment sign in front of the line. If the file does not contain the line, the files content will not be changed (but the file will be touched in every case)....
[ "def", "comment_out_line", "(", "filename", ",", "line", ",", "comment", "=", "'#'", ",", "update_or_append_line", "=", "update_or_append_line", ")", ":", "update_or_append_line", "(", "filename", ",", "prefix", "=", "line", ",", "new_line", "=", "comment", "+",...
48
0.002273
def _traverse(summary, function, *args): """Traverse all objects of a summary and call function with each as a parameter. Using this function, the following objects will be traversed: - the summary - each row - each item of a row """ function(summary, *args) for row in summary: ...
[ "def", "_traverse", "(", "summary", ",", "function", ",", "*", "args", ")", ":", "function", "(", "summary", ",", "*", "args", ")", "for", "row", "in", "summary", ":", "function", "(", "row", ",", "*", "args", ")", "for", "item", "in", "row", ":", ...
27.857143
0.002481
def addFilter(self, filterclass): """Add a filter class to the parser.""" if filterclass not in self.filters: self.filters.append(filterclass)
[ "def", "addFilter", "(", "self", ",", "filterclass", ")", ":", "if", "filterclass", "not", "in", "self", ".", "filters", ":", "self", ".", "filters", ".", "append", "(", "filterclass", ")" ]
41.75
0.011765
def connect_model(self, model): """Link the Database to the Model instance. In case a new database is created from scratch, ``connect_model`` creates Trace objects for all tallyable pymc objects defined in `model`. If the database is being loaded from an existing file, ``connec...
[ "def", "connect_model", "(", "self", ",", "model", ")", ":", "# Changed this to allow non-Model models. -AP", "# We could also remove it altogether. -DH", "if", "isinstance", "(", "model", ",", "pymc", ".", "Model", ")", ":", "self", ".", "model", "=", "model", "els...
40.456522
0.001574
def trypsinize(proseq, proline_cut=False): # TODO add cysteine to non cut options, use enums """Trypsinize a protein sequence. Returns a list of peptides. Peptides include both cut and non-cut when P is behind a tryptic residue. Multiple consequent tryptic residues are treated as follows: PEPKKKTIDE...
[ "def", "trypsinize", "(", "proseq", ",", "proline_cut", "=", "False", ")", ":", "# TODO add cysteine to non cut options, use enums", "outpeps", "=", "[", "]", "currentpeps", "=", "[", "''", "]", "trypres", "=", "set", "(", "[", "'K'", ",", "'R'", "]", ")", ...
40.774194
0.000773
def hacking_docstring_summary(physical_line, previous_logical, tokens): r"""Check multi line docstring summary is separated with empty line. OpenStack HACKING guide recommendation for docstring: Docstring should start with a one-line summary, less than 80 characters. Okay: def foo():\n a = '''\nnot...
[ "def", "hacking_docstring_summary", "(", "physical_line", ",", "previous_logical", ",", "tokens", ")", ":", "docstring", "=", "is_docstring", "(", "tokens", ",", "previous_logical", ")", "if", "docstring", ":", "if", "'\\n'", "not", "in", "docstring", ":", "# no...
44.086957
0.000965
def get_session(self, notebook_dir=None, no_browser=True, **kwargs): ''' Return handle to IPython session for specified notebook directory. If an IPython notebook session has already been launched for the notebook directory, reuse it. Otherwise, launch a new IPython notebook se...
[ "def", "get_session", "(", "self", ",", "notebook_dir", "=", "None", ",", "no_browser", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "notebook_dir", "in", "self", ".", "sessions", "and", "self", ".", "sessions", "[", "notebook_dir", "]", ".", ...
41.205128
0.001824
def delete_async(self, url, name, callback=None, params=None, headers=None): """ Asynchronous DELETE request with the process pool. """ if not name: name = '' params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, name) self...
[ "def", "delete_async", "(", "self", ",", "url", ",", "name", ",", "callback", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "''", "params", "=", "params", "or", "{", "}", "h...
42.545455
0.008368
def float(self, var, default=NOTSET): """ :rtype: float """ return self.get_value(var, cast=float, default=default)
[ "def", "float", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ")", ":", "return", "self", ".", "get_value", "(", "var", ",", "cast", "=", "float", ",", "default", "=", "default", ")" ]
28.6
0.013605
def equals_exact(self, other, tolerance): """ invariant to crs. """ # This method cannot be delegated because it has an extra parameter return self._shape.equals_exact(other.get_shape(self.crs), tolerance=tolerance)
[ "def", "equals_exact", "(", "self", ",", "other", ",", "tolerance", ")", ":", "# This method cannot be delegated because it has an extra parameter", "return", "self", ".", "_shape", ".", "equals_exact", "(", "other", ".", "get_shape", "(", "self", ".", "crs", ")", ...
59
0.012552
def sidereal_time(t): """Compute Greenwich sidereal time at the given ``Time``.""" # Compute the Earth Rotation Angle. Time argument is UT1. theta = earth_rotation_angle(t.ut1) # The equinox method. See Circular 179, Section 2.6.2. # Precession-in-RA terms in mean sidereal time taken from third...
[ "def", "sidereal_time", "(", "t", ")", ":", "# Compute the Earth Rotation Angle. Time argument is UT1.", "theta", "=", "earth_rotation_angle", "(", "t", ".", "ut1", ")", "# The equinox method. See Circular 179, Section 2.6.2.", "# Precession-in-RA terms in mean sidereal time taken ...
31.636364
0.02371
def ext(self, extension): """ Match files with an extension - e.g. 'js', 'txt' """ new_pathq = copy(self) new_pathq._pattern.ext = extension return new_pathq
[ "def", "ext", "(", "self", ",", "extension", ")", ":", "new_pathq", "=", "copy", "(", "self", ")", "new_pathq", ".", "_pattern", ".", "ext", "=", "extension", "return", "new_pathq" ]
28.428571
0.009756
def _defrag_logic(plist, complete=False): """Internal function used to defragment a list of packets. It contains the logic behind the defrag() and defragment() functions """ frags = defaultdict(lambda: []) final = [] pos = 0 for p in plist: p._defrag_pos = pos pos += 1 ...
[ "def", "_defrag_logic", "(", "plist", ",", "complete", "=", "False", ")", ":", "frags", "=", "defaultdict", "(", "lambda", ":", "[", "]", ")", "final", "=", "[", "]", "pos", "=", "0", "for", "p", "in", "plist", ":", "p", ".", "_defrag_pos", "=", ...
30.4
0.000797
def _get_resource_view(self, resource_view): # type: (Union[ResourceView,Dict]) -> ResourceView """Get resource view id Args: resource_view (Union[ResourceView,Dict]): ResourceView metadata from a ResourceView object or dictionary Returns: ResourceView: Resource...
[ "def", "_get_resource_view", "(", "self", ",", "resource_view", ")", ":", "# type: (Union[ResourceView,Dict]) -> ResourceView", "if", "isinstance", "(", "resource_view", ",", "dict", ")", ":", "resource_view", "=", "ResourceView", "(", "resource_view", ",", "configurati...
42.866667
0.009132
def OnMouse(self, event): """Reduces clicks to enter an edit control""" self.SetGridCursor(event.Row, event.Col) self.EnableCellEditControl(True) event.Skip()
[ "def", "OnMouse", "(", "self", ",", "event", ")", ":", "self", ".", "SetGridCursor", "(", "event", ".", "Row", ",", "event", ".", "Col", ")", "self", ".", "EnableCellEditControl", "(", "True", ")", "event", ".", "Skip", "(", ")" ]
31
0.010471
def cache_dir() -> str: """Return the default cache directory where downloaded models are stored.""" if config.VENDOR is None: raise RuntimeError("modelforge is not configured; look at modelforge.configuration. " "Depending on your objective you may or may not ...
[ "def", "cache_dir", "(", ")", "->", "str", ":", "if", "config", ".", "VENDOR", "is", "None", ":", "raise", "RuntimeError", "(", "\"modelforge is not configured; look at modelforge.configuration. \"", "\"Depending on your objective you may or may not want to create a \"", "\"mod...
67.714286
0.0125
def get_flow(self): """Reassemble the flow and return all the info/data""" if self.meta['protocol'] == 'TCP': self.meta['packet_list'].sort(key=lambda packet: packet['transport']['seq']) for packet in self.meta['packet_list']: self.meta['payload'] += packet['trans...
[ "def", "get_flow", "(", "self", ")", ":", "if", "self", ".", "meta", "[", "'protocol'", "]", "==", "'TCP'", ":", "self", ".", "meta", "[", "'packet_list'", "]", ".", "sort", "(", "key", "=", "lambda", "packet", ":", "packet", "[", "'transport'", "]",...
44.125
0.008333
def _maximization(X, posterior, force_weights=None): """Estimate new centers, weights, and concentrations from Parameters ---------- posterior : array, [n_centers, n_examples] The posterior matrix from the expectation step. force_weights : None or array, [n_centers, ] If None is pa...
[ "def", "_maximization", "(", "X", ",", "posterior", ",", "force_weights", "=", "None", ")", ":", "n_examples", ",", "n_features", "=", "X", ".", "shape", "n_clusters", ",", "n_examples", "=", "posterior", ".", "shape", "concentrations", "=", "np", ".", "ze...
33.610169
0.00049
def likelihood_markov_blanket(self, beta): """ Creates likelihood markov blanket of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- - Negative loglikelihood """ ...
[ "def", "likelihood_markov_blanket", "(", "self", ",", "beta", ")", ":", "states", "=", "beta", "[", "self", ".", "z_no", ":", "self", ".", "z_no", "+", "self", ".", "data_length", "]", "# the local level (untransformed)", "parm", "=", "np", ".", "array", "...
44.375
0.011034
def delete_attachment(request, link_field=None, uri=None): """Delete existing file and link.""" if link_field is None: link_field = "record_uri" if uri is None: uri = record_uri(request) # Remove file. filters = [Filter(link_field, uri, core_utils.COMPARISON.EQ)] storage = reque...
[ "def", "delete_attachment", "(", "request", ",", "link_field", "=", "None", ",", "uri", "=", "None", ")", ":", "if", "link_field", "is", "None", ":", "link_field", "=", "\"record_uri\"", "if", "uri", "is", "None", ":", "uri", "=", "record_uri", "(", "req...
35.5625
0.001712
def add_document(self, question, answer): """Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: An answer to a question :type answer: :class:`str` """ question = question.strip() answer = ...
[ "def", "add_document", "(", "self", ",", "question", ",", "answer", ")", ":", "question", "=", "question", ".", "strip", "(", ")", "answer", "=", "answer", ".", "strip", "(", ")", "session", "=", "self", ".", "Session", "(", ")", "if", "session", "."...
29.068966
0.002296
def draw(data, format='auto', size=(400, 300), drawing_type='ball and stick', camera_type='perspective', shader='lambert', display_html=True, element_properties=None, show_save=False): """Draws an interactive 3D visualization of the inputted chemical. Args: data: A string or file repr...
[ "def", "draw", "(", "data", ",", "format", "=", "'auto'", ",", "size", "=", "(", "400", ",", "300", ")", ",", "drawing_type", "=", "'ball and stick'", ",", "camera_type", "=", "'perspective'", ",", "shader", "=", "'lambert'", ",", "display_html", "=", "T...
44.98374
0.000177
def point_arrays(self): """ Returns the all point arrays """ pdata = self.GetPointData() narr = pdata.GetNumberOfArrays() # Update data if necessary if hasattr(self, '_point_arrays'): keys = list(self._point_arrays.keys()) if narr == len(keys): ...
[ "def", "point_arrays", "(", "self", ")", ":", "pdata", "=", "self", ".", "GetPointData", "(", ")", "narr", "=", "pdata", ".", "GetNumberOfArrays", "(", ")", "# Update data if necessary", "if", "hasattr", "(", "self", ",", "'_point_arrays'", ")", ":", "keys",...
33.666667
0.002407
def c_func(funcname, reverse=False, nans=False, scalar=False): """ Fill c_funcs with constructed code from the templates """ varnames = ['group_idx', 'a', 'ret', 'counter'] codebase = c_base_reverse if reverse else c_base iteration = c_iter_scalar[funcname] if scalar else c_iter[funcname] if scalar:...
[ "def", "c_func", "(", "funcname", ",", "reverse", "=", "False", ",", "nans", "=", "False", ",", "scalar", "=", "False", ")", ":", "varnames", "=", "[", "'group_idx'", ",", "'a'", ",", "'ret'", ",", "'counter'", "]", "codebase", "=", "c_base_reverse", "...
53.6
0.001835
def from_scaledproto(cls, scaledproto_mesh, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None): """ TODO: add documentation """ mesh = cls(**scaledproto_mesh.items()) # roche coordin...
[ "def", "from_scaledproto", "(", "cls", ",", "scaledproto_mesh", ",", "pos", ",", "vel", ",", "euler", ",", "euler_vel", ",", "rotation_vel", "=", "(", "0", ",", "0", ",", "0", ")", ",", "component_com_x", "=", "None", ")", ":", "mesh", "=", "cls", "(...
33.333333
0.015564
def kick(self, group_name, user): """ https://api.slack.com/methods/groups.kick """ group_id = self.get_group_id(group_name) self.params.update({ 'channel': group_id, 'user': user, }) return FromUrl('https://slack.com/api/groups.kick', self....
[ "def", "kick", "(", "self", ",", "group_name", ",", "user", ")", ":", "group_id", "=", "self", ".", "get_group_id", "(", "group_name", ")", "self", ".", "params", ".", "update", "(", "{", "'channel'", ":", "group_id", ",", "'user'", ":", "user", ",", ...
38.555556
0.008451
def get_returner_options(virtualname=None, ret=None, attrs=None, **kwargs): ''' Get the returner options from salt. :param str virtualname: The returner virtualname (as returned by __virtual__() :param ret: result of the...
[ "def", "get_returner_options", "(", "virtualname", "=", "None", ",", "ret", "=", "None", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret_config", "=", "_fetch_ret_config", "(", "ret", ")", "attrs", "=", "attrs", "or", "{", "}", "prof...
30.597826
0.000344
def write_cycle(filename, graph, cycle, directed): """Write an eulerian tour in DOT format :param filename: the file to be written in DOT format :param graph: graph in listlist format, cannot be listdict :param bool directed: describes the graph :param cycle: tour as a vertex list ...
[ "def", "write_cycle", "(", "filename", ",", "graph", ",", "cycle", ",", "directed", ")", ":", "n", "=", "len", "(", "graph", ")", "weight", "=", "[", "[", "float", "(", "'inf'", ")", "]", "*", "n", "for", "_", "in", "range", "(", "n", ")", "]",...
38.529412
0.00149
def felsensteins(binaryTree, subMatrices, ancestorProbs, leaves, alphabetSize): """ calculates the un-normalised probabilties of each non-gap residue position """ l = {} def upPass(binaryTree): if binaryTree.internal: #is internal binaryTree i = branchUp(binaryTree.left) ...
[ "def", "felsensteins", "(", "binaryTree", ",", "subMatrices", ",", "ancestorProbs", ",", "leaves", ",", "alphabetSize", ")", ":", "l", "=", "{", "}", "def", "upPass", "(", "binaryTree", ")", ":", "if", "binaryTree", ".", "internal", ":", "#is internal binary...
50.962963
0.010699
def speed(self, factor): '''Adjust the audio speed (pitch and tempo together). Technically, the speed effect only changes the sample rate information, leaving the samples themselves untouched. The rate effect is invoked automatically to resample to the output sample rate, using its defa...
[ "def", "speed", "(", "self", ",", "factor", ")", ":", "if", "not", "is_number", "(", "factor", ")", "or", "factor", "<=", "0", ":", "raise", "ValueError", "(", "\"factor must be a positive number\"", ")", "if", "factor", "<", "0.5", "or", "factor", ">", ...
36.055556
0.0015
def process(self, context, data): """ Will modify the context.target_backend attribute based on the requester identifier. :param context: request context :param data: the internal request """ context.target_backend = self.requester_mapping[data.requester] return s...
[ "def", "process", "(", "self", ",", "context", ",", "data", ")", ":", "context", ".", "target_backend", "=", "self", ".", "requester_mapping", "[", "data", ".", "requester", "]", "return", "super", "(", ")", ".", "process", "(", "context", ",", "data", ...
42.75
0.008596
def info(calculators, gsims, views, exports, extracts, parameters, report, input_file=''): """ Give information. You can pass the name of an available calculator, a job.ini file, or a zip archive with the input files. """ if calculators: for calc in sorted(base.calculators): ...
[ "def", "info", "(", "calculators", ",", "gsims", ",", "views", ",", "exports", ",", "extracts", ",", "parameters", ",", "report", ",", "input_file", "=", "''", ")", ":", "if", "calculators", ":", "for", "calc", "in", "sorted", "(", "base", ".", "calcul...
38.028986
0.000371
def get_list_store(data_frame): ''' Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame` and a `gtk.ListStore` matching the contents of the data frame. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: ...
[ "def", "get_list_store", "(", "data_frame", ")", ":", "df_py_dtypes", "=", "get_py_dtypes", "(", "data_frame", ")", "list_store", "=", "gtk", ".", "ListStore", "(", "*", "df_py_dtypes", ".", "dtype", ")", "for", "i", ",", "row_i", "in", "data_frame", ".", ...
33.809524
0.00137
def query_parameters(param_list, defaults=None): """ Asks the user for parameters. If available, proposes some defaults. Args: param_list (list): List of parameters to ask the user for values. defaults (list): A list of proposed defaults. It must be a list of the same length as ...
[ "def", "query_parameters", "(", "param_list", ",", "defaults", "=", "None", ")", ":", "script_params", "=", "collections", ".", "OrderedDict", "(", "[", "k", ",", "[", "]", "]", "for", "k", "in", "param_list", ")", "for", "param", ",", "default", "in", ...
39.736842
0.001294
def _add_error(self, message): """Add an error test to the suite.""" error_line = Result(False, None, message, Directive("")) self._suite.addTest(Adapter(self._filename, error_line))
[ "def", "_add_error", "(", "self", ",", "message", ")", ":", "error_line", "=", "Result", "(", "False", ",", "None", ",", "message", ",", "Directive", "(", "\"\"", ")", ")", "self", ".", "_suite", ".", "addTest", "(", "Adapter", "(", "self", ".", "_fi...
50.75
0.009709
def filter(self, filter_func): """Return a new SampleCollection containing only samples meeting the filter criteria. Will pass any kwargs (e.g., field or skip_missing) used when instantiating the current class on to the new SampleCollection that is returned. Parameters --------...
[ "def", "filter", "(", "self", ",", "filter_func", ")", ":", "if", "callable", "(", "filter_func", ")", ":", "return", "self", ".", "__class__", "(", "[", "obj", "for", "obj", "in", "self", "if", "filter_func", "(", "obj", ")", "is", "True", "]", ",",...
42.034483
0.008821
def _parse_profile(profile): ''' From a pillar key, or a dictionary, return index and host keys. ''' if isinstance(profile, string_types): _profile = __salt__['config.option'](profile) if not _profile: msg = 'Pillar key for profile {0} not found.'.format(profile) ...
[ "def", "_parse_profile", "(", "profile", ")", ":", "if", "isinstance", "(", "profile", ",", "string_types", ")", ":", "_profile", "=", "__salt__", "[", "'config.option'", "]", "(", "profile", ")", "if", "not", "_profile", ":", "msg", "=", "'Pillar key for pr...
33.428571
0.002079
def do_rm(self, path): path = path[0] """delete a file or directory""" self.n.delete(self.current_path + path) self.dirs = self.dir_complete() self.files = self.file_complete()
[ "def", "do_rm", "(", "self", ",", "path", ")", ":", "path", "=", "path", "[", "0", "]", "self", ".", "n", ".", "delete", "(", "self", ".", "current_path", "+", "path", ")", "self", ".", "dirs", "=", "self", ".", "dir_complete", "(", ")", "self", ...
30.142857
0.009217
def Impute(name, dist_class, imputable, **parents): """ This function accomodates missing elements for the data of simple Stochastic distribution subclasses. The masked_values argument is an object of type numpy.ma.MaskedArray, which contains the raw data and a boolean mask indicating missing values...
[ "def", "Impute", "(", "name", ",", "dist_class", ",", "imputable", ",", "*", "*", "parents", ")", ":", "dims", "=", "np", ".", "shape", "(", "imputable", ")", "masked_values", "=", "np", ".", "ravel", "(", "imputable", ")", "if", "not", "isinstance", ...
37.238806
0.00039
def upload_predictions(self, file_path, tournament=1): """Upload predictions from file. Args: file_path (str): CSV file with predictions that will get uploaded tournament (int): ID of the tournament (optional, defaults to 1) Returns: str: submission_id ...
[ "def", "upload_predictions", "(", "self", ",", "file_path", ",", "tournament", "=", "1", ")", ":", "self", ".", "logger", ".", "info", "(", "\"uploading predictions...\"", ")", "auth_query", "=", "'''\n query($filename: String!\n $tournament: I...
38.270833
0.001062
def _reversePoints(points): """ Reverse the points. This differs from the reversal point pen in RoboFab in that it doesn't worry about maintaing the start point position. That has no benefit within the context of this module. """ # copy the points points = _copyPoints(points) # find ...
[ "def", "_reversePoints", "(", "points", ")", ":", "# copy the points", "points", "=", "_copyPoints", "(", "points", ")", "# find the first on curve type and recycle", "# it for the last on curve type", "firstOnCurve", "=", "None", "for", "index", ",", "point", "in", "en...
33.0625
0.000918
def from_jwt(self, txt, keyjar, verify=True, **kwargs): """ Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature o...
[ "def", "from_jwt", "(", "self", ",", "txt", ",", "keyjar", ",", "verify", "=", "True", ",", "*", "*", "kwargs", ")", ":", "algarg", "=", "{", "}", "if", "'encalg'", "in", "kwargs", ":", "algarg", "[", "'alg'", "]", "=", "kwargs", "[", "'encalg'", ...
35.674699
0.000986
def raw_conf_process_pyramid(raw_conf): """ Loads the process pyramid of a raw configuration. Parameters ---------- raw_conf : dict Raw mapchete configuration as dictionary. Returns ------- BufferedTilePyramid """ return BufferedTilePyramid( raw_conf["pyramid"][...
[ "def", "raw_conf_process_pyramid", "(", "raw_conf", ")", ":", "return", "BufferedTilePyramid", "(", "raw_conf", "[", "\"pyramid\"", "]", "[", "\"grid\"", "]", ",", "metatiling", "=", "raw_conf", "[", "\"pyramid\"", "]", ".", "get", "(", "\"metatiling\"", ",", ...
24.444444
0.002188
def handle_onchain_secretreveal( initiator_state: InitiatorTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: """ When a secret is revealed on-chain all n...
[ "def", "handle_onchain_secretreveal", "(", "initiator_state", ":", "InitiatorTransferState", ",", "state_change", ":", "ContractReceiveSecretReveal", ",", "channel_state", ":", "NettingChannelState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", ...
34.823529
0.001095
def is_new_preorder( self, preorder_hash, lastblock=None ): """ Given a preorder hash of a name, determine whether or not it is unseen before. """ if lastblock is None: lastblock = self.lastblock preorder = namedb_get_name_preorder( self.db, preorder_hash, lastblock...
[ "def", "is_new_preorder", "(", "self", ",", "preorder_hash", ",", "lastblock", "=", "None", ")", ":", "if", "lastblock", "is", "None", ":", "lastblock", "=", "self", ".", "lastblock", "preorder", "=", "namedb_get_name_preorder", "(", "self", ".", "db", ",", ...
33.916667
0.021531
def faceted_search(cls, query=None, filters=None, search=None): """Return faceted search instance with defaults set. :param query: Elastic DSL query object (``Q``). :param filters: Dictionary with selected facet values. :param search: An instance of ``Search`` class. (default: ``cls()``...
[ "def", "faceted_search", "(", "cls", ",", "query", "=", "None", ",", "filters", "=", "None", ",", "search", "=", "None", ")", ":", "search_", "=", "search", "or", "cls", "(", ")", "class", "RecordsFacetedSearch", "(", "FacetedSearch", ")", ":", "\"\"\"Pa...
45.777778
0.001585
def get_scaled_cutout_basic_view(shp, p1, p2, scales): """ Like get_scaled_cutout_basic, but returns the view/slice to extract from an image, instead of the extraction itself """ x1, y1 = p1[:2] x2, y2 = p2[:2] scale_x, scale_y = scales[:2] # calculate dimensions of NON-scaled cutout ...
[ "def", "get_scaled_cutout_basic_view", "(", "shp", ",", "p1", ",", "p2", ",", "scales", ")", ":", "x1", ",", "y1", "=", "p1", "[", ":", "2", "]", "x2", ",", "y2", "=", "p2", "[", ":", "2", "]", "scale_x", ",", "scale_y", "=", "scales", "[", ":"...
33.608696
0.001258
def _write_training_loss(self, iteration:int, last_loss:Tensor)->None: "Writes training loss to Tensorboard." scalar_value = to_np(last_loss) tag = self.metrics_root + 'train_loss' self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
[ "def", "_write_training_loss", "(", "self", ",", "iteration", ":", "int", ",", "last_loss", ":", "Tensor", ")", "->", "None", ":", "scalar_value", "=", "to_np", "(", "last_loss", ")", "tag", "=", "self", ".", "metrics_root", "+", "'train_loss'", "self", "....
58.4
0.02027
def remove_external_tracker(self, ids=None, ext_type_id=None, ext_type_description=None, ext_type_url=None, ext_bz_bug_id=None, bug_ids=None): """ Wrapper method to allow removal of external tracking bugs using the ExternalBugs::Web...
[ "def", "remove_external_tracker", "(", "self", ",", "ids", "=", "None", ",", "ext_type_id", "=", "None", ",", "ext_type_description", "=", "None", ",", "ext_type_url", "=", "None", ",", "ext_bz_bug_id", "=", "None", ",", "bug_ids", "=", "None", ")", ":", "...
47.432432
0.002233
def about(self): """Create About Spyder dialog with general information.""" versions = get_versions() # Show Git revision for development version revlink = '' if versions['revision']: rev = versions['revision'] revlink = " (<a href='https://github.c...
[ "def", "about", "(", "self", ")", ":", "versions", "=", "get_versions", "(", ")", "# Show Git revision for development version\r", "revlink", "=", "''", "if", "versions", "[", "'revision'", "]", ":", "rev", "=", "versions", "[", "'revision'", "]", "revlink", "...
47.520408
0.000421
def get_config_value(request, key, default, search_in_settings=True): """Retrieves the value of `key` from configuration in the following order: - from the session; if not found there then - from cookies; if not found there then - from the settings file if `search_in_settings` is True, otherwise ...
[ "def", "get_config_value", "(", "request", ",", "key", ",", "default", ",", "search_in_settings", "=", "True", ")", ":", "value", "=", "request", ".", "session", ".", "get", "(", "key", ",", "request", ".", "COOKIES", ".", "get", "(", "key", ")", ")", ...
31.791667
0.001272