text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def gen_anytext(*args): """ Convenience function to create bag of words for anytext property """ bag = [] for term in args: if term is not None: if isinstance(term, list): for term2 in term: if term2 is not None: bag.a...
[ "def", "gen_anytext", "(", "*", "args", ")", ":", "bag", "=", "[", "]", "for", "term", "in", "args", ":", "if", "term", "is", "not", "None", ":", "if", "isinstance", "(", "term", ",", "list", ")", ":", "for", "term2", "in", "term", ":", "if", "...
24.5625
15.0625
def get_sequences(self, pdb_id = None): '''Create Sequence objects for each FASTA sequence.''' sequences = {} if pdb_id: for chain_id, sequence in self.get(pdb_id, {}).iteritems(): sequences[chain_id] = Sequence.from_sequence(chain_id, sequence) else: ...
[ "def", "get_sequences", "(", "self", ",", "pdb_id", "=", "None", ")", ":", "sequences", "=", "{", "}", "if", "pdb_id", ":", "for", "chain_id", ",", "sequence", "in", "self", ".", "get", "(", "pdb_id", ",", "{", "}", ")", ".", "iteritems", "(", ")",...
46.75
21.083333
def _get_v_angle(self, case, B, v_angle_guess, p_businj, iref): """ Calculates the voltage phase angles. """ buses = case.connected_buses pv_idxs = [bus._i for bus in buses if bus.type == PV] pq_idxs = [bus._i for bus in buses if bus.type == PQ] pvpq_idxs = pv_idxs + pq_...
[ "def", "_get_v_angle", "(", "self", ",", "case", ",", "B", ",", "v_angle_guess", ",", "p_businj", ",", "iref", ")", ":", "buses", "=", "case", ".", "connected_buses", "pv_idxs", "=", "[", "bus", ".", "_i", "for", "bus", "in", "buses", "if", "bus", "....
34.882353
20.970588
def get_waiting_list(self, force=False): """ Add lines for any waiting fields that can be completed now. """ code_lines = [] skip_autofield = self.options['skip_autofield'] # Process normal fields for field in list(self.waiting_list): try: # Find the...
[ "def", "get_waiting_list", "(", "self", ",", "force", "=", "False", ")", ":", "code_lines", "=", "[", "]", "skip_autofield", "=", "self", ".", "options", "[", "'skip_autofield'", "]", "# Process normal fields", "for", "field", "in", "list", "(", "self", ".",...
41.090909
21.409091
def migrate_config_file( self, config_file_path, always_update=False, current_file_type=None, output_file_name=None, output_file_type=None, create=True, update_defaults=True, dump_kwargs=None, include_bootstrap=True, ): """Migra...
[ "def", "migrate_config_file", "(", "self", ",", "config_file_path", ",", "always_update", "=", "False", ",", "current_file_type", "=", "None", ",", "output_file_name", "=", "None", ",", "output_file_type", "=", "None", ",", "create", "=", "True", ",", "update_de...
37.295455
22.25
def _parse_curves(block, **kwargs): """Parse nonlinear curves block.""" count = int(block.pop(0)) curves = [] for i in range(count): for param in ['mod_reduc', 'damping']: length, name = parse_fixed_width([(5, int), (65, to_str)], block) curves.append( si...
[ "def", "_parse_curves", "(", "block", ",", "*", "*", "kwargs", ")", ":", "count", "=", "int", "(", "block", ".", "pop", "(", "0", ")", ")", "curves", "=", "[", "]", "for", "i", "in", "range", "(", "count", ")", ":", "for", "param", "in", "[", ...
38.315789
21
def get_extension(filepath, check_if_exists=False): """Return the extension of fpath. Parameters ---------- fpath: string File name or path check_if_exists: bool Returns ------- str The extension of the file name or path """ if check_if_exists: if not os.path.e...
[ "def", "get_extension", "(", "filepath", ",", "check_if_exists", "=", "False", ")", ":", "if", "check_if_exists", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "err", "=", "'File not found: '", "+", "filepath", "log", ".", ...
19.555556
21.037037
def label_list_parser(self, url): """ Extracts comma separate tag=value pairs from a string Assumes all characters other than / and , are valid """ labels = re.findall('([^/,]+=[^/,]+)', url) slabels = set(labels) if '' in slabels: slabels.remove('') ...
[ "def", "label_list_parser", "(", "self", ",", "url", ")", ":", "labels", "=", "re", ".", "findall", "(", "'([^/,]+=[^/,]+)'", ",", "url", ")", "slabels", "=", "set", "(", "labels", ")", "if", "''", "in", "slabels", ":", "slabels", ".", "remove", "(", ...
33.2
11.2
def as_wires(val, bitwidth=None, truncating=True, block=None): """ Return wires from val which may be wires, integers, strings, or bools. :param val: a wirevector-like object or something that can be converted into a Const :param bitwidth: The bitwidth the resulting wire should be :param bool tru...
[ "def", "as_wires", "(", "val", ",", "bitwidth", "=", "None", ",", "truncating", "=", "True", ",", "block", "=", "None", ")", ":", "from", ".", "memory", "import", "_MemIndexed", "block", "=", "working_block", "(", "block", ")", "if", "isinstance", "(", ...
43.0625
21.583333
def finish(self, code, data=NotImplemented): """ Set response as {'code': xxx, 'data': xxx} :param code: :param data: :return: """ if data is NotImplemented: data = RETCODE.txt_cn.get(code, None) self.ret_val = {'code': code, 'data': data} # f...
[ "def", "finish", "(", "self", ",", "code", ",", "data", "=", "NotImplemented", ")", ":", "if", "data", "is", "NotImplemented", ":", "data", "=", "RETCODE", ".", "txt_cn", ".", "get", "(", "code", ",", "None", ")", "self", ".", "ret_val", "=", "{", ...
37.692308
15.076923
def write(self, filename=None, skipempty=False): """Write mdp file to *filename*. :Keywords: *filename* output mdp file; default is the filename the mdp was read from *skipempty* : boolean ``True`` removes any parameter lines from outpu...
[ "def", "write", "(", "self", ",", "filename", "=", "None", ",", "skipempty", "=", "False", ")", ":", "with", "open", "(", "self", ".", "filename", "(", "filename", ",", "ext", "=", "'mdp'", ")", ",", "'w'", ")", "as", "mdp", ":", "for", "k", ",",...
42.392857
18.785714
def get_instance(self, payload): """ Build an instance of WebhookInstance :param dict payload: Payload response from the API :returns: twilio.rest.messaging.v1.session.webhook.WebhookInstance :rtype: twilio.rest.messaging.v1.session.webhook.WebhookInstance """ r...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "WebhookInstance", "(", "self", ".", "_version", ",", "payload", ",", "session_sid", "=", "self", ".", "_solution", "[", "'session_sid'", "]", ",", ")" ]
40.1
23.5
def varianceOfLaplacian(img): ''''LAPV' algorithm (Pech2000)''' lap = cv2.Laplacian(img, ddepth=-1)#cv2.cv.CV_64F) stdev = cv2.meanStdDev(lap)[1] s = stdev[0]**2 return s[0]
[ "def", "varianceOfLaplacian", "(", "img", ")", ":", "lap", "=", "cv2", ".", "Laplacian", "(", "img", ",", "ddepth", "=", "-", "1", ")", "#cv2.cv.CV_64F)\r", "stdev", "=", "cv2", ".", "meanStdDev", "(", "lap", ")", "[", "1", "]", "s", "=", "stdev", ...
32.166667
12.833333
def plot(self, fmt=None): """ Make a simple plot of the legend. Simply calls Decor.plot() on all of its members. TODO: Build a more attractive plot. """ for d in self.__list: d.plot(fmt=fmt) return None
[ "def", "plot", "(", "self", ",", "fmt", "=", "None", ")", ":", "for", "d", "in", "self", ".", "__list", ":", "d", ".", "plot", "(", "fmt", "=", "fmt", ")", "return", "None" ]
21.833333
16.666667
def make_quadratic(poly, strength, vartype=None, bqm=None): """Create a binary quadratic model from a higher order polynomial. Args: poly (dict): Polynomial as a dict of form {term: bias, ...}, where `term` is a tuple of variables and `bias` the associated bias. strengt...
[ "def", "make_quadratic", "(", "poly", ",", "strength", ",", "vartype", "=", "None", ",", "bqm", "=", "None", ")", ":", "if", "bqm", "is", "None", ":", "if", "vartype", "is", "None", ":", "raise", "ValueError", "(", "\"one of vartype and bqm must be provided\...
35.823529
25.411765
def search_one(self, keyword, arg=None, children=None): """Return receiver's substmt with `keyword` and optionally `arg`. """ if children is None: children = self.substmts for ch in children: if ch.keyword == keyword and (arg is None or ch.arg == arg): ...
[ "def", "search_one", "(", "self", ",", "keyword", ",", "arg", "=", "None", ",", "children", "=", "None", ")", ":", "if", "children", "is", "None", ":", "children", "=", "self", ".", "substmts", "for", "ch", "in", "children", ":", "if", "ch", ".", "...
38.444444
12.444444
def surface_2D(num_lat=90, num_lon=180, water_depth=10., lon=None, lat=None, **kwargs): """Creates a 2D slab ocean Domain in latitude and longitude with uniform water depth. Domain has a single heat capacity according to the specified water depth. **Function-call argument** \n :param i...
[ "def", "surface_2D", "(", "num_lat", "=", "90", ",", "num_lon", "=", "180", ",", "water_depth", "=", "10.", ",", "lon", "=", "None", ",", "lat", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "lat", "is", "None", ":", "latax", "=", "Axis",...
39.660377
25.735849
def _get_size(self) -> Tuple[int, int]: """Return the (width, height) for this Image. Returns: Tuple[int, int]: The (width, height) of this Image """ w = ffi.new("int *") h = ffi.new("int *") lib.TCOD_image_get_size(self.image_c, w, h) return w[0], h[...
[ "def", "_get_size", "(", "self", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "w", "=", "ffi", ".", "new", "(", "\"int *\"", ")", "h", "=", "ffi", ".", "new", "(", "\"int *\"", ")", "lib", ".", "TCOD_image_get_size", "(", "self", ".", "i...
31.3
13.7
def dwmAll(data, db, configName='', config={}, udfNamespace=__name__, verbose=False): """ Return list of dictionaries after cleaning rules have been applied; optionally with a history record ID appended. :param list data: list of dictionaries (records) to which cleaning rules should be applied :param M...
[ "def", "dwmAll", "(", "data", ",", "db", ",", "configName", "=", "''", ",", "config", "=", "{", "}", ",", "udfNamespace", "=", "__name__", ",", "verbose", "=", "False", ")", ":", "if", "config", "==", "{", "}", "and", "configName", "==", "''", ":",...
47.235294
35.431373
def reload(self): """ Refreshes the file with the data from the server. """ try: data = self._api.get(self.href, append_base=False).json() resource = File(api=self._api, **data) except Exception: try: data = self._api.get( ...
[ "def", "reload", "(", "self", ")", ":", "try", ":", "data", "=", "self", ".", "_api", ".", "get", "(", "self", ".", "href", ",", "append_base", "=", "False", ")", ".", "json", "(", ")", "resource", "=", "File", "(", "api", "=", "self", ".", "_a...
36.714286
17.5
def set_index(self, index): """Set the current index to the row of the given index :param index: the index to set the level to :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ self.setCurrentIndex(index) self.new_root....
[ "def", "set_index", "(", "self", ",", "index", ")", ":", "self", ".", "setCurrentIndex", "(", "index", ")", "self", ".", "new_root", ".", "emit", "(", "index", ")", "self", ".", "scrollTo", "(", "index", ")" ]
29.083333
12.166667
def calc_equivalent_modulus(self): """Calculates the equivalent laminate properties. The following attributes are calculated: e1, e2, g12, nu12, nu21 """ AI = np.matrix(self.ABD, dtype=np.float64).I a11, a12, a22, a33 = AI[0,0], AI[0,1], AI[1,1], AI[2,2] sel...
[ "def", "calc_equivalent_modulus", "(", "self", ")", ":", "AI", "=", "np", ".", "matrix", "(", "self", ".", "ABD", ",", "dtype", "=", "np", ".", "float64", ")", ".", "I", "a11", ",", "a12", ",", "a22", ",", "a33", "=", "AI", "[", "0", ",", "0", ...
33
12.285714
def run(self, dag): """ Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1. Args: dag (DAGCircuit): DAG to find layout for. Raises: TranspilerError: if dag wider than self.coupling_map """ num_dag_qubits = sum([qreg.size for ...
[ "def", "run", "(", "self", ",", "dag", ")", ":", "num_dag_qubits", "=", "sum", "(", "[", "qreg", ".", "size", "for", "qreg", "in", "dag", ".", "qregs", ".", "values", "(", ")", "]", ")", "if", "num_dag_qubits", ">", "self", ".", "coupling_map", "."...
39.571429
25.571429
def get_spectre_plot(self, sigma=0.05, step=0.01): """ Get a matplotlib plot of the UV-visible xas. Transition are plotted as vertical lines and as a sum of normal functions with sigma with. The broadening is applied in energy and the xas is plotted as a function of the wavelengt...
[ "def", "get_spectre_plot", "(", "self", ",", "sigma", "=", "0.05", ",", "step", "=", "0.01", ")", ":", "from", "pymatgen", ".", "util", ".", "plotting", "import", "pretty_plot", "from", "matplotlib", ".", "mlab", "import", "normpdf", "plt", "=", "pretty_pl...
36.54717
20.207547
def controlprompt_cmd(self, cmd): """Perform a "controlpromptentry" command.""" data = tags.string_tag('cmbe', cmd) + tags.uint8_tag('cmcc', 0) return self.daap.post(_CTRL_PROMPT_CMD, data=data)
[ "def", "controlprompt_cmd", "(", "self", ",", "cmd", ")", ":", "data", "=", "tags", ".", "string_tag", "(", "'cmbe'", ",", "cmd", ")", "+", "tags", ".", "uint8_tag", "(", "'cmcc'", ",", "0", ")", "return", "self", ".", "daap", ".", "post", "(", "_C...
53.75
14
def validate_conversion_arguments(to_wrap): """ Validates arguments for conversion functions. - Only a single argument is present - Kwarg must be 'primitive' 'hexstr' or 'text' - If it is 'hexstr' or 'text' that it is a text type """ @functools.wraps(to_wrap) def wrapper(*args, **kwargs...
[ "def", "validate_conversion_arguments", "(", "to_wrap", ")", ":", "@", "functools", ".", "wraps", "(", "to_wrap", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_assert_one_val", "(", "*", "args", ",", "*", "*", "kwargs", ...
31.157895
14
def get_primary(self): """Return primary's address or None.""" # Implemented here in Topology instead of MongoClient, so it can lock. with self._lock: topology_type = self._description.topology_type if topology_type != TOPOLOGY_TYPE.ReplicaSetWithPrimary: ...
[ "def", "get_primary", "(", "self", ")", ":", "# Implemented here in Topology instead of MongoClient, so it can lock.", "with", "self", ".", "_lock", ":", "topology_type", "=", "self", ".", "_description", ".", "topology_type", "if", "topology_type", "!=", "TOPOLOGY_TYPE",...
44.666667
23.222222
def fit(self, X, y=None, **fit_params): """Fit the StackingEstimator meta-transformer. Parameters ---------- X: array-like of shape (n_samples, n_features) The training input samples. y: array-like, shape (n_samples,) The target values (integers that corr...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "fit_params", ")", ":", "self", ".", "estimator", ".", "fit", "(", "X", ",", "y", ",", "*", "*", "fit_params", ")", "return", "self" ]
32.263158
18.105263
def _log_level_changed(self, name, old, new): """Adjust the log level when log_level is set.""" if isinstance(new, basestring): new = getattr(logging, new) self.log_level = new self.log.setLevel(new)
[ "def", "_log_level_changed", "(", "self", ",", "name", ",", "old", ",", "new", ")", ":", "if", "isinstance", "(", "new", ",", "basestring", ")", ":", "new", "=", "getattr", "(", "logging", ",", "new", ")", "self", ".", "log_level", "=", "new", "self"...
40.333333
4.166667
def connect(self, f, t): """Connect two existing vertices. Nothing happens if the vertices are already connected. """ if t not in self._vertices: raise KeyError(t) self._forwards[f].add(t) self._backwards[t].add(f)
[ "def", "connect", "(", "self", ",", "f", ",", "t", ")", ":", "if", "t", "not", "in", "self", ".", "_vertices", ":", "raise", "KeyError", "(", "t", ")", "self", ".", "_forwards", "[", "f", "]", ".", "add", "(", "t", ")", "self", ".", "_backwards...
29.666667
12.111111
def plot_chain(chain, joints, ax, target=None, show=False): """Plots the chain""" # LIst of nodes and orientations nodes = [] axes = [] transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True) # Get the nodes and the orientation from the tranformation matrix for (in...
[ "def", "plot_chain", "(", "chain", ",", "joints", ",", "ax", ",", "target", "=", "None", ",", "show", "=", "False", ")", ":", "# LIst of nodes and orientations", "nodes", "=", "[", "]", "axes", "=", "[", "]", "transformation_matrixes", "=", "chain", ".", ...
42.5
27.615385
def handle_fault(self, event): """ handle failure/error processing for event """ msg = "Faulty event '{}' with payload '{}' was received by state '{}'".format(event.name, event.payload, self.name) raise RuntimeError(msg)
[ "def", "handle_fault", "(", "self", ",", "event", ")", ":", "msg", "=", "\"Faulty event '{}' with payload '{}' was received by state '{}'\"", ".", "format", "(", "event", ".", "name", ",", "event", ".", "payload", ",", "self", ".", "name", ")", "raise", "Runtime...
42.5
18.5
def set_loader(fxn): """Set __loader__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_loader_wrapper(self, *args, **kwargs): warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2...
[ "def", "set_loader", "(", "fxn", ")", ":", "@", "functools", ".", "wraps", "(", "fxn", ")", "def", "set_loader_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'The import system now takes care of t...
38.307692
12.307692
def get(obj_name, init=False): "Find an object already created" wx_parent = None # check if new_parent is given as string (useful for designer!) if isinstance(obj_name, basestring): # find the object reference in the already created gui2py objects # TODO: only useful for designer, ...
[ "def", "get", "(", "obj_name", ",", "init", "=", "False", ")", ":", "wx_parent", "=", "None", "# check if new_parent is given as string (useful for designer!)\r", "if", "isinstance", "(", "obj_name", ",", "basestring", ")", ":", "# find the object reference in the already...
45.090909
15.636364
def infer_transportation_modes(self, dt_threshold=10): """In-place transportation inferring of segments Returns: This track """ self.segments = [ segment.infer_transportation_mode(dt_threshold=dt_threshold) for segment in self.segments ] ...
[ "def", "infer_transportation_modes", "(", "self", ",", "dt_threshold", "=", "10", ")", ":", "self", ".", "segments", "=", "[", "segment", ".", "infer_transportation_mode", "(", "dt_threshold", "=", "dt_threshold", ")", "for", "segment", "in", "self", ".", "seg...
29.818182
17.363636
def to_period(self, freq=None): """ Cast to PeriodArray/Index at a particular frequency. Converts DatetimeArray/Index to PeriodArray/Index. Parameters ---------- freq : str or Offset, optional One of pandas' :ref:`offset strings <timeseries.offset_aliases>` ...
[ "def", "to_period", "(", "self", ",", "freq", "=", "None", ")", ":", "from", "pandas", ".", "core", ".", "arrays", "import", "PeriodArray", "if", "self", ".", "tz", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"Converting to PeriodArray/Index ...
33.3
23.333333
def list(self, search=False, **kwargs): """ Returns a list of :class:`Message` objects and a pager dict. :Example: messages, pager = client.messages.list() :param bool search: If True then search messages using `ids`, `sessionId`, and/or `query`. Default=False :par...
[ "def", "list", "(", "self", ",", "search", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"search\"", "]", "=", "search", "return", "self", ".", "get_instances", "(", "kwargs", ")" ]
46.294118
27.470588
def add_activity(self, activity): """ Add an activity to the component. :param activity: The activity. """ self.gl.structure.validate_account_names( activity.get_referenced_accounts()) self.activities.append(activity) activity.set_parent_path(self.pa...
[ "def", "add_activity", "(", "self", ",", "activity", ")", ":", "self", ".", "gl", ".", "structure", ".", "validate_account_names", "(", "activity", ".", "get_referenced_accounts", "(", ")", ")", "self", ".", "activities", ".", "append", "(", "activity", ")",...
28.454545
9.909091
def _send_loop(self): """ Waits for data in the output queue to send. """ while True: try: line = self.oqueue.get().splitlines()[0][:500] self._obuffer += line + '\r\n' while self._obuffer: sent = self._socke...
[ "def", "_send_loop", "(", "self", ")", ":", "while", "True", ":", "try", ":", "line", "=", "self", ".", "oqueue", ".", "get", "(", ")", ".", "splitlines", "(", ")", "[", "0", "]", "[", ":", "500", "]", "self", ".", "_obuffer", "+=", "line", "+"...
33.692308
13.230769
def run(self): """Runs the command. Args: self (CleanCommand): the ``CleanCommand`` instance Returns: ``None`` """ for build_dir in self.build_dirs: if os.path.isdir(build_dir): sys.stdout.write('Removing %s%s' % (build_dir, os.li...
[ "def", "run", "(", "self", ")", ":", "for", "build_dir", "in", "self", ".", "build_dirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "build_dir", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Removing %s%s'", "%", "(", "build_dir", ",", ...
34.3
19.35
def parse_number_of_html_pages(html_question): """Parse number of answer pages to paginate over them. :param html_question: raw HTML question element :returns: an integer with the number of pages """ bs_question = bs4.BeautifulSoup(html_question, "html.parser") try: ...
[ "def", "parse_number_of_html_pages", "(", "html_question", ")", ":", "bs_question", "=", "bs4", ".", "BeautifulSoup", "(", "html_question", ",", "\"html.parser\"", ")", "try", ":", "bs_question", ".", "select", "(", "'div.paginator'", ")", "[", "0", "]", "except...
35.928571
20.571429
def ip(ip_address, return_format=None): """Returns a summary of the information our database holds for a particular IP address (similar to /ipinfo.html). In the returned data: Count: (also reports or records) total number of packets blocked from this IP. Attacks: (also targets) number of uniqu...
[ "def", "ip", "(", "ip_address", ",", "return_format", "=", "None", ")", ":", "response", "=", "_get", "(", "'ip/{address}'", ".", "format", "(", "address", "=", "ip_address", ")", ",", "return_format", ")", "if", "'bad IP address'", "in", "str", "(", "resp...
35.166667
21.444444
def send(sms_to, sms_body, **kwargs): """ Site: http://smsaero.ru/ API: http://smsaero.ru/api/ """ headers = { "User-Agent": "DBMail/%s" % get_version(), } kwargs.update({ 'user': settings.SMSAERO_LOGIN, 'password': settings.SMSAERO_MD5_PASSWORD, 'from': kwar...
[ "def", "send", "(", "sms_to", ",", "sms_body", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "{", "\"User-Agent\"", ":", "\"DBMail/%s\"", "%", "get_version", "(", ")", ",", "}", "kwargs", ".", "update", "(", "{", "'user'", ":", "settings", ".", ...
25.948718
19.333333
def load(self): '''获取当前的离线任务列表''' def on_list_task(info, error=None): self.loading_spin.stop() self.loading_spin.hide() if not info: self.app.toast(_('Network error, info is empty')) if error or not info: logger.error('Cloud...
[ "def", "load", "(", "self", ")", ":", "def", "on_list_task", "(", "info", ",", "error", "=", "None", ")", ":", "self", ".", "loading_spin", ".", "stop", "(", ")", "self", ".", "loading_spin", ".", "hide", "(", ")", "if", "not", "info", ":", "self",...
35.756757
14.567568
def parse(bin_payload, block_height): """ Interpret a block's nulldata back into a name. The first three bytes (2 magic + 1 opcode) will not be present in bin_payload. The name will be directly represented by the bytes given. This works for registrations and renewals. Record format (pre...
[ "def", "parse", "(", "bin_payload", ",", "block_height", ")", ":", "# pre F-day 2017: bin_payload is the name.", "# post F-day 2017: bin_payload is the name and possibly the update hash", "# STACKs phase 1: bin_payload possibly has a token burn attached to the end", "epoch_features", "=", ...
42.301075
28.451613
def _set_zone(self, v, load=False): """ Setter method for zone, mapped from YANG variable /zoning/defined_configuration/zone (list) If this variable is read-only (config: false) in the source YANG file, then _set_zone is considered as a private method. Backends looking to populate this variable shou...
[ "def", "_set_zone", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
115.545455
55.863636
def sign(self, filename): """ Signs the filename with the certificate associated with this builder. :param filename | <str> :return <bool> | success """ sign = self.signcmd() certificate = self.certificate() if not sign: ...
[ "def", "sign", "(", "self", ",", "filename", ")", ":", "sign", "=", "self", ".", "signcmd", "(", ")", "certificate", "=", "self", ".", "certificate", "(", ")", "if", "not", "sign", ":", "log", ".", "error", "(", "'No signcmd defined.'", ")", "return", ...
34.08
16.4
def get_instance(self, payload): """ Build an instance of AssistantFallbackActionsInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance :rtype: twilio.rest.previ...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "AssistantFallbackActionsInstance", "(", "self", ".", "_version", ",", "payload", ",", "assistant_sid", "=", "self", ".", "_solution", "[", "'assistant_sid'", "]", ",", ")" ]
40.571429
26.571429
def get_plain_image_as_widget(self): """Used for generating thumbnails. Does not include overlaid graphics. """ arr = self.getwin_array(order=self.rgb_order) # convert numpy array to native image widget image_w = self._get_wimage(arr) return image_w
[ "def", "get_plain_image_as_widget", "(", "self", ")", ":", "arr", "=", "self", ".", "getwin_array", "(", "order", "=", "self", ".", "rgb_order", ")", "# convert numpy array to native image widget", "image_w", "=", "self", ".", "_get_wimage", "(", "arr", ")", "re...
33.222222
12.333333
def _get_config_type(cla55: type) -> Optional[str]: """ Find the name (if any) that a subclass was registered under. We do this simply by iterating through the registry until we find it. """ # Special handling for pytorch RNN types: if cla55 == torch.nn.RNN: return "rnn" elif cla...
[ "def", "_get_config_type", "(", "cla55", ":", "type", ")", "->", "Optional", "[", "str", "]", ":", "# Special handling for pytorch RNN types:", "if", "cla55", "==", "torch", ".", "nn", ".", "RNN", ":", "return", "\"rnn\"", "elif", "cla55", "==", "torch", "."...
31.730769
16.423077
def merge(self, other): """ Merge another stats. """ Stats.merge(self, other) self.changes += other.changes
[ "def", "merge", "(", "self", ",", "other", ")", ":", "Stats", ".", "merge", "(", "self", ",", "other", ")", "self", ".", "changes", "+=", "other", ".", "changes" ]
32
7
def setval(key, val, dict_=None, delim=DEFAULT_TARGET_DELIM): ''' Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. ...
[ "def", "setval", "(", "key", ",", "val", ",", "dict_", "=", "None", ",", "delim", "=", "DEFAULT_TARGET_DELIM", ")", ":", "if", "not", "dict_", ":", "dict_", "=", "{", "}", "prev_hier", "=", "dict_", "dict_hier", "=", "key", ".", "split", "(", "delim"...
26.703704
20.703704
def _check_syntax(code, lang, temp_dir, enforce=True): """ Checks that the code whose text is in CODE parses as LANG. Raises DXSyntaxError if there is a problem and "enforce" is True. """ # This function needs the language to be explicitly set, so we can # generate an appropriate temp filename....
[ "def", "_check_syntax", "(", "code", ",", "lang", ",", "temp_dir", ",", "enforce", "=", "True", ")", ":", "# This function needs the language to be explicitly set, so we can", "# generate an appropriate temp filename.", "if", "lang", "==", "'python2.7'", ":", "temp_basename...
46.333333
22.777778
def hist_from_values_list(values_list, fillers=(None,), normalize=False, cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None): """Compute an emprical histogram, PMF or CDF in a list of lists or a csv string Only works for discrete (integer) values (doesn't bin real val...
[ "def", "hist_from_values_list", "(", "values_list", ",", "fillers", "=", "(", "None", ",", ")", ",", "normalize", "=", "False", ",", "cumulative", "=", "False", ",", "to_str", "=", "False", ",", "sep", "=", "','", ",", "min_bin", "=", "None", ",", "max...
49.461538
31.025641
def parse(self, argv, usedname, location): """Consume and process arguments and store the result. ARGS: argv <list str>: The argument list to parse. usedname <str>: The string used by the user to invoke the option. location <str>: A user friend...
[ "def", "parse", "(", "self", ",", "argv", ",", "usedname", ",", "location", ")", ":", "try", ":", "value", "=", "self", ".", "format", ".", "parse", "(", "argv", ")", "except", "formats", ".", "BadNumberOfArguments", ",", "e", ":", "raise", "BadNumberO...
34.826087
15.043478
def start(cls, now, number, firstweekday=calendar.SATURDAY, **options): """ Return the starting datetime: ``number`` of weeks before ``now``. ``firstweekday`` determines when the week starts. It defaults to Saturday. """ week = cls.mask(now, firstweekday=firstweekday, **...
[ "def", "start", "(", "cls", ",", "now", ",", "number", ",", "firstweekday", "=", "calendar", ".", "SATURDAY", ",", "*", "*", "options", ")", ":", "week", "=", "cls", ".", "mask", "(", "now", ",", "firstweekday", "=", "firstweekday", ",", "*", "*", ...
40.9
18.7
def forward_on_instances(self, instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]: """ Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :f...
[ "def", "forward_on_instances", "(", "self", ",", "instances", ":", "List", "[", "Instance", "]", ")", "->", "List", "[", "Dict", "[", "str", ",", "numpy", ".", "ndarray", "]", "]", ":", "batch_size", "=", "len", "(", "instances", ")", "with", "torch", ...
50.191489
24.446809
def show_group(self, group_id): """ Get information about a group :type group_id: int :param group_id: Group ID Number :rtype: dict :return: a dictionary containing group information """ res = self.post('loadGroups', {'groupId': group_id}) if isi...
[ "def", "show_group", "(", "self", ",", "group_id", ")", ":", "res", "=", "self", ".", "post", "(", "'loadGroups'", ",", "{", "'groupId'", ":", "group_id", "}", ")", "if", "isinstance", "(", "res", ",", "list", ")", ":", "return", "_fix_group", "(", "...
27.466667
13.733333
def to_camel(s): """ :param string s: under_scored string to be CamelCased :return: CamelCase version of input :rtype: str """ # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)
[ "def", "to_camel", "(", "s", ")", ":", "# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups", "return", "re", ".", "sub", "(", "r'_([a-zA-Z])'", ",", "lambda", "m", ":", "m", ".", "group", "(", "1", ")", ".", "upper", "(", ")", ",", "'_'", "+", ...
35
15.75
def _render_relationships(self, resource): """Render the resource's relationships.""" relationships = {} related_models = resource.__mapper__.relationships.keys() primary_key_val = getattr(resource, self.primary_key) if self.dasherize: mapped_relationships = { ...
[ "def", "_render_relationships", "(", "self", ",", "resource", ")", ":", "relationships", "=", "{", "}", "related_models", "=", "resource", ".", "__mapper__", ".", "relationships", ".", "keys", "(", ")", "primary_key_val", "=", "getattr", "(", "resource", ",", ...
39.230769
15.692308
def get_human_readable_type(item): """Return human-readable type string of an item""" if isinstance(item, (ndarray, MaskedArray)): return item.dtype.name elif isinstance(item, Image): return "Image" else: text = get_type_string(item) if text is None: text = to...
[ "def", "get_human_readable_type", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "(", "ndarray", ",", "MaskedArray", ")", ")", ":", "return", "item", ".", "dtype", ".", "name", "elif", "isinstance", "(", "item", ",", "Image", ")", ":", "r...
32.416667
11.083333
def add_config(self, key, type_, default=NOT_SET, env_var=None): """Add a configuration setting. Parameters ---------- key : str The name of the configuration setting. This must be a valid Python attribute name i.e. alphanumeric with underscores. type : f...
[ "def", "add_config", "(", "self", ",", "key", ",", "type_", ",", "default", "=", "NOT_SET", ",", "env_var", "=", "None", ")", ":", "self", ".", "config", "[", "key", "]", "=", "{", "'type'", ":", "type_", "}", "if", "env_var", "is", "not", "None", ...
45.241379
19.931034
def tryCppComment(self, block): """C++ comment checking. when we want to insert slashes: #, #/, #! #/<, #!< and ##... return: filler string or null, if not in a star comment NOTE: otherwise comments get skipped generally and we use the last code-line """ if not block.prev...
[ "def", "tryCppComment", "(", "self", ",", "block", ")", ":", "if", "not", "block", ".", "previous", "(", ")", ".", "isValid", "(", ")", "or", "not", "CFG_AUTO_INSERT_SLACHES", ":", "return", "None", "prevLineText", "=", "block", ".", "previous", "(", ")"...
38.651163
18.72093
def from_data(source): """Infers a table/view schema from its JSON representation, a list of records, or a Pandas dataframe. Args: source: the Pandas Dataframe, a dictionary representing a record, a list of heterogeneous data (record) or homogeneous data (list of records) from which to i...
[ "def", "from_data", "(", "source", ")", ":", "if", "isinstance", "(", "source", ",", "pandas", ".", "DataFrame", ")", ":", "bq_schema", "=", "Schema", ".", "_from_dataframe", "(", "source", ")", "elif", "isinstance", "(", "source", ",", "list", ")", ":",...
54.3
29.2
def verify(self): """ Executes ``ansible-playbook`` against the verify playbook and returns None. :return: None """ pb = self._get_ansible_playbook(self.playbooks.verify) pb.execute()
[ "def", "verify", "(", "self", ")", ":", "pb", "=", "self", ".", "_get_ansible_playbook", "(", "self", ".", "playbooks", ".", "verify", ")", "pb", ".", "execute", "(", ")" ]
25.777778
20.888889
def profile(self, tile=None): """ Create a metadata dictionary for rasterio. Parameters ---------- tile : ``BufferedTile`` Returns ------- metadata : dictionary output profile dictionary used for rasterio. """ dst_metadata = G...
[ "def", "profile", "(", "self", ",", "tile", "=", "None", ")", ":", "dst_metadata", "=", "GTIFF_DEFAULT_PROFILE", "dst_metadata", ".", "pop", "(", "\"transform\"", ",", "None", ")", "dst_metadata", ".", "update", "(", "count", "=", "self", ".", "output_params...
34.463415
17.878049
def get_parameter_defaults(self, include_flags=True): """ Get a dict mapping parameter names to their defaults (if set). :rtype: dict[str, object] """ return { name: parameter.default for (name, parameter) in self.parameters.items() ...
[ "def", "get_parameter_defaults", "(", "self", ",", "include_flags", "=", "True", ")", ":", "return", "{", "name", ":", "parameter", ".", "default", "for", "(", "name", ",", "parameter", ")", "in", "self", ".", "parameters", ".", "items", "(", ")", "if", ...
36.454545
15.545455
def _dispatch_event(self, event, data=None): """Dispatches the event and executes any associated callbacks. Note: To prevent the app from crashing due to callback errors. We catch all exceptions and send all data to the logger. Args: event (str): The type of event. e.g. 'bo...
[ "def", "_dispatch_event", "(", "self", ",", "event", ",", "data", "=", "None", ")", ":", "for", "callback", "in", "self", ".", "_callbacks", "[", "event", "]", ":", "self", ".", "_logger", ".", "debug", "(", "\"Running %s callbacks for event: '%s'\"", ",", ...
38.282051
18.358974
def delete_unit(unit_id, **kwargs): """ Delete a unit from the DB. Raises and exception if the unit does not exist """ try: db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() db.DBSession.delete(db_unit) db.DBSession.flush() return True ex...
[ "def", "delete_unit", "(", "unit_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "db_unit", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "filter", "(", "Unit", ".", "id", "==", "unit_id", ")", ".", "one", "(", ")", "db", ...
28.785714
18.5
def ax(self): """Axes instance of the plot""" if self._ax is None: import matplotlib.pyplot as plt plt.figure() self._ax = plt.axes(projection=self._get_sample_projection()) return self._ax
[ "def", "ax", "(", "self", ")", ":", "if", "self", ".", "_ax", "is", "None", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", ")", "self", ".", "_ax", "=", "plt", ".", "axes", "(", "projection", "=", "self", ".",...
34.714286
15.428571
def _confirm_or_prompt_or_command(pymux): " True when we are waiting for a command, prompt or confirmation. " client_state = pymux.get_client_state() if client_state.confirm_text or client_state.prompt_command or client_state.command_mode: return True
[ "def", "_confirm_or_prompt_or_command", "(", "pymux", ")", ":", "client_state", "=", "pymux", ".", "get_client_state", "(", ")", "if", "client_state", ".", "confirm_text", "or", "client_state", ".", "prompt_command", "or", "client_state", ".", "command_mode", ":", ...
53.4
21.8
def release_client(self, client): """Releases a client object to the pool. Args: client: Client object. """ if isinstance(client, Client): if not self._is_expired_client(client): LOG.debug('Client is not expired. Adding back to pool') ...
[ "def", "release_client", "(", "self", ",", "client", ")", ":", "if", "isinstance", "(", "client", ",", "Client", ")", ":", "if", "not", "self", ".", "_is_expired_client", "(", "client", ")", ":", "LOG", ".", "debug", "(", "'Client is not expired. Adding back...
37.066667
12.066667
def parse_lcov_file_info(args, filepath, line_iter, line_coverage_re, file_end_string): """ Parse the file content in lcov info file """ coverage = [] lines_covered = [] for line in line_iter: if line != "end_of_record": line_coverage_match = line_coverage_re.match(line) ...
[ "def", "parse_lcov_file_info", "(", "args", ",", "filepath", ",", "line_iter", ",", "line_coverage_re", ",", "file_end_string", ")", ":", "coverage", "=", "[", "]", "lines_covered", "=", "[", "]", "for", "line", "in", "line_iter", ":", "if", "line", "!=", ...
38.5
18.041667
def xmon_op_from_proto_dict(proto_dict: Dict) -> ops.Operation: """Convert the proto dictionary to the corresponding operation. See protos in api/google/v1 for specification of the protos. Args: proto_dict: Dictionary representing the proto. Keys are always strings, but values may be t...
[ "def", "xmon_op_from_proto_dict", "(", "proto_dict", ":", "Dict", ")", "->", "ops", ".", "Operation", ":", "def", "raise_missing_fields", "(", "gate_name", ":", "str", ")", ":", "raise", "ValueError", "(", "'{} missing required fields: {}'", ".", "format", "(", ...
40.844828
16.12069
def _get_text_for_grounding(stmt, agent_text): """Get text context for Deft disambiguation If the INDRA database is available, attempts to get the fulltext from which the statement was extracted. If the fulltext is not available, the abstract is returned. If the indra database is not available, uses th...
[ "def", "_get_text_for_grounding", "(", "stmt", ",", "agent_text", ")", ":", "text", "=", "None", "# First we will try to get content from the DB", "try", ":", "from", "indra_db", ".", "util", ".", "content_scripts", "import", "get_text_content_from_text_refs", "from", "...
36.839286
19.303571
def _loadDummyModelParameters(self, params): """ Loads all the parameters for this dummy model. For any paramters specified as lists, read the appropriate value for this model using the model index """ for key, value in params.iteritems(): if type(value) == list: index = self.modelIndex %...
[ "def", "_loadDummyModelParameters", "(", "self", ",", "params", ")", ":", "for", "key", ",", "value", "in", "params", ".", "iteritems", "(", ")", ":", "if", "type", "(", "value", ")", "==", "list", ":", "index", "=", "self", ".", "modelIndex", "%", "...
38.727273
13
def get_uri(self, alias): """ Get the URI for a given alias. A registered URI will return itself, otherwise ``None`` is returned. """ if alias in self.aliases.keys(): return self.aliases[alias] if alias in self.aliases.values(): return alias raise GraphExc...
[ "def", "get_uri", "(", "self", ",", "alias", ")", ":", "if", "alias", "in", "self", ".", "aliases", ".", "keys", "(", ")", ":", "return", "self", ".", "aliases", "[", "alias", "]", "if", "alias", "in", "self", ".", "aliases", ".", "values", "(", ...
43.625
6.625
def add_text(self, text): """ Append the run content elements corresponding to *text* to the ``<w:r>`` element of this instance. """ for char in text: self.add_char(char) self.flush()
[ "def", "add_text", "(", "self", ",", "text", ")", ":", "for", "char", "in", "text", ":", "self", ".", "add_char", "(", "char", ")", "self", ".", "flush", "(", ")" ]
29.5
11.5
def capabilities(self): """Returns the list of system capabilities. :return: A ``list`` of capabilities. """ response = self.get(PATH_CAPABILITIES) return _load_atom(response, MATCH_ENTRY_CONTENT).capabilities
[ "def", "capabilities", "(", "self", ")", ":", "response", "=", "self", ".", "get", "(", "PATH_CAPABILITIES", ")", "return", "_load_atom", "(", "response", ",", "MATCH_ENTRY_CONTENT", ")", ".", "capabilities" ]
34.857143
13.714286
def get_vert_connectivity(mesh_v, mesh_f): """Returns a sparse matrix (of size #verts x #verts) where each nonzero element indicates a neighborhood relation. For example, if there is a nonzero element in position (15,12), that means vertex 15 is connected by an edge to vertex 12.""" vpv = sp.csc_ma...
[ "def", "get_vert_connectivity", "(", "mesh_v", ",", "mesh_f", ")", ":", "vpv", "=", "sp", ".", "csc_matrix", "(", "(", "len", "(", "mesh_v", ")", ",", "len", "(", "mesh_v", ")", ")", ")", "# for each column in the faces...", "for", "i", "in", "range", "(...
36.222222
18.222222
def preston_bin(data, max_num): """ Bins data on base 2 using Preston's method Parameters ---------- data : array-like Data to be binned max_num : float The maximum upper value of the data Returns ------- tuple (binned_data, bin_edges) Notes ----- ...
[ "def", "preston_bin", "(", "data", ",", "max_num", ")", ":", "log_ub", "=", "np", ".", "ceil", "(", "np", ".", "log2", "(", "max_num", ")", ")", "# Make an exclusive lower bound in keeping with Preston", "if", "log_ub", "==", "0", ":", "boundaries", "=", "np...
24.8
21.854545
def _ip_int_from_string(cls, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. ...
[ "def", "_ip_int_from_string", "(", "cls", ",", "ip_str", ")", ":", "if", "not", "ip_str", ":", "raise", "AddressValueError", "(", "'Address cannot be empty'", ")", "octets", "=", "ip_str", ".", "split", "(", "'.'", ")", "if", "len", "(", "octets", ")", "!=...
29.4
20.68
def get_subclass(cls, name): """Get Benchmark subclass by name :param name: name returned by ``Benchmark.name`` property :return: instance of ``Benchmark`` class """ for subclass in cls.__subclasses__(): if subclass.name == name: return subclass ...
[ "def", "get_subclass", "(", "cls", ",", "name", ")", ":", "for", "subclass", "in", "cls", ".", "__subclasses__", "(", ")", ":", "if", "subclass", ".", "name", "==", "name", ":", "return", "subclass", "raise", "NameError", "(", "\"Not a valid Benchmark class:...
41
9.444444
def rebuild(self, **kwargs): '''Repopulate the node-tracking data structures. Shouldn't really ever be needed. ''' self.nodes = [] self.node_types = [] self.id_dict = {} self.type_dict = {} self.add_node(self.root)
[ "def", "rebuild", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "nodes", "=", "[", "]", "self", ".", "node_types", "=", "[", "]", "self", ".", "id_dict", "=", "{", "}", "self", ".", "type_dict", "=", "{", "}", "self", ".", "add_n...
27.1
18.3
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: SuperOp: the linear addition self + other as a SuperOp object. Raises: QiskitError: if other cannot be converted to a channel ...
[ "def", "add", "(", "self", ",", "other", ")", ":", "# Convert other to SuperOp", "if", "not", "isinstance", "(", "other", ",", "SuperOp", ")", ":", "other", "=", "SuperOp", "(", "other", ")", "if", "self", ".", "dim", "!=", "other", ".", "dim", ":", ...
34.6
18.95
def remove_domain_user_role(request, user, role, domain=None): """Removes a given single role for a user from a domain.""" manager = keystoneclient(request, admin=True).roles return manager.revoke(role, user=user, domain=domain)
[ "def", "remove_domain_user_role", "(", "request", ",", "user", ",", "role", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "return", "manager", ".", "revoke", "(", "ro...
59.25
13.5
def default_job_name(self): """Slurm job name if not already specified in the `sbatch` section""" name = '' if not self.root.existing_campaign: campaign_file = osp.basename(self.root.campaign_file) campaign = osp.splitext(campaign_file)[0] name += camp...
[ "def", "default_job_name", "(", "self", ")", ":", "name", "=", "''", "if", "not", "self", ".", "root", ".", "existing_campaign", ":", "campaign_file", "=", "osp", ".", "basename", "(", "self", ".", "root", ".", "campaign_file", ")", "campaign", "=", "osp...
36.6
12
def sort_data(data, cols): """Sort `data` rows and order columns""" return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)
[ "def", "sort_data", "(", "data", ",", "cols", ")", ":", "return", "data", ".", "sort_values", "(", "cols", ")", "[", "cols", "+", "[", "'value'", "]", "]", ".", "reset_index", "(", "drop", "=", "True", ")" ]
48
16
def stream_fastq_full(fastq, threads): """Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght """ logging.info("Nanoget: Starting to collect full metrics from plain fastq file.") inputfastq = handle_compress...
[ "def", "stream_fastq_full", "(", "fastq", ",", "threads", ")", ":", "logging", ".", "info", "(", "\"Nanoget: Starting to collect full metrics from plain fastq file.\"", ")", "inputfastq", "=", "handle_compressed_input", "(", "fastq", ")", "with", "cfutures", ".", "Proce...
42.714286
21.785714
def strip_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet m...
[ "def", "strip_tweet", "(", "text", ",", "remove_url", "=", "True", ")", ":", "if", "remove_url", ":", "text", "=", "url_pattern", ".", "sub", "(", "''", ",", "text", ")", "else", ":", "text", "=", "expand_url", "(", "text", ")", "text", "=", "mention...
24.304348
17
def __draw_block(ax, pair, block, density_scale): """! @brief Display BANG-block on the specified ax. @param[in] ax (Axis): Axis where block should be displayed. @param[in] pair (tuple): Pair of coordinate index that should be displayed. @param[in] block (bang_block): BANG...
[ "def", "__draw_block", "(", "ax", ",", "pair", ",", "block", ",", "density_scale", ")", ":", "max_corner", ",", "min_corner", "=", "bang_visualizer", ".", "__get_rectangle_description", "(", "block", ",", "pair", ")", "belong_cluster", "=", "block", ".", "get_...
47.923077
29.653846
def _merge_setting(cli_options, conf, name, name_cli=None, default=None): # type: (dict, dict, str, str, Any) -> Any """Merge a setting, preferring the CLI option if set :param dict cli_options: cli options :param dict conf: configuration sub-block :param str name: key name :param str name_cli: ...
[ "def", "_merge_setting", "(", "cli_options", ",", "conf", ",", "name", ",", "name_cli", "=", "None", ",", "default", "=", "None", ")", ":", "# type: (dict, dict, str, str, Any) -> Any", "val", "=", "cli_options", ".", "get", "(", "name_cli", "or", "name", ")",...
38
11.533333
def chrome_decrypt(encrypted_value: bytes, key: bytes, init_vector: bytes) \ -> str: """Decrypt Chrome/Chromium's encrypted cookies. Args: encrypted_value: Encrypted cookie from Chrome/Chromium's cookie file key: Key to decrypt encrypted_value init_vector: Initialization vector ...
[ "def", "chrome_decrypt", "(", "encrypted_value", ":", "bytes", ",", "key", ":", "bytes", ",", "init_vector", ":", "bytes", ")", "->", "str", ":", "# Encrypted cookies should be prefixed with 'v10' or 'v11' according to the", "# Chromium code. Strip it off.", "encrypted_value"...
34.35
21.75
def create(cls, name, certificate): """ Create a new external VPN CA for signing internal gateway certificates. :param str name: Name of VPN CA :param str certificate: file name, path or certificate string. :raises CreateElementFailed: Failed creating cert with r...
[ "def", "create", "(", "cls", ",", "name", ",", "certificate", ")", ":", "json", "=", "{", "'name'", ":", "name", ",", "'certificate'", ":", "certificate", "}", "return", "ElementCreator", "(", "cls", ",", "json", ")" ]
34.357143
13.928571
def _write4bits(self, value): """Write 4 bits of data into the data bus.""" for i in range(4): bit = (value >> i) & 0x01 GPIO.output(self.pins[i + 7], bit) self._pulse_enable()
[ "def", "_write4bits", "(", "self", ",", "value", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "bit", "=", "(", "value", ">>", "i", ")", "&", "0x01", "GPIO", ".", "output", "(", "self", ".", "pins", "[", "i", "+", "7", "]", ",", ...
36.5
7.666667
def main(): """ NAME sort_specimens.py DESCRIPTION Reads in a pmag_specimen formatted file and separates it into different components (A,B...etc.) SYNTAX sort_specimens.py [-h] [command line options] INPUT takes pmag_specimens.txt formatted input file OPTIONS...
[ "def", "main", "(", ")", ":", "dir_path", "=", "'.'", "inspec", "=", "\"pmag_specimens.txt\"", "if", "'-WD'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "(", "'-WD'", ")", "dir_path", "=", "sys", ".", "argv", "[", ...
37.758065
25.080645
def convert_table(self, markup): """ Subtitutes <table> content to Wikipedia markup. """ for table in re.findall(self.re["html-table"], markup): wiki = table wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki) wiki = re.sub(r"<tr(.*?)>", "|-\\1", w...
[ "def", "convert_table", "(", "self", ",", "markup", ")", ":", "for", "table", "in", "re", ".", "findall", "(", "self", ".", "re", "[", "\"html-table\"", "]", ",", "markup", ")", ":", "wiki", "=", "table", "wiki", "=", "re", ".", "sub", "(", "r\"<ta...
36.875
14.875
def parse_individual(self, individual): """Converts a deap individual into a full list of parameters. Parameters ---------- individual: deap individual from optimization Details vary according to type of optimization, but parameters within deap individual are alwa...
[ "def", "parse_individual", "(", "self", ",", "individual", ")", ":", "scaled_ind", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_params", "[", "'value_means'", "]", ")", ")", ":", "scaled_ind", ".", "append", "(", "self", ...
42.32
17.6
def cluster_on_extra_high_voltage(network, busmap, with_time=True): """ Main function of the EHV-Clustering approach. Creates a new clustered pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the same network. Parameters ---------- network : pypsa.Network Container fo...
[ "def", "cluster_on_extra_high_voltage", "(", "network", ",", "busmap", ",", "with_time", "=", "True", ")", ":", "network_c", "=", "Network", "(", ")", "buses", "=", "aggregatebuses", "(", "network", ",", "busmap", ",", "{", "'x'", ":", "_leading", "(", "bu...
33.493506
20.402597
def set_baselines(self): """ Modify coords to shift tree position for x,y baseline arguments. This is useful for arrangeing trees onto a Canvas with other plots, but still sharing a common cartesian axes coordinates. """ if self.style.xbaseline: if self.styl...
[ "def", "set_baselines", "(", "self", ")", ":", "if", "self", ".", "style", ".", "xbaseline", ":", "if", "self", ".", "style", ".", "orient", "in", "(", "\"up\"", ",", "\"down\"", ")", ":", "self", ".", "coords", ".", "coords", "[", ":", ",", "0", ...
48.230769
19.923077