text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _derX(self,x,y): ''' Returns the first derivative of the function with respect to X at each value in (x,y). Only called internally by HARKinterpolator2D._derX. ''' m = len(x) temp = np.zeros((m,self.funcCount)) for j in range(self.funcCount): temp...
[ "def", "_derX", "(", "self", ",", "x", ",", "y", ")", ":", "m", "=", "len", "(", "x", ")", "temp", "=", "np", ".", "zeros", "(", "(", "m", ",", "self", ".", "funcCount", ")", ")", "for", "j", "in", "range", "(", "self", ".", "funcCount", ")...
36.625
0.014975
def pcklof(filename): """ Load a binary PCK file for use by the readers. Return the handle of the loaded file which is used by other PCK routines to refer to the file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pcklof_c.html :param filename: Name of the file to be loaded. :ty...
[ "def", "pcklof", "(", "filename", ")", ":", "filename", "=", "stypes", ".", "stringToCharP", "(", "filename", ")", "handle", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "pcklof_c", "(", "filename", ",", "ctypes", ".", "byref", "(", "handle", ...
31.235294
0.001828
def update_deps( self ): """Update dependencies on all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.update_deps_on_field( name ) return
[ "def", "update_deps", "(", "self", ")", ":", "klass", "=", "self", ".", "__class__", "for", "name", "in", "klass", ".", "_fields", ":", "self", ".", "update_deps_on_field", "(", "name", ")", "return" ]
31.714286
0.026316
def generate_supremacy_circuit_google_v2(qubits: Iterable[devices.GridQubit], cz_depth: int, seed: int) -> circuits.Circuit: """ Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.or...
[ "def", "generate_supremacy_circuit_google_v2", "(", "qubits", ":", "Iterable", "[", "devices", ".", "GridQubit", "]", ",", "cz_depth", ":", "int", ",", "seed", ":", "int", ")", "->", "circuits", ".", "Circuit", ":", "non_diagonal_gates", "=", "[", "ops", "."...
40.466667
0.000402
def iterateBlocksBackFrom(block): """Generator, which iterates QTextBlocks from block until the Start of a document But, yields not more than MAX_SEARCH_OFFSET_LINES """ count = 0 while block.isValid() and count < MAX_SEARCH_OFFSET_LINES: yield block block...
[ "def", "iterateBlocksBackFrom", "(", "block", ")", ":", "count", "=", "0", "while", "block", ".", "isValid", "(", ")", "and", "count", "<", "MAX_SEARCH_OFFSET_LINES", ":", "yield", "block", "block", "=", "block", ".", "previous", "(", ")", "count", "+=", ...
39.333333
0.008287
def _get_mean(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # Zhao et al. 2006 - Vs30 + Rrup mean_zh06, stds1 = super().get_mean_and_...
[ "def", "_get_mean", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# Zhao et al. 2006 - Vs30 + Rrup", "mean_zh06", ",", "stds1", "=", "super", "(", ")", ".", "get_mean_and_stddevs", "(", "sites", ",", "rup", ...
46.8
0.001396
def posted(self): """ True if bug was moved to POST in given time frame """ for who, record in self.logs: if record["field_name"] == "status" and record["added"] == "POST": return True return False
[ "def", "posted", "(", "self", ")", ":", "for", "who", ",", "record", "in", "self", ".", "logs", ":", "if", "record", "[", "\"field_name\"", "]", "==", "\"status\"", "and", "record", "[", "\"added\"", "]", "==", "\"POST\"", ":", "return", "True", "retur...
40.666667
0.008032
def open_raw(self, page, parms=None, payload=None, HTTPrequest=None, payload_type='application/json' ): '''Opens a page from the server with optional XML. Returns a response file-like object''' if not parms: parms={} # if we're using a key, but it's not going in the header, add it ...
[ "def", "open_raw", "(", "self", ",", "page", ",", "parms", "=", "None", ",", "payload", "=", "None", ",", "HTTPrequest", "=", "None", ",", "payload_type", "=", "'application/json'", ")", ":", "if", "not", "parms", ":", "parms", "=", "{", "}", "# if we'...
32.333333
0.01236
def get_parent_id(self): '''Returns parent id''' parent_id = parsers.get_parent_id(self.__chebi_id) return None if math.isnan(parent_id) else 'CHEBI:' + str(parent_id)
[ "def", "get_parent_id", "(", "self", ")", ":", "parent_id", "=", "parsers", ".", "get_parent_id", "(", "self", ".", "__chebi_id", ")", "return", "None", "if", "math", ".", "isnan", "(", "parent_id", ")", "else", "'CHEBI:'", "+", "str", "(", "parent_id", ...
47
0.010471
def intent(method): """Helps object methods handle MatrixRequestError. Args: method(function): Object method to be wrapped Method's object must have _handle_request_exception method that deals with specific status codes and errcodes. """ def wrapper(self, *args, **kwargs): try...
[ "def", "intent", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "exceptions", "."...
32.521739
0.001299
def max(self, constraints, X: BitVec, M=10000): """ Iteratively finds the maximum value for a symbol within given constraints. :param X: a symbol or expression :param M: maximum number of iterations allowed """ assert isinstance(X, BitVec) return self.optimize(con...
[ "def", "max", "(", "self", ",", "constraints", ",", "X", ":", "BitVec", ",", "M", "=", "10000", ")", ":", "assert", "isinstance", "(", "X", ",", "BitVec", ")", "return", "self", ".", "optimize", "(", "constraints", ",", "X", ",", "'maximize'", ",", ...
42.5
0.008646
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :ma...
[ "def", "partial_distance_correlation", "(", "x", ",", "y", ",", "z", ")", ":", "# pylint:disable=too-many-locals", "a", "=", "_u_distance_matrix", "(", "x", ")", "b", "=", "_u_distance_matrix", "(", "y", ")", "c", "=", "_u_distance_matrix", "(", "z", ")", "a...
31.191781
0.000426
def validateDtd(self, ctxt, dtd): """Try to validate the document against the dtd instance Basically it does check all the definitions in the DtD. Note the the internal subset (if present) is de-coupled (i.e. not used), which could give problems if ID or IDREF is present...
[ "def", "validateDtd", "(", "self", ",", "ctxt", ",", "dtd", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "if", "dtd", "is", "None", ":", "dtd__o", "=", "None", "else", ":", "dt...
44.916667
0.010909
def readall_fast(stm, size): """ Slightly faster version of readall, it reads no more than two chunks. Meaning that it can only be used to read small data that doesn't span more that two packets. :param stm: Stream to read from, should have read method. :param size: Number of bytes to read. ...
[ "def", "readall_fast", "(", "stm", ",", "size", ")", ":", "buf", ",", "offset", "=", "stm", ".", "read_fast", "(", "size", ")", "if", "len", "(", "buf", ")", "-", "offset", "<", "size", ":", "# slow case", "buf", "=", "buf", "[", "offset", ":", "...
30.882353
0.001848
def AddLeafNodes(self, prefix, node): """Adds leaf nodes begin with prefix to this tree.""" if not node: self.AddPath(prefix) for name in node: child_path = prefix + '.' + name self.AddLeafNodes(child_path, node[name])
[ "def", "AddLeafNodes", "(", "self", ",", "prefix", ",", "node", ")", ":", "if", "not", "node", ":", "self", ".", "AddPath", "(", "prefix", ")", "for", "name", "in", "node", ":", "child_path", "=", "prefix", "+", "'.'", "+", "name", "self", ".", "Ad...
34.571429
0.016129
def get_host(environ, trusted_hosts=None): """Return the real host for the given WSGI environment. This first checks the `X-Forwarded-Host` header, then the normal `Host` header, and finally the `SERVER_NAME` environment variable (using the first one it finds). Optionally it verifies that the host is ...
[ "def", "get_host", "(", "environ", ",", "trusted_hosts", "=", "None", ")", ":", "if", "'HTTP_X_FORWARDED_HOST'", "in", "environ", ":", "rv", "=", "environ", "[", "'HTTP_X_FORWARDED_HOST'", "]", ".", "split", "(", "','", ",", "1", ")", "[", "0", "]", ".",...
45.518519
0.000797
def fit_mle(self, init_vals, init_shapes=None, init_intercepts=None, init_coefs=None, print_res=True, method="BFGS", loss_tol=1e-06, gradient_tol=1e-06, maxiter=1000, ...
[ "def", "fit_mle", "(", "self", ",", "init_vals", ",", "init_shapes", "=", "None", ",", "init_intercepts", "=", "None", ",", "init_coefs", "=", "None", ",", "print_res", "=", "True", ",", "method", "=", "\"BFGS\"", ",", "loss_tol", "=", "1e-06", ",", "gra...
47.722222
0.001711
def SegmentMax(a, ids): """ Segmented max op. """ func = lambda idxs: np.amax(a[idxs], axis=0) return seg_map(func, a, ids),
[ "def", "SegmentMax", "(", "a", ",", "ids", ")", ":", "func", "=", "lambda", "idxs", ":", "np", ".", "amax", "(", "a", "[", "idxs", "]", ",", "axis", "=", "0", ")", "return", "seg_map", "(", "func", ",", "a", ",", "ids", ")", "," ]
23.166667
0.013889
def _make_login(self): """ Private method that makes login """ login_url = '{}data/v1/session/login?user={}&pass={}&sid={}'.format(self.base_url, self.username, self.password, self._parse_session_id(self._session_info)) ...
[ "def", "_make_login", "(", "self", ")", ":", "login_url", "=", "'{}data/v1/session/login?user={}&pass={}&sid={}'", ".", "format", "(", "self", ".", "base_url", ",", "self", ".", "username", ",", "self", ".", "password", ",", "self", ".", "_parse_session_id", "("...
60.5
0.01087
def delete(self, id): """ Deletes document with ID on all Solr cores """ for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\" : { \"id\" : \"%s\"}}" % (id,))
[ "def", "delete", "(", "self", ",", "id", ")", ":", "for", "core", "in", "self", ".", "endpoints", ":", "self", ".", "_send_solr_command", "(", "self", ".", "endpoints", "[", "core", "]", ",", "\"{\\\"delete\\\" : { \\\"id\\\" : \\\"%s\\\"}}\"", "%", "(", "id...
38.333333
0.012766
def setup_alignak_logger(self): """ Setup alignak logger: - with the daemon log configuration properties - configure the global daemon handler (root logger) - log the daemon Alignak header - configure the global Alignak monitoring log This function is called very early ...
[ "def", "setup_alignak_logger", "(", "self", ")", ":", "# Configure the daemon logger", "try", ":", "# Make sure that the log directory is existing", "self", ".", "check_dir", "(", "self", ".", "logdir", ")", "setup_logger", "(", "logger_configuration_file", "=", "self", ...
43.738462
0.00172
def keyring_parser(path): """ This is a very, very, dumb parser that will look for `[entity]` sections and return a list of those sections. It is not possible to parse this with ConfigParser even though it is almost the same thing. Since this is only used to spit out warnings, it is OK to just be n...
[ "def", "keyring_parser", "(", "path", ")", ":", "sections", "=", "[", "]", "with", "open", "(", "path", ")", "as", "keyring", ":", "lines", "=", "keyring", ".", "readlines", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "st...
36.352941
0.001577
def refine_arccalibration(sp, poly_initial, wv_master, poldeg, nrepeat=3, ntimes_match_wv=2, nwinwidth_initial=7, nwinwidth_refined=5, times_sigma_reject=5, interac...
[ "def", "refine_arccalibration", "(", "sp", ",", "poly_initial", ",", "wv_master", ",", "poldeg", ",", "nrepeat", "=", "3", ",", "ntimes_match_wv", "=", "2", ",", "nwinwidth_initial", "=", "7", ",", "nwinwidth_refined", "=", "5", ",", "times_sigma_reject", "=",...
40.376953
0.000047
def oval(document, coords): "circle/ellipse" x1, y1, x2, y2 = coords # circle if x2-x1 == y2-y1: return setattribs(document.createElement('circle'), cx = (x1+x2)/2, cy = (y1+y2)/2, r = abs(x2-x1)/2, ) # ellipse else: return setattribs(document.createElement('ellipse'), cx = (x1+x2)/2, cy ...
[ "def", "oval", "(", "document", ",", "coords", ")", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "coords", "# circle", "if", "x2", "-", "x1", "==", "y2", "-", "y1", ":", "return", "setattribs", "(", "document", ".", "createElement", "(", "'circ...
17.136364
0.100503
def link_mountpoint(self, repo): ''' Ensure that the mountpoint is present in the correct location and points at the correct path ''' lcachelink = salt.utils.path.join(repo.linkdir, repo._mountpoint) lcachedest = salt.utils.path.join(repo.cachedir, repo.root()).rstrip(os....
[ "def", "link_mountpoint", "(", "self", ",", "repo", ")", ":", "lcachelink", "=", "salt", ".", "utils", ".", "path", ".", "join", "(", "repo", ".", "linkdir", ",", "repo", ".", "_mountpoint", ")", "lcachedest", "=", "salt", ".", "utils", ".", "path", ...
48.141593
0.00072
def fmt_text(text, bg = None, fg = None, attr = None, plain = False): """ Apply given console formating around given text. """ if not plain: if fg is not None: text = TEXT_FORMATING['fg'][fg] + text if bg is not None: text = TEXT_FO...
[ "def", "fmt_text", "(", "text", ",", "bg", "=", "None", ",", "fg", "=", "None", ",", "attr", "=", "None", ",", "plain", "=", "False", ")", ":", "if", "not", "plain", ":", "if", "fg", "is", "not", "None", ":", "text", "=", "TEXT_FORMATING", "[", ...
40.285714
0.017331
def count(self): """Total number of all tests/traces/reps currently in this protocol :returns: int -- the total """ total = 0 for test in self.protocol_model.allTests(): total += test.traceCount()*test.loopCount()*test.repCount() + test.repCount() return tota...
[ "def", "count", "(", "self", ")", ":", "total", "=", "0", "for", "test", "in", "self", ".", "protocol_model", ".", "allTests", "(", ")", ":", "total", "+=", "test", ".", "traceCount", "(", ")", "*", "test", ".", "loopCount", "(", ")", "*", "test", ...
34.777778
0.009346
def low_rank_approximation(A, r): """ Returns approximation of A of rank r in least-squares sense.""" try: u, s, v = np.linalg.svd(A, full_matrices=False) except np.linalg.LinAlgError as e: print('Matrix:', A) print('Matrix rank:', np.linalg.matrix_rank(A)) raise Ar = np...
[ "def", "low_rank_approximation", "(", "A", ",", "r", ")", ":", "try", ":", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "A", ",", "full_matrices", "=", "False", ")", "except", "np", ".", "linalg", ".", "LinAlgError", "as", ...
33.588235
0.001704
def generate_add_sub(self): ''' Generates prefixes/suffixes in a short form to parse and remove some redundancy ''' # Prefix or Suffix affix_type = 'p:' if self.opt == "PFX" else 's:' remove_char = '-' + self.char_to_strip if self.char_to_strip != '' else '' return affix_type + ...
[ "def", "generate_add_sub", "(", "self", ")", ":", "# Prefix or Suffix", "affix_type", "=", "'p:'", "if", "self", ".", "opt", "==", "\"PFX\"", "else", "'s:'", "remove_char", "=", "'-'", "+", "self", ".", "char_to_strip", "if", "self", ".", "char_to_strip", "!...
49.142857
0.011429
def generate_shared_access_signature(self, services, resource_types, permission, expiry, start=None, ip=None, protocol=None): ''' Generates a shared access signature for the account. Use the returned signature with...
[ "def", "generate_shared_access_signature", "(", "self", ",", "services", ",", "resource_types", ",", "permission", ",", "expiry", ",", "start", "=", "None", ",", "ip", "=", "None", ",", "protocol", "=", "None", ")", ":", "_validate_not_none", "(", "'self.accou...
60.296296
0.011182
def bulk_log(self, log_message=u"Еще одна пачка обработана", total=None, part_log_time_minutes=5): """ Возвращает инстант логгера для обработки списокв данных :param log_message: То, что будет написано, когда время придет :param total: Общее кол-во объектов, если вы знаете его :p...
[ "def", "bulk_log", "(", "self", ",", "log_message", "=", "u\"Еще одна пачка обработана\", total=None, part_log", "_", "ime_m", "i", "nute", "s", "5):", "", "", "", "", "return", "BulkLogger", "(", "log", "=", "self", ".", "log", ",", "log_message", "=", "log...
60.777778
0.009009
def _batched_op_msg( operation, command, docs, check_keys, ack, opts, ctx): """OP_MSG implementation entry point.""" buf = StringIO() # Save space for message length and request id buf.write(_ZERO_64) # responseTo, opCode buf.write(b"\x00\x00\x00\x00\xdd\x07\x00\x00") to_send, leng...
[ "def", "_batched_op_msg", "(", "operation", ",", "command", ",", "docs", ",", "check_keys", ",", "ack", ",", "opts", ",", "ctx", ")", ":", "buf", "=", "StringIO", "(", ")", "# Save space for message length and request id", "buf", ".", "write", "(", "_ZERO_64",...
29.380952
0.00157
def _timeout_from_retry_config(retry_params): """Creates a ExponentialTimeout object given a gapic retry configuration. Args: retry_params (dict): The retry parameter values, for example:: { "initial_retry_delay_millis": 1000, "retry_delay_multiplier": 2.5, ...
[ "def", "_timeout_from_retry_config", "(", "retry_params", ")", ":", "return", "timeout", ".", "ExponentialTimeout", "(", "initial", "=", "(", "retry_params", "[", "\"initial_rpc_timeout_millis\"", "]", "/", "_MILLIS_PER_SECOND", ")", ",", "maximum", "=", "(", "retry...
39.384615
0.001907
def get_resource_path(self, relative_path): """ NOTE: This API may change in the future. Return the absolute path to a resource file with the given relative path. :param relative_path: The path, relative to .dist-info, of the resource of interest. ...
[ "def", "get_resource_path", "(", "self", ",", "relative_path", ")", ":", "r", "=", "self", ".", "get_distinfo_resource", "(", "'RESOURCES'", ")", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", "stream", ":", "with", ...
43.789474
0.002353
def onerror(function, path, excinfo): """Error handler for `shutil.rmtree`. If the error is due to an access error (read-only file), it attempts to add write permission and then retries. If the error is for another reason, it re-raises the error. Usage: `shutil.rmtree(path, onerror=onerror)...
[ "def", "onerror", "(", "function", ",", "path", ",", "excinfo", ")", ":", "if", "not", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")", ":", "# Is the error an access error?\r", "os", ".", "chmod", "(", "path", ",", "stat", ".", "S_IWUSR"...
34.071429
0.002041
def resample(self, inds): """Returns copy of constraint, with mask rearranged according to indices """ new = copy.deepcopy(self) for arr in self.arrays: x = getattr(new, arr) setattr(new, arr, x[inds]) return new
[ "def", "resample", "(", "self", ",", "inds", ")", ":", "new", "=", "copy", ".", "deepcopy", "(", "self", ")", "for", "arr", "in", "self", ".", "arrays", ":", "x", "=", "getattr", "(", "new", ",", "arr", ")", "setattr", "(", "new", ",", "arr", "...
33.625
0.01087
def function_args(callable_, *args, **kwargs): """ Return (args, kwargs) matching the function signature :param callable: callable to inspect :type callable: callable :param args: :type args: :param kwargs: :type kwargs: :return: (args, kwargs) matching the function signature :r...
[ "def", "function_args", "(", "callable_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "argspec", "=", "getargspec", "(", "callable_", ")", "# pylint:disable=deprecated-method", "return", "argspec_args", "(", "argspec", ",", "False", ",", "*", "args", ...
30.266667
0.002137
def remove_decorators(src): """ Remove decorators from the source code """ src = src.strip() src_lines = src.splitlines() multi_line = False n_deleted = 0 for n in range(len(src_lines)): line = src_lines[n - n_deleted].strip() if (line.startswith('@') and 'Benchmark' in line) or ...
[ "def", "remove_decorators", "(", "src", ")", ":", "src", "=", "src", ".", "strip", "(", ")", "src_lines", "=", "src", ".", "splitlines", "(", ")", "multi_line", "=", "False", "n_deleted", "=", "0", "for", "n", "in", "range", "(", "len", "(", "src_lin...
33.117647
0.001727
def none_to_blank(s, exchange=''): """Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to retur...
[ "def", "none_to_blank", "(", "s", ",", "exchange", "=", "''", ")", ":", "if", "isinstance", "(", "s", ",", "list", ")", ":", "return", "[", "none_to_blank", "(", "z", ")", "for", "y", ",", "z", "in", "enumerate", "(", "s", ")", "]", "return", "ex...
27.526316
0.001848
def store_job_info_artifact(job, job_info_artifact): """ Store the contents of the job info artifact in job details """ job_details = json.loads(job_info_artifact['blob'])['job_details'] for job_detail in job_details: job_detail_dict = { 'title': job_detail.get('title'), ...
[ "def", "store_job_info_artifact", "(", "job", ",", "job_info_artifact", ")", ":", "job_details", "=", "json", ".", "loads", "(", "job_info_artifact", "[", "'blob'", "]", ")", "[", "'job_details'", "]", "for", "job_detail", "in", "job_details", ":", "job_detail_d...
40.185185
0.0018
def truthtable2expr(tt, conj=False): """Convert a truth table into an expression.""" if conj: outer, inner = (And, Or) nums = tt.pcdata.iter_zeros() else: outer, inner = (Or, And) nums = tt.pcdata.iter_ones() inputs = [exprvar(v.names, v.indices) for v in tt.inputs] t...
[ "def", "truthtable2expr", "(", "tt", ",", "conj", "=", "False", ")", ":", "if", "conj", ":", "outer", ",", "inner", "=", "(", "And", ",", "Or", ")", "nums", "=", "tt", ".", "pcdata", ".", "iter_zeros", "(", ")", "else", ":", "outer", ",", "inner"...
38.454545
0.002309
def df_to_dat(net, df, define_cat_colors=False): ''' This is always run when data is loaded. ''' from . import categories # check if df has unique values df['mat'] = make_unique_labels.main(net, df['mat']) net.dat['mat'] = df['mat'].values net.dat['nodes']['row'] = df['mat'].index.tolist() net.dat['...
[ "def", "df_to_dat", "(", "net", ",", "df", ",", "define_cat_colors", "=", "False", ")", ":", "from", ".", "import", "categories", "# check if df has unique values", "df", "[", "'mat'", "]", "=", "make_unique_labels", ".", "main", "(", "net", ",", "df", "[", ...
32.162162
0.015498
def check_correct_host(self): """The method checks whether the host is correctly set and whether it can configure the connection to this host. Does not check the base host knoema.com """ if self._host == 'knoema.com': return url = self._get_url('/api/1.0/frontend/tags') ...
[ "def", "check_correct_host", "(", "self", ")", ":", "if", "self", ".", "_host", "==", "'knoema.com'", ":", "return", "url", "=", "self", ".", "_get_url", "(", "'/api/1.0/frontend/tags'", ")", "req", "=", "urllib", ".", "request", ".", "Request", "(", "url"...
51.2
0.009597
def connect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None: '''Connect to a device via TCP/IP directly.''' self.device_sn = f'{host}:{port}' if not is_connectable(host, port): raise ConnectionError(f'Cannot connect to {self.device_sn}.') self._execute(...
[ "def", "connect", "(", "self", ",", "host", ":", "str", "=", "'192.168.0.3'", ",", "port", ":", "Union", "[", "int", ",", "str", "]", "=", "5555", ")", "->", "None", ":", "self", ".", "device_sn", "=", "f'{host}:{port}'", "if", "not", "is_connectable",...
56.833333
0.008671
def angle(self, value): """gets/sets the angle""" if self._angle != value and \ isinstance(value, (int, float, long)): self._angle = value
[ "def", "angle", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_angle", "!=", "value", "and", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "long", ")", ")", ":", "self", ".", "_angle", "=", "value" ]
34.6
0.011299
def inspect_sensors(self, name=None, timeout=None): """Inspect all or one sensor on the device. Update sensors index. Parameters ---------- name : str or None, optional Name of the sensor or None to get all sensors. timeout : float or None, optional Timeo...
[ "def", "inspect_sensors", "(", "self", ",", "name", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "name", "is", "None", ":", "msg", "=", "katcp", ".", "Message", ".", "request", "(", "'sensor-list'", ")", "else", ":", "msg", "=", "katcp",...
38.603175
0.001604
def colorspace(self): """PDF name of the colorspace that best describes this image""" if self.image_mask: return None # Undefined for image masks if self._colorspaces: if self._colorspaces[0] in self.SIMPLE_COLORSPACES: return self._colorspaces[0] ...
[ "def", "colorspace", "(", "self", ")", ":", "if", "self", ".", "image_mask", ":", "return", "None", "# Undefined for image masks", "if", "self", ".", "_colorspaces", ":", "if", "self", ".", "_colorspaces", "[", "0", "]", "in", "self", ".", "SIMPLE_COLORSPACE...
43
0.002275
def verify(self, smessage, signature=None, encoder=encoding.RawEncoder): """ Verifies the signature of a signed message, returning the message if it has not been tampered with else raising :class:`~ValueError`. :param smessage: [:class:`bytes`] Either the original messaged or a ...
[ "def", "verify", "(", "self", ",", "smessage", ",", "signature", "=", "None", ",", "encoder", "=", "encoding", ".", "RawEncoder", ")", ":", "if", "signature", "is", "not", "None", ":", "# If we were given the message and signature separately, combine", "# them.", ...
41.695652
0.002039
def _convert_to_image_color(self, color): """:return: a color that can be used by the image""" rgb = self._convert_color_to_rrggbb(color) return self._convert_rrggbb_to_image_color(rgb)
[ "def", "_convert_to_image_color", "(", "self", ",", "color", ")", ":", "rgb", "=", "self", ".", "_convert_color_to_rrggbb", "(", "color", ")", "return", "self", ".", "_convert_rrggbb_to_image_color", "(", "rgb", ")" ]
51.5
0.009569
def to_triangulation(self): """ Returns the mesh as a matplotlib.tri.Triangulation instance. (2D only) """ from matplotlib.tri import Triangulation conn = self.split("simplices").unstack() coords = self.nodes.coords.copy() node_map = pd.Series(data = np.arange(len(coords)), index = coords.i...
[ "def", "to_triangulation", "(", "self", ")", ":", "from", "matplotlib", ".", "tri", "import", "Triangulation", "conn", "=", "self", ".", "split", "(", "\"simplices\"", ")", ".", "unstack", "(", ")", "coords", "=", "self", ".", "nodes", ".", "coords", "."...
45.6
0.012903
async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If th...
[ "async", "def", "ehlo_or_helo_if_needed", "(", "self", ")", ":", "no_helo", "=", "self", ".", "last_helo_response", "==", "(", "None", ",", "None", ")", "no_ehlo", "=", "self", ".", "last_ehlo_response", "==", "(", "None", ",", "None", ")", "if", "no_helo"...
36.347826
0.002331
def data_url(content, mimetype=None): """ Returns content encoded as base64 Data URI. :param content: bytes or str or Path :param mimetype: mimetype for :return: str object (consisting only of ASCII, though) .. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme """ if isinstance(c...
[ "def", "data_url", "(", "content", ",", "mimetype", "=", "None", ")", ":", "if", "isinstance", "(", "content", ",", "pathlib", ".", "Path", ")", ":", "if", "not", "mimetype", ":", "mimetype", "=", "guess_type", "(", "content", ".", "name", ")", "[", ...
34.3
0.001418
def setup_prefix_logging(logdir): """ Sets up a file logger that will create a log in the given logdir (usually a lago prefix) Args: logdir (str): path to create the log into, will be created if it does not exist Returns: None """ if not os.path.exists(logdir): ...
[ "def", "setup_prefix_logging", "(", "logdir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "logdir", ")", ":", "os", ".", "mkdir", "(", "logdir", ")", "file_handler", "=", "logging", ".", "FileHandler", "(", "filename", "=", "os", ".",...
26.434783
0.001587
def get_parameter_dd(self, parameter): """ This method returns parameters as nested dicts in case of decision diagram parameter. """ dag = defaultdict(list) dag_elem = parameter.find('DAG') node = dag_elem.find('Node') root = node.get('var') def g...
[ "def", "get_parameter_dd", "(", "self", ",", "parameter", ")", ":", "dag", "=", "defaultdict", "(", "list", ")", "dag_elem", "=", "parameter", ".", "find", "(", "'DAG'", ")", "node", "=", "dag_elem", ".", "find", "(", "'Node'", ")", "root", "=", "node"...
45.333333
0.00096
def _ions(self, f): """ This is a generator that returns the mzs being measured during each time segment, one segment at a time. """ outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes b...
[ "def", "_ions", "(", "self", ",", "f", ")", ":", "outside_pos", "=", "f", ".", "tell", "(", ")", "doff", "=", "find_offset", "(", "f", ",", "4", "*", "b'\\xff'", "+", "'HapsSearch'", ".", "encode", "(", "'ascii'", ")", ")", "# actual end of prev sectio...
43.875
0.001115
def namedtuple_asdict(obj): """ Serializing a nested namedtuple into a Python dict """ if obj is None: return obj if hasattr(obj, "_asdict"): # detect namedtuple return OrderedDict(zip(obj._fields, (namedtuple_asdict(item) for item in obj...
[ "def", "namedtuple_asdict", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "if", "hasattr", "(", "obj", ",", "\"_asdict\"", ")", ":", "# detect namedtuple", "return", "OrderedDict", "(", "zip", "(", "obj", ".", "_fields", ",", "("...
41.944444
0.001295
def lookup_comments(self, reverse=False): "Implement as required by parent to lookup comments in file system." comments = [] if self.thread_id is None: self.thread_id = self.lookup_thread_id() path = self.thread_id with open(self.thread_id, 'r', newline='') as fdesc:...
[ "def", "lookup_comments", "(", "self", ",", "reverse", "=", "False", ")", ":", "comments", "=", "[", "]", "if", "self", ".", "thread_id", "is", "None", ":", "self", ".", "thread_id", "=", "self", ".", "lookup_thread_id", "(", ")", "path", "=", "self", ...
39.227273
0.002262
def parse_personalities(personalities_line): """Parse the "personalities" line of ``/proc/mdstat``. Lines are expected to be like: Personalities : [linear] [raid0] [raid1] [raid5] [raid4] [raid6] If they do not have this format, an error will be raised since it would be considered an unexpect...
[ "def", "parse_personalities", "(", "personalities_line", ")", ":", "tokens", "=", "personalities_line", ".", "split", "(", ")", "assert", "tokens", ".", "pop", "(", "0", ")", "==", "\"Personalities\"", "assert", "tokens", ".", "pop", "(", "0", ")", "==", "...
27.7
0.001163
def multi_feat_match(template, image, options=None): """ Match template and image by extracting multiple features (specified) from it. :param template: Template image :param image: Search image :param options: Options include - features: List of options for each feature :return: ""...
[ "def", "multi_feat_match", "(", "template", ",", "image", ",", "options", "=", "None", ")", ":", "h", ",", "w", "=", "image", ".", "shape", "[", ":", "2", "]", "scale", "=", "1", "if", "options", "is", "not", "None", "and", "'features'", "in", "opt...
37.238095
0.002494
def parse_rotation(self, rotation=None): """Check and interpret rotation. Uses value of self.rotation as starting point unless rotation parameter is specified in the call. Sets self.rotation_deg to a floating point number 0 <= angle < 360. Includes translation of 360 to 0. If th...
[ "def", "parse_rotation", "(", "self", ",", "rotation", "=", "None", ")", ":", "if", "(", "rotation", "is", "not", "None", ")", ":", "self", ".", "rotation", "=", "rotation", "self", ".", "rotation_deg", "=", "0.0", "self", ".", "rotation_mirror", "=", ...
42.6
0.001311
def gen_gausprocess_se(ntrain, ntest, noise=1., lenscale=1., scale=1., xmin=-10, xmax=10): """ Generate a random (noisy) draw from a Gaussian Process with a RBF kernel. """ # Xtrain = np.linspace(xmin, xmax, ntrain)[:, np.newaxis] Xtrain = np.random.rand(ntrain)[:, np.newaxis...
[ "def", "gen_gausprocess_se", "(", "ntrain", ",", "ntest", ",", "noise", "=", "1.", ",", "lenscale", "=", "1.", ",", "scale", "=", "1.", ",", "xmin", "=", "-", "10", ",", "xmax", "=", "10", ")", ":", "# Xtrain = np.linspace(xmin, xmax, ntrain)[:, np.newaxis]"...
36.809524
0.001261
def parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. ...
[ "def", "parse_get_list_response", "(", "content", ")", ":", "try", ":", "tree", "=", "etree", ".", "fromstring", "(", "content", ")", "hrees", "=", "[", "Urn", ".", "separate", "+", "unquote", "(", "urlsplit", "(", "hree", ".", "text", ")", ".", "path"...
49.916667
0.008197
def listClients(self, *args, **kwargs): """ List Clients Get a list of all clients. With `prefix`, only clients for which it is a prefix of the clientId are returned. By default this end-point will try to return up to 1000 clients in one request. But it **may return le...
[ "def", "listClients", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"listClients\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
40.2
0.00243
def refresh(self): """ Security endpoint for the refresh token, so we can obtain a new token without forcing the user to login again --- post: responses: 200: description: Refresh Successful content: applic...
[ "def", "refresh", "(", "self", ")", ":", "resp", "=", "{", "API_SECURITY_REFRESH_TOKEN_KEY", ":", "create_access_token", "(", "identity", "=", "get_jwt_identity", "(", ")", ",", "fresh", "=", "False", ")", "}", "return", "self", ".", "response", "(", "200", ...
30.333333
0.002367
def significant_tornado(sbcape, surface_based_lcl_height, storm_helicity_1km, shear_6km): r"""Calculate the significant tornado parameter (fixed layer). The significant tornado parameter is designed to identify environments favorable for the production of significant tornadoes contingent upon the devel...
[ "def", "significant_tornado", "(", "sbcape", ",", "surface_based_lcl_height", ",", "storm_helicity_1km", ",", "shear_6km", ")", ":", "surface_based_lcl_height", "=", "np", ".", "clip", "(", "atleast_1d", "(", "surface_based_lcl_height", ")", ",", "1000", "*", "units...
41.530612
0.00192
def write_modified(self, url_data): """Write url_data.modified.""" self.write(self.part("modified") + self.spaces("modified")) self.writeln(self.format_modified(url_data.modified))
[ "def", "write_modified", "(", "self", ",", "url_data", ")", ":", "self", ".", "write", "(", "self", ".", "part", "(", "\"modified\"", ")", "+", "self", ".", "spaces", "(", "\"modified\"", ")", ")", "self", ".", "writeln", "(", "self", ".", "format_modi...
50.25
0.009804
def _connect_command(self): ''' Generates a JSON string with the params to be used when sending CONNECT to the server. ->> CONNECT {"lang": "python3"} ''' options = { "verbose": self.options["verbose"], "pedantic": self.options["pedantic"], ...
[ "def", "_connect_command", "(", "self", ")", ":", "options", "=", "{", "\"verbose\"", ":", "self", ".", "options", "[", "\"verbose\"", "]", ",", "\"pedantic\"", ":", "self", ".", "options", "[", "\"pedantic\"", "]", ",", "\"lang\"", ":", "__lang__", ",", ...
44.138889
0.001847
def get_projects(bq_service): """Given the BigQuery service, return data about all projects.""" projects_request = bq_service.projects().list().execute() projects = [] for project in projects_request.get('projects', []): project_data = { 'id': project['id'], 'name': proj...
[ "def", "get_projects", "(", "bq_service", ")", ":", "projects_request", "=", "bq_service", ".", "projects", "(", ")", ".", "list", "(", ")", ".", "execute", "(", ")", "projects", "=", "[", "]", "for", "project", "in", "projects_request", ".", "get", "(",...
33
0.002457
def filter_reads_by_length(fq1, fq2, quality_format, min_length=20): """ removes reads from a pair of fastq files that are shorter than a minimum length. removes both ends of a read if one end falls below the threshold while maintaining the order of the reads """ logger.info("Removing reads in...
[ "def", "filter_reads_by_length", "(", "fq1", ",", "fq2", ",", "quality_format", ",", "min_length", "=", "20", ")", ":", "logger", ".", "info", "(", "\"Removing reads in %s and %s that \"", "\"are less than %d bases.\"", "%", "(", "fq1", ",", "fq2", ",", "min_lengt...
42.72093
0.001064
def unitResponse(self,band): """This is used internally for :ref:`pysynphot-formula-effstim` calculations.""" sp=band*self.vegaspec total=sp.integrate() return 2.5*math.log10(total)
[ "def", "unitResponse", "(", "self", ",", "band", ")", ":", "sp", "=", "band", "*", "self", ".", "vegaspec", "total", "=", "sp", ".", "integrate", "(", ")", "return", "2.5", "*", "math", ".", "log10", "(", "total", ")" ]
36
0.022624
def uri_to_iri(uri, charset='utf-8', errors='replace'): r""" Converts a URI in a given charset to a IRI. Examples for URI versus IRI: >>> uri_to_iri(b'http://xn--n3h.net/') u'http://\u2603.net/' >>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th') u'http://\xfcser:p\xe4s...
[ "def", "uri_to_iri", "(", "uri", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "if", "isinstance", "(", "uri", ",", "tuple", ")", ":", "uri", "=", "url_unparse", "(", "uri", ")", "uri", "=", "url_parse", "(", "to_unicode", ...
33.133333
0.000978
def crosstalk_correction(pathway_definitions, random_seed=2015, gene_set=set(), all_genes=True, max_iters=1000): """A wrapper function around the maximum impact estimation algorithm. Parameters ----------- ...
[ "def", "crosstalk_correction", "(", "pathway_definitions", ",", "random_seed", "=", "2015", ",", "gene_set", "=", "set", "(", ")", ",", "all_genes", "=", "True", ",", "max_iters", "=", "1000", ")", ":", "np", ".", "random", ".", "seed", "(", "seed", "=",...
42.78022
0.000251
def delete_service(self, service_id): """Delete a service.""" content = self._fetch("/service/%s" % service_id, method="DELETE") return self._status(content)
[ "def", "delete_service", "(", "self", ",", "service_id", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s\"", "%", "service_id", ",", "method", "=", "\"DELETE\"", ")", "return", "self", ".", "_status", "(", "content", ")" ]
40
0.030675
def lfriedmanchisquare(*args): """ Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated probability value. It assumes 3 or more repeated measures. Only 3 levels require...
[ "def", "lfriedmanchisquare", "(", "*", "args", ")", ":", "k", "=", "len", "(", "args", ")", "if", "k", "<", "3", ":", "raise", "ValueError", "(", "'Less than 3 levels. Friedman test not appropriate.'", ")", "n", "=", "len", "(", "args", "[", "0", "]", "...
36.416667
0.00223
def set_option(self, name, value): """Sets an option's value""" _assert_value_is_valid(name) self._options[name] = value
[ "def", "set_option", "(", "self", ",", "name", ",", "value", ")", ":", "_assert_value_is_valid", "(", "name", ")", "self", ".", "_options", "[", "name", "]", "=", "value" ]
36
0.013605
def parse(code, filename='<unknown>', mode='exec', tree=None): """Parse the source into an AST node with PyPosAST. Enhance nodes with positions Arguments: code -- code text Keyword Arguments: filename -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if i...
[ "def", "parse", "(", "code", ",", "filename", "=", "'<unknown>'", ",", "mode", "=", "'exec'", ",", "tree", "=", "None", ")", ":", "visitor", "=", "Visitor", "(", "code", ",", "filename", ",", "mode", ",", "tree", "=", "tree", ")", "return", "visitor"...
25.4375
0.00237
def convert_key_to_attr_names(cls, original): """ convert key names to their corresponding attribute names """ attrs = fields(cls) updated = {} keys_pulled = set() for a in attrs: key_name = a.metadata.get('key') or a.name if key_name in original: updated[a.name] = origi...
[ "def", "convert_key_to_attr_names", "(", "cls", ",", "original", ")", ":", "attrs", "=", "fields", "(", "cls", ")", "updated", "=", "{", "}", "keys_pulled", "=", "set", "(", ")", "for", "a", "in", "attrs", ":", "key_name", "=", "a", ".", "metadata", ...
32.111111
0.001681
def metadefs_namespace_list(request, filters=None, sort_dir='asc', sort_key='namespace', marker=None, paginate=False): """Retrieve a listing of Namespaces :param paginate:...
[ "def", "metadefs_namespace_list", "(", "request", ",", "filters", "=", "None", ",", "sort_dir", "=", "'asc'", ",", "sort_key", "=", "'namespace'", ",", "marker", "=", "None", ",", "paginate", "=", "False", ")", ":", "# Listing namespaces requires the v2 API. If no...
40.309524
0.000288
def entropy_score(var,bins, w=None, decimate=True): '''Compute entropy scores, given a variance and # of bins ''' if w is None: n = len(var) w = np.arange(0,n,n//bins) / float(n) if decimate: n = len(var) var = var[0:n:n//bins] score = w * np.log(var * w * np.sqr...
[ "def", "entropy_score", "(", "var", ",", "bins", ",", "w", "=", "None", ",", "decimate", "=", "True", ")", ":", "if", "w", "is", "None", ":", "n", "=", "len", "(", "var", ")", "w", "=", "np", ".", "arange", "(", "0", ",", "n", ",", "n", "//...
29.230769
0.015306
def autolink(el, link_regexes=_link_regexes, avoid_elements=_avoid_elements, avoid_hosts=_avoid_hosts, avoid_classes=_avoid_classes): """ Turn any URLs into links. It will search for links identified by the given regular expressions (by default mailto and http(s) ...
[ "def", "autolink", "(", "el", ",", "link_regexes", "=", "_link_regexes", ",", "avoid_elements", "=", "_avoid_elements", ",", "avoid_hosts", "=", "_avoid_hosts", ",", "avoid_classes", "=", "_avoid_classes", ")", ":", "if", "el", ".", "tag", "in", "avoid_elements"...
37.113636
0.000597
async def async_request(session, url, **kwargs): """Do a web request and manage response.""" _LOGGER.debug("Sending %s to %s", kwargs, url) try: res = await session(url, **kwargs) if res.content_type != 'application/json': raise ResponseError( "Invalid content t...
[ "async", "def", "async_request", "(", "session", ",", "url", ",", "*", "*", "kwargs", ")", ":", "_LOGGER", ".", "debug", "(", "\"Sending %s to %s\"", ",", "kwargs", ",", "url", ")", "try", ":", "res", "=", "await", "session", "(", "url", ",", "*", "*...
30.090909
0.001464
def null_concept(self): """Return the null concept of this subsystem. The null concept is a point in concept space identified with the unconstrained cause and effect repertoire of this subsystem. """ # Unconstrained cause repertoire. cause_repertoire = self.cause_reperto...
[ "def", "null_concept", "(", "self", ")", ":", "# Unconstrained cause repertoire.", "cause_repertoire", "=", "self", ".", "cause_repertoire", "(", "(", ")", ",", "(", ")", ")", "# Unconstrained effect repertoire.", "effect_repertoire", "=", "self", ".", "effect_reperto...
37.391304
0.002268
def show_current_state(self): """Setup the UI for QTextEdit to show the current state.""" right_panel_heading = QLabel(tr('Status')) right_panel_heading.setFont(big_font) right_panel_heading.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Maximum) self.right_layout.ad...
[ "def", "show_current_state", "(", "self", ")", ":", "right_panel_heading", "=", "QLabel", "(", "tr", "(", "'Status'", ")", ")", "right_panel_heading", ".", "setFont", "(", "big_font", ")", "right_panel_heading", ".", "setSizePolicy", "(", "QSizePolicy", ".", "Ma...
44.088608
0.000562
def det_refpoint(self, angle): """Return the detector reference point position at ``angle``. For an angle ``phi``, the detector position is given by :: det_ref(phi) = translation + rot_matrix(phi) * (det_rad * src_to_det_init) + (offset...
[ "def", "det_refpoint", "(", "self", ",", "angle", ")", ":", "squeeze_out", "=", "(", "np", ".", "shape", "(", "angle", ")", "==", "(", ")", ")", "angle", "=", "np", ".", "array", "(", "angle", ",", "dtype", "=", "float", ",", "copy", "=", "False"...
37.564706
0.00061
def _get_instance(self, **kwargs): '''Return the first existing instance of the response record. ''' return session.query(self.response_class).filter_by(**kwargs).first()
[ "def", "_get_instance", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "session", ".", "query", "(", "self", ".", "response_class", ")", ".", "filter_by", "(", "*", "*", "kwargs", ")", ".", "first", "(", ")" ]
47.75
0.010309
def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None): r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\ri...
[ "def", "batch_normalization", "(", "x", ",", "beta", ",", "gamma", ",", "mean", ",", "variance", ",", "axes", "=", "[", "1", "]", ",", "decay_rate", "=", "0.9", ",", "eps", "=", "1e-05", ",", "batch_stat", "=", "True", ",", "output_stat", "=", "False...
48.805825
0.001755
def _transform(self, var): ''' Rename happens automatically in the base class, so all we need to do is unset the original variable in the collection. ''' self.collection.variables.pop(var.name) return var.values
[ "def", "_transform", "(", "self", ",", "var", ")", ":", "self", ".", "collection", ".", "variables", ".", "pop", "(", "var", ".", "name", ")", "return", "var", ".", "values" ]
47.8
0.00823
def disconnect(self, receiver): """Remove receiver.""" try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
[ "def", "disconnect", "(", "self", ",", "receiver", ")", ":", "try", ":", "self", ".", "receivers", ".", "remove", "(", "receiver", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unknown receiver: %s'", "%", "receiver", ")" ]
34.166667
0.009524
def tersoff_potential(self, structure): """ Generate the species, tersoff potential lines for an oxide structure Args: structure: pymatgen.core.structure.Structure """ bv = BVAnalyzer() el = [site.specie.symbol for site in structure] valences = bv.get...
[ "def", "tersoff_potential", "(", "self", ",", "structure", ")", ":", "bv", "=", "BVAnalyzer", "(", ")", "el", "=", "[", "site", ".", "specie", ".", "symbol", "for", "site", "in", "structure", "]", "valences", "=", "bv", ".", "get_valences", "(", "struc...
34.90625
0.001742
def validate(self): """ Verify that the value of the Enumeration is valid. Raises: TypeError: if the enum is not of type Enum ValueError: if the value is not of the expected Enum subtype or if the value cannot be represented by an unsigned 32-bit integer ...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "enum", ",", "enumeration", ".", "EnumMeta", ")", ":", "raise", "TypeError", "(", "'enumeration type {0} must be of type EnumMeta'", ".", "format", "(", "self", ".", "enum",...
44.851852
0.001617
def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
[ "def", "_invoke", "(", "self", ",", "arguments", ",", "autoescape", ")", ":", "rv", "=", "self", ".", "_func", "(", "*", "arguments", ")", "if", "autoescape", ":", "rv", "=", "Markup", "(", "rv", ")", "return", "rv" ]
36.166667
0.009009
def handle_one_of(schema, field, validator, parent_schema): """Adds the validation logic for ``marshmallow.validate.OneOf`` by setting the JSONSchema `enum` property to the allowed choices in the validator. Args: schema (dict): The original JSON schema we generated. This is what we want...
[ "def", "handle_one_of", "(", "schema", ",", "field", ",", "validator", ",", "parent_schema", ")", ":", "if", "validator", ".", "choices", ":", "schema", "[", "'enum'", "]", "=", "list", "(", "validator", ".", "choices", ")", "schema", "[", "'enumNames'", ...
39.913043
0.001064
def generate_excise_subparser(subparsers): """Adds a sub-command parser to `subparsers` to excise n-grams from witnesses.""" parser = subparsers.add_parser( 'excise', description=constants.EXCISE_DESCRIPTION, help=constants.EXCISE_HELP) parser.set_defaults(func=excise) utils.add_comm...
[ "def", "generate_excise_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'excise'", ",", "description", "=", "constants", ".", "EXCISE_DESCRIPTION", ",", "help", "=", "constants", ".", "EXCISE_HELP", ")", "parser", "...
48.764706
0.001183
def read_tf_records(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, interleave=True, filter_amount=1.0): """ Args: batch_size: batch size to return tf_records: a list of tf_r...
[ "def", "read_tf_records", "(", "batch_size", ",", "tf_records", ",", "num_repeats", "=", "1", ",", "shuffle_records", "=", "True", ",", "shuffle_examples", "=", "True", ",", "shuffle_buffer_size", "=", "None", ",", "interleave", "=", "True", ",", "filter_amount"...
39.42
0.000495
def zscore(self, key, member): """Get the score associated with the given member in a sorted set.""" fut = self.execute(b'ZSCORE', key, member) return wait_convert(fut, optional_int_or_float)
[ "def", "zscore", "(", "self", ",", "key", ",", "member", ")", ":", "fut", "=", "self", ".", "execute", "(", "b'ZSCORE'", ",", "key", ",", "member", ")", "return", "wait_convert", "(", "fut", ",", "optional_int_or_float", ")" ]
53
0.009302
def calculate_A50(ctgsizes, cutoff=0, percent=50): """ Given an array of contig sizes, produce A50, N50, and L50 values """ ctgsizes = np.array(ctgsizes, dtype="int") ctgsizes = np.sort(ctgsizes)[::-1] ctgsizes = ctgsizes[ctgsizes >= cutoff] a50 = np.cumsum(ctgsizes) total = np.sum(ct...
[ "def", "calculate_A50", "(", "ctgsizes", ",", "cutoff", "=", "0", ",", "percent", "=", "50", ")", ":", "ctgsizes", "=", "np", ".", "array", "(", "ctgsizes", ",", "dtype", "=", "\"int\"", ")", "ctgsizes", "=", "np", ".", "sort", "(", "ctgsizes", ")", ...
25
0.002268
def integer(_object): """ Validates a given input is of type int.. Example usage:: data = {'a' : 21} schema = ('a', integer) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argu...
[ "def", "integer", "(", "_object", ")", ":", "if", "is_callable", "(", "_object", ")", ":", "_validator", "=", "_object", "@", "wraps", "(", "_validator", ")", "def", "decorated", "(", "value", ")", ":", "ensure", "(", "isinstance", "(", "value", ",", "...
28.56
0.001355
def parse_modes(params, mode_types=None, prefixes=''): """Return a modelist. Args: params (list of str): Parameters from MODE event. mode_types (list): CHANMODES-like mode types. prefixes (str): PREFIX-like mode types. """ # we don't accept bare strings because we don't want to ...
[ "def", "parse_modes", "(", "params", ",", "mode_types", "=", "None", ",", "prefixes", "=", "''", ")", ":", "# we don't accept bare strings because we don't want to try to do", "# intelligent parameter splitting", "params", "=", "list", "(", "params", ")", "if", "param...
28.378378
0.001842
def _convert_to_hashable(data, types=True): r""" Converts `data` into a hashable byte representation if an appropriate hashing function is known. Args: data (object): ordered data with structure types (bool): include type prefixes in the hash Returns: tuple(bytes, bytes): p...
[ "def", "_convert_to_hashable", "(", "data", ",", "types", "=", "True", ")", ":", "# HANDLE MOST COMMON TYPES FIRST", "if", "data", "is", "None", ":", "hashable", "=", "b'NONE'", "prefix", "=", "b'NULL'", "elif", "isinstance", "(", "data", ",", "six", ".", "b...
34.846154
0.001074
def is_text_file(file_path: str) -> bool: """Returns if a file contains only ASCII or UTF-8 encoded text. :param file_path: path to the file being checked :return: True if the file is a text file, False if it is binary. """ import codecs expanded_path = os.path.abspath(os.path.expanduser(file_...
[ "def", "is_text_file", "(", "file_path", ":", "str", ")", "->", "bool", ":", "import", "codecs", "expanded_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "file_path", ".", "strip", "(", ")", ")", ")", "...
35.371429
0.002358