text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def convenience_split_params(self, params, return_all_types=False): """ Splits parameter vector into nest parameters and index parameters. Parameters ---------- all_params : 1D ndarray. Should contain all of the parameters being estimated (i.e. all the ne...
[ "def", "convenience_split_params", "(", "self", ",", "params", ",", "return_all_types", "=", "False", ")", ":", "return", "split_param_vec", "(", "params", ",", "self", ".", "rows_to_nests", ",", "return_all_types", "=", "return_all_types", ")" ]
46.6
0.001051
def pixelizeCatalog(infiles, config, force=False): """ Break catalog into chunks by healpix pixel. Parameters: ----------- infiles : List of input files config : Configuration file force : Overwrite existing files (depricated) Returns: -------- None """ nside...
[ "def", "pixelizeCatalog", "(", "infiles", ",", "config", ",", "force", "=", "False", ")", ":", "nside_catalog", "=", "config", "[", "'coords'", "]", "[", "'nside_catalog'", "]", "nside_pixel", "=", "config", "[", "'coords'", "]", "[", "'nside_pixel'", "]", ...
37.411765
0.017463
def V_horiz_conical(D, L, a, h, headonly=False): r'''Calculates volume of a tank with conical ends, according to [1]_. .. math:: V_f = A_fL + \frac{2aR^2}{3}K, \;\;0 \le h < R\\ .. math:: V_f = A_fL + \frac{2aR^2}{3}\pi/2,\;\; h = R\\ .. math:: V_f = A_fL + \frac{2aR^2}{3}(\pi...
[ "def", "V_horiz_conical", "(", "D", ",", "L", ",", "a", ",", "h", ",", "headonly", "=", "False", ")", ":", "R", "=", "D", "/", "2.", "Af", "=", "R", "*", "R", "*", "acos", "(", "(", "R", "-", "h", ")", "/", "R", ")", "-", "(", "R", "-",...
26
0.001123
def max_bipartite_matching2(bigraph): """Bipartie maximum matching :param bigraph: adjacency list, index = vertex in U, value = neighbor list in V :comment: U and V can have different cardinalities :returns: matching list, match[v] == u iff (u, v) in matching :co...
[ "def", "max_bipartite_matching2", "(", "bigraph", ")", ":", "nU", "=", "len", "(", "bigraph", ")", "# the following line works only in Python version ≥ 2.5", "# nV = max(max(adjlist, default=-1) for adjlist in bigraph) + 1", "nV", "=", "0", "for", "adjlist", "in", "bigraph", ...
33.952381
0.001364
def mroc(adjacency_matrix, alpha): """ Extracts hierarchical community features using the MROC method. Introduced in: Wang, X., Tang, L., Liu, H., & Wang, L. (2013). Learning with multi-resolution overlapping communities. Knowledge and information systems, 36(2), 517-5...
[ "def", "mroc", "(", "adjacency_matrix", ",", "alpha", ")", ":", "# Find number of nodes", "number_of_nodes", "=", "adjacency_matrix", ".", "shape", "[", "0", "]", "####################################################################################################################",...
37.270588
0.001691
def purge(self): """ Purge the stream. This removes all data and clears the calculated intervals :return: None """ self.channel.purge_stream(self.stream_id, remove_definition=False, sandbox=None)
[ "def", "purge", "(", "self", ")", ":", "self", ".", "channel", ".", "purge_stream", "(", "self", ".", "stream_id", ",", "remove_definition", "=", "False", ",", "sandbox", "=", "None", ")" ]
32.857143
0.016949
def submit_tasks(self, wait=False): """ Submits the task in self and wait. TODO: change name. """ for task in self: task.start() if wait: for task in self: task.wait()
[ "def", "submit_tasks", "(", "self", ",", "wait", "=", "False", ")", ":", "for", "task", "in", "self", ":", "task", ".", "start", "(", ")", "if", "wait", ":", "for", "task", "in", "self", ":", "task", ".", "wait", "(", ")" ]
23.1
0.0125
def purge_db(self): """ Clear all matching our user_id. """ with self.engine.begin() as db: purge_user(db, self.user_id)
[ "def", "purge_db", "(", "self", ")", ":", "with", "self", ".", "engine", ".", "begin", "(", ")", "as", "db", ":", "purge_user", "(", "db", ",", "self", ".", "user_id", ")" ]
26.5
0.012195
def find_natural_neighbors(tri, grid_points): r"""Return the natural neighbor triangles for each given grid cell. These are determined by the properties of the given delaunay triangulation. A triangle is a natural neighbor of a grid cell if that triangles circumcenter is within the circumradius of the ...
[ "def", "find_natural_neighbors", "(", "tri", ",", "grid_points", ")", ":", "tree", "=", "cKDTree", "(", "grid_points", ")", "in_triangulation", "=", "tri", ".", "find_simplex", "(", "tree", ".", "data", ")", ">=", "0", "triangle_info", "=", "{", "}", "memb...
26.75
0.001503
def tran3(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
[ "def", "tran3", "(", "self", ",", "a", ",", "b", ",", "c", ",", "n", ")", ":", "return", "(", "(", "(", "TRAN", "[", "(", "a", "+", "n", ")", "&", "255", "]", "^", "TRAN", "[", "b", "]", "*", "(", "n", "+", "n", "+", "1", ")", ")", ...
57.666667
0.034286
def _check_minions_directories(pki_dir): ''' Return the minion keys directory paths. This function is a copy of salt.key.Key._check_minions_directories. ''' minions_accepted = os.path.join(pki_dir, salt.key.Key.ACC) minions_pre = os.path.join(pki_dir, salt.key.Key.PEND) minions_rejected = o...
[ "def", "_check_minions_directories", "(", "pki_dir", ")", ":", "minions_accepted", "=", "os", ".", "path", ".", "join", "(", "pki_dir", ",", "salt", ".", "key", ".", "Key", ".", "ACC", ")", "minions_pre", "=", "os", ".", "path", ".", "join", "(", "pki_...
40.333333
0.00202
def allowed(name, collection='all'): ''' Return true if this name is allowed (e.g. not in the forbidden list, indicated by 'collection'), false otherwise. ''' if not valid(name): return False blacklist = names() for forbidden in blacklist[collection]: if name.lower() == for...
[ "def", "allowed", "(", "name", ",", "collection", "=", "'all'", ")", ":", "if", "not", "valid", "(", "name", ")", ":", "return", "False", "blacklist", "=", "names", "(", ")", "for", "forbidden", "in", "blacklist", "[", "collection", "]", ":", "if", "...
29.791667
0.001355
def make_dep_graph(depender): """Returns a digraph string fragment based on the passed-in module """ shutit_global.shutit_global_object.yield_to_draw() digraph = '' for dependee_id in depender.depends_on: digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n') return digraph
[ "def", "make_dep_graph", "(", "depender", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "digraph", "=", "''", "for", "dependee_id", "in", "depender", ".", "depends_on", ":", "digraph", "=", "(", "digraph", "+", "'\"'",...
37.375
0.029412
def get_week_dates(year, week, as_timestamp=False): """ Get the dates or timestamp of a week in a year. param year: The year. param week: The week. param as_timestamp: Return values as timestamps. returns: The begin and end of the week as datetime.date or as timestamp. """ year = int(ye...
[ "def", "get_week_dates", "(", "year", ",", "week", ",", "as_timestamp", "=", "False", ")", ":", "year", "=", "int", "(", "year", ")", "week", "=", "int", "(", "week", ")", "start_date", "=", "date", "(", "year", ",", "1", ",", "1", ")", "if", "st...
36.28
0.001074
def reflected_binary_operator(op): """ Factory function for making binary operator methods on a Factor. Returns a function, "reflected_binary_operator" suitable for implementing functions like __radd__. """ assert not is_comparison(op) @with_name(method_name_for_op(op, commute=True)) @...
[ "def", "reflected_binary_operator", "(", "op", ")", ":", "assert", "not", "is_comparison", "(", "op", ")", "@", "with_name", "(", "method_name_for_op", "(", "op", ",", "commute", "=", "True", ")", ")", "@", "coerce_numbers_to_my_dtype", "def", "reflected_binary_...
35.810811
0.000735
def clear_data(self, queues=None, edge=None, edge_type=None): """Clears data from all queues. If none of the parameters are given then every queue's data is cleared. Parameters ---------- queues : int or an iterable of int (optional) The edge index (or an it...
[ "def", "clear_data", "(", "self", ",", "queues", "=", "None", ",", "edge", "=", "None", ",", "edge_type", "=", "None", ")", ":", "queues", "=", "_get_queues", "(", "self", ".", "g", ",", "queues", ",", "edge", ",", "edge_type", ")", "for", "k", "in...
37.137931
0.00181
def finish(self, value): '''Give the future it's value and trigger any associated callbacks :param value: the new value for the future :raises: :class:`AlreadyComplete <junction.errors.AlreadyComplete>` if already complete ''' if self._done.is_set(): ...
[ "def", "finish", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_done", ".", "is_set", "(", ")", ":", "raise", "errors", ".", "AlreadyComplete", "(", ")", "self", ".", "_value", "=", "value", "for", "cb", "in", "self", ".", "_cbacks", ":"...
27
0.002466
def list_files(x, path=""): """ Lists file(s) in given path of the X type. :param str x: File extension that we are interested in. :param str path: Path, if user would like to check a specific directory outside of the CWD :return list of str: File name(s) to be worked on """ logger_directory...
[ "def", "list_files", "(", "x", ",", "path", "=", "\"\"", ")", ":", "logger_directory", ".", "info", "(", "\"enter list_files\"", ")", "file_list", "=", "[", "]", "if", "path", ":", "# list files from target directory", "files", "=", "os", ".", "listdir", "("...
40
0.001953
def no_auto_store(): """ Temporarily disable automatic registration of records in the auto_store Decorator factory. This is _NOT_ thread safe >>> @no_auto_store() ... class BarRecord(Record): ... pass >>> BarRecord in auto_store False """ original_auto_register_value = PySchem...
[ "def", "no_auto_store", "(", ")", ":", "original_auto_register_value", "=", "PySchema", ".", "auto_register", "disable_auto_register", "(", ")", "def", "decorator", "(", "cls", ")", ":", "PySchema", ".", "auto_register", "=", "original_auto_register_value", "return", ...
23.6
0.002037
def saveCurrentNetworkToNdex(self, body, verbose=None): """ Save current network/collection to NDEx :param body: Properties required to save current network to NDEx. :param verbose: print more :returns: 200: successful operation; 404: Current network does not exist """ ...
[ "def", "saveCurrentNetworkToNdex", "(", "self", ",", "body", ",", "verbose", "=", "None", ")", ":", "surl", "=", "self", ".", "___url", "sv", "=", "surl", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "surl", "=", "surl", ".", "rstrip", "(", ...
35.8125
0.017007
def network_trigger(st, parameters, thr_coincidence_sum, moveout, max_trigger_length=60, despike=True, debug=0): """ Main function to compute triggers for a network of stations. Computes single-channel characteristic functions using given parameters, then combines these to find netwo...
[ "def", "network_trigger", "(", "st", ",", "parameters", ",", "thr_coincidence_sum", ",", "moveout", ",", "max_trigger_length", "=", "60", ",", "despike", "=", "True", ",", "debug", "=", "0", ")", ":", "triggers", "=", "[", "]", "trace_ids", "=", "[", "tr...
42.864286
0.000163
def delete_user(self, user): """ Delete user and all data""" assert self.user == 'catroot' or self.user == 'postgres' assert not user == 'public' con = self.connection or self._connect() cur = con.cursor() cur.execute('DROP SCHEMA {user} CASCADE;'.format(user=user)) ...
[ "def", "delete_user", "(", "self", ",", "user", ")", ":", "assert", "self", ".", "user", "==", "'catroot'", "or", "self", ".", "user", "==", "'postgres'", "assert", "not", "user", "==", "'public'", "con", "=", "self", ".", "connection", "or", "self", "...
35.636364
0.002484
def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (int(self.major), int(self.minor), str(self.label), str(self.name))
[ "def", "get_comparable_values", "(", "self", ")", ":", "return", "(", "int", "(", "self", ".", "major", ")", ",", "int", "(", "self", ".", "minor", ")", ",", "str", "(", "self", ".", "label", ")", ",", "str", "(", "self", ".", "name", ")", ")" ]
50
0.014778
def default_tool_argparser(description, example_parameters): """Create default parser for single tools. """ import argparse epilog = '\n' for k, v in sorted(example_parameters.items()): epilog += ' ' + k + '\n' p = argparse.ArgumentParser( description=description, add_he...
[ "def", "default_tool_argparser", "(", "description", ",", "example_parameters", ")", ":", "import", "argparse", "epilog", "=", "'\\n'", "for", "k", ",", "v", "in", "sorted", "(", "example_parameters", ".", "items", "(", ")", ")", ":", "epilog", "+=", "' '",...
35.230769
0.002128
def _get_args(op, name): """Hack to get relevant arguments for lineage computation. We need a better way to determine the relevant arguments of an expression. """ # Could use multipledispatch here to avoid the pasta if isinstance(op, ops.Selection): assert name is not None, 'name is None' ...
[ "def", "_get_args", "(", "op", ",", "name", ")", ":", "# Could use multipledispatch here to avoid the pasta", "if", "isinstance", "(", "op", ",", "ops", ".", "Selection", ")", ":", "assert", "name", "is", "not", "None", ",", "'name is None'", "result", "=", "o...
35.045455
0.001263
def SignalAbort(self): """Signals the process to abort.""" self._abort = True if self._foreman_status_wait_event: self._foreman_status_wait_event.set() if self._analysis_mediator: self._analysis_mediator.SignalAbort()
[ "def", "SignalAbort", "(", "self", ")", ":", "self", ".", "_abort", "=", "True", "if", "self", ".", "_foreman_status_wait_event", ":", "self", ".", "_foreman_status_wait_event", ".", "set", "(", ")", "if", "self", ".", "_analysis_mediator", ":", "self", ".",...
34.142857
0.012245
def get_certificate_json(self, certificate_uid): """ Returns certificate as json. Propagates KeyError if key isn't found :param certificate_uid: :return: """ if certificate_uid.startswith(URN_UUID_PREFIX): uid = certificate_uid[len(URN_UUID_PREFIX):] ...
[ "def", "get_certificate_json", "(", "self", ",", "certificate_uid", ")", ":", "if", "certificate_uid", ".", "startswith", "(", "URN_UUID_PREFIX", ")", ":", "uid", "=", "certificate_uid", "[", "len", "(", "URN_UUID_PREFIX", ")", ":", "]", "elif", "certificate_uid...
41.473684
0.002481
def write_checktime (self, url_data): """Write url_data.checktime.""" self.write(self.part("checktime") + self.spaces("checktime")) self.writeln(_("%.3f seconds") % url_data.checktime, color=self.colordltime)
[ "def", "write_checktime", "(", "self", ",", "url_data", ")", ":", "self", ".", "write", "(", "self", ".", "part", "(", "\"checktime\"", ")", "+", "self", ".", "spaces", "(", "\"checktime\"", ")", ")", "self", ".", "writeln", "(", "_", "(", "\"%.3f seco...
49.8
0.011858
def annotated_reads(txome,sorted_read_stream,output,args): if not os.path.exists(args.tempdir+'/'+output): os.makedirs(args.tempdir+'/'+output) ts = OrderedStream(iter(txome.transcript_stream())) rs = OrderedStream(GPDStream(sorted_read_stream)) mls = MultiLocusStream([ts,rs]) aof = gzip.open(a...
[ "def", "annotated_reads", "(", "txome", ",", "sorted_read_stream", ",", "output", ",", "args", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "args", ".", "tempdir", "+", "'/'", "+", "output", ")", ":", "os", ".", "makedirs", "(", "arg...
53.775362
0.026462
def replacePatterns(self, vector, layer = None): """ Replaces patterned inputs or targets with activation vectors. """ if not self.patterned: return vector if type(vector) == str: return self.replacePatterns(self.lookupPattern(vector, layer), layer) elif type(...
[ "def", "replacePatterns", "(", "self", ",", "vector", ",", "layer", "=", "None", ")", ":", "if", "not", "self", ".", "patterned", ":", "return", "vector", "if", "type", "(", "vector", ")", "==", "str", ":", "return", "self", ".", "replacePatterns", "("...
36.190476
0.016667
def update_docstring(docstring, options_dict): """Update a method docstring by inserting option docstrings defined in the options dictionary. The input docstring should define `{options}` at the location where the options docstring block should be inserted. Parameters ---------- docstring : st...
[ "def", "update_docstring", "(", "docstring", ",", "options_dict", ")", ":", "options_str", "=", "[", "]", "for", "i", ",", "(", "k", ",", "v", ")", "in", "enumerate", "(", "sorted", "(", "options_dict", ".", "items", "(", ")", ")", ")", ":", "option_...
31.85
0.000762
def _generate_list_skippers(self): """ Generate the list of skippers of page. :return: The list of skippers of page. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ container = self.parser.find( '#' + AccessibleNavigationImplementati...
[ "def", "_generate_list_skippers", "(", "self", ")", ":", "container", "=", "self", ".", "parser", ".", "find", "(", "'#'", "+", "AccessibleNavigationImplementation", ".", "ID_CONTAINER_SKIPPERS", ")", ".", "first_result", "(", ")", "html_list", "=", "None", "if"...
35.125
0.001732
def samples_like(X, hop_length=512, n_fft=None, axis=-1): """Return an array of sample indices to match the time axis from a feature matrix. Parameters ---------- X : np.ndarray or scalar - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. - If scalar, X repr...
[ "def", "samples_like", "(", "X", ",", "hop_length", "=", "512", ",", "n_fft", "=", "None", ",", "axis", "=", "-", "1", ")", ":", "if", "np", ".", "isscalar", "(", "X", ")", ":", "frames", "=", "np", ".", "arange", "(", "X", ")", "else", ":", ...
31.673077
0.002356
def unwrap(self): """Return a deep copy of myself as a list, and unwrap any wrapper objects in me.""" return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self]
[ "def", "unwrap", "(", "self", ")", ":", "return", "[", "v", ".", "unwrap", "(", ")", "if", "hasattr", "(", "v", ",", "'unwrap'", ")", "and", "not", "hasattr", "(", "v", ",", "'no_unwrap'", ")", "else", "v", "for", "v", "in", "self", "]" ]
70.666667
0.018692
def reject_outliers(a, threshold=3.5): """ Iglewicz and Hoaglin's robust test for multiple outliers (two sided test). <http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm> See also: <http://contchart.com/outliers.aspx> >>> a = [0, 1, 2, 4, 12, 58, 188, 189] >>> list(reject_outl...
[ "def", "reject_outliers", "(", "a", ",", "threshold", "=", "3.5", ")", ":", "if", "len", "(", "a", ")", "<", "3", ":", "return", "np", ".", "zeros", "(", "len", "(", "a", ")", ",", "dtype", "=", "bool", ")", "A", "=", "np", ".", "array", "(",...
31.5
0.001712
def debye_E_single(x): """ calculate Debye energy using old fortran routine :params x: Debye x value :return: Debye energy """ # make the function handles both scalar and array if ((x > 0.0) & (x <= 0.1)): result = 1. - 0.375 * x + x * x * \ (0.05 - (5.952380953e-4) * x ...
[ "def", "debye_E_single", "(", "x", ")", ":", "# make the function handles both scalar and array", "if", "(", "(", "x", ">", "0.0", ")", "&", "(", "x", "<=", "0.1", ")", ")", ":", "result", "=", "1.", "-", "0.375", "*", "x", "+", "x", "*", "x", "*", ...
34.394737
0.000744
def DecoratorMixin(decorator): """ Converts a decorator written for a function view into a mixin for a class-based view. :: LoginRequiredMixin = DecoratorMixin(login_required) class MyView(LoginRequiredMixin): pass class SomeView(DecoratorMixin(some_decorator), ...
[ "def", "DecoratorMixin", "(", "decorator", ")", ":", "class", "Mixin", "(", "object", ")", ":", "__doc__", "=", "decorator", ".", "__doc__", "@", "classmethod", "def", "as_view", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "view", ...
24.357143
0.00141
def _init_health_checker(self): """ start the health checker stub and start a thread to ping it every 30 seconds :return: None """ stub = Health_pb2_grpc.HealthStub(channel=self._channel) self._health_check = stub.Check health_check_thread = threading.Thread(targe...
[ "def", "_init_health_checker", "(", "self", ")", ":", "stub", "=", "Health_pb2_grpc", ".", "HealthStub", "(", "channel", "=", "self", ".", "_channel", ")", "self", ".", "_health_check", "=", "stub", ".", "Check", "health_check_thread", "=", "threading", ".", ...
41.7
0.00939
def rate(s=switchpoint, e=early_mean, l=late_mean): ''' Concatenate Poisson means ''' out = empty(len(disasters_array)) out[:s] = e out[s:] = l return out
[ "def", "rate", "(", "s", "=", "switchpoint", ",", "e", "=", "early_mean", ",", "l", "=", "late_mean", ")", ":", "out", "=", "empty", "(", "len", "(", "disasters_array", ")", ")", "out", "[", ":", "s", "]", "=", "e", "out", "[", "s", ":", "]", ...
28.166667
0.011494
def make_release(ctx, bump=None, skip_local=False, skip_test=False, skip_pypi=False, skip_isort=False): """Make and upload the release.""" colorama.init() text.title("Minchin 'Make Release' for Python Projects v{}".format(__version__)) print() text.subtitle("Configuration") ext...
[ "def", "make_release", "(", "ctx", ",", "bump", "=", "None", ",", "skip_local", "=", "False", ",", "skip_test", "=", "False", ",", "skip_pypi", "=", "False", ",", "skip_isort", "=", "False", ")", ":", "colorama", ".", "init", "(", ")", "text", ".", "...
37.927273
0.001168
def build_agg_vec(agg_vec, **source): """ Builds an combined aggregation vector based on various classifications This function build an aggregation vector based on the order in agg_vec. The naming and actual mapping is given in source, either explicitly or by pointing to a folder with the mapping. ...
[ "def", "build_agg_vec", "(", "agg_vec", ",", "*", "*", "source", ")", ":", "# build a dict with aggregation vectors in source and folder", "if", "type", "(", "agg_vec", ")", "is", "str", ":", "agg_vec", "=", "[", "agg_vec", "]", "agg_dict", "=", "dict", "(", "...
40.954128
0.000219
def keypair_add(name, pubfile=None, pubkey=None, profile=None, **kwargs): ''' Add a keypair to nova (nova keypair-add) CLI Examples: .. code-block:: bash salt '*' nova.keypair_add mykey pubfile='/home/myuser/.ssh/id_rsa.pub' salt '*' nova.keypair_add mykey pubkey='ssh-rsa <key> myuser...
[ "def", "keypair_add", "(", "name", ",", "pubfile", "=", "None", ",", "pubkey", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "_auth", "(", "profile", ",", "*", "*", "kwargs", ")", "return", "conn", ".", ...
25.647059
0.002212
def read_elements(fd, endian, mtps, is_name=False): """Read elements from the file. If list of possible matrix data types mtps is provided, the data type of the elements are verified. """ mtpn, num_bytes, data = read_element_tag(fd, endian) if mtps and mtpn not in [etypes[mtp]['n'] for mtp in m...
[ "def", "read_elements", "(", "fd", ",", "endian", ",", "mtps", ",", "is_name", "=", "False", ")", ":", "mtpn", ",", "num_bytes", ",", "data", "=", "read_element_tag", "(", "fd", ",", "endian", ")", "if", "mtps", "and", "mtpn", "not", "in", "[", "etyp...
32.314286
0.000858
def timesince_or_never(dt, default=None): """Call the Django ``timesince`` filter or a given default string. It returns the string *default* if *dt* is not a valid ``date`` or ``datetime`` object. When *default* is None, "Never" is returned. """ if default is None: default = _("Never") ...
[ "def", "timesince_or_never", "(", "dt", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "_", "(", "\"Never\"", ")", "if", "isinstance", "(", "dt", ",", "datetime", ".", "date", ")", ":", "return", "timesince",...
29.071429
0.002381
def subsets_of_fileinfo_from_txt(filename): """Returns a dictionary with subsets of FileInfo instances from a TXT file. Each subset of files must be preceded by a line: @ <number> <label> where <number> indicates the number of files in that subset, and <label> is a label for that subset. Any additi...
[ "def", "subsets_of_fileinfo_from_txt", "(", "filename", ")", ":", "# check for input file", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "ValueError", "(", "\"File \"", "+", "filename", "+", "\" not found!\"", ")", "# read i...
37.604651
0.001205
def get_bounds(changeset): """Get the bounds of the changeset and return it as a Polygon object. If the changeset has not coordinates (case of the changesets that deal only with relations), it returns an empty Polygon. Args: changeset: the XML string of the changeset. """ try: r...
[ "def", "get_bounds", "(", "changeset", ")", ":", "try", ":", "return", "Polygon", "(", "[", "(", "float", "(", "changeset", ".", "get", "(", "'min_lon'", ")", ")", ",", "float", "(", "changeset", ".", "get", "(", "'min_lat'", ")", ")", ")", ",", "(...
43.333333
0.001255
def plot_data(self): """ Add the data points to the plot. """ self.plt.plot(*self.fit.data, **self.options['data'])
[ "def", "plot_data", "(", "self", ")", ":", "self", ".", "plt", ".", "plot", "(", "*", "self", ".", "fit", ".", "data", ",", "*", "*", "self", ".", "options", "[", "'data'", "]", ")" ]
28.6
0.013605
def do_print (self, url_data): """Determine if URL entry should be logged or not.""" if self.verbose: return True if self.warnings and url_data.warnings: return True return not url_data.valid
[ "def", "do_print", "(", "self", ",", "url_data", ")", ":", "if", "self", ".", "verbose", ":", "return", "True", "if", "self", ".", "warnings", "and", "url_data", ".", "warnings", ":", "return", "True", "return", "not", "url_data", ".", "valid" ]
34.428571
0.012146
def _pdf_value(pdf, population, fitnesses, fitness_threshold): """Give the value of a pdf. This represents the likelihood of a pdf generating solutions that exceed the threshold. """ # Add the chance of obtaining a solution from the pdf # when the fitness for that solution exceeds a threshold ...
[ "def", "_pdf_value", "(", "pdf", ",", "population", ",", "fitnesses", ",", "fitness_threshold", ")", ":", "# Add the chance of obtaining a solution from the pdf", "# when the fitness for that solution exceeds a threshold", "value", "=", "0.0", "for", "solution", ",", "fitness...
42.055556
0.001292
def _get_stddevs(self, C, rup, dists, sites, stddev_types): """ Returns the aleatory uncertainty terms described in equations (13) to (17) """ stddevs = [] num_sites = len(sites.vs30) tau = self._get_inter_event_tau(C, rup.mag, num_sites) phi = self._get_i...
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "rup", ",", "dists", ",", "sites", ",", "stddev_types", ")", ":", "stddevs", "=", "[", "]", "num_sites", "=", "len", "(", "sites", ".", "vs30", ")", "tau", "=", "self", ".", "_get_inter_event_tau", "...
43.909091
0.002026
def convert(obj, ids, attr_type, item_func, cdata, parent='root'): """Routes the elements of an object to the right function to convert them based on their data type""" LOG.info('Inside convert(). obj type is: "%s", obj="%s"' % (type(obj).__name__, unicode_me(obj))) item_name = item_func(pare...
[ "def", "convert", "(", "obj", ",", "ids", ",", "attr_type", ",", "item_func", ",", "cdata", ",", "parent", "=", "'root'", ")", ":", "LOG", ".", "info", "(", "'Inside convert(). obj type is: \"%s\", obj=\"%s\"'", "%", "(", "type", "(", "obj", ")", ".", "__n...
39.62963
0.011861
def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. Monkeypatched to store the final stack on the object itself. """ pos = 0 tokendefs = self._tokens if hasattr(self, '_saved_state_stack'): statestack = list(self._saved_state_sta...
[ "def", "get_tokens_unprocessed", "(", "self", ",", "text", ",", "stack", "=", "(", "'root'", ",", ")", ")", ":", "pos", "=", "0", "tokendefs", "=", "self", ".", "_tokens", "if", "hasattr", "(", "self", ",", "'_saved_state_stack'", ")", ":", "statestack",...
38.218182
0.000464
def _clear_temp_dir(): """ Clear the temporary directory. """ tempdir = get_tempdir() for fname in os.listdir(tempdir): try: os.remove( os.path.join(tempdir, fname) ) except Exception: pass
[ "def", "_clear_temp_dir", "(", ")", ":", "tempdir", "=", "get_tempdir", "(", ")", "for", "fname", "in", "os", ".", "listdir", "(", "tempdir", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "tempdir", ",", "fnam...
26.333333
0.012245
def mixing_phases(U): """Return the angles and CP phases of the CKM or PMNS matrix in standard parametrization, starting from a matrix with arbitrary phase convention.""" f = {} # angles f['t13'] = asin(abs(U[0,2])) if U[0,0] == 0: f['t12'] = pi/2 else: f['t12'] = atan(ab...
[ "def", "mixing_phases", "(", "U", ")", ":", "f", "=", "{", "}", "# angles", "f", "[", "'t13'", "]", "=", "asin", "(", "abs", "(", "U", "[", "0", ",", "2", "]", ")", ")", "if", "U", "[", "0", ",", "0", "]", "==", "0", ":", "f", "[", "'t1...
32.212121
0.014612
def get_analysis_dict( root, pos, form ): ''' Takes *root*, *pos* and *form* from Filosoft's mrf input and reformats as EstNLTK's analysis dict: { "clitic": string, "ending": string, "form": string, "partofspeech": string, ...
[ "def", "get_analysis_dict", "(", "root", ",", "pos", ",", "form", ")", ":", "import", "sys", "result", "=", "{", "CLITIC", ":", "\"\"", ",", "ENDING", ":", "\"\"", ",", "FORM", ":", "form", ",", "POSTAG", ":", "pos", ",", "ROOT", ":", "\"\"", "}", ...
36.945946
0.015681
def d2logpdf_dlink2_dvar(self, link_f, y, Y_metadata=None): """ :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata not used in gaussian :returns: derivative of log likelihood evaluated at...
[ "def", "d2logpdf_dlink2_dvar", "(", "self", ",", "link_f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "c", "=", "np", ".", "zeros_like", "(", "y", ")", "if", "Y_metadata", "is", "not", "None", "and", "'censored'", "in", "Y_metadata", ".", "key...
58.714286
0.014363
def unpack_boolean(self, data): """ Unpack a string value of CIM type 'boolean' and return its CIM data type object, or None. data (unicode string): CIM-XML string value, or None (in which case None is returned). """ if data is None: return None ...
[ "def", "unpack_boolean", "(", "self", ",", "data", ")", ":", "if", "data", "is", "None", ":", "return", "None", "# CIM-XML says \"These values MUST be treated as case-insensitive\"", "# (even though the XML definition requires them to be lowercase.)", "data_", "=", "data", "....
31.545455
0.001864
def progress(self) -> List[bool]: """A list of True/False for the number of games the played in the mini series indicating if the player won or lost.""" return [True if p == "W" else False for p in self._data[MiniSeriesData].progress if p != "N"]
[ "def", "progress", "(", "self", ")", "->", "List", "[", "bool", "]", ":", "return", "[", "True", "if", "p", "==", "\"W\"", "else", "False", "for", "p", "in", "self", ".", "_data", "[", "MiniSeriesData", "]", ".", "progress", "if", "p", "!=", "\"N\"...
86.666667
0.015267
def disembowel(rest): "Disembowel some(one|thing)!" if rest: stabee = rest karma.Karma.store.change(stabee, -1) else: stabee = "someone nearby" return ( "/me takes %s, brings them down to the basement, ties them to a " "leaky pipe, and once bored of playing with them mercifully " "ritually disembowels t...
[ "def", "disembowel", "(", "rest", ")", ":", "if", "rest", ":", "stabee", "=", "rest", "karma", ".", "Karma", ".", "store", ".", "change", "(", "stabee", ",", "-", "1", ")", "else", ":", "stabee", "=", "\"someone nearby\"", "return", "(", "\"/me takes %...
29.727273
0.032641
def encode_int(code, bits_per_char=6): """Encode int into a string preserving order It is using 2, 4 or 6 bits per coding character (default 6). Parameters: code: int Positive integer. bits_per_char: int The number of bits per coding character. Returns: str: the enc...
[ "def", "encode_int", "(", "code", ",", "bits_per_char", "=", "6", ")", ":", "if", "code", "<", "0", ":", "raise", "ValueError", "(", "'Only positive ints are allowed!'", ")", "if", "bits_per_char", "==", "6", ":", "return", "_encode_int64", "(", "code", ")",...
27.956522
0.001504
def _get_coord_axis_map(self, ds): ''' Returns a dictionary mapping each coordinate to a letter identifier describing the _kind_ of coordinate. :param netCDF4.Dataset ds: An open netCDF dataset :rtype: dict :return: A dictionary with variable names mapped to axis abbrev...
[ "def", "_get_coord_axis_map", "(", "self", ",", "ds", ")", ":", "expected", "=", "[", "'T'", ",", "'Z'", ",", "'Y'", ",", "'X'", "]", "coord_vars", "=", "self", ".", "_find_coord_vars", "(", "ds", ")", "coord_axis_map", "=", "{", "}", "# L - Unlimited Co...
41.035714
0.000567
def listar_por_id(self, id): """Obtém um equipamento a partir do seu identificador. :param id: ID do equipamento. :return: Dicionário com a seguinte estrutura: :: {'equipamento': {'id': < id_equipamento >, 'nome': < nome_equipamento >, 'id_tipo_equ...
[ "def", "listar_por_id", "(", "self", ",", "id", ")", ":", "if", "id", "is", "None", ":", "raise", "InvalidParameterError", "(", "u'O id do equipamento não foi informado.')", "", "url", "=", "'equipamento/id/'", "+", "urllib", ".", "quote", "(", "id", ")", "+",...
34.352941
0.001665
def weighted_median(y, w): """ Compute weighted median of `y` with weights `w`. """ items = sorted(zip(y, w)) midpoint = sum(w) / 2 yvals = [] wsum = 0 for yy, ww in items: wsum += ww if wsum > midpoint: yvals.append(yy) break elif wsum =...
[ "def", "weighted_median", "(", "y", ",", "w", ")", ":", "items", "=", "sorted", "(", "zip", "(", "y", ",", "w", ")", ")", "midpoint", "=", "sum", "(", "w", ")", "/", "2", "yvals", "=", "[", "]", "wsum", "=", "0", "for", "yy", ",", "ww", "in...
19.238095
0.002358
def isrot(m, ntol, dtol): """ Indicate whether a 3x3 matrix is a rotation matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrot_c.html :param m: A matrix to be tested. :type m: 3x3-Element Array of floats :param ntol: Tolerance for the norms of the columns of m. :type ntol:...
[ "def", "isrot", "(", "m", ",", "ntol", ",", "dtol", ")", ":", "m", "=", "stypes", ".", "toDoubleMatrix", "(", "m", ")", "ntol", "=", "ctypes", ".", "c_double", "(", "ntol", ")", "dtol", "=", "ctypes", ".", "c_double", "(", "dtol", ")", "return", ...
33.047619
0.001401
def require_json(): """ Load the best available json library on demand. """ # Fails when "json" is missing and "simplejson" is not installed either try: import json # pylint: disable=F0401 return json except ImportError: try: import simplejson # pylint: disable=F0...
[ "def", "require_json", "(", ")", ":", "# Fails when \"json\" is missing and \"simplejson\" is not installed either", "try", ":", "import", "json", "# pylint: disable=F0401", "return", "json", "except", "ImportError", ":", "try", ":", "import", "simplejson", "# pylint: disable...
36
0.008333
def registerDirs(self,json_dirs): """ Registers multiple new server directories. Inputs: json_dirs - Array of Server Directories in JSON format. """ url = self._url + "/directories/registerDirs" params = { "f" : "json", "directories" : ...
[ "def", "registerDirs", "(", "self", ",", "json_dirs", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/directories/registerDirs\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"directories\"", ":", "json_dirs", "}", "res", "=", "self", ".", "_p...
31.052632
0.008224
def htmlNodeDumpOutput(self, buf, cur, encoding): """Dump an HTML node, recursive behaviour,children are printed too, and formatting returns/spaces are added. """ if buf is None: buf__o = None else: buf__o = buf._o if cur is None: cur__o = None else: cur__o = cur._o ...
[ "def", "htmlNodeDumpOutput", "(", "self", ",", "buf", ",", "cur", ",", "encoding", ")", ":", "if", "buf", "is", "None", ":", "buf__o", "=", "None", "else", ":", "buf__o", "=", "buf", ".", "_o", "if", "cur", "is", "None", ":", "cur__o", "=", "None",...
47.875
0.015385
def ABC(self): ''' A list of the triangle's vertices, list. ''' try: return self._ABC except AttributeError: pass self._ABC = [self.A, self.B, self.C] return self._ABC
[ "def", "ABC", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_ABC", "except", "AttributeError", ":", "pass", "self", ".", "_ABC", "=", "[", "self", ".", "A", ",", "self", ".", "B", ",", "self", ".", "C", "]", "return", "self", ".", ...
21.636364
0.008065
def Record(self, value, fields=None): """Records the given observation in a distribution.""" key = _FieldsToKey(fields) metric_value = self._metric_values.get(key) if metric_value is None: metric_value = self._DefaultValue() self._metric_values[key] = metric_value metric_value.Record(val...
[ "def", "Record", "(", "self", ",", "value", ",", "fields", "=", "None", ")", ":", "key", "=", "_FieldsToKey", "(", "fields", ")", "metric_value", "=", "self", ".", "_metric_values", ".", "get", "(", "key", ")", "if", "metric_value", "is", "None", ":", ...
39.5
0.009288
def prompt(questions: List[Dict[Text, Any]], answers: Optional[Dict[Text, Any]] = None, patch_stdout: bool = False, true_color: bool = False, kbi_msg: Text = DEFAULT_KBI_MESSAGE, **kwargs): """Prompt the user for input on all the questions.""" if isinstanc...
[ "def", "prompt", "(", "questions", ":", "List", "[", "Dict", "[", "Text", ",", "Any", "]", "]", ",", "answers", ":", "Optional", "[", "Dict", "[", "Text", ",", "Any", "]", "]", "=", "None", ",", "patch_stdout", ":", "bool", "=", "False", ",", "tr...
37.011494
0.000605
def ARPLimitExceeded_originator_switch_info_switchIpV6Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ARPLimitExceeded = ET.SubElement(config, "ARPLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info =...
[ "def", "ARPLimitExceeded_originator_switch_info_switchIpV6Address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ARPLimitExceeded", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ARPLimitExceed...
55.545455
0.008052
def _interchange_level_from_filename(fullname): # type: (bytes) -> int ''' A function to determine the ISO interchange level from the filename. In theory, there are 3 levels, but in practice we only deal with level 1 and level 3. Parameters: name - The name to use to determine the intercha...
[ "def", "_interchange_level_from_filename", "(", "fullname", ")", ":", "# type: (bytes) -> int", "(", "name", ",", "extension", ",", "version", ")", "=", "_split_iso9660_filename", "(", "fullname", ")", "interchange_level", "=", "1", "if", "version", "!=", "b''", "...
28.59375
0.001057
def encodeIntoArray(self, input, output,learn=None): """ [overrides nupic.encoders.scalar.ScalarEncoder.encodeIntoArray] """ self.recordNum +=1 if learn is None: learn = self._learningEnabled if input == SENTINEL_VALUE_FOR_MISSING_DATA: output[0:self.n] = 0 elif not math.isnan...
[ "def", "encodeIntoArray", "(", "self", ",", "input", ",", "output", ",", "learn", "=", "None", ")", ":", "self", ".", "recordNum", "+=", "1", "if", "learn", "is", "None", ":", "learn", "=", "self", ".", "_learningEnabled", "if", "input", "==", "SENTINE...
30.357143
0.011416
def update(self, **kwargs): """ Update selected objects with the given keyword parameters and mark them as changed """ super(ModelQuerySet, self).update(_changed=True, **kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "ModelQuerySet", ",", "self", ")", ".", "update", "(", "_changed", "=", "True", ",", "*", "*", "kwargs", ")" ]
35.333333
0.009217
def extend_selection(): """Checks is the selection is to be extended The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed. :return: If to extend the selection :rtype: True """ from rafcon.gui.singleton import main_window_controller currently_presse...
[ "def", "extend_selection", "(", ")", ":", "from", "rafcon", ".", "gui", ".", "singleton", "import", "main_window_controller", "currently_pressed_keys", "=", "main_window_controller", ".", "currently_pressed_keys", "if", "main_window_controller", "else", "set", "(", ")",...
43.642857
0.008013
def great_circle_dist(lat1, lon1, lat2, lon2): """ Get the distance (in meters) between two lat/lon points via the Haversine formula. Parameters ---------- lat1, lon1, lat2, lon2 : float Latitude and longitude in degrees. Returns ------- dist : float Distance in met...
[ "def", "great_circle_dist", "(", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", ")", ":", "radius", "=", "6372795", "# meters", "lat1", "=", "math", ".", "radians", "(", "lat1", ")", "lon1", "=", "math", ".", "radians", "(", "lon1", ")", "lat2", "=",...
23.424242
0.001242
def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement, price, consumer_address, condition_ids): """ Process the agreement events during the register of the service agreement for the publisher side :param publisher_account: Acco...
[ "def", "process_agreement_events_publisher", "(", "publisher_account", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer_address", ",", "condition_ids", ")", ":", "conditions_dict", "=", "service_agreement", ".", "condition_by_name", ...
40.02381
0.002323
def quit(self): """ Quit socket server """ logging.info("quiting sock server") if self.__quit is not None: self.__quit.set() self.join() return
[ "def", "quit", "(", "self", ")", ":", "logging", ".", "info", "(", "\"quiting sock server\"", ")", "if", "self", ".", "__quit", "is", "not", "None", ":", "self", ".", "__quit", ".", "set", "(", ")", "self", ".", "join", "(", ")", "return" ]
23.444444
0.009132
def addi(self, begin, end, data=None): """ Shortcut for add(Interval(begin, end, data)). Completes in O(log n) time. """ return self.add(Interval(begin, end, data))
[ "def", "addi", "(", "self", ",", "begin", ",", "end", ",", "data", "=", "None", ")", ":", "return", "self", ".", "add", "(", "Interval", "(", "begin", ",", "end", ",", "data", ")", ")" ]
28.428571
0.009756
def wiki(i): """ Input: { (repo_uoa) (module_uoa) (data_uoa) } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 ...
[ "def", "wiki", "(", "i", ")", ":", "ruoa", "=", "i", ".", "get", "(", "'repo_uoa'", ",", "''", ")", "muoa", "=", "i", ".", "get", "(", "'module_uoa'", ",", "''", ")", "duoa", "=", "i", ".", "get", "(", "'data_uoa'", ",", "''", ")", "url", "="...
22.490196
0.035923
def DiffDataObjects(self, oldObj, newObj): """Diff Data Objects""" if oldObj == newObj: return True if not oldObj or not newObj: __Log__.debug('DiffDataObjects: One of the objects in None') return False oldType = Type(oldObj) newType = Type(newObj) if oldTy...
[ "def", "DiffDataObjects", "(", "self", ",", "oldObj", ",", "newObj", ")", ":", "if", "oldObj", "==", "newObj", ":", "return", "True", "if", "not", "oldObj", "or", "not", "newObj", ":", "__Log__", ".", "debug", "(", "'DiffDataObjects: One of the objects in None...
39.777778
0.016356
def CheckValue(self, proposed_value): """Type check the provided value and return it. The returned value might have been normalized to another type. """ if not isinstance(proposed_value, self._acceptable_types): message = ('%.1024r has type %s, but expected one of: %s' % (propose...
[ "def", "CheckValue", "(", "self", ",", "proposed_value", ")", ":", "if", "not", "isinstance", "(", "proposed_value", ",", "self", ".", "_acceptable_types", ")", ":", "message", "=", "(", "'%.1024r has type %s, but expected one of: %s'", "%", "(", "proposed_value", ...
42.3
0.009259
def _fillVolumesAndPaths(self, paths): """ Fill in paths. :arg paths: = { Store.Volume: ["linux path",]} """ with self.btrfs as mount: for bv in mount.subvolumes: if not bv.readOnly: continue vol = self._btrfsVol2StoreVol(...
[ "def", "_fillVolumesAndPaths", "(", "self", ",", "paths", ")", ":", "with", "self", ".", "btrfs", "as", "mount", ":", "for", "bv", "in", "mount", ".", "subvolumes", ":", "if", "not", "bv", ".", "readOnly", ":", "continue", "vol", "=", "self", ".", "_...
31.981818
0.001103
def on_menu_exit(self, event): """ Exit the GUI """ # also delete appropriate copy file try: self.help_window.Destroy() except: pass if '-i' in sys.argv: self.Destroy() try: sys.exit() # can raise TypeError i...
[ "def", "on_menu_exit", "(", "self", ",", "event", ")", ":", "# also delete appropriate copy file", "try", ":", "self", ".", "help_window", ".", "Destroy", "(", ")", "except", ":", "pass", "if", "'-i'", "in", "sys", ".", "argv", ":", "self", ".", "Destroy",...
25.777778
0.008316
def search(self, fields=None, query=None, filters=None): """Search for entities with missing attribute :param fields: A set naming which fields should be used when generating a search query. If ``None``, all values on the entity are used. If an empty set, no values are used. ...
[ "def", "search", "(", "self", ",", "fields", "=", "None", ",", "query", "=", "None", ",", "filters", "=", "None", ")", ":", "results", "=", "self", ".", "search_json", "(", "fields", ",", "query", ")", "[", "'results'", "]", "results", "=", "self", ...
45.459459
0.001164
def wr_long(f, x): """Internal; write a 32-bit int to a file in little-endian order.""" if PYTHON3: f.write(bytes([x & 0xff])) f.write(bytes([(x >> 8) & 0xff])) f.write(bytes([(x >> 16) & 0xff])) f.write(bytes([(x >> 24) & 0xff])) else: f.write(chr( x &...
[ "def", "wr_long", "(", "f", ",", "x", ")", ":", "if", "PYTHON3", ":", "f", ".", "write", "(", "bytes", "(", "[", "x", "&", "0xff", "]", ")", ")", "f", ".", "write", "(", "bytes", "(", "[", "(", "x", ">>", "8", ")", "&", "0xff", "]", ")", ...
36.083333
0.013514
def get_backup_blocks(cls, impl, working_dir): """ Get the set of block IDs that were backed up """ ret = [] backup_dir = config.get_backups_directory(impl, working_dir) if not os.path.exists(backup_dir): return [] for name in os.listdir( backup_dir )...
[ "def", "get_backup_blocks", "(", "cls", ",", "impl", ",", "working_dir", ")", ":", "ret", "=", "[", "]", "backup_dir", "=", "config", ".", "get_backups_directory", "(", "impl", ",", "working_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", ...
28.875
0.008377
def build_java_worker_command( java_worker_options, redis_address, plasma_store_name, raylet_name, redis_password, temp_dir, ): """This method assembles the command used to start a Java worker. Args: java_worker_options (str): The command options for Java...
[ "def", "build_java_worker_command", "(", "java_worker_options", ",", "redis_address", ",", "plasma_store_name", ",", "raylet_name", ",", "redis_password", ",", "temp_dir", ",", ")", ":", "assert", "java_worker_options", "is", "not", "None", "command", "=", "\"java \""...
35.4375
0.000572
def extract_all(self, directory=".", members=None): """Extract all member from the archive to the specified working directory. """ if self.handle: self.handle.extractall(path=directory, members=members)
[ "def", "extract_all", "(", "self", ",", "directory", "=", "\".\"", ",", "members", "=", "None", ")", ":", "if", "self", ".", "handle", ":", "self", ".", "handle", ".", "extractall", "(", "path", "=", "directory", ",", "members", "=", "members", ")" ]
40.166667
0.00813
def submit(xml_root, submit_config, session, dry_run=None, **kwargs): """Submits data to the Polarion Importer.""" properties.xunit_fill_testrun_id(xml_root, kwargs.get("testrun_id")) if dry_run is not None: properties.set_dry_run(xml_root, dry_run) xml_input = utils.etree_to_string(xml_root) ...
[ "def", "submit", "(", "xml_root", ",", "submit_config", ",", "session", ",", "dry_run", "=", "None", ",", "*", "*", "kwargs", ")", ":", "properties", ".", "xunit_fill_testrun_id", "(", "xml_root", ",", "kwargs", ".", "get", "(", "\"testrun_id\"", ")", ")",...
38.529412
0.00149
def access(self): """TextureAccess: The actual access to the texture.""" access = ffi.new('int *') check_int_err(lib.SDL_QueryTexture(self._ptr, ffi.NULL, access, ffi.NULL, ffi.NULL)) return TextureAccess(access[0])
[ "def", "access", "(", "self", ")", ":", "access", "=", "ffi", ".", "new", "(", "'int *'", ")", "check_int_err", "(", "lib", ".", "SDL_QueryTexture", "(", "self", ".", "_ptr", ",", "ffi", ".", "NULL", ",", "access", ",", "ffi", ".", "NULL", ",", "ff...
48.6
0.012146
def cdivide(a, b): ''' cdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function or a/b syntax, divide will thread over the latest dimension possible. Unlike numpy's divide, cdivide works with sparse matrices. Note that warnings/errors are raised by this fun...
[ "def", "cdivide", "(", "a", ",", "b", ")", ":", "if", "sps", ".", "issparse", "(", "a", ")", ":", "return", "a", ".", "multiply", "(", "inv", "(", "b", ")", ")", "elif", "sps", ".", "issparse", "(", "b", ")", ":", "return", "np", ".", "asarra...
51.583333
0.015873
def _warn(message, warn_type='user'): """ message (unicode): The message to display. category (Warning): The Warning to show. """ w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE: category = WA...
[ "def", "_warn", "(", "message", ",", "warn_type", "=", "'user'", ")", ":", "w_id", "=", "message", ".", "split", "(", "'['", ",", "1", ")", "[", "1", "]", ".", "split", "(", "']'", ",", "1", ")", "[", "0", "]", "# get ID from string", "if", "warn...
44.769231
0.001684
def check_abbreviation_unique(self, abbreviation, newFilterPattern, targetItem): """ Checks that the given abbreviation is not already in use. @param abbreviation: the abbreviation to check @param newFilterPattern: @param targetItem: the phrase for which the abbreviation...
[ "def", "check_abbreviation_unique", "(", "self", ",", "abbreviation", ",", "newFilterPattern", ",", "targetItem", ")", ":", "for", "item", "in", "self", ".", "allFolders", ":", "if", "model", ".", "TriggerMode", ".", "ABBREVIATION", "in", "item", ".", "modes",...
45.157895
0.009132
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None): ''' .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be use...
[ "def", "filter_by", "(", "lookup_dict", ",", "grain", "=", "'os_family'", ",", "merge", "=", "None", ",", "default", "=", "'default'", ",", "base", "=", "None", ")", ":", "ret", "=", "lookup_dict", ".", "get", "(", "__grains__", ".", "get", "(", "grain...
36.227273
0.001221
def compute_cusum_ts(self, ts): """ Compute the Cumulative Sum at each point 't' of the time series. """ mean = np.mean(ts) cusums = np.zeros(len(ts)) cusum[0] = (ts[0] - mean) for i in np.arange(1, len(ts)): cusums[i] = cusums[i - 1] + (ts[i] - mean) assert(...
[ "def", "compute_cusum_ts", "(", "self", ",", "ts", ")", ":", "mean", "=", "np", ".", "mean", "(", "ts", ")", "cusums", "=", "np", ".", "zeros", "(", "len", "(", "ts", ")", ")", "cusum", "[", "0", "]", "=", "(", "ts", "[", "0", "]", "-", "me...
36.1
0.008108
def _split_compound_string_(compound_string): """ Split a compound's combined formula and phase into separate strings for the formula and phase. :param compound_string: Formula and phase of a chemical compound, e.g. 'SiO2[S1]'. :returns: Formula of chemical compound. :returns: Phase of c...
[ "def", "_split_compound_string_", "(", "compound_string", ")", ":", "formula", "=", "compound_string", ".", "replace", "(", "']'", ",", "''", ")", ".", "split", "(", "'['", ")", "[", "0", "]", "phase", "=", "compound_string", ".", "replace", "(", "']'", ...
29.875
0.002028
def handle_invocation(self, message): """ Passes the invocation request to the appropriate callback. """ req_id = message.request_id reg_id = message.registration_id if reg_id in self._registered_calls: handler = self._registered_calls[reg_id][REGISTERED_C...
[ "def", "handle_invocation", "(", "self", ",", "message", ")", ":", "req_id", "=", "message", ".", "request_id", "reg_id", "=", "message", ".", "registration_id", "if", "reg_id", "in", "self", ".", "_registered_calls", ":", "handler", "=", "self", ".", "_regi...
37.833333
0.015759
def generate_pymol_session(self, pymol_executable = 'pymol', settings = {}): ''' Generates the PyMOL session for the scaffold, model, and design structures. Returns this session and the script which generated it.''' b = BatchBuilder(pymol_executable = pymol_executable) structures_li...
[ "def", "generate_pymol_session", "(", "self", ",", "pymol_executable", "=", "'pymol'", ",", "settings", "=", "{", "}", ")", ":", "b", "=", "BatchBuilder", "(", "pymol_executable", "=", "pymol_executable", ")", "structures_list", "=", "[", "(", "self", ".", "...
55.076923
0.019231
def list_(narrow=None, all_versions=False, pre_versions=False, source=None, local_only=False, exact=False): ''' Instructs Chocolatey to pull a vague package list from the repository. Args: narrow (str): Term used to narrow down results....
[ "def", "list_", "(", "narrow", "=", "None", ",", "all_versions", "=", "False", ",", "pre_versions", "=", "False", ",", "source", "=", "None", ",", "local_only", "=", "False", ",", "exact", "=", "False", ")", ":", "choc_path", "=", "_find_chocolatey", "("...
28.120482
0.000828