text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def from_xdr_object(cls, op_xdr_object): """Creates a :class:`PathPayment` object from an XDR Operation object. """ if not op_xdr_object.sourceAccount: source = None else: source = encode_check( 'account', op_xdr_object.sourceAccount[0].ed...
[ "def", "from_xdr_object", "(", "cls", ",", "op_xdr_object", ")", ":", "if", "not", "op_xdr_object", ".", "sourceAccount", ":", "source", "=", "None", "else", ":", "source", "=", "encode_check", "(", "'account'", ",", "op_xdr_object", ".", "sourceAccount", "[",...
35.277778
0.001533
def unpack_results( data: bytes, repetitions: int, key_sizes: Sequence[Tuple[str, int]] ) -> Dict[str, np.ndarray]: """Unpack data from a bitstring into individual measurement results. Args: data: Packed measurement results, in the form <rep0><rep1>... where each rep...
[ "def", "unpack_results", "(", "data", ":", "bytes", ",", "repetitions", ":", "int", ",", "key_sizes", ":", "Sequence", "[", "Tuple", "[", "str", ",", "int", "]", "]", ")", "->", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ":", "bits_per_rep",...
36.03125
0.000845
def _check_pypi_version(self): """ When the version is out of date or we have trouble retrieving it print a error to stderr and pause. """ try: check_version() except VersionException as err: print(str(err), file=sys.stderr) time.sleep(TWO_SECO...
[ "def", "_check_pypi_version", "(", "self", ")", ":", "try", ":", "check_version", "(", ")", "except", "VersionException", "as", "err", ":", "print", "(", "str", "(", "err", ")", ",", "file", "=", "sys", ".", "stderr", ")", "time", ".", "sleep", "(", ...
35.111111
0.009259
def write_base (self, url_data): """Write url_data.base_ref.""" self.write(self.part("base") + self.spaces("base")) self.writeln(url_data.base_ref, color=self.colorbase)
[ "def", "write_base", "(", "self", ",", "url_data", ")", ":", "self", ".", "write", "(", "self", ".", "part", "(", "\"base\"", ")", "+", "self", ".", "spaces", "(", "\"base\"", ")", ")", "self", ".", "writeln", "(", "url_data", ".", "base_ref", ",", ...
47.5
0.015544
def __recursive_parser(self, onlysymbol, data, production, showerrors = False): """ Aux function. helps check_word""" LOG.debug("__recursive_parser: Begin ") if not data: return [] from pydsl.grammar.symbol import TerminalSymbol, NullSymbol, NonTerminalSymbol if isins...
[ "def", "__recursive_parser", "(", "self", ",", "onlysymbol", ",", "data", ",", "production", ",", "showerrors", "=", "False", ")", ":", "LOG", ".", "debug", "(", "\"__recursive_parser: Begin \"", ")", "if", "not", "data", ":", "return", "[", "]", "from", "...
56.779221
0.008543
def debug_print(self): '''Print tree''' def print_node(node, depth=0): print('{}{}'.format(' ' * depth, repr(node))) if node.is_container(): for child in node.children: print_node(child, depth + 1) for root in self.stack: p...
[ "def", "debug_print", "(", "self", ")", ":", "def", "print_node", "(", "node", ",", "depth", "=", "0", ")", ":", "print", "(", "'{}{}'", ".", "format", "(", "' '", "*", "depth", ",", "repr", "(", "node", ")", ")", ")", "if", "node", ".", "is_con...
29.545455
0.01194
def p_factor_unary_operators(self, p): """ term : SUB factor | ADD factor """ p[0] = p[2] if p[1] == '-': p[0] = Instruction('-x', context={'x': p[0]})
[ "def", "p_factor_unary_operators", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]", "if", "p", "[", "1", "]", "==", "'-'", ":", "p", "[", "0", "]", "=", "Instruction", "(", "'-x'", ",", "context", "=", "{", "'x'",...
23.222222
0.009217
def _unascii(s): """Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8 This method takes the output of the JSONEncoder and expands any \\uNNNN escapes it finds (except for \\u0000 to \\u001F, which are converted to \\xNN escapes). For performance, it assumes that the input is valid JSO...
[ "def", "_unascii", "(", "s", ")", ":", "# make the fast path fast: if there are no matches in the string, the", "# whole thing is ascii. On python 2, that means we're done. On python 3,", "# we have to turn it into a bytes, which is quickest with encode('utf-8')", "m", "=", "_U_ESCAPE", ".",...
35.824324
0.000367
def plot_sediment_memory(self, ax=None): """Plot sediment memory prior and posterior distributions""" if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_memory() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_memory ...
[ "def", "plot_sediment_memory", "(", "self", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "y_prior", ",", "x_prior", "=", "self", ".", "prior_sediment_memory", "(", ")", "ax", ".", "plot", ...
42.08
0.001859
def save(name, data, rc_file='~/.odoorpcrc'): """Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeou...
[ "def", "save", "(", "name", ",", "data", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf"...
35.09375
0.000867
def sha256_file(path): """Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method """ h = hashlib.sha256() with open(path, 'rb')...
[ "def", "sha256_file", "(", "path", ")", ":", "h", "=", "hashlib", ".", "sha256", "(", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "CHUNK_SIZE", ")", ...
28.4
0.002273
def translate(to_translate, to_language="auto", from_language="auto"): """Returns the translation using google translate you must shortcut the language you define (French = fr, English = en, Spanish = es, etc...) if not defined it will detect it or use english by default Example: print(translat...
[ "def", "translate", "(", "to_translate", ",", "to_language", "=", "\"auto\"", ",", "from_language", "=", "\"auto\"", ")", ":", "base_link", "=", "\"http://translate.google.com/m?hl=%s&sl=%s&q=%s\"", "if", "(", "sys", ".", "version_info", "[", "0", "]", "<", "3", ...
40.206897
0.000838
def cast(cast_fn): """ >>> from Redy.Magic.Classic import cast >>> @cast(list) >>> def f(x): >>> for each in x: >>> if each % 2: >>> continue >>> yield each """ def inner(func): def call(*args, **kwargs): return cast_fn(func(*a...
[ "def", "cast", "(", "cast_fn", ")", ":", "def", "inner", "(", "func", ")", ":", "def", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "cast_fn", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "functool...
21.105263
0.002387
def generate(env): """Add Builders and construction variables for the mwcc to an Environment.""" import SCons.Defaults import SCons.Tool set_vars(env) static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CActi...
[ "def", "generate", "(", "env", ")", ":", "import", "SCons", ".", "Defaults", "import", "SCons", ".", "Tool", "set_vars", "(", "env", ")", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "for", "suffi...
31.375
0.01391
def create_wf_instances(self, roles=None): """ Creates wf instances. Args: roles (list): role list Returns: (list): wf instances """ # if roles specified then create an instance for each role # else create only one instance if ro...
[ "def", "create_wf_instances", "(", "self", ",", "roles", "=", "None", ")", ":", "# if roles specified then create an instance for each role", "# else create only one instance", "if", "roles", ":", "wf_instances", "=", "[", "WFInstance", "(", "wf", "=", "self", ".", "w...
30.792453
0.001781
def parse_pattern(s): """Parse a string such as 'foo/bar/*.py' Assumes is_pattern(s) has been called and returned True 1. directory to process 2. pattern to match""" if '{' in s: return None, None # Unsupported by fnmatch if s and s[0] == '~': s = os.path.expanduser(s) parts...
[ "def", "parse_pattern", "(", "s", ")", ":", "if", "'{'", "in", "s", ":", "return", "None", ",", "None", "# Unsupported by fnmatch", "if", "s", "and", "s", "[", "0", "]", "==", "'~'", ":", "s", "=", "os", ".", "path", ".", "expanduser", "(", "s", ...
33.24
0.002339
def list_mapping(html_cleaned): """将预处理后的网页文档映射成列表和字典,并提取虚假标题 Keyword arguments: html_cleaned -- 预处理后的网页源代码,字符串类型 Return: unit_raw -- 网页文本行 init_dict -- 字典的key是索引,value是网页文本行,并按照网页文本行长度降序排序 fake_title -- 虚假标题,即网页源代码<title>中的文本...
[ "def", "list_mapping", "(", "html_cleaned", ")", ":", "unit_raw", "=", "html_cleaned", ".", "split", "(", "'\\n'", ")", "for", "i", "in", "unit_raw", ":", "c", "=", "CDM", "(", "i", ")", "if", "c", ".", "PTN", "is", "not", "0", ":", "fake_title", "...
30.166667
0.002141
def google(language, word, n = 8, *args, **kwargs): ''' Downloads suitable images for a given word from Google Images. ''' if not kwargs.has_key('start'): kwargs['start'] = 0 if not kwargs.has_key('itype'): kwargs['itype'] = 'photo|clipart|lineart' if not kwargs.has_key('isize'): kwargs['isize'] = 'small|med...
[ "def", "google", "(", "language", ",", "word", ",", "n", "=", "8", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "has_key", "(", "'start'", ")", ":", "kwargs", "[", "'start'", "]", "=", "0", "if", "not", "kwar...
38.758621
0.03559
def evpn_afi_peer_activate(self, **kwargs): """ Activate EVPN AFI for a peer. Args: ip_addr (str): IP Address of BGP neighbor. rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. delete (bool): Delet...
[ "def", "evpn_afi_peer_activate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "peer_ip", "=", "kwargs", ".", "pop", "(", "'peer_ip'", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "evpn_activate", "...
45.105263
0.000761
def fix_text(s, ignore_sym_pat=False): if not ignore_sym_pat: # Fix descriptions like D7TDB1 ( s = re.sub("([A-Z0-9]){6} \(", "", s) s = s.split(";")[0] # Fix parantheses containing names s = s.translate(None, "[]") s = s.replace("(-)", "[-]") s = s.replace("(+)", "[+]") ...
[ "def", "fix_text", "(", "s", ",", "ignore_sym_pat", "=", "False", ")", ":", "if", "not", "ignore_sym_pat", ":", "# Fix descriptions like D7TDB1 (", "s", "=", "re", ".", "sub", "(", "\"([A-Z0-9]){6} \\(\"", ",", "\"\"", ",", "s", ")", "s", "=", "s", ".", ...
31.565836
0.001967
def rouge(hypotheses, references): """Calculates average rouge scores for a list of hypotheses and references""" # Filter out hyps that are of 0 length # hyps_and_refs = zip(hypotheses, references) # hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0] # hypotheses, references = zip(*hyp...
[ "def", "rouge", "(", "hypotheses", ",", "references", ")", ":", "# Filter out hyps that are of 0 length", "# hyps_and_refs = zip(hypotheses, references)", "# hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0]", "# hypotheses, references = zip(*hyps_and_refs)", "# Calculate ROUGE-1 F...
34.153846
0.00073
def set_base_step_parameters(self, filename, bp_step, parameters='all', step_range=True, helical=False): """To read and store base-step (Shift, Slide, Rise, Tilt, Roll and Twist) and helical base-step (X-disp, Y-disp, h-Rise, Inclination, Tip and h-Twist) parameters from an input file Parameter...
[ "def", "set_base_step_parameters", "(", "self", ",", "filename", ",", "bp_step", ",", "parameters", "=", "'all'", ",", "step_range", "=", "True", ",", "helical", "=", "False", ")", ":", "if", "not", "(", "isinstance", "(", "bp_step", ",", "list", ")", "o...
46.494845
0.010855
def _next_rotation_id(rotated_files): """Given the hanoi_rotator generated files in the output directory, returns the rotation_id that will be given to the current file. If there are no existing rotated files, return 0. """ if not rotated_files: return 0 else: highest_rotated_fil...
[ "def", "_next_rotation_id", "(", "rotated_files", ")", ":", "if", "not", "rotated_files", ":", "return", "0", "else", ":", "highest_rotated_file", "=", "max", "(", "rotated_files", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "return", "...
39.6
0.002469
def plotRates (include =['allCells', 'eachPop'], peakBin = 5, timeRanges = None, timeRangeLabels = None, colors = None, figSize = ((5,5)), saveData = None, ylim = None, saveFig = None, showFig = True): ''' Calculate avg and peak rate of different subsets of cells for specific time period - inc...
[ "def", "plotRates", "(", "include", "=", "[", "'allCells'", ",", "'eachPop'", "]", ",", "peakBin", "=", "5", ",", "timeRanges", "=", "None", ",", "timeRangeLabels", "=", "None", ",", "colors", "=", "None", ",", "figSize", "=", "(", "(", "5", ",", "5"...
37.524752
0.015681
def interceptable(func): """Decorator that wraps `func` so that its execution is intercepted. The wrapper passes `func` to the interceptor for the current thread. If there is no next interceptor, we perform an "immediate" call to `func`. That is, `func` terminates without forwarding its execution to another ...
[ "def", "interceptable", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "func_wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "get_next_interceptor", "(", ")", "as", "interceptor", ":", "return", "...
27.47619
0.01005
def create_window(self, pane, name=None, set_active=True): """ Create a new window that contains just this pane. :param pane: The :class:`.Pane` instance to put in the new window. :param name: If given, name for the new window. :param set_active: When True, focus the new window....
[ "def", "create_window", "(", "self", ",", "pane", ",", "name", "=", "None", ",", "set_active", "=", "True", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "assert", "name", "is", "None", "or", "isinstance", "(", "name", ",", "six", ...
29.833333
0.001803
def justify_token(tok, col_width): """ Justify a string to fill one or more columns. """ get_len = tools.display_len if PY3 else len tok_len = get_len(tok) diff_len = tok_len - len(tok) if PY3 else 0 cols = (int(math.ceil(float(tok_len) / col_width)) if col_width < tok_len + 4 e...
[ "def", "justify_token", "(", "tok", ",", "col_width", ")", ":", "get_len", "=", "tools", ".", "display_len", "if", "PY3", "else", "len", "tok_len", "=", "get_len", "(", "tok", ")", "diff_len", "=", "tok_len", "-", "len", "(", "tok", ")", "if", "PY3", ...
30.666667
0.00211
def save(filename, contents, include_params=False, variable_batch_size=True): '''Save network definition, inference/training execution configurations etc. Args: filename (str): Filename to store information. The file extension is used to determine the saving file format. ``....
[ "def", "save", "(", "filename", ",", "contents", ",", "include_params", "=", "False", ",", "variable_batch_size", "=", "True", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "==", "'.nntxt'", "or"...
40.643357
0.000336
def get_devices_from_response_dict(response_dict, device_type): """ :rtype: list of WinkDevice """ items = response_dict.get('data') devices = [] api_interface = WinkApiInterface() check_list = isinstance(device_type, (list,)) for item in items: if (check_list and get_object_t...
[ "def", "get_devices_from_response_dict", "(", "response_dict", ",", "device_type", ")", ":", "items", "=", "response_dict", ".", "get", "(", "'data'", ")", "devices", "=", "[", "]", "api_interface", "=", "WinkApiInterface", "(", ")", "check_list", "=", "isinstan...
29.421053
0.001733
def path (self): """ Returns the directory for this target. """ if not self.path_: if self.action_: p = self.action_.properties () (target_path, relative_to_build_dir) = p.target_path () if relative_to_build_dir: # ...
[ "def", "path", "(", "self", ")", ":", "if", "not", "self", ".", "path_", ":", "if", "self", ".", "action_", ":", "p", "=", "self", ".", "action_", ".", "properties", "(", ")", "(", "target_path", ",", "relative_to_build_dir", ")", "=", "p", ".", "t...
36
0.01203
def remove_listener(self, event_name, listener): """Removes a listener.""" self.listeners[event_name].remove(listener) return self
[ "def", "remove_listener", "(", "self", ",", "event_name", ",", "listener", ")", ":", "self", ".", "listeners", "[", "event_name", "]", ".", "remove", "(", "listener", ")", "return", "self" ]
37.75
0.012987
def _publish(tgt, fun, arg=None, tgt_type='glob', returner='', timeout=None, form='clean', roster=None): ''' Publish a command "from the minion out to other minions". In reality, the minion does not execute this funct...
[ "def", "_publish", "(", "tgt", ",", "fun", ",", "arg", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "returner", "=", "''", ",", "timeout", "=", "None", ",", "form", "=", "'clean'", ",", "roster", "=", "None", ")", ":", "if", "fun", ".", "sta...
29.45679
0.000811
def read(self): """Read a DNS master file and build a zone object. @raises dns.zone.NoSOA: No SOA RR was found at the zone origin @raises dns.zone.NoNS: No NS RRset was found at the zone origin """ try: while 1: token = self.tok.get(True, True).unesc...
[ "def", "read", "(", "self", ")", ":", "try", ":", "while", "1", ":", "token", "=", "self", ".", "tok", ".", "get", "(", "True", ",", "True", ")", ".", "unescape", "(", ")", "if", "token", ".", "is_eof", "(", ")", ":", "if", "not", "self", "."...
47.894737
0.002423
def resend_sent(self, route_family, peer): """For given `peer` re-send sent paths. Parameters: - `route-family`: (RouteFamily) of the sent paths to re-send - `peer`: (Peer) peer for which we need to re-send sent paths """ if peer not in self._peers.values(): ...
[ "def", "resend_sent", "(", "self", ",", "route_family", ",", "peer", ")", ":", "if", "peer", "not", "in", "self", ".", "_peers", ".", "values", "(", ")", ":", "raise", "ValueError", "(", "'Could not find given peer (%s)'", "%", "peer", ")", "if", "route_fa...
45.413043
0.000937
def combine_magic(filenames, outfile='measurements.txt', data_model=3, magic_table='measurements', dir_path=".", input_dir_path=""): """ Takes a list of magic-formatted files, concatenates them, and creates a single file. Returns output filename if the operation was successful. Parame...
[ "def", "combine_magic", "(", "filenames", ",", "outfile", "=", "'measurements.txt'", ",", "data_model", "=", "3", ",", "magic_table", "=", "'measurements'", ",", "dir_path", "=", "\".\"", ",", "input_dir_path", "=", "\"\"", ")", ":", "input_dir_path", ",", "ou...
44.901099
0.001916
def stack_2_eqn(self,p): """returns equation string for program stack""" stack_eqn = [] if p: # if stack is not empty for n in p.stack: self.eval_eqn(n,stack_eqn) return stack_eqn[-1] return []
[ "def", "stack_2_eqn", "(", "self", ",", "p", ")", ":", "stack_eqn", "=", "[", "]", "if", "p", ":", "# if stack is not empty", "for", "n", "in", "p", ".", "stack", ":", "self", ".", "eval_eqn", "(", "n", ",", "stack_eqn", ")", "return", "stack_eqn", "...
32.25
0.018868
def plot_f(self, plot_limits=None, fixed_inputs=None, resolution=None, apply_link=False, which_data_ycols='all', which_data_rows='all', visible_dims=None, levels=20, samples=0, lower=2.5, upper=97.5, plot_density=False, pl...
[ "def", "plot_f", "(", "self", ",", "plot_limits", "=", "None", ",", "fixed_inputs", "=", "None", ",", "resolution", "=", "None", ",", "apply_link", "=", "False", ",", "which_data_ycols", "=", "'all'", ",", "which_data_rows", "=", "'all'", ",", "visible_dims"...
60.408163
0.008976
def create_dir(self, jbfile): """Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None """ try: ...
[ "def", "create_dir", "(", "self", ",", "jbfile", ")", ":", "try", ":", "jbfile", ".", "create_directory", "(", ")", "except", "os", ".", "error", ":", "self", ".", "statusbar", ".", "showMessage", "(", "'Could not create path: %s'", "%", "jbfile", ".", "ge...
34.461538
0.008696
def _stream_annotation(file_name, pb_dir): """ Stream an entire remote annotation file from physiobank Parameters ---------- file_name : str The name of the annotation file to be read. pb_dir : str The physiobank directory where the annotation file is located. """ # Ful...
[ "def", "_stream_annotation", "(", "file_name", ",", "pb_dir", ")", ":", "# Full url of annotation file", "url", "=", "posixpath", ".", "join", "(", "config", ".", "db_index_url", ",", "pb_dir", ",", "file_name", ")", "# Get the content", "response", "=", "requests...
26.333333
0.001527
def resp_set_group(self, resp, group=None): """Default callback for get_group/set_group """ if group: self.group=group elif resp: self.group=resp.label.decode().replace("\x00", "")
[ "def", "resp_set_group", "(", "self", ",", "resp", ",", "group", "=", "None", ")", ":", "if", "group", ":", "self", ".", "group", "=", "group", "elif", "resp", ":", "self", ".", "group", "=", "resp", ".", "label", ".", "decode", "(", ")", ".", "r...
32.857143
0.016949
def reset(self): """Remove from sys.modules the modules imported by the debuggee.""" if not self.hooked: self.hooked = True sys.path_hooks.append(self) sys.path.insert(0, self.PATH_ENTRY) return for modname in self: if modname in sys.m...
[ "def", "reset", "(", "self", ")", ":", "if", "not", "self", ".", "hooked", ":", "self", ".", "hooked", "=", "True", "sys", ".", "path_hooks", ".", "append", "(", "self", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "self", ".", "PATH_EN...
39.333333
0.002364
def _HostPrefix(client_id): """Build a host prefix for a notification message based on a client id.""" if not client_id: return "" hostname = None if data_store.RelationalDBEnabled(): client_snapshot = data_store.REL_DB.ReadClientSnapshot(client_id) if client_snapshot: hostname = client_snaps...
[ "def", "_HostPrefix", "(", "client_id", ")", ":", "if", "not", "client_id", ":", "return", "\"\"", "hostname", "=", "None", "if", "data_store", ".", "RelationalDBEnabled", "(", ")", ":", "client_snapshot", "=", "data_store", ".", "REL_DB", ".", "ReadClientSnap...
28.611111
0.016917
def add_movie(self, movie_file, left, top, width, height, poster_frame_image=None, mime_type=CT.VIDEO): """Return newly added movie shape displaying video in *movie_file*. **EXPERIMENTAL.** This method has important limitations: * The size must be specified; no auto-scaling s...
[ "def", "add_movie", "(", "self", ",", "movie_file", ",", "left", ",", "top", ",", "width", ",", "height", ",", "poster_frame_image", "=", "None", ",", "mime_type", "=", "CT", ".", "VIDEO", ")", ":", "movie_pic", "=", "_MoviePicElementCreator", ".", "new_mo...
51.071429
0.002059
def spatial_clip(catalog, corners, mindepth=None, maxdepth=None): """ Clip the catalog to a spatial box, can be irregular. Can only be irregular in 2D, depth must be between bounds. :type catalog: :class:`obspy.core.catalog.Catalog` :param catalog: Catalog to clip. :type corners: :class:`matpl...
[ "def", "spatial_clip", "(", "catalog", ",", "corners", ",", "mindepth", "=", "None", ",", "maxdepth", "=", "None", ")", ":", "cat_out", "=", "catalog", ".", "copy", "(", ")", "if", "mindepth", "is", "not", "None", ":", "for", "event", "in", "cat_out", ...
33.727273
0.000655
def validate(self, uri): """ Check an URI for compatibility with this specification. Return True if the URI is compatible. :param uri: an URI to check :return: bool """ requirement = self.requirement() uri_component = uri.component(self.component()) if uri_component is None: return requirement != WU...
[ "def", "validate", "(", "self", ",", "uri", ")", ":", "requirement", "=", "self", ".", "requirement", "(", ")", "uri_component", "=", "uri", ".", "component", "(", "self", ".", "component", "(", ")", ")", "if", "uri_component", "is", "None", ":", "retu...
28.421053
0.030466
def catch(do, my_exception=TypeError, hints='', do_raise=None, prt_tb=True): """ 防止程序出现 exception后异常退出, 但是这里的异常捕获机制仅仅是为了防止程序退出, 无法做相应处理 可以支持有参数或者无参数模式 - ``do == True`` , 则启用捕获异常 - 无参数也启用 try-catch .. code:: python @catch def fnc(): pass - 在有...
[ "def", "catch", "(", "do", ",", "my_exception", "=", "TypeError", ",", "hints", "=", "''", ",", "do_raise", "=", "None", ",", "prt_tb", "=", "True", ")", ":", "if", "not", "hasattr", "(", "do", ",", "'__call__'", ")", ":", "def", "dec", "(", "fn", ...
28.296296
0.000422
def check_structure(data): """ Check whether the structure is flat dictionary. If not, try to convert it to dictionary. Args: data: Whatever data you have (dict/tuple/list). Returns: dict: When the conversion was successful or `data` was already `good`. Raises: MetaPar...
[ "def", "check_structure", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "try", ":", "data", "=", "_convert_to_dict", "(", "data", ")", "except", "MetaParsingException", ":", "raise", "except", ":", "raise", "MetaPars...
29.525
0.001639
def setup(): """Walk the user though the Wallace setup.""" # Create the Wallace config file if it does not already exist. config_name = ".wallaceconfig" config_path = os.path.join(os.path.expanduser("~"), config_name) if os.path.isfile(config_path): log("Wallace config file already exists."...
[ "def", "setup", "(", ")", ":", "# Create the Wallace config file if it does not already exist.", "config_name", "=", "\".wallaceconfig\"", "config_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ",", "confi...
41.066667
0.001587
def create_default_config(self): """Write default config file to disk. Backs up existing configuration file. Returns ------- filename : string Path to config file. """ filename = self.config_file.as_posix() logger.info("Creating default confi...
[ "def", "create_default_config", "(", "self", ")", ":", "filename", "=", "self", ".", "config_file", ".", "as_posix", "(", ")", "logger", ".", "info", "(", "\"Creating default config file: %s\"", ",", "filename", ")", "config_dir", "=", "self", ".", "config_file"...
36.928571
0.001885
def print_menu(place, static=False): """Function for printing the menu Keyword arguments: place -- name of the cafeteria / mensa static -- set true if a static menu exists (default: False) """ day = get_day() if static: plan = get(FILES[1]) for meal in plan["weeks"][0]["days...
[ "def", "print_menu", "(", "place", ",", "static", "=", "False", ")", ":", "day", "=", "get_day", "(", ")", "if", "static", ":", "plan", "=", "get", "(", "FILES", "[", "1", "]", ")", "for", "meal", "in", "plan", "[", "\"weeks\"", "]", "[", "0", ...
34.947368
0.001466
def addModification(self, aa,position, modMass, modType): """ !!!!MODIFICATION POSITION IS 0 BASED!!!!!! Modifications are stored internally as a tuple with this format: (amino acid modified, index in peptide of amino acid, modification type, modification mass) ie (M, 7, Oxidatio...
[ "def", "addModification", "(", "self", ",", "aa", ",", "position", ",", "modMass", ",", "modType", ")", ":", "#clean up xtandem", "if", "not", "modType", ":", "#try to figure out what it is", "tmass", "=", "abs", "(", "modMass", ")", "smass", "=", "str", "("...
43.541667
0.009363
def execute(self, *, args: Union[list, tuple], options: dict) -> tuple: '''Execute command.''' cmd = self._build_cmd(args) process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, encoding='utf-8', shell=options.get('shell', False), env=options.get...
[ "def", "execute", "(", "self", ",", "*", ",", "args", ":", "Union", "[", "list", ",", "tuple", "]", ",", "options", ":", "dict", ")", "->", "tuple", ":", "cmd", "=", "self", ".", "_build_cmd", "(", "args", ")", "process", "=", "subprocess", ".", ...
57.666667
0.008547
def start(self, request: Request) -> Response: '''Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine....
[ "def", "start", "(", "self", ",", "request", ":", "Request", ")", "->", "Response", ":", "if", "self", ".", "_session_state", "!=", "SessionState", ".", "ready", ":", "raise", "RuntimeError", "(", "'Session not ready'", ")", "response", "=", "Response", "(",...
28.789474
0.001768
def to_time(value, ctx): """ Tries conversion of any value to a time """ if isinstance(value, str): time = ctx.get_date_parser().time(value) if time is not None: return time elif isinstance(value, datetime.time): return value elif isinstance(value, datetime.da...
[ "def", "to_time", "(", "value", ",", "ctx", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "time", "=", "ctx", ".", "get_date_parser", "(", ")", ".", "time", "(", "value", ")", "if", "time", "is", "not", "None", ":", "return", ...
31.428571
0.002208
def get_query_cache_key(compiler): """ Generates a cache key from a SQLCompiler. This cache key is specific to the SQL query and its context (which database is used). The same query in the same context (= the same database) must generate the same cache key. :arg compiler: A SQLCompiler that w...
[ "def", "get_query_cache_key", "(", "compiler", ")", ":", "sql", ",", "params", "=", "compiler", ".", "as_sql", "(", ")", "check_parameter_types", "(", "params", ")", "cache_key", "=", "'%s:%s:%s'", "%", "(", "compiler", ".", "using", ",", "sql", ",", "[", ...
37.666667
0.001439
def return_obj(cols, df, return_cols=False): """Construct a DataFrameHolder and then return either that or the DataFrame.""" df_holder = DataFrameHolder(cols=cols, df=df) return df_holder.return_self(return_cols=return_cols)
[ "def", "return_obj", "(", "cols", ",", "df", ",", "return_cols", "=", "False", ")", ":", "df_holder", "=", "DataFrameHolder", "(", "cols", "=", "cols", ",", "df", "=", "df", ")", "return", "df_holder", ".", "return_self", "(", "return_cols", "=", "return...
61.25
0.012097
def calc_riseset(t, target_name, location, prev_next, rise_set, horizon): """ Time at next rise/set of ``target``. Parameters ---------- t : `~astropy.time.Time` or other (see below) Time of observation. This will be passed in as the first argument to the `~astropy.time.Time` initia...
[ "def", "calc_riseset", "(", "t", ",", "target_name", ",", "location", ",", "prev_next", ",", "rise_set", ",", "horizon", ")", ":", "target", "=", "coord", ".", "get_body", "(", "target_name", ",", "t", ")", "t0", "=", "_rise_set_trig", "(", "t", ",", "...
34.978261
0.000605
def instance_admin_client(self): """Getter for the gRPC stub used for the Table Admin API. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_instance_admin_client] :end-before: [END bigtable_instance_admin_client] :rtype: :class:`.bigta...
[ "def", "instance_admin_client", "(", "self", ")", ":", "if", "self", ".", "_instance_admin_client", "is", "None", ":", "if", "not", "self", ".", "_admin", ":", "raise", "ValueError", "(", "\"Client is not an admin client.\"", ")", "self", ".", "_instance_admin_cli...
41.590909
0.002137
def nucmer(args): """ %prog nucmer ref.fasta query.fasta Run NUCMER using query against reference. Parallel implementation derived from: <https://github.com/fritzsedlazeck/sge_mummer> """ from itertools import product from jcvi.apps.grid import MakeManager from jcvi.formats.base import...
[ "def", "nucmer", "(", "args", ")", ":", "from", "itertools", "import", "product", "from", "jcvi", ".", "apps", ".", "grid", "import", "MakeManager", "from", "jcvi", ".", "formats", ".", "base", "import", "split", "p", "=", "OptionParser", "(", "nucmer", ...
30.585366
0.000773
def down(auth_token, force, app_name): """Brings down a Heroku app.""" if not app_name: click.echo( 'WARNING: Inferring the app name when deleting is deprecated. ' 'Starting with happy 2.0, the app_name parameter will be required.' ) app_name = app_name or _read_app_...
[ "def", "down", "(", "auth_token", ",", "force", ",", "app_name", ")", ":", "if", "not", "app_name", ":", "click", ".", "echo", "(", "'WARNING: Inferring the app name when deleting is deprecated. '", "'Starting with happy 2.0, the app_name parameter will be required.'", ")", ...
24.8
0.001294
def envs(backend=None, sources=False): ''' Return the available fileserver environments. If no backend is provided, then the environments for all configured backends will be returned. backend Narrow fileserver backends to a subset of the enabled ones. .. versionchanged:: 2015.5.0 ...
[ "def", "envs", "(", "backend", "=", "None", ",", "sources", "=", "False", ")", ":", "fileserver", "=", "salt", ".", "fileserver", ".", "Fileserver", "(", "__opts__", ")", "return", "sorted", "(", "fileserver", ".", "envs", "(", "back", "=", "backend", ...
39.172414
0.000859
def join_keys(x, y, by=None): """ Join keys. Given two data frames, create a unique key for each row. Parameters ----------- x : dataframe y : dataframe by : list-like Column names to join by Returns ------- out : dict Dictionary with keys x and y. The valu...
[ "def", "join_keys", "(", "x", ",", "y", ",", "by", "=", "None", ")", ":", "if", "by", "is", "None", ":", "by", "=", "slice", "(", "None", ",", "None", ",", "None", ")", "if", "isinstance", "(", "by", ",", "tuple", ")", ":", "by", "=", "list",...
24.666667
0.001182
def get_arrhenius_plot(temps, diffusivities, diffusivity_errors=None, **kwargs): """ Returns an Arrhenius plot. Args: temps ([float]): A sequence of temperatures. diffusivities ([float]): A sequence of diffusivities (e.g., from DiffusionAnalyzer.diffusivit...
[ "def", "get_arrhenius_plot", "(", "temps", ",", "diffusivities", ",", "diffusivity_errors", "=", "None", ",", "*", "*", "kwargs", ")", ":", "Ea", ",", "c", ",", "_", "=", "fit_arrhenius", "(", "temps", ",", "diffusivities", ")", "from", "pymatgen", ".", ...
35.146341
0.000675
def configurar_interface_de_rede(self, configuracao): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ retorno = super(ClienteSATLocal, self).\ configurar_in...
[ "def", "configurar_interface_de_rede", "(", "self", ",", "configuracao", ")", ":", "retorno", "=", "super", "(", "ClienteSATLocal", ",", "self", ")", ".", "configurar_interface_de_rede", "(", "configuracao", ")", "return", "RespostaSAT", ".", "configurar_interface_de_...
45.111111
0.009662
def p_create_class_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CLASS''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
[ "def", "p_create_class_event_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "CreateClassEventNode", "(", "variable_name", "=", "p", "[", "4", "]", ",", "event_specification", "=", "p", "[", "6", "]", ",", "key_letter", "=", "p", ...
63.2
0.009375
def validatetag(context): "Check to make sure that a tag exists for the current HEAD and it looks like a valid version number" # Validate that a Git tag exists for the current commit HEAD result = context.run("git describe --exact-match --tags $(git log -n1 --pretty='%h')") tag = result.stdout.rstrip() ...
[ "def", "validatetag", "(", "context", ")", ":", "# Validate that a Git tag exists for the current commit HEAD", "result", "=", "context", ".", "run", "(", "\"git describe --exact-match --tags $(git log -n1 --pretty='%h')\"", ")", "tag", "=", "result", ".", "stdout", ".", "r...
48.142857
0.0131
def available_output_formats(): """ Return all available output formats. Returns ------- formats : list all available output formats """ output_formats = [] for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT): driver_ = v.load() if hasattr(driver_, "MET...
[ "def", "available_output_formats", "(", ")", ":", "output_formats", "=", "[", "]", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "DRIVERS_ENTRY_POINT", ")", ":", "driver_", "=", "v", ".", "load", "(", ")", "if", "hasattr", "(", "driver_",...
27.823529
0.002045
def list_commented_topics(self, start=0): """ 回复过的话题列表 :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_LIST_USER_COMMENTED_TOPICS % self.api.user_alias, params={'start': start}) return build_list_result(self._parse_topic_table(xml, 'tit...
[ "def", "list_commented_topics", "(", "self", ",", "start", "=", "0", ")", ":", "xml", "=", "self", ".", "api", ".", "xml", "(", "API_GROUP_LIST_USER_COMMENTED_TOPICS", "%", "self", ".", "api", ".", "user_alias", ",", "params", "=", "{", "'start'", ":", "...
37.888889
0.014327
def check_dependencies(self): "Checks if the test program is available in the python environnement" if self.test_program == 'nose': try: import nose except ImportError: sys.exit('Nosetests is not available on your system. Please install it and try ...
[ "def", "check_dependencies", "(", "self", ")", ":", "if", "self", ".", "test_program", "==", "'nose'", ":", "try", ":", "import", "nose", "except", "ImportError", ":", "sys", ".", "exit", "(", "'Nosetests is not available on your system. Please install it and try to r...
45.518519
0.009562
def just_find_proxy(pacfile, url, host=None): """ This function is a wrapper around init, parse_pac, find_proxy and cleanup. This is the function to call if you want to find proxy just for one url. """ if not os.path.isfile(pacfile): raise IOError('Pac file does not exist: {}'.format(pacfile)) init() ...
[ "def", "just_find_proxy", "(", "pacfile", ",", "url", ",", "host", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "pacfile", ")", ":", "raise", "IOError", "(", "'Pac file does not exist: {}'", ".", "format", "(", "pacfile", ")...
29.692308
0.022613
def _resolve_by_settings_urls(request, url, urlconf=None): """ Finds appropriate URL in settings dictionary ``NAVIGATION_URL_MAP`` and returns the Crumb object based on the value. The values can be strings or functions (or any callables). The functions are called as views. The callable values do not...
[ "def", "_resolve_by_settings_urls", "(", "request", ",", "url", ",", "urlconf", "=", "None", ")", ":", "mapping", "=", "getattr", "(", "settings", ",", "'NAVIGATION_URL_MAP'", ",", "{", "}", ")", "title", "=", "mapping", ".", "get", "(", "url", ",", "Non...
45.652174
0.000933
def _read(self, fp, fpname): """Read the configuration from the given file. If the file lacks any section header, add a [general] section header that encompasses the whole thing. """ # Attempt to read the file using the superclass implementation. # # Check the pe...
[ "def", "_read", "(", "self", ",", "fp", ",", "fpname", ")", ":", "# Attempt to read the file using the superclass implementation.", "#", "# Check the permissions of the file we are considering reading", "# if the file exists and the permissions expose it to reads from", "# other users, r...
47.241379
0.001431
def new_result(self, job, update_model=True): """ registers finished runs Every time a run has finished, this function should be called to register it with the result logger. If overwritten, make sure to call this method from the base class to ensure proper logging. Parameters ---------- job: insta...
[ "def", "new_result", "(", "self", ",", "job", ",", "update_model", "=", "True", ")", ":", "if", "not", "job", ".", "exception", "is", "None", ":", "self", ".", "logger", ".", "warning", "(", "\"job {} failed with exception\\n{}\"", ".", "format", "(", "job...
32.894737
0.029549
def plot_layout( title="TDA KMapper", width=600, height=600, bgcolor="rgba(255, 255, 255, 1)", annotation_text=None, annotation_x=0, annotation_y=-0.01, top=100, left=60, right=60, bottom=60, ): """Set the plotly layout Parameters ---------- ...
[ "def", "plot_layout", "(", "title", "=", "\"TDA KMapper\"", ",", "width", "=", "600", ",", "height", "=", "600", ",", "bgcolor", "=", "\"rgba(255, 255, 255, 1)\"", ",", "annotation_text", "=", "None", ",", "annotation_x", "=", "0", ",", "annotation_y", "=", ...
27.135593
0.002411
def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): """Merge two revisions together. Creates a new migration file""" if alembic_version >= (0, 7, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.merge(...
[ "def", "merge", "(", "directory", "=", "None", ",", "revisions", "=", "''", ",", "message", "=", "None", ",", "branch_label", "=", "None", ",", "rev_id", "=", "None", ")", ":", "if", "alembic_version", ">=", "(", "0", ",", "7", ",", "0", ")", ":", ...
48.7
0.002016
def iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False): r""" Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always uses utf-8 URLs internally because this is what browsers and HTTP do as well. In some places where it accepts an URL it also accepts a unicode IRI...
[ "def", "iri_to_uri", "(", "iri", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'strict'", ",", "safe_conversion", "=", "False", ")", ":", "if", "isinstance", "(", "iri", ",", "tuple", ")", ":", "iri", "=", "url_unparse", "(", "iri", ")", "if", ...
39.190476
0.000395
def convertfields_old(key_comm, obj, inblock=None): """convert the float and interger fields""" convinidd = ConvInIDD() typefunc = dict(integer=convinidd.integer, real=convinidd.real) types = [] for comm in key_comm: types.append(comm.get('type', [None])[0]) convs = [typefunc.get(typ, co...
[ "def", "convertfields_old", "(", "key_comm", ",", "obj", ",", "inblock", "=", "None", ")", ":", "convinidd", "=", "ConvInIDD", "(", ")", "typefunc", "=", "dict", "(", "integer", "=", "convinidd", ".", "integer", ",", "real", "=", "convinidd", ".", "real"...
34.45
0.001412
def installed(package, version): """ Check if the package meets the required version. The version specifier consists of an optional comparator (one of =, ==, >, <, >=, <=) and an arbitrarily long version number separated by dots. The should be as you would expect, e.g. for an installed version '0.1...
[ "def", "installed", "(", "package", ",", "version", ")", ":", "if", "not", "exists", "(", "package", ")", ":", "return", "False", "number", ",", "comparator", "=", "_split_version_specifier", "(", "version", ")", "modversion", "=", "_query", "(", "package", ...
25.886364
0.000846
def calculate_bv_sum_unordered(site, nn_list, scale_factor=1): """ Calculates the BV sum of a site for unordered structures. Args: site: The site nn_list: List of nearest neighbors in the format [(nn_site, dist), ...]. scale_factor: A scale factor...
[ "def", "calculate_bv_sum_unordered", "(", "site", ",", "nn_list", ",", "scale_factor", "=", "1", ")", ":", "# If the site \"site\" has N partial occupations as : f_{site}_0,", "# f_{site}_1, ... f_{site}_N of elements", "# X_{site}_0, X_{site}_1, ... X_{site}_N, and each neighbors nn_i i...
45.289474
0.000569
def register_flag_by_module(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: str, the name of a Python module. flag: Flag, the Flag instance...
[ "def", "register_flag_by_module", "(", "self", ",", "module_name", ",", "flag", ")", ":", "flags_by_module", "=", "self", ".", "flags_by_module_dict", "(", ")", "flags_by_module", ".", "setdefault", "(", "module_name", ",", "[", "]", ")", ".", "append", "(", ...
37.916667
0.002146
def assert_daily(var): r"""Assert that the series is daily and monotonic (no jumps in time index). A ValueError is raised otherwise.""" t0, t1 = var.time[:2] # This won't work for non-standard calendars. Needs to be implemented in xarray. Comment for now if isinstance(t0.values, np.datetime64): ...
[ "def", "assert_daily", "(", "var", ")", ":", "t0", ",", "t1", "=", "var", ".", "time", "[", ":", "2", "]", "# This won't work for non-standard calendars. Needs to be implemented in xarray. Comment for now", "if", "isinstance", "(", "t0", ".", "values", ",", "np", ...
41.368421
0.002488
def get_uuid_list(dbconn): """ Get a list of tables that exist in dbconn :param dbconn: master database connection :return: List of uuids in the database """ cur = dbconn.cursor() tables = get_table_list(dbconn) uuids = set() for table in tables: cur.execute("SELECT (UUID) FR...
[ "def", "get_uuid_list", "(", "dbconn", ")", ":", "cur", "=", "dbconn", ".", "cursor", "(", ")", "tables", "=", "get_table_list", "(", "dbconn", ")", "uuids", "=", "set", "(", ")", "for", "table", "in", "tables", ":", "cur", ".", "execute", "(", "\"SE...
30.4
0.002128
async def set_reply_markup(msg: Dict, request: 'Request', stack: 'Stack') \ -> None: """ Add the "reply markup" to a message from the layers :param msg: Message dictionary :param request: Current request being replied :param stack: Stack to analyze """ from bernard.platforms.telegr...
[ "async", "def", "set_reply_markup", "(", "msg", ":", "Dict", ",", "request", ":", "'Request'", ",", "stack", ":", "'Stack'", ")", "->", "None", ":", "from", "bernard", ".", "platforms", ".", "telegram", ".", "layers", "import", "InlineKeyboard", ",", "Repl...
27.125
0.001112
def get_server_api(token=None, site=None, cls=None, config=None, **kwargs): """ Get the anaconda server api class """ if not cls: from binstar_client import Binstar cls = Binstar config = config if config is not None else get_config(site=site) url = config.get('url', DEFAULT_UR...
[ "def", "get_server_api", "(", "token", "=", "None", ",", "site", "=", "None", ",", "cls", "=", "None", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "cls", ":", "from", "binstar_client", "import", "Binstar", "cls", "=", ...
33.464286
0.002075
def reads(s): """ Parse a String and return the data :param s: The string to read :type s: :py:obj:`str` :returns: A dict object containing the data from s :raises: SyntaxError - An error occured reading the data. """ _dict = PyVDF.__UseDict _len = len _whitespace = frozenset('\...
[ "def", "reads", "(", "s", ")", ":", "_dict", "=", "PyVDF", ".", "__UseDict", "_len", "=", "len", "_whitespace", "=", "frozenset", "(", "'\\t '", ")", "_newline", "=", "frozenset", "(", "'\\n\\r'", ")", "_quote_match", "=", "PyVDF", ".", "__RE_Token_Quoted"...
21.495413
0.011424
def get_placeholders_list(self, format_string, matches=None): """ Returns a list of placeholders in ``format_string``. If ``matches`` is provided then it is used to filter the result using fnmatch so the following patterns can be used: .. code-block:: none * ...
[ "def", "get_placeholders_list", "(", "self", ",", "format_string", ",", "matches", "=", "None", ")", ":", "if", "format_string", "not", "in", "self", ".", "_format_placeholders", ":", "placeholders", "=", "self", ".", "_formatter", ".", "get_placeholders", "(", ...
36.611111
0.001478
def from_template(filename, **kwargs): """ Like from_template_string(), but reads the template from the file with the given name instead. :type filename: string :param filename: The name of the template file. :type kwargs: str :param kwargs: Variables to replace in the template. :rtyp...
[ "def", "from_template", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ")", "as", "fp", ":", "return", "from_template_string", "(", "fp", ".", "read", "(", ")", ",", "*", "*", "kwargs", ")" ]
31.714286
0.002188
def expand(sconf, cwd=None, parent=None): """Return config with shorthand and inline properties expanded. This is necessary to keep the code in the :class:`WorkspaceBuilder` clean and also allow for neat, short-hand configurations. As a simple example, internally, tmuxp expects that config options ...
[ "def", "expand", "(", "sconf", ",", "cwd", "=", "None", ",", "parent", "=", "None", ")", ":", "# Note: cli.py will expand configs relative to project's config directory", "# for the first cwd argument.", "if", "not", "cwd", ":", "cwd", "=", "os", ".", "getcwd", "(",...
36.15493
0.000758
def existingDirectory(string): """ A custom type for the argparse commandline parser. Check whether the supplied string points to a valid directory. Examples -------- >>> parser.add_argument('argname', type=existingDirectory, help='help') """ if not os.path.isdir(string): ...
[ "def", "existingDirectory", "(", "string", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "string", ")", ":", "argparse", ".", "ArgumentTypeError", "(", "'{} is not a valid directory.'", ".", "format", "(", "string", ")", ")", "return", "string...
31.230769
0.011962
def get_log_lines(self): """ Get the log text for a scan object :rtype: Iterator over log lines. """ rel = self._client.reverse_url('SCAN', self.url) return self._manager.get_log_lines(**rel)
[ "def", "get_log_lines", "(", "self", ")", ":", "rel", "=", "self", ".", "_client", ".", "reverse_url", "(", "'SCAN'", ",", "self", ".", "url", ")", "return", "self", ".", "_manager", ".", "get_log_lines", "(", "*", "*", "rel", ")" ]
29.125
0.008333
def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for for...
[ "def", "get_all_cleaned_data", "(", "self", ")", ":", "cleaned_data", "=", "{", "}", "for", "form_key", "in", "self", ".", "get_form_list", "(", ")", ":", "form_obj", "=", "self", ".", "get_form", "(", "step", "=", "form_key", ",", "data", "=", "self", ...
42.190476
0.002208
def cytoscape(namespace,command="",PARAMS={},host=cytoscape_host,port=cytoscape_port,method="POST",verbose=False): """ General function for interacting with Cytoscape API. :param namespace: namespace where the request should be executed. eg. "string" :param commnand: command to execute. eg. "protei...
[ "def", "cytoscape", "(", "namespace", ",", "command", "=", "\"\"", ",", "PARAMS", "=", "{", "}", ",", "host", "=", "cytoscape_host", ",", "port", "=", "cytoscape_port", ",", "method", "=", "\"POST\"", ",", "verbose", "=", "False", ")", ":", "if", "(", ...
35.384615
0.020728
def _readline_echo(self, char, echo): """Echo a recieved character, move cursor etc...""" if self._readline_do_echo(echo): self.write(char)
[ "def", "_readline_echo", "(", "self", ",", "char", ",", "echo", ")", ":", "if", "self", ".", "_readline_do_echo", "(", "echo", ")", ":", "self", ".", "write", "(", "char", ")" ]
41
0.011976
def QA_data_tick_resample_1min(tick, type_='1min', if_drop=True): """ tick 采样为 分钟数据 1. 仅使用将 tick 采样为 1 分钟数据 2. 仅测试过,与通达信 1 分钟数据达成一致 3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试 demo: df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001', ...
[ "def", "QA_data_tick_resample_1min", "(", "tick", ",", "type_", "=", "'1min'", ",", "if_drop", "=", "True", ")", ":", "tick", "=", "tick", ".", "assign", "(", "amount", "=", "tick", ".", "price", "*", "tick", ".", "vol", ")", "resx", "=", "pd", ".", ...
46.860465
0.000364
def get_provisioned_table_write_units(table_name): """ Returns the number of provisioned write units for the table :type table_name: str :param table_name: Name of the DynamoDB table :returns: int -- Number of write units """ try: desc = DYNAMODB_CONNECTION.describe_table(table_name) ...
[ "def", "get_provisioned_table_write_units", "(", "table_name", ")", ":", "try", ":", "desc", "=", "DYNAMODB_CONNECTION", ".", "describe_table", "(", "table_name", ")", "except", "JSONResponseError", ":", "raise", "write_units", "=", "int", "(", "desc", "[", "u'Tab...
31.833333
0.001695
def register(linter): """ Registering additional checkers. """ # add all of the checkers register_checkers(linter) # register any checking fiddlers try: from pylint_django.augmentations import apply_augmentations apply_augmentations(linter) except ImportError: # ...
[ "def", "register", "(", "linter", ")", ":", "# add all of the checkers", "register_checkers", "(", "linter", ")", "# register any checking fiddlers", "try", ":", "from", "pylint_django", ".", "augmentations", "import", "apply_augmentations", "apply_augmentations", "(", "l...
29.833333
0.001805
def show_feature_destibution(self, data = None): """! @brief Shows feature distribution. @details Only features in 1D, 2D, 3D space can be visualized. @param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displa...
[ "def", "show_feature_destibution", "(", "self", ",", "data", "=", "None", ")", ":", "visualizer", "=", "cluster_visualizer", "(", ")", "print", "(", "\"amount of nodes: \"", ",", "self", ".", "__amount_nodes", ")", "if", "(", "data", "is", "not", "None", ")"...
40.318182
0.028634
def _sql_params(sql): """ Identify `sql` as either SQL string or 2-tuple of SQL and params. Same format as supported by Django's RunSQL operation for sql/reverse_sql. """ params = None if isinstance(sql, (list, tuple)): elements = len(sql) if elements == 2: sql, param...
[ "def", "_sql_params", "(", "sql", ")", ":", "params", "=", "None", "if", "isinstance", "(", "sql", ",", "(", "list", ",", "tuple", ")", ")", ":", "elements", "=", "len", "(", "sql", ")", "if", "elements", "==", "2", ":", "sql", ",", "params", "="...
32.692308
0.002288
def parse_property_array(self, tup_tree): """ :: <!ELEMENT PROPERTY.ARRAY (QUALIFIER*, VALUE.ARRAY?)> <!ATTLIST PROPERTY.ARRAY %CIMName; %CIMType; #REQUIRED %ArraySize; %ClassOrigin; %...
[ "def", "parse_property_array", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'PROPERTY.ARRAY'", ",", "(", "'NAME'", ",", "'TYPE'", ")", ",", "(", "'CLASSORIGIN'", ",", "'PROPAGATED'", ",", "'ARRAYSIZE'", ",", "'Emb...
36.037736
0.001019
def manage_git_folder(gh_token, temp_dir, git_id, *, pr_number=None): """Context manager to avoid readonly problem while cleanup the temp dir. If PR number is given, use magic branches "pull" from Github. """ _LOGGER.debug("Git ID %s", git_id) if Path(git_id).exists(): yield git_id ...
[ "def", "manage_git_folder", "(", "gh_token", ",", "temp_dir", ",", "git_id", ",", "*", ",", "pr_number", "=", "None", ")", ":", "_LOGGER", ".", "debug", "(", "\"Git ID %s\"", ",", "git_id", ")", "if", "Path", "(", "git_id", ")", ".", "exists", "(", ")"...
40.25
0.002427