text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def remove_monitor(self, handle): """Remove a previously registered monitor. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ action = (handle, "delete", None, None) if self._currently_notifying: self._deferred_adjustments.append(action) else: ...
[ "def", "remove_monitor", "(", "self", ",", "handle", ")", ":", "action", "=", "(", "handle", ",", "\"delete\"", ",", "None", ",", "None", ")", "if", "self", ".", "_currently_notifying", ":", "self", ".", "_deferred_adjustments", ".", "append", "(", "action...
31.909091
14.909091
def get_scenfit(instance, OS, FP, FC, EP): '''returns the scenfit of data and model described by the ``TermSet`` object [instance]. ''' sem = [sign_cons_prg, bwd_prop_prg] if OS : sem.append(one_state_prg) if FP : sem.append(fwd_prop_prg) if FC : sem.append(founded_prg) if EP : sem.append(elem_path_prg)...
[ "def", "get_scenfit", "(", "instance", ",", "OS", ",", "FP", ",", "FC", ",", "EP", ")", ":", "sem", "=", "[", "sign_cons_prg", ",", "bwd_prop_prg", "]", "if", "OS", ":", "sem", ".", "append", "(", "one_state_prg", ")", "if", "FP", ":", "sem", ".", ...
29.3
16.3
def plot_data_filter(data, data_f, b, a, cutoff, fs): '''Plot frequency response and filter overlay for butter filtered data Args ---- data: ndarray Signal array data_f: float Signal sampling rate b: array_like Numerator of a linear filter a: array_like Denom...
[ "def", "plot_data_filter", "(", "data", ",", "data_f", ",", "b", ",", "a", ",", "cutoff", ",", "fs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "numpy", "import", "scipy", ".", "signal", "n", "=", "len", "(", "data", ")",...
24.943396
20.603774
def plot_joint_sfs_folded(*args, **kwargs): """Plot a joint site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes_pop1/2, n_chromosomes_pop2/2) Joint site frequency spectrum. ax : axes, optional Axes on which to draw. If not provided, a new figure ...
[ "def", "plot_joint_sfs_folded", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "plot_joint_sfs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "ax", ".", "set_xlabel", "(", "'minor allele count (population 1)'", ")", "ax", ".", "set_ylab...
30.590909
20.454545
def time(lancet, issue): """ Start an Harvest timer for the given issue. This command takes care of linking the timer with the issue tracker page for the given issue. If the issue is not passed to command it's taken from currently active branch. """ issue = get_issue(lancet, issue) wit...
[ "def", "time", "(", "lancet", ",", "issue", ")", ":", "issue", "=", "get_issue", "(", "lancet", ",", "issue", ")", "with", "taskstatus", "(", "\"Starting harvest timer\"", ")", "as", "ts", ":", "lancet", ".", "timer", ".", "start", "(", "issue", ")", "...
32.769231
15.692308
def load(self, filenames=None, goto=None, word='', editorwindow=None, processevents=True, start_column=None, set_focus=True, add_where='end'): """ Load a text file editorwindow: load in this editorwindow (useful when clicking on outline explorer with multi...
[ "def", "load", "(", "self", ",", "filenames", "=", "None", ",", "goto", "=", "None", ",", "word", "=", "''", ",", "editorwindow", "=", "None", ",", "processevents", "=", "True", ",", "start_column", "=", "None", ",", "set_focus", "=", "True", ",", "a...
47.935714
17.95
def ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_ssh_vrf_shutdown(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services") ssh = ET.SubElement(ssh_sa, "ssh") server = ET...
[ "def", "ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_ssh_vrf_shutdown", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ssh_sa", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ssh-sa\"", ",", "xmlns...
49.066667
18.6
def show_description(self): """ Prints the formatted response for the matching return type """ def printit(c, v): underline = "-" * len(dr.get_name(c)) resp = self.responses[v["type"]] name = "%s[%s] %s%s" % (resp.color, resp.label, dr.get_name(c), Style.RESET_ALL) ...
[ "def", "show_description", "(", "self", ")", ":", "def", "printit", "(", "c", ",", "v", ")", ":", "underline", "=", "\"-\"", "*", "len", "(", "dr", ".", "get_name", "(", "c", ")", ")", "resp", "=", "self", ".", "responses", "[", "v", "[", "\"type...
45.230769
19.461538
def pylab_activate(user_ns, gui=None, import_all=True, shell=None): """Activate pylab mode in the user's namespace. Loads and initializes numpy, matplotlib and friends for interactive use. Parameters ---------- user_ns : dict Namespace where the imports will occur. gui : optional, strin...
[ "def", "pylab_activate", "(", "user_ns", ",", "gui", "=", "None", ",", "import_all", "=", "True", ",", "shell", "=", "None", ")", ":", "gui", ",", "backend", "=", "find_gui_and_backend", "(", "gui", ")", "activate_matplotlib", "(", "backend", ")", "import_...
31.411765
21.558824
def weighted_random(sequence): """ Given a sequence of pairs (element, weight) where weight is an addable/total-order-comparable (e.g. a number), it returns a random element (first item in each pair) given in a non-uniform way given by the weight of the element (second item in each pair) :param ...
[ "def", "weighted_random", "(", "sequence", ")", ":", "if", "isinstance", "(", "sequence", ",", "dict", ")", ":", "sequence", "=", "sequence", ".", "items", "(", ")", "accumulated", "=", "list", "(", "labeled_accumulate", "(", "sequence", ")", ")", "r", "...
37.315789
20.684211
def restore_boolean_setting(self, key, check_box): """Set check_box according to setting of key. :param key: Key to retrieve setting value. :type key: str :param check_box: Check box to show and set the setting. :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox """ ...
[ "def", "restore_boolean_setting", "(", "self", ",", "key", ",", "check_box", ")", ":", "flag", "=", "setting", "(", "key", ",", "expected_type", "=", "bool", ",", "qsettings", "=", "self", ".", "settings", ")", "check_box", ".", "setChecked", "(", "flag", ...
37.818182
18.181818
def convert_crop(node, **kwargs): """Map MXNet's crop operator attributes to onnx's Crop operator and return the created node. """ name, inputs, attrs = get_inputs(node, kwargs) num_inputs = len(inputs) y, x = list(parse_helper(attrs, "offset", [0, 0])) h, w = list(parse_helper(attrs, "h_w"...
[ "def", "convert_crop", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "inputs", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "num_inputs", "=", "len", "(", "inputs", ")", "y", ",", "x", "=", "list", "(", "parse_he...
26.592593
16.888889
def remove_edge_fun(graph): """ Returns a function that removes an edge from the `graph`. ..note:: The out node is removed if this is isolate. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that remove an edge from the `graph`...
[ "def", "remove_edge_fun", "(", "graph", ")", ":", "# Namespace shortcut for speed.", "rm_edge", ",", "rm_node", "=", "graph", ".", "remove_edge", ",", "graph", ".", "remove_node", "from", "networkx", "import", "is_isolate", "def", "remove_edge", "(", "u", ",", "...
26.68
19.8
def _setup_amplification(self, fle): """ If amplification data is specified then reads into memory and updates the required rupture and site parameters """ self.amplification = AmplificationTable(fle["Amplification"], self.m_w, ...
[ "def", "_setup_amplification", "(", "self", ",", "fle", ")", ":", "self", ".", "amplification", "=", "AmplificationTable", "(", "fle", "[", "\"Amplification\"", "]", ",", "self", ".", "m_w", ",", "self", ".", "distances", ")", "if", "self", ".", "amplifica...
48.823529
12.705882
def getdirs(self,libname): '''Implements the dylib search as specified in Apple documentation: http://developer.apple.com/documentation/DeveloperTools/Conceptual/ DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html Before commencing the standard search, the method first ch...
[ "def", "getdirs", "(", "self", ",", "libname", ")", ":", "dyld_fallback_library_path", "=", "_environ_path", "(", "\"DYLD_FALLBACK_LIBRARY_PATH\"", ")", "if", "not", "dyld_fallback_library_path", ":", "dyld_fallback_library_path", "=", "[", "os", ".", "path", ".", "...
35.189189
24.594595
def _value_with_fmt(self, val): """Convert numpy types to Python types for the Excel writers. Parameters ---------- val : object Value to be written into cells Returns ------- Tuple with the first element being the converted value and the second ...
[ "def", "_value_with_fmt", "(", "self", ",", "val", ")", ":", "fmt", "=", "None", "if", "is_integer", "(", "val", ")", ":", "val", "=", "int", "(", "val", ")", "elif", "is_float", "(", "val", ")", ":", "val", "=", "float", "(", "val", ")", "elif",...
26.9375
16.25
def run(self, value, errors, request): """Return thing, but abort validation if request.user cannot edit.""" thing = super(AccessibleDBThing, self).run(value, errors, request) if errors: return None if not thing.can_access(request.user): message = 'Insufficient pe...
[ "def", "run", "(", "self", ",", "value", ",", "errors", ",", "request", ")", ":", "thing", "=", "super", "(", "AccessibleDBThing", ",", "self", ")", ".", "run", "(", "value", ",", "errors", ",", "request", ")", "if", "errors", ":", "return", "None", ...
45.666667
15.111111
def copy_params_from(self, arg_params, aux_params=None, allow_extra_params=False): """Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. ...
[ "def", "copy_params_from", "(", "self", ",", "arg_params", ",", "aux_params", "=", "None", ",", "allow_extra_params", "=", "False", ")", ":", "for", "name", ",", "array", "in", "arg_params", ".", "items", "(", ")", ":", "if", "name", "in", "self", ".", ...
40.318182
22.159091
def findStyleFor(self, element, attrName, default=NotImplemented): """Attempts to find the style setting for attrName in the CSSRulesets. Note: This method does not attempt to resolve rules that return "inherited", "default", or values that have units (including "%"). This is left up to...
[ "def", "findStyleFor", "(", "self", ",", "element", ",", "attrName", ",", "default", "=", "NotImplemented", ")", ":", "rule", "=", "self", ".", "findCSSRulesFor", "(", "element", ",", "attrName", ")", "return", "self", ".", "_extractStyleForRule", "(", "rule...
52.6
20.9
def dispatch_event(self, event_, **kwargs): """ Dispatch section event. Notes: You MUST NOT call event.trigger() directly because it will circumvent the section settings as well as ignore the section tree. If hooks are disabled somewhere up in th...
[ "def", "dispatch_event", "(", "self", ",", "event_", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "settings", ".", "hooks_enabled", ":", "result", "=", "self", ".", "hooks", ".", "dispatch_event", "(", "event_", ",", "*", "*", "kwargs", ")", ...
37.961538
18.653846
def get_mute(self): """Return if the TV is muted.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetMute', params) root = ET.fromstring(res) el_mute = root.find('./...
[ "def", "get_mute", "(", "self", ")", ":", "params", "=", "'<InstanceID>0</InstanceID><Channel>Master</Channel>'", "res", "=", "self", ".", "soap_request", "(", "URL_CONTROL_DMR", ",", "URN_RENDERING_CONTROL", ",", "'GetMute'", ",", "params", ")", "root", "=", "ET", ...
45.25
13.75
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.""" self.Y = np.asarray(sp.prox_l1(self.AX + self.U, (self.lmbda / self.rho) * self.wl1), dtype=self.dtype) super(BPDN, self).ystep()
[ "def", "ystep", "(", "self", ")", ":", "self", ".", "Y", "=", "np", ".", "asarray", "(", "sp", ".", "prox_l1", "(", "self", ".", "AX", "+", "self", ".", "U", ",", "(", "self", ".", "lmbda", "/", "self", ".", "rho", ")", "*", "self", ".", "w...
39
15.875
def pdos_select( self, atoms=None, spin=None, l=None, m=None ): """ Returns a subset of the projected density of states array. Args: atoms (int or list(int)): Atom numbers to include in the selection. Atom numbers count from 1. Default is to selec...
[ "def", "pdos_select", "(", "self", ",", "atoms", "=", "None", ",", "spin", "=", "None", ",", "l", "=", "None", ",", "m", "=", "None", ")", ":", "valid_m_values", "=", "{", "'s'", ":", "[", "]", ",", "'p'", ":", "[", "'x'", ",", "'y'", ",", "'...
49.606061
27.424242
def get_first_content(el_list, alt=None, strip=True): """ Return content of the first element in `el_list` or `alt`. Also return `alt` if the content string of first element is blank. Args: el_list (list): List of HTMLElement objects. alt (default None): Value returner when list or cont...
[ "def", "get_first_content", "(", "el_list", ",", "alt", "=", "None", ",", "strip", "=", "True", ")", ":", "if", "not", "el_list", ":", "return", "alt", "content", "=", "el_list", "[", "0", "]", ".", "getContent", "(", ")", "if", "strip", ":", "conten...
27
23.692308
def check_value( config, section, option, jinja_pattern=JINJA_PATTERN, ): """try to figure out if value is valid or jinja2 template value Args: config (:obj:`configparser.ConfigParser`): config object to read key from section (str): name of section in configparse...
[ "def", "check_value", "(", "config", ",", "section", ",", "option", ",", "jinja_pattern", "=", "JINJA_PATTERN", ",", ")", ":", "value", "=", "config", "[", "section", "]", "[", "option", "]", "if", "re", ".", "match", "(", "jinja_pattern", ",", "value", ...
25.428571
22.357143
def simulate(args): """Main function that manage simulatin of small RNAs""" if args.fasta: name = None seq = "" reads = dict() with open(args.fasta) as in_handle: for line in in_handle: if line.startswith(">"): if name: ...
[ "def", "simulate", "(", "args", ")", ":", "if", "args", ".", "fasta", ":", "name", "=", "None", "seq", "=", "\"\"", "reads", "=", "dict", "(", ")", "with", "open", "(", "args", ".", "fasta", ")", "as", "in_handle", ":", "for", "line", "in", "in_h...
31.555556
13.388889
def city(random=random, *args, **kwargs): """ Produce a city name >>> mock_random.seed(0) >>> city(random=mock_random) 'east mysteryhall' >>> city(random=mock_random, capitalize=True) 'Birmingchimp' >>> city(random=mock_random, slugify=True) 'wonderfulsecretsound' """ retur...
[ "def", "city", "(", "random", "=", "random", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "random", ".", "choice", "(", "[", "\"{direction} {noun}{city_suffix}\"", ",", "\"{noun}{city_suffix}\"", ",", "\"{adjective}{noun}{city_suffix}\"", ",", ...
30.518519
11.037037
def _string_find(self, substr, start=None, end=None): """ Returns position (0 indexed) of first occurence of substring, optionally after a particular position (0 indexed) Parameters ---------- substr : string start : int, default None end : int, default None Not currently implem...
[ "def", "_string_find", "(", "self", ",", "substr", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "end", "is", "not", "None", ":", "raise", "NotImplementedError", "return", "ops", ".", "StringFind", "(", "self", ",", "substr", ",",...
25.789474
18.421053
def Value(cls, val, ctx: SerializerCtx): """ :param dst: is signal connected with value :param val: value object, can be instance of Signal or Value """ t = val._dtype if isinstance(val, RtlSignalBase): return cls.SignalItem(val, ctx) c = cls.Value_t...
[ "def", "Value", "(", "cls", ",", "val", ",", "ctx", ":", "SerializerCtx", ")", ":", "t", "=", "val", ".", "_dtype", "if", "isinstance", "(", "val", ",", "RtlSignalBase", ")", ":", "return", "cls", ".", "SignalItem", "(", "val", ",", "ctx", ")", "c"...
34.25
13
def list_subdomains(self, limit=None, offset=None): """ Returns a list of all subdomains for this domain. """ return self.manager.list_subdomains(self, limit=limit, offset=offset)
[ "def", "list_subdomains", "(", "self", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "return", "self", ".", "manager", ".", "list_subdomains", "(", "self", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ")" ]
41.4
13
def run_rep(self, params, rep): """ run a single repetition including directory creation, log files, etc. """ try: name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) # check if repet...
[ "def", "run_rep", "(", "self", ",", "params", ",", "rep", ")", ":", "try", ":", "name", "=", "params", "[", "'name'", "]", "fullpath", "=", "os", ".", "path", ".", "join", "(", "params", "[", "'path'", "]", ",", "params", "[", "'name'", "]", ")",...
35.222222
17.12963
def np_to_list(elem): """Returns list from list, tuple or ndarray.""" if isinstance(elem, list): return elem elif isinstance(elem, tuple): return list(elem) elif isinstance(elem, np.ndarray): return list(elem) else: raise ValueError( 'Input elements of a sequence should be either a num...
[ "def", "np_to_list", "(", "elem", ")", ":", "if", "isinstance", "(", "elem", ",", "list", ")", ":", "return", "elem", "elif", "isinstance", "(", "elem", ",", "tuple", ")", ":", "return", "list", "(", "elem", ")", "elif", "isinstance", "(", "elem", ",...
31.75
17.5
def n_way_models(mdr_instance, X, y, n=[2], feature_names=None): """Fits a MDR model to all n-way combinations of the features in X. Note that this function performs an exhaustive search through all feature combinations and can be computationally expensive. Parameters ---------- mdr_instance: obje...
[ "def", "n_way_models", "(", "mdr_instance", ",", "X", ",", "y", ",", "n", "=", "[", "2", "]", ",", "feature_names", "=", "None", ")", ":", "if", "feature_names", "is", "None", ":", "feature_names", "=", "list", "(", "range", "(", "X", ".", "shape", ...
44.447368
24.657895
def file_writelines_flush_sync(path, lines): """ Fill file at @path with @lines then flush all buffers (Python and system buffers) """ fp = open(path, 'w') try: fp.writelines(lines) flush_sync_file_object(fp) finally: fp.close()
[ "def", "file_writelines_flush_sync", "(", "path", ",", "lines", ")", ":", "fp", "=", "open", "(", "path", ",", "'w'", ")", "try", ":", "fp", ".", "writelines", "(", "lines", ")", "flush_sync_file_object", "(", "fp", ")", "finally", ":", "fp", ".", "clo...
24.545455
13.272727
def _serialize(self, convert_to_key_and_value, ignore_missing=False): """ serialize model object to dictionary :param convert_to_key_and_value: function(field_name, value, property_detail) -> key, value :return: """ serialized = {} properties = self._get_property...
[ "def", "_serialize", "(", "self", ",", "convert_to_key_and_value", ",", "ignore_missing", "=", "False", ")", ":", "serialized", "=", "{", "}", "properties", "=", "self", ".", "_get_property_names", "(", "self", ")", "def", "get_property_detail", "(", "name", "...
35.148148
21.518519
def set_attributes(d, elm): """Set attributes from dictionary of values.""" for key in d: elm.setAttribute(key, d[key])
[ "def", "set_attributes", "(", "d", ",", "elm", ")", ":", "for", "key", "in", "d", ":", "elm", ".", "setAttribute", "(", "key", ",", "d", "[", "key", "]", ")" ]
33
9.75
def init(): """Try loading each binding in turn Please note: the entire Qt module is replaced with this code: sys.modules["Qt"] = binding() This means no functions or variables can be called after this has executed. For debugging and testing, this module may be accessed through `Qt.__...
[ "def", "init", "(", ")", ":", "preferred", "=", "os", ".", "getenv", "(", "\"QT_PREFERRED_BINDING\"", ")", "verbose", "=", "os", ".", "getenv", "(", "\"QT_VERBOSE\"", ")", "is", "not", "None", "bindings", "=", "(", "_pyside2", ",", "_pyqt5", ",", "_pysid...
25.940299
20.895522
def parse_manifest(manifest_path): """ Parse manifest file :param str manifest_path: Path to manifest file :return: samples :rtype: list[str, list] """ samples = [] with open(manifest_path, 'r') as f: for line in f: if not line.isspace() and not line.startswith('#'):...
[ "def", "parse_manifest", "(", "manifest_path", ")", ":", "samples", "=", "[", "]", "with", "open", "(", "manifest_path", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "not", "line", ".", "isspace", "(", ")", "and", "not", "l...
38.666667
19.333333
def parse(self, input): """Passes input to each QueryLineHandler in use""" query = None for handler in self._line_handlers: try: query = handler.handle(input) except Exception as e: query = None finally: if query...
[ "def", "parse", "(", "self", ",", "input", ")", ":", "query", "=", "None", "for", "handler", "in", "self", ".", "_line_handlers", ":", "try", ":", "query", "=", "handler", ".", "handle", "(", "input", ")", "except", "Exception", "as", "e", ":", "quer...
31.25
11.583333
def start(self): """ Start the timer by recoding the current ``time.time()`` preparing to report the number of seconds since this timestamp. """ if self.start_time is None: self.start_time = time.time() # Play after pause else: # Add the du...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "start_time", "is", "None", ":", "self", ".", "start_time", "=", "time", ".", "time", "(", ")", "# Play after pause", "else", ":", "# Add the duration of the paused interval to the total offset", "pause_dur...
40.266667
14.933333
def _draw(self, data): """ Draw text """ self._cursor.clearSelection() self._cursor.setPosition(self._last_cursor_pos) if '\x07' in data.txt: print('\a') txt = data.txt.replace('\x07', '') if '\x08' in txt: parts = txt.split('\x08...
[ "def", "_draw", "(", "self", ",", "data", ")", ":", "self", ".", "_cursor", ".", "clearSelection", "(", ")", "self", ".", "_cursor", ".", "setPosition", "(", "self", ".", "_last_cursor_pos", ")", "if", "'\\x07'", "in", "data", ".", "txt", ":", "print",...
38.02
13.54
def write_pad_codewords(buff, version, capacity, length): """\ Writes the pad codewords iff the data does not fill the capacity of the symbol. :param buff: The byte buffer. :param int version: The (Micro) QR Code version. :param int capacity: The total capacity of the symbol (incl. error correc...
[ "def", "write_pad_codewords", "(", "buff", ",", "version", ",", "capacity", ",", "length", ")", ":", "# ISO/IEC 18004:2015(E) -- 7.4.10 Bit stream to codeword conversion (page 32)", "# The message bit stream shall then be extended to fill the data capacity", "# of the symbol correspondin...
49.8
23.52
def resolve_feats(feat_list, seqin, seqref, start, locus, missing, verbose=False, verbosity=0): """ resolve_feats - Resolves features from alignments :param feat_list: List of the found features :type feat_list: ``List`` :param seqin: The input sequence :type seqin: ``str`` :param locus: Th...
[ "def", "resolve_feats", "(", "feat_list", ",", "seqin", ",", "seqref", ",", "start", ",", "locus", ",", "missing", ",", "verbose", "=", "False", ",", "verbosity", "=", "0", ")", ":", "structures", "=", "get_structures", "(", ")", "logger", "=", "logging"...
38.405405
16.837838
def distLinf(x1,y1,x2,y2): """Compute the Linfty distance between two points (see TSPLIB documentation)""" return int(max(abs(x2-x1),abs(y2-y1)))
[ "def", "distLinf", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "return", "int", "(", "max", "(", "abs", "(", "x2", "-", "x1", ")", ",", "abs", "(", "y2", "-", "y1", ")", ")", ")" ]
50.333333
5.333333
def add_bgp_speaker_to_dragent(self, bgp_dragent, body): """Adds a BGP speaker to Dynamic Routing agent.""" return self.post((self.agent_path + self.BGP_DRINSTANCES) % bgp_dragent, body=body)
[ "def", "add_bgp_speaker_to_dragent", "(", "self", ",", "bgp_dragent", ",", "body", ")", ":", "return", "self", ".", "post", "(", "(", "self", ".", "agent_path", "+", "self", ".", "BGP_DRINSTANCES", ")", "%", "bgp_dragent", ",", "body", "=", "body", ")" ]
57.25
12.75
def write(self, file): """Write YAML campaign template to the given open file """ render( self.template, file, benchmarks=self.benchmarks, hostname=socket.gethostname(), )
[ "def", "write", "(", "self", ",", "file", ")", ":", "render", "(", "self", ".", "template", ",", "file", ",", "benchmarks", "=", "self", ".", "benchmarks", ",", "hostname", "=", "socket", ".", "gethostname", "(", ")", ",", ")" ]
27
12.666667
def create_widget(self): """ Create the toolkit widget for the proxy object. This method is called during the top-down pass, just before the 'init_widget()' method is called. This method should create the toolkit widget and assign it to the 'widget' attribute. """ self....
[ "def", "create_widget", "(", "self", ")", ":", "self", ".", "widget", "=", "SubElement", "(", "self", ".", "parent_widget", "(", ")", ",", "self", ".", "declaration", ".", "tag", ")" ]
41.666667
24.111111
def install(force=False): """Install git hooks.""" ret, git_dir, _ = run("git rev-parse --show-toplevel") if ret != 0: click.echo( "ERROR: Please run from within a GIT repository.", file=sys.stderr) raise click.Abort git_dir = git_dir[0] hooks_dir = os.path.j...
[ "def", "install", "(", "force", "=", "False", ")", ":", "ret", ",", "git_dir", ",", "_", "=", "run", "(", "\"git rev-parse --show-toplevel\"", ")", "if", "ret", "!=", "0", ":", "click", ".", "echo", "(", "\"ERROR: Please run from within a GIT repository.\"", "...
31.461538
18.384615
def margin( self, axis=None, weighted=True, include_missing=False, include_transforms_for_dims=None, prune=False, include_mr_cat=False, ): """Get margin for the selected axis. the selected axis. For MR variables, this is the sum of the selecte...
[ "def", "margin", "(", "self", ",", "axis", "=", "None", ",", "weighted", "=", "True", ",", "include_missing", "=", "False", ",", "include_transforms_for_dims", "=", "None", ",", "prune", "=", "False", ",", "include_mr_cat", "=", "False", ",", ")", ":", "...
33.03876
22.054264
def simxReadVisionSensor(clientID, sensorHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' detectionState = ct.c_ubyte() auxValues = ct.POINTER(ct.c_float)() auxValuesCount = ct.POINTER(ct.c_int)() ret = c_ReadVisionSe...
[ "def", "simxReadVisionSensor", "(", "clientID", ",", "sensorHandle", ",", "operationMode", ")", ":", "detectionState", "=", "ct", ".", "c_ubyte", "(", ")", "auxValues", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_float", ")", "(", ")", "auxValuesCount", ...
35.272727
25.181818
def get_terminal_size(): """ getTerminalSize() - get width and height of console - works on linux,os x,windows,cygwin(windows) originally retrieved from: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python """ current_os = platform.system() tuple_xy = ...
[ "def", "get_terminal_size", "(", ")", ":", "current_os", "=", "platform", ".", "system", "(", ")", "tuple_xy", "=", "None", "if", "current_os", "==", "'Windows'", ":", "tuple_xy", "=", "_get_terminal_size_windows", "(", ")", "if", "tuple_xy", "is", "None", "...
39
13.315789
def _exp_lt(self, t): """ Parameters ---------- t : float time to propagate Returns -------- exp_lt : numpy.array Array of values exp(lambda(i) * t), where (i) - alphabet index (the eigenvalue number). """ r...
[ "def", "_exp_lt", "(", "self", ",", "t", ")", ":", "return", "np", ".", "exp", "(", "self", ".", "mu", "*", "t", "*", "self", ".", "eigenvals", ")" ]
21.6875
19.8125
def convert_yielded(yielded): """Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. If the `~functools.singledispatch` library is available, this function may be extended to support additional types. For example:: @convert_yielded.r...
[ "def", "convert_yielded", "(", "yielded", ")", ":", "# Lists and dicts containing YieldPoints were handled earlier.", "if", "yielded", "is", "None", ":", "return", "moment", "elif", "isinstance", "(", "yielded", ",", "(", "list", ",", "dict", ")", ")", ":", "retur...
34.12
20.28
def _get_mvar(cls, df, column, windows): """ get moving variance :param df: data :param column: column to calculate :param windows: collection of window of moving variance :return: None """ window = cls.get_only_one_positive_int(windows) column_n...
[ "def", "_get_mvar", "(", "cls", ",", "df", ",", "column", ",", "windows", ")", ":", "window", "=", "cls", ".", "get_only_one_positive_int", "(", "windows", ")", "column_name", "=", "'{}_{}_mvar'", ".", "format", "(", "column", ",", "window", ")", "df", "...
38.333333
13.5
def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name """reraises an exception for exception translation. This is primarily used for when you immediately reraise an exception that is thrown in a library, so that your client will not have to depend on various exceptions defined i...
[ "def", "reraise", "(", "exc_type", ",", "message", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name", "last_lineno", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", ".", "f_lineno", "line_msg", ...
39.018868
23.396226
def _set_group(self, v, load=False): """ Setter method for group, mapped from YANG variable /openflow_state/group (container) If this variable is read-only (config: false) in the source YANG file, then _set_group is considered as a private method. Backends looking to populate this variable should ...
[ "def", "_set_group", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
69.625
33.541667
async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: """Make an HTTP request."""
[ "async", "def", "_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", "=", "b''", ")", "->", "Tuple", "[", "int", ",", "Mapping", "[", ...
64
25.666667
def __interact_copy( self, escape_character=None, input_filter=None, output_filter=None ): '''This is used by the interact() method. ''' while self.isalive(): if self.use_poll: r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO]) el...
[ "def", "__interact_copy", "(", "self", ",", "escape_character", "=", "None", ",", "input_filter", "=", "None", ",", "output_filter", "=", "None", ")", ":", "while", "self", ".", "isalive", "(", ")", ":", "if", "self", ".", "use_poll", ":", "r", "=", "p...
36.840909
14.840909
def getname(exprresolver): """Get expression resolver name. Expression resolver name is given by the attribute __resolver__. If not exist, then the it is given by the attribute __name__. Otherwise, given by the __class__.__name__ attribute. :raises: TypeError if exprresolver is not callable.""" ...
[ "def", "getname", "(", "exprresolver", ")", ":", "result", "=", "None", "if", "not", "callable", "(", "exprresolver", ")", ":", "raise", "TypeError", "(", "'Expression resolver must be a callable object.'", ")", "result", "=", "getattr", "(", "exprresolver", ",", ...
27.782609
23.521739
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ for f in self.resolve_option("files"): self._output.append(Token(f)) return None
[ "def", "do_execute", "(", "self", ")", ":", "for", "f", "in", "self", ".", "resolve_option", "(", "\"files\"", ")", ":", "self", ".", "_output", ".", "append", "(", "Token", "(", "f", ")", ")", "return", "None" ]
27
13
def load(self, cnf, metadata_construction=False): """ The base load method, loads the configuration :param cnf: The configuration as a dictionary :param metadata_construction: Is this only to be able to construct metadata. If so some things can be left out. :return: The Conf...
[ "def", "load", "(", "self", ",", "cnf", ",", "metadata_construction", "=", "False", ")", ":", "_uc", "=", "self", ".", "unicode_convert", "for", "arg", "in", "COMMON_ARGS", ":", "if", "arg", "==", "\"virtual_organization\"", ":", "if", "\"virtual_organization\...
39.086957
17.434783
def calculate_amr(cls, is_extended, from_id, to_id, rtr_only=False, rtr_too=True): """ Calculates AMR using CAN-ID range as parameter. :param bool is_extended: If True parameters from_id and to_id contains 29-bit CAN-ID. :param int from_id: First CAN-ID which should be received. ...
[ "def", "calculate_amr", "(", "cls", ",", "is_extended", ",", "from_id", ",", "to_id", ",", "rtr_only", "=", "False", ",", "rtr_too", "=", "True", ")", ":", "return", "(", "(", "(", "from_id", "^", "to_id", ")", "<<", "3", ")", "|", "(", "0x7", "if"...
58.928571
33.071429
def open_mfdataset(paths, decode_cf=True, decode_times=True, decode_coords=True, engine=None, gridfile=None, t_format=None, **kwargs): """ Open multiple files as a single dataset. This function is essentially the same as the :func:`xarray.open_mfdataset` function b...
[ "def", "open_mfdataset", "(", "paths", ",", "decode_cf", "=", "True", ",", "decode_times", "=", "True", ",", "decode_coords", "=", "True", ",", "engine", "=", "None", ",", "gridfile", "=", "None", ",", "t_format", "=", "None", ",", "*", "*", "kwargs", ...
37.76087
17.5
def list(self, all_tenants=False, **search_opts): """Fetches a list of all floating IPs. :returns: List of FloatingIp object """ if not all_tenants: tenant_id = self.request.user.tenant_id # In Neutron, list_floatingips returns Floating IPs from # all...
[ "def", "list", "(", "self", ",", "all_tenants", "=", "False", ",", "*", "*", "search_opts", ")", ":", "if", "not", "all_tenants", ":", "tenant_id", "=", "self", ".", "request", ".", "user", ".", "tenant_id", "# In Neutron, list_floatingips returns Floating IPs f...
45.73913
15.869565
def enumerate(self, mol): """Enumerate all possible tautomers and return them as a list. :param mol: The input molecule. :type mol: rdkit.Chem.rdchem.Mol :return: A list of all possible tautomers of the molecule. :rtype: list of rdkit.Chem.rdchem.Mol """ smiles =...
[ "def", "enumerate", "(", "self", ",", "mol", ")", ":", "smiles", "=", "Chem", ".", "MolToSmiles", "(", "mol", ",", "isomericSmiles", "=", "True", ")", "tautomers", "=", "{", "smiles", ":", "copy", ".", "deepcopy", "(", "mol", ")", "}", "# Create a keku...
68.556818
33.022727
def file(self, file=None): """Saves the dump in a file-like object in text mode. :param file: :obj:`None` or a file-like object. :return: a file-like object If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO` is returned. If :paramref:`file` is not :obj:`None...
[ "def", "file", "(", "self", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "StringIO", "(", ")", "self", ".", "_file", "(", "file", ")", "return", "file" ]
34.294118
21
def peaks(data, method='max', axis='time', limits=None): """Return the values of an index where the data is at max or min Parameters ---------- method : str, optional 'max' or 'min' axis : str, optional the axis where you want to detect the peaks limits : tuple of two values, op...
[ "def", "peaks", "(", "data", ",", "method", "=", "'max'", ",", "axis", "=", "'time'", ",", "limits", "=", "None", ")", ":", "idx_axis", "=", "data", ".", "index_of", "(", "axis", ")", "output", "=", "data", ".", "_copy", "(", ")", "output", ".", ...
30.54
20.92
def ecb(base, target): """Parse data from European Central Bank.""" api_url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' resp = requests.get(api_url, timeout=1) text = resp.text def _find_rate(symbol): if symbol == 'EUR': return decimal.Decimal(1.00) ...
[ "def", "ecb", "(", "base", ",", "target", ")", ":", "api_url", "=", "'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'", "resp", "=", "requests", ".", "get", "(", "api_url", ",", "timeout", "=", "1", ")", "text", "=", "resp", ".", "text", "def", ...
35.384615
17.538462
def get_version(dev_version=False): """Generates a version string. Arguments: dev_version: Generate a verbose development version from git commits. Examples: 1.1 1.1.dev43 # If 'dev_version' was passed. """ if dev_version: version = git_dev_version() if not ...
[ "def", "get_version", "(", "dev_version", "=", "False", ")", ":", "if", "dev_version", ":", "version", "=", "git_dev_version", "(", ")", "if", "not", "version", ":", "raise", "RuntimeError", "(", "\"Could not generate dev version from git.\"", ")", "return", "vers...
24.944444
21.666667
def patch_clean_fields(model): """ Patch clean_fields method to handle different form types submission. """ old_clean_fields = model.clean_fields def new_clean_fields(self, exclude=None): if hasattr(self, '_mt_form_pending_clear'): # Some form translation fields has been marked ...
[ "def", "patch_clean_fields", "(", "model", ")", ":", "old_clean_fields", "=", "model", ".", "clean_fields", "def", "new_clean_fields", "(", "self", ",", "exclude", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'_mt_form_pending_clear'", ")", ":", ...
51.619048
19.619048
def add_listener(self, on_message=None): """ Subscribes to this topic. When someone publishes a message on this topic, on_message() function is called if provided. :param on_message: (Function), function to be called when a message is published. :return: (str), a registration id...
[ "def", "add_listener", "(", "self", ",", "on_message", "=", "None", ")", ":", "request", "=", "topic_add_message_listener_codec", ".", "encode_request", "(", "self", ".", "name", ",", "False", ")", "def", "handle", "(", "item", ",", "publish_time", ",", "uui...
52.789474
31.526316
def remove_line(self, section): """Base implementation just pops the item from collection. Re-implements to add global behaviour """ self.beginResetModel() self.collection.pop(section) self.endResetModel()
[ "def", "remove_line", "(", "self", ",", "section", ")", ":", "self", ".", "beginResetModel", "(", ")", "self", ".", "collection", ".", "pop", "(", "section", ")", "self", ".", "endResetModel", "(", ")" ]
35.285714
5.714286
def revoke_cert( ca_name, CN, cacert_path=None, ca_filename=None, cert_path=None, cert_filename=None, crl_file=None, digest='sha256', ): ''' Revoke a certificate. .. versionadded:: 2015.8.0 ca_name Name of the CA. CN ...
[ "def", "revoke_cert", "(", "ca_name", ",", "CN", ",", "cacert_path", "=", "None", ",", "ca_filename", "=", "None", ",", "cert_path", "=", "None", ",", "cert_filename", "=", "None", ",", "crl_file", "=", "None", ",", "digest", "=", "'sha256'", ",", ")", ...
30.424581
20.703911
def get_analysis(self, current_class): """ Returns the :class:`~androguard.core.analysis.analysis.Analysis` object which contains the `current_class`. :param current_class: The class to search for :type current_class: androguard.core.bytecodes.dvm.ClassDefItem :rtype: an...
[ "def", "get_analysis", "(", "self", ",", "current_class", ")", ":", "for", "digest", "in", "self", ".", "analyzed_vms", ":", "dx", "=", "self", ".", "analyzed_vms", "[", "digest", "]", "if", "dx", ".", "is_class_present", "(", "current_class", ".", "get_na...
39.357143
14.642857
def get_app_token(self, scope): """Gets the app auth token""" app_token = self.__get_app_token(scope) if app_token: return app_token if self.__cache is not None: token = self.__cache.get(self.__app_token_cache_key(scope)) if token: r...
[ "def", "get_app_token", "(", "self", ",", "scope", ")", ":", "app_token", "=", "self", ".", "__get_app_token", "(", "scope", ")", "if", "app_token", ":", "return", "app_token", "if", "self", ".", "__cache", "is", "not", "None", ":", "token", "=", "self",...
32.028571
24.228571
def _post_action(self, action): """Optionally performs gripper visualization after the actions.""" ret = super()._post_action(action) self._gripper_visualization() return ret
[ "def", "_post_action", "(", "self", ",", "action", ")", ":", "ret", "=", "super", "(", ")", ".", "_post_action", "(", "action", ")", "self", ".", "_gripper_visualization", "(", ")", "return", "ret" ]
40.4
7.2
def end(self): """End of the Glances stats.""" # Close export modules for e in self._exports: self._exports[e].exit() # Close plugins for p in self._plugins: self._plugins[p].exit()
[ "def", "end", "(", "self", ")", ":", "# Close export modules", "for", "e", "in", "self", ".", "_exports", ":", "self", ".", "_exports", "[", "e", "]", ".", "exit", "(", ")", "# Close plugins", "for", "p", "in", "self", ".", "_plugins", ":", "self", "...
29.75
10.125
def response_as_single(self, copy=0): """ convert the response map to a single data frame with Multi-Index columns """ arr = [] for sid, frame in self.response.iteritems(): if copy: frame = frame.copy() 'security' not in frame and frame.insert(0, 'security...
[ "def", "response_as_single", "(", "self", ",", "copy", "=", "0", ")", ":", "arr", "=", "[", "]", "for", "sid", ",", "frame", "in", "self", ".", "response", ".", "iteritems", "(", ")", ":", "if", "copy", ":", "frame", "=", "frame", ".", "copy", "(...
48
14.888889
def validate(wire, keyname, secret, now, request_mac, tsig_start, tsig_rdata, tsig_rdlen, ctx=None, multi=False, first=True): """Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew betwe...
[ "def", "validate", "(", "wire", ",", "keyname", ",", "secret", ",", "now", ",", "request_mac", ",", "tsig_start", ",", "tsig_rdata", ",", "tsig_rdlen", ",", "ctx", "=", "None", ",", "multi", "=", "False", ",", "first", "=", "True", ")", ":", "(", "ad...
38.403846
16.807692
def set_rudder(self, angle): ''' Set the angle of the rudder to be `angle` degrees. :param angle: rudder angle :type angle: float between -90 and 90 ''' angle = float(angle) request = self.boatd.post({'value': float(angle)}, '/rudder') return request.get(...
[ "def", "set_rudder", "(", "self", ",", "angle", ")", ":", "angle", "=", "float", "(", "angle", ")", "request", "=", "self", ".", "boatd", ".", "post", "(", "{", "'value'", ":", "float", "(", "angle", ")", "}", ",", "'/rudder'", ")", "return", "requ...
32
18.4
def contains_version(self, version): """Returns True if version is contained in this range.""" if len(self.bounds) < 5: # not worth overhead of binary search for bound in self.bounds: i = bound.version_containment(version) if i == 0: ...
[ "def", "contains_version", "(", "self", ",", "version", ")", ":", "if", "len", "(", "self", ".", "bounds", ")", "<", "5", ":", "# not worth overhead of binary search", "for", "bound", "in", "self", ".", "bounds", ":", "i", "=", "bound", ".", "version_conta...
33.733333
13.266667
def find(cls, api_name): """ Find or create an API model object by name """ if api_name in cls.apis_by_name: return cls.apis_by_name[api_name] api = cls(api_name) api._fetch_from_aws() if api.exists_in_aws: api._fetch_resources() cls.apis_by_name[a...
[ "def", "find", "(", "cls", ",", "api_name", ")", ":", "if", "api_name", "in", "cls", ".", "apis_by_name", ":", "return", "cls", ".", "apis_by_name", "[", "api_name", "]", "api", "=", "cls", "(", "api_name", ")", "api", ".", "_fetch_from_aws", "(", ")",...
34.4
8.4
def _fftconv(a, b, axes=(0, 1)): """Patched version of :func:`sporco.linalg.fftconv`.""" if cp.isrealobj(a) and cp.isrealobj(b): fft = cp.fft.rfftn ifft = cp.fft.irfftn else: fft = cp.fft.fftn ifft = cp.fft.ifftn dims = cp.maximum(cp.asarray([a.shape[i] for i in axes]), ...
[ "def", "_fftconv", "(", "a", ",", "b", ",", "axes", "=", "(", "0", ",", "1", ")", ")", ":", "if", "cp", ".", "isrealobj", "(", "a", ")", "and", "cp", ".", "isrealobj", "(", "b", ")", ":", "fft", "=", "cp", ".", "fft", ".", "rfftn", "ifft", ...
32.933333
14.333333
def to_json(self, data): """ Converts the given object to a pretty-formatted JSON string :param data: the object to convert to JSON :return: A pretty-formatted JSON string """ # Don't forget the empty line at the end of the file return ( json.dumps( ...
[ "def", "to_json", "(", "self", ",", "data", ")", ":", "# Don't forget the empty line at the end of the file", "return", "(", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",",...
28.277778
16.055556
def reopen(args): """reopens a closed poll.""" if not args.isadmin: return "Nope, not gonna do it." msg = args.msg.split() if not msg: return "Syntax: !poll reopen <pollnum>" if not msg[0].isdigit(): return "Not a valid positve integer." pid = int(msg[0]) poll = get_o...
[ "def", "reopen", "(", "args", ")", ":", "if", "not", "args", ".", "isadmin", ":", "return", "\"Nope, not gonna do it.\"", "msg", "=", "args", ".", "msg", ".", "split", "(", ")", "if", "not", "msg", ":", "return", "\"Syntax: !poll reopen <pollnum>\"", "if", ...
31.533333
12.733333
def _handle_resps(self, root): """Returns `root` with a resp list added to the TEI header and @resp values changed to references.""" resps, bearers = self.get_resps(root) if not resps: return root file_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:f...
[ "def", "_handle_resps", "(", "self", ",", "root", ")", ":", "resps", ",", "bearers", "=", "self", ".", "get_resps", "(", "root", ")", "if", "not", "resps", ":", "return", "root", "file_desc", "=", "root", ".", "xpath", "(", "'/tei:teiCorpus/tei:teiHeader/t...
47.318182
13.863636
def aes_encrypt(key: bytes, plain_text: bytes) -> bytes: """ AES-GCM encryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys plain_text: bytes Plain text to encrypt Returns ------- bytes nonce(16 bytes) + tag(16 byt...
[ "def", "aes_encrypt", "(", "key", ":", "bytes", ",", "plain_text", ":", "bytes", ")", "->", "bytes", ":", "aes_cipher", "=", "AES", ".", "new", "(", "key", ",", "AES_CIPHER_MODE", ")", "encrypted", ",", "tag", "=", "aes_cipher", ".", "encrypt_and_digest", ...
24.958333
19.125
def upload_job_chunk_list(self, upload_job_id, **kwargs): # noqa: E501 """List all metadata for uploaded chunks # noqa: E501 List all metadata for uploaded chunks # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass a...
[ "def", "upload_job_chunk_list", "(", "self", ",", "upload_job_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ...
150.692308
122.346154
def _realign(seq, precursor, start): """ The actual fn that will realign the sequence """ error = set() pattern_addition = [[1, 1, 0], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 0, 1], [1, 1, 1]] for pos in range(0, len(seq)): if seq[pos] != precursor[(start + pos)]: error.add(pos)...
[ "def", "_realign", "(", "seq", ",", "precursor", ",", "start", ")", ":", "error", "=", "set", "(", ")", "pattern_addition", "=", "[", "[", "1", ",", "1", ",", "0", "]", ",", "[", "1", ",", "0", ",", "1", "]", ",", "[", "0", ",", "1", ",", ...
28.322581
16.258065
def _retrieve_station_history(self, station_ID, limit, interval): """ Helper method for station_X_history functions. """ params = {'id': station_ID, 'type': interval, 'lang': self._language} if limit is not None: params['cnt'] = limit uri = http_client.HttpCli...
[ "def", "_retrieve_station_history", "(", "self", ",", "station_ID", ",", "limit", ",", "interval", ")", ":", "params", "=", "{", "'id'", ":", "station_ID", ",", "'type'", ":", "interval", ",", "'lang'", ":", "self", ".", "_language", "}", "if", "limit", ...
48.555556
16.444444
def _decode_data(self, data): """`data` is array.array""" self.major = data[0] if data[1] is 0xff: self.minor = data[1] elif data[1] <= 0x99: self.minor = int(data[1:2].tostring().decode('bcd+')) else: raise DecodingError()
[ "def", "_decode_data", "(", "self", ",", "data", ")", ":", "self", ".", "major", "=", "data", "[", "0", "]", "if", "data", "[", "1", "]", "is", "0xff", ":", "self", ".", "minor", "=", "data", "[", "1", "]", "elif", "data", "[", "1", "]", "<="...
29.1
15.4
def clean_locks(root=None): ''' Remove unused locks that do not currently (with regard to repositories used) lock any package. root Operate on a different root directory. CLI Example: .. code-block:: bash salt '*' pkg.clean_locks ''' LCK = "removed" out = {LCK: 0}...
[ "def", "clean_locks", "(", "root", "=", "None", ")", ":", "LCK", "=", "\"removed\"", "out", "=", "{", "LCK", ":", "0", "}", "locks", "=", "os", ".", "path", ".", "join", "(", "root", ",", "os", ".", "path", ".", "relpath", "(", "LOCKS", ",", "o...
25.259259
25.333333
def trace_filter(self, from_block: int = 1, to_block: Optional[int] = None, from_address: Optional[List[str]] = None, to_address: Optional[List[str]] = None, after: Optional[int] = None, count: Optional[int] = None) -> List[Dict[str, any]]: """ :param from_block...
[ "def", "trace_filter", "(", "self", ",", "from_block", ":", "int", "=", "1", ",", "to_block", ":", "Optional", "[", "int", "]", "=", "None", ",", "from_address", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "to_address", ":",...
107.763158
87.789474
def start(self): """Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.thread = threading.currentThread() sys.settrace(self._trace) return self._trace
[ "def", "start", "(", "self", ")", ":", "self", ".", "thread", "=", "threading", ".", "currentThread", "(", ")", "sys", ".", "settrace", "(", "self", ".", "_trace", ")", "return", "self", ".", "_trace" ]
25.777778
18
def _select_position(self, width, height): """ Search for the placement with the bes fitness for the rectangle. Returns: tuple (Rectangle, fitness) - Rectangle placed in the fittest position None - Rectangle couldn't be placed """ positions = self._genera...
[ "def", "_select_position", "(", "self", ",", "width", ",", "height", ")", ":", "positions", "=", "self", ".", "_generate_placements", "(", "width", ",", "height", ")", "if", "self", ".", "rot", "and", "width", "!=", "height", ":", "positions", "+=", "sel...
40.866667
16.733333
def print_recs(listofrec, format=1, tags=None): """ Print a list of records. :param format: 1 XML, 2 HTML (not implemented) :param tags: list of tags to be printed if 'listofrec' is not a list it returns empty string """ if tags is None: tags = [] text = "" if type(l...
[ "def", "print_recs", "(", "listofrec", ",", "format", "=", "1", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "text", "=", "\"\"", "if", "type", "(", "listofrec", ")", ".", "__name__", "!=", "'list'", ...
26.277778
17.944444
def scale_channel(self, ch, value): '''scale a channel to 1000/1500/2000''' v = value/10000.0 if v < -1: v = -1 elif v > 1: v = 1 if ch == 3 and self.mpstate.vehicle_type != 'rover': if v < 0: v = 0 return int(1000 +...
[ "def", "scale_channel", "(", "self", ",", "ch", ",", "value", ")", ":", "v", "=", "value", "/", "10000.0", "if", "v", "<", "-", "1", ":", "v", "=", "-", "1", "elif", "v", ">", "1", ":", "v", "=", "1", "if", "ch", "==", "3", "and", "self", ...
29.166667
15.333333
def refresh(cls, path=None): """This gets called by the refresh function (see the top level __init__). """ # discern which path to refresh with if path is not None: new_git = os.path.expanduser(path) new_git = os.path.abspath(new_git) else: ...
[ "def", "refresh", "(", "cls", ",", "path", "=", "None", ")", ":", "# discern which path to refresh with", "if", "path", "is", "not", "None", ":", "new_git", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "new_git", "=", "os", ".", "path", ...
40.583333
18.916667
def handle_request(self): """ Handle one request - serve current process to one connection. Use close_request() to disconnect this process. """ try: request, client_address = self.get_request() except socket.error: return if self.v...
[ "def", "handle_request", "(", "self", ")", ":", "try", ":", "request", ",", "client_address", "=", "self", ".", "get_request", "(", ")", "except", "socket", ".", "error", ":", "return", "if", "self", ".", "verify_request", "(", "request", ",", "client_addr...
37.409091
16.045455
def remember(self, user_name): ''' Remember the authenticated identity. This method simply delegates to another IIdentifier plugin if configured. ''' log.debug('Repoze OAuth remember') environ = toolkit.request.environ rememberer = self._get_rememberer(environ) ...
[ "def", "remember", "(", "self", ",", "user_name", ")", ":", "log", ".", "debug", "(", "'Repoze OAuth remember'", ")", "environ", "=", "toolkit", ".", "request", ".", "environ", "rememberer", "=", "self", ".", "_get_rememberer", "(", "environ", ")", "identity...
39.153846
16.230769