text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def do_ls(self, subcmd, opts, folder=""): """${cmd_name}: list messages in the specified folder ${cmd_usage} ${cmd_option_list} SINCE can be used with epoch times, for example: md ls -s $(date '+%s') """ client = MdClient(self.maildir, filesystem=self.filesys...
[ "def", "do_ls", "(", "self", ",", "subcmd", ",", "opts", ",", "folder", "=", "\"\"", ")", ":", "client", "=", "MdClient", "(", "self", ".", "maildir", ",", "filesystem", "=", "self", ".", "filesystem", ")", "client", ".", "ls", "(", "foldername", "="...
34.222222
0.026856
def plotOutputsOverTime(vectors, buVectors=None, title='On-times'): """ Generate a figure that shows each output over time. Time goes left to right, and each output is plotted on a different line, allowing you to see the overlap in the outputs, when they turn on/off, etc. Parameters: ----------------------...
[ "def", "plotOutputsOverTime", "(", "vectors", ",", "buVectors", "=", "None", ",", "title", "=", "'On-times'", ")", ":", "# Produce the plot", "import", "pylab", "pylab", ".", "ion", "(", ")", "pylab", ".", "figure", "(", ")", "imData", "=", "vectors", ".",...
41.457143
0.009428
def taxon_table(self): """ Returns the .tests list of taxa as a pandas dataframe. By auto-generating this table from tests it means that the table itself cannot be modified unless it is returned and saved. """ if self.tests: keys = sorted(self.test...
[ "def", "taxon_table", "(", "self", ")", ":", "if", "self", ".", "tests", ":", "keys", "=", "sorted", "(", "self", ".", "tests", "[", "0", "]", ".", "keys", "(", ")", ")", "if", "isinstance", "(", "self", ".", "tests", ",", "list", ")", ":", "ld...
36.611111
0.008876
def get_inline_func(inline_str, modules=None, **stream_kwargs): """returns a function decorated by `cbox.stream` decorator. :param str inline_str: the inline function to execute, can use `s` - local variable as the input line/char/raw (according to `input_type` param). :param str modules: comma...
[ "def", "get_inline_func", "(", "inline_str", ",", "modules", "=", "None", ",", "*", "*", "stream_kwargs", ")", ":", "if", "not", "_is_compilable", "(", "inline_str", ")", ":", "raise", "ValueError", "(", "'cannot compile the inline expression - \"%s\"'", "%", "inl...
40.578947
0.001267
def _pnums_with_leading_space(self, phonetic): """Join prefixes & suffixes in cases of alternate phonetic values. Parameters ---------- phonetic : str A Beider-Morse phonetic encoding Returns ------- str A Beider-Morse phonetic code ...
[ "def", "_pnums_with_leading_space", "(", "self", ",", "phonetic", ")", ":", "alt_start", "=", "phonetic", ".", "find", "(", "'('", ")", "if", "alt_start", "==", "-", "1", ":", "return", "' '", "+", "self", ".", "_phonetic_number", "(", "phonetic", ")", "...
28.833333
0.002237
def sanitize_mimetype(mimetype, filename=None): """Sanitize a MIME type so the browser does not render the file.""" # Allow some few mime type like plain text, images and audio. if mimetype in MIMETYPE_WHITELIST: return mimetype # Rewrite HTML, JavaScript, CSS etc to text/plain. if mimetype ...
[ "def", "sanitize_mimetype", "(", "mimetype", ",", "filename", "=", "None", ")", ":", "# Allow some few mime type like plain text, images and audio.", "if", "mimetype", "in", "MIMETYPE_WHITELIST", ":", "return", "mimetype", "# Rewrite HTML, JavaScript, CSS etc to text/plain.", "...
43.909091
0.002028
def etherscan_verify_contract( chain_id: int, apikey: str, source_module: DeploymentModule, contract_name: str, ): """ Calls Etherscan API for verifying the Solidity source of a contract. Args: chain_id: EIP-155 chain id of the Ethereum chain apikey: key for call...
[ "def", "etherscan_verify_contract", "(", "chain_id", ":", "int", ",", "apikey", ":", "str", ",", "source_module", ":", "DeploymentModule", ",", "contract_name", ":", "str", ",", ")", ":", "etherscan_api", "=", "api_of_chain_id", "[", "chain_id", "]", "deployment...
37.513889
0.002165
def p_config(self, p): """config : config contents | contents """ n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = ['config', p[1]]
[ "def", "p_config", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0...
24.333333
0.008811
def _adjust_files(xs, adjust_fn): """Walk over key/value, tuples applying adjust_fn to files. """ if isinstance(xs, dict): if "path" in xs: out = {} out["path"] = adjust_fn(xs["path"]) for k, vs in xs.items(): if k != "path": ou...
[ "def", "_adjust_files", "(", "xs", ",", "adjust_fn", ")", ":", "if", "isinstance", "(", "xs", ",", "dict", ")", ":", "if", "\"path\"", "in", "xs", ":", "out", "=", "{", "}", "out", "[", "\"path\"", "]", "=", "adjust_fn", "(", "xs", "[", "\"path\"",...
31.65
0.001534
def t_STRING(self, t): r'"[^"\n]*"' t.endlexpos = t.lexpos + len(t.value) return t
[ "def", "t_STRING", "(", "self", ",", "t", ")", ":", "t", ".", "endlexpos", "=", "t", ".", "lexpos", "+", "len", "(", "t", ".", "value", ")", "return", "t" ]
25.75
0.018868
def network_delete_event(self, network_info): """Process network delete event.""" net_id = network_info['network_id'] if net_id not in self.network: LOG.error('network_delete_event: net_id %s does not exist.', net_id) return segid = self.ne...
[ "def", "network_delete_event", "(", "self", ",", "network_info", ")", ":", "net_id", "=", "network_info", "[", "'network_id'", "]", "if", "net_id", "not", "in", "self", ".", "network", ":", "LOG", ".", "error", "(", "'network_delete_event: net_id %s does not exist...
43.195122
0.001104
def message(self): """ returns the user submitted text """ try: with open(join(self.fs_path, u'message')) as message_file: return u''.join([line.decode('utf-8') for line in message_file.readlines()]) except IOError: return u''
[ "def", "message", "(", "self", ")", ":", "try", ":", "with", "open", "(", "join", "(", "self", ".", "fs_path", ",", "u'message'", ")", ")", "as", "message_file", ":", "return", "u''", ".", "join", "(", "[", "line", ".", "decode", "(", "'utf-8'", ")...
36.375
0.010067
def v_reference_choice(ctx, stmt): """Make sure that the default case exists""" d = stmt.search_one('default') if d is not None: m = stmt.search_one('mandatory') if m is not None and m.arg == 'true': err_add(ctx.errors, stmt.pos, 'DEFAULT_AND_MANDATORY', ()) ptr = attrsea...
[ "def", "v_reference_choice", "(", "ctx", ",", "stmt", ")", ":", "d", "=", "stmt", ".", "search_one", "(", "'default'", ")", "if", "d", "is", "not", "None", ":", "m", "=", "stmt", ".", "search_one", "(", "'mandatory'", ")", "if", "m", "is", "not", "...
49.482759
0.001367
def _overwrite(self, filename, func, force=False): """Overwrite a file with the specified contents. Write times are tracked, too-frequent overwrites are skipped, for performance reasons. :param filename: The path under the html dir to write to. :param func: A no-arg function that returns the contents ...
[ "def", "_overwrite", "(", "self", ",", "filename", ",", "func", ",", "force", "=", "False", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "last_overwrite_time", "=", "self", ".", "_last_overwrite_time", ".", "get", ...
49.647059
0.00814
def get_term_after(aterm): """ Returns a uw_sws.models.Term object, for the term after the term given. """ next_year = aterm.year if aterm.quarter == "autumn": next_quarter = QUARTER_SEQ[0] else: next_quarter = QUARTER_SEQ[QUARTER_SEQ.index(aterm.quarter) + 1] if next_qu...
[ "def", "get_term_after", "(", "aterm", ")", ":", "next_year", "=", "aterm", ".", "year", "if", "aterm", ".", "quarter", "==", "\"autumn\"", ":", "next_quarter", "=", "QUARTER_SEQ", "[", "0", "]", "else", ":", "next_quarter", "=", "QUARTER_SEQ", "[", "QUART...
27.533333
0.002342
def sinogram_as_radon(uSin, align=True): r"""Compute the phase from a complex wave field sinogram This step is essential when using the ray approximation before computation of the refractive index with the inverse Radon transform. Parameters ---------- uSin: 2d or 3d complex ndarray ...
[ "def", "sinogram_as_radon", "(", "uSin", ",", "align", "=", "True", ")", ":", "ndims", "=", "len", "(", "uSin", ".", "shape", ")", "if", "ndims", "==", "2", ":", "# unwrapping is very important", "phiR", "=", "np", ".", "unwrap", "(", "np", ".", "angle...
30.348837
0.000742
def sign_data(self, data, expires_in=None, url_safe=True): """ To safely sign a user data. It will be signed with the user key :param data: mixed :param expires_in: The time for it to expire :param url_safe: bool. If true it will allow it to be passed in URL :return: str ...
[ "def", "sign_data", "(", "self", ",", "data", ",", "expires_in", "=", "None", ",", "url_safe", "=", "True", ")", ":", "if", "url_safe", ":", "return", "utils", ".", "sign_url_safe", "(", "data", ",", "secret_key", "=", "self", ".", "secret_key", ",", "...
45.888889
0.002372
def __descendants(self): """Implementation for descendants, hacky workaround for __getattr__ issues. """ return itertools.chain(self.contents, *[c.descendants for c in self.children])
[ "def", "__descendants", "(", "self", ")", ":", "return", "itertools", ".", "chain", "(", "self", ".", "contents", ",", "*", "[", "c", ".", "descendants", "for", "c", "in", "self", ".", "children", "]", ")" ]
40.166667
0.00813
def create_course_completion(self, user_id, payload): """ Send a completion status payload to the SuccessFactors OCN Completion Status endpoint Args: user_id (str): The sap user id that the completion status is being sent for. payload (str): JSON encoded object (serializ...
[ "def", "create_course_completion", "(", "self", ",", "user_id", ",", "payload", ")", ":", "url", "=", "self", ".", "enterprise_configuration", ".", "sapsf_base_url", "+", "self", ".", "global_sap_config", ".", "completion_status_api_path", "return", "self", ".", "...
52.3125
0.00939
def _gitignore(root): """ Parses a .gitignore file and returns patterns to match dirs and files. Only basic gitignore patterns are supported. Pattern negation, ** wildcards and anchored patterns are not currently implemented. :param root: A unicode string of the path to the git repository ...
[ "def", "_gitignore", "(", "root", ")", ":", "gitignore_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'.gitignore'", ")", "dir_patterns", "=", "[", "'.git'", "]", "file_patterns", "=", "[", "]", "if", "not", "os", ".", "path", ".", "e...
34.891304
0.002424
def maybe_convert_dtype(data, copy): """ Convert data based on dtype conventions, issuing deprecation warnings or errors where appropriate. Parameters ---------- data : np.ndarray or pd.Index copy : bool Returns ------- data : np.ndarray or pd.Index copy : bool Raises ...
[ "def", "maybe_convert_dtype", "(", "data", ",", "copy", ")", ":", "if", "is_float_dtype", "(", "data", ")", ":", "# Note: we must cast to datetime64[ns] here in order to treat these", "# as wall-times instead of UTC timestamps.", "data", "=", "data", ".", "astype", "(", ...
33.320755
0.00055
def get_task_detail(current): """ Show task details .. code-block:: python # request: { 'view': '_zops_get_task_detail', 'key': key, } # response: { ...
[ "def", "get_task_detail", "(", "current", ")", ":", "task_inv", "=", "TaskInvitation", ".", "objects", ".", "get", "(", "current", ".", "input", "[", "'key'", "]", ")", "obj", "=", "task_inv", ".", "instance", ".", "get_object", "(", ")", "current", ".",...
31
0.001361
def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. ...
[ "def", "_register_callback", "(", "cnx", ",", "tag_prefix", ",", "obj", ",", "event", ",", "real_id", ")", ":", "libvirt_name", "=", "real_id", "if", "real_id", "is", "None", ":", "libvirt_name", "=", "'VIR_{0}_EVENT_ID_{1}'", ".", "format", "(", "obj", ",",...
37.121212
0.000796
def process(name): ''' Return whether the specified signature is found in the process tree. This differs slightly from the services states, in that it may refer to a process that is not managed via the init system. ''' # Monitoring state, no changes will be made so no test interface needed r...
[ "def", "process", "(", "name", ")", ":", "# Monitoring state, no changes will be made so no test interface needed", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", ",", "'data'"...
31
0.001203
def delete_value(hive, key, vname=None, use_32bit_registry=False): r''' Delete a registry value entry or the default value for a key. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or...
[ "def", "delete_value", "(", "hive", ",", "key", ",", "vname", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "return", "__utils__", "[", "'reg.delete_value'", "]", "(", "hive", "=", "hive", ",", "key", "=", "key", ",", "vname", "=", "v...
32.461538
0.002301
def aggregate_keywords(keywords, sep, prefix, raw=False): """ take our keyword arguments, and a separator, and compose the list of flat long (and short) arguments. example {'color': 'never', 't': True, 'something': True} with sep '=' becomes ['--color=never', '-t', '--something'] th...
[ "def", "aggregate_keywords", "(", "keywords", ",", "sep", ",", "prefix", ",", "raw", "=", "False", ")", ":", "processed", "=", "[", "]", "encode", "=", "encode_to_py3bytes_or_py2str", "for", "k", ",", "v", "in", "keywords", ".", "items", "(", ")", ":", ...
29.9375
0.000505
def set_i(self, i, data, field, side): """ Assigns data on the i'th tile to the data 'field' of the 'side' edge of that tile """ edge = self.get_i(i, side) setattr(edge, field, data[edge.slice])
[ "def", "set_i", "(", "self", ",", "i", ",", "data", ",", "field", ",", "side", ")", ":", "edge", "=", "self", ".", "get_i", "(", "i", ",", "side", ")", "setattr", "(", "edge", ",", "field", ",", "data", "[", "edge", ".", "slice", "]", ")" ]
38.166667
0.008547
def qteIsQtmacsWidget(widgetObj): """ Determine if a widget is part of Qtmacs widget hierarchy. A widget belongs to the Qtmacs hierarchy if it, or one of its parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``). Since every applet has this attribute is guaranteed that the function ...
[ "def", "qteIsQtmacsWidget", "(", "widgetObj", ")", ":", "if", "widgetObj", "is", "None", ":", "return", "False", "if", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "return", "True", "# Keep track of the already visited objects to avoid infinite loops.", ...
26.955556
0.000796
def _lucas_sequence(n, P, Q, k): """Return the modular Lucas sequence (U_k, V_k, Q_k). Given a Lucas sequence defined by P, Q, returns the kth values for U and V, along with Q^k, all modulo n. """ D = P * P - 4 * Q if n < 2: raise ValueError("n must be >= 2") if k < 0: raise ...
[ "def", "_lucas_sequence", "(", "n", ",", "P", ",", "Q", ",", "k", ")", ":", "D", "=", "P", "*", "P", "-", "4", "*", "Q", "if", "n", "<", "2", ":", "raise", "ValueError", "(", "\"n must be >= 2\"", ")", "if", "k", "<", "0", ":", "raise", "Valu...
24.820513
0.000497
def calc_qv_v1(self): """Calculate the discharge of both forelands after Manning-Strickler. Required control parameters: |EKV| |SKV| |Gef| Required flux sequence: |AV| |UV| Calculated flux sequence: |lstream_fluxes.QV| Examples: For appropriate strict...
[ "def", "calc_qv_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "for", "i", "in", "range", "(", "2", ")", ":", "if", "(", ...
24.510638
0.000835
def http_error_default(self, url, fp, errcode, errmsg, headers): """Default error handling -- don't raise an exception.""" return addinfourl(fp, headers, "http:" + url, errcode)
[ "def", "http_error_default", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ")", ":", "return", "addinfourl", "(", "fp", ",", "headers", ",", "\"http:\"", "+", "url", ",", "errcode", ")" ]
63.666667
0.010363
def set_password(url, ownerToken, password): ''' set or change the password required to download a file hosted on a send server. ''' service, fileId, key = sendclient.common.splitkeyurl(url) rawKey = sendclient.common.unpadded_urlsafe_b64decode(key) keys = sendclient.common.secretKeys(r...
[ "def", "set_password", "(", "url", ",", "ownerToken", ",", "password", ")", ":", "service", ",", "fileId", ",", "key", "=", "sendclient", ".", "common", ".", "splitkeyurl", "(", "url", ")", "rawKey", "=", "sendclient", ".", "common", ".", "unpadded_urlsafe...
40.7
0.009615
def decode (cls, bytes, cmddict): """Decodes a sequence command from an array of bytes, according to the given command dictionary, and returns a new SeqCmd. """ attrs = SeqCmdAttrs.decode(bytes[0:1]) delay = SeqDelay .decode(bytes[1:4]) cmd = cmddict .decode(bytes[4:] ) return cls(cmd...
[ "def", "decode", "(", "cls", ",", "bytes", ",", "cmddict", ")", ":", "attrs", "=", "SeqCmdAttrs", ".", "decode", "(", "bytes", "[", "0", ":", "1", "]", ")", "delay", "=", "SeqDelay", ".", "decode", "(", "bytes", "[", "1", ":", "4", "]", ")", "c...
41
0.01194
def remove(name=None, pkgs=None, **kwargs): ''' Remove the passed package(s) from the system using winrepo .. versionadded:: 0.16.0 Args: name (str): The name(s) of the package(s) to be uninstalled. Can be a single package or a comma delimited list of packages, no space...
[ "def", "remove", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "saltenv", "=", "kwargs", ".", "get", "(", "'saltenv'", ",", "'base'", ")", "refresh", "=", "salt", ".", "utils", ".", "data", ".", "is_true", ...
43.9375
0.0017
def remove_from_user(self, name, *args): """Remove attributes from a user. """ user = self.get_user(name=name) attrs_ = user['user'] for a in args: del attrs_[a]
[ "def", "remove_from_user", "(", "self", ",", "name", ",", "*", "args", ")", ":", "user", "=", "self", ".", "get_user", "(", "name", "=", "name", ")", "attrs_", "=", "user", "[", "'user'", "]", "for", "a", "in", "args", ":", "del", "attrs_", "[", ...
29.571429
0.00939
def settings(self) -> typing.Union[None, SharedCache]: """The settings associated with this project.""" return self._project.settings if self._project else None
[ "def", "settings", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "SharedCache", "]", ":", "return", "self", ".", "_project", ".", "settings", "if", "self", ".", "_project", "else", "None" ]
58
0.011364
def _readbytes(self, length, start): """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, ...
[ "def", "_readbytes", "(", "self", ",", "length", ",", "start", ")", ":", "assert", "length", "%", "8", "==", "0", "assert", "start", "+", "length", "<=", "self", ".", "len", "if", "not", "(", "start", "+", "self", ".", "_offset", ")", "%", "8", "...
56.5
0.008715
def expand(tmpl, *args, **kwargs): """Expand a path template with the given variables. ..code-block:: python >>> expand('users/*/messages/*', 'me', '123') users/me/messages/123 >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3') /v1/shelves/1/books/3 Args:...
[ "def", "expand", "(", "tmpl", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "replacer", "=", "functools", ".", "partial", "(", "_expand_variable_match", ",", "list", "(", "args", ")", ",", "kwargs", ")", "return", "_VARIABLE_RE", ".", "sub", "("...
32.2
0.001206
def append(self, value): """Append a new value to the end of the array.""" self.database.run_script( 'array_append', keys=[self.key], args=[value])
[ "def", "append", "(", "self", ",", "value", ")", ":", "self", ".", "database", ".", "run_script", "(", "'array_append'", ",", "keys", "=", "[", "self", ".", "key", "]", ",", "args", "=", "[", "value", "]", ")" ]
32.333333
0.01005
def _repr(self, *args, **kwargs): """Return a __repr__ string from the arguments provided to __init__. @param args: list of arguments to __init__ @param kwargs: dictionary of keyword arguments to __init__ @return: __repr__ string """ # Remove unnecessary empty keywords ...
[ "def", "_repr", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Remove unnecessary empty keywords arguments and sort the arguments", "kwargs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if",...
40.95
0.002387
def _backup(path, filename): """ Backup a file. """ target = os.path.join(path, filename) if os.path.isfile(target): dt = datetime.now() new_filename = ".{0}.{1}.{2}".format( filename, dt.isoformat(), "backup" ) destination = os.path.join(path, new_filenam...
[ "def", "_backup", "(", "path", ",", "filename", ")", ":", "target", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", ":", "dt", "=", "datetime", ".", "now", "(", ...
28.117647
0.002024
def create_customer(name, email, phone): """ Create a customer with the name. Then attach the email and phone as contact methods """ Party = client.model('party.party') ContactMechanism = client.model('party.contact_mechanism') party, = Party.create([{'name': name}]) # Bulk create the ...
[ "def", "create_customer", "(", "name", ",", "email", ",", "phone", ")", ":", "Party", "=", "client", ".", "model", "(", "'party.party'", ")", "ContactMechanism", "=", "client", ".", "model", "(", "'party.contact_mechanism'", ")", "party", ",", "=", "Party", ...
28.941176
0.001969
def update(self, dict_name, mapping=None, priorities=None, expire=None, locks=None): '''Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing ...
[ "def", "update", "(", "self", ",", "dict_name", ",", "mapping", "=", "None", ",", "priorities", "=", "None", ",", "expire", "=", "None", ",", "locks", "=", "None", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "Pr...
43.761364
0.002031
def forward_local( self, local_port, remote_port=None, remote_host="localhost", local_host="localhost", ): """ Open a tunnel connecting ``local_port`` to the server's environment. For example, say you want to connect to a remote PostgreSQL database ...
[ "def", "forward_local", "(", "self", ",", "local_port", ",", "remote_port", "=", "None", ",", "remote_host", "=", "\"localhost\"", ",", "local_host", "=", "\"localhost\"", ",", ")", ":", "if", "not", "remote_port", ":", "remote_port", "=", "local_port", "# Tun...
38.461538
0.000836
def residual_degrees_of_freedom(self, train=False, valid=False, xval=False): """ Retreive the residual degress of freedom if this model has the attribute, or None otherwise. :param bool train: Get the residual dof for the training set. If both train and valid are False, then train i...
[ "def", "residual_degrees_of_freedom", "(", "self", ",", "train", "=", "False", ",", "valid", "=", "False", ",", "xval", "=", "False", ")", ":", "if", "xval", ":", "raise", "H2OValueError", "(", "\"Cross-validation metrics are not available.\"", ")", "if", "not",...
54
0.011122
def calc_bca_interval(self, conf_percentage): """ Calculates Bias-Corrected and Accelerated (BCa) Bootstrap Confidence Intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the...
[ "def", "calc_bca_interval", "(", "self", ",", "conf_percentage", ")", ":", "# Get the alpha % that corresponds to the given confidence percentage.", "alpha", "=", "bc", ".", "get_alpha_from_conf_percentage", "(", "conf_percentage", ")", "# Create the column names for the dataframe ...
42.394737
0.001214
def get_session(self, token=None): ''' If provided, the `token` parameter is used to initialize an authenticated session, otherwise an unauthenticated session object is generated. Returns an instance of :attr:`session_obj`.. :param token: A token with which to initilize the sess...
[ "def", "get_session", "(", "self", ",", "token", "=", "None", ")", ":", "if", "token", "is", "not", "None", ":", "session", "=", "self", ".", "session_obj", "(", "self", ".", "client_id", ",", "self", ".", "client_secret", ",", "token", ",", "service",...
42.631579
0.002415
def _create_analysis_wizard_action(self): """Create action for IF-centric wizard.""" icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('Impact Function Centric Wizard'), self.iface.main...
[ "def", "_create_analysis_wizard_action", "(", "self", ")", ":", "icon", "=", "resources_path", "(", "'img'", ",", "'icons'", ",", "'show-wizard.svg'", ")", "self", ".", "action_function_centric_wizard", "=", "QAction", "(", "QIcon", "(", "icon", ")", ",", "self"...
53.266667
0.00246
def update(verbose=False): """ Update local dictionnaries by downloading the latest version from the server, if there's one. """ local = local_list() remote = dict(remote_list()) updated = False for name, date in local: if name in remote and remote[name] > date: upd...
[ "def", "update", "(", "verbose", "=", "False", ")", ":", "local", "=", "local_list", "(", ")", "remote", "=", "dict", "(", "remote_list", "(", ")", ")", "updated", "=", "False", "for", "name", ",", "date", "in", "local", ":", "if", "name", "in", "r...
25.368421
0.002
def _travis_job_state(state): """ Converts a Travis state into a state character, color, and whether it's still running or a stopped state. """ if state in [None, 'queued', 'created', 'received']: return colorama.Fore.YELLOW, '*', True elif state in ['started', 'running']: return coloram...
[ "def", "_travis_job_state", "(", "state", ")", ":", "if", "state", "in", "[", "None", ",", "'queued'", ",", "'created'", ",", "'received'", "]", ":", "return", "colorama", ".", "Fore", ".", "YELLOW", ",", "'*'", ",", "True", "elif", "state", "in", "[",...
43.411765
0.001326
def as_url(self): ''' Reverse object converted to `web.URL`. If Reverse is bound to env: * try to build relative URL, * use current domain name, port and scheme as default ''' if '' in self._scope: return self._finalize().as_url if no...
[ "def", "as_url", "(", "self", ")", ":", "if", "''", "in", "self", ".", "_scope", ":", "return", "self", ".", "_finalize", "(", ")", ".", "as_url", "if", "not", "self", ".", "_is_endpoint", ":", "raise", "UrlBuildingError", "(", "'Not an endpoint {}'", "....
39.22449
0.00203
def add_offset(dateobj, hr_offset: str, sign: str): """add a human readable offset to `dateobj` and return corresponding date. rely on `pandas.Timedelta` and add the following extra shortcuts: - "w", "week" and "weeks" for a week (i.e. 7days) - "month', "months" for a month (i.e. no day computation, ju...
[ "def", "add_offset", "(", "dateobj", ",", "hr_offset", ":", "str", ",", "sign", ":", "str", ")", ":", "sign_coeff", "=", "1", "if", "sign", "==", "'+'", "else", "-", "1", "try", ":", "return", "dateobj", "+", "sign_coeff", "*", "pd", ".", "Timedelta"...
42.37931
0.002387
def _validate_num_channels(input_filepath_list, combine_type): ''' Check if files in input file list have the same number of channels ''' channels = [ file_info.channels(f) for f in input_filepath_list ] if not core.all_equal(channels): raise IOError( "Input files do not ...
[ "def", "_validate_num_channels", "(", "input_filepath_list", ",", "combine_type", ")", ":", "channels", "=", "[", "file_info", ".", "channels", "(", "f", ")", "for", "f", "in", "input_filepath_list", "]", "if", "not", "core", ".", "all_equal", "(", "channels",...
37.923077
0.00198
def match(self, query): """Try to find a match for a query in the channel commands. """ if not self.can_select: ch_id = self._device._properties['selected_channel'].get_value() if ch_id in self._ids: self._selected = ch_id else: ...
[ "def", "match", "(", "self", ",", "query", ")", ":", "if", "not", "self", ".", "can_select", ":", "ch_id", "=", "self", ".", "_device", ".", "_properties", "[", "'selected_channel'", "]", ".", "get_value", "(", ")", "if", "ch_id", "in", "self", ".", ...
33.722222
0.001601
def boolparser(true_strings=('true', 't', 'yes', 'y', '1'), false_strings=('false', 'f', 'no', 'n', '0'), case_sensitive=False, strict=True): """Return a function to parse strings as :class:`bool` objects using a given set of string representations for `True` and `Fa...
[ "def", "boolparser", "(", "true_strings", "=", "(", "'true'", ",", "'t'", ",", "'yes'", ",", "'y'", ",", "'1'", ")", ",", "false_strings", "=", "(", "'false'", ",", "'f'", ",", "'no'", ",", "'n'", ",", "'0'", ")", ",", "case_sensitive", "=", "False",...
30.685185
0.00117
def parse(timeseries_expression, method=None, functions=None, debug=False): '''Function for parsing :ref:`timeseries expressions <dsl-script>`. If succesful, it returns an instance of :class:`dynts.dsl.Expr` which can be used to to populate timeseries or scatters once data is available. Parsing is...
[ "def", "parse", "(", "timeseries_expression", ",", "method", "=", "None", ",", "functions", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "not", "parsefunc", ":", "raise", "ExpressionError", "(", "'Could not parse. No parser installed.'", ")", "functi...
44.923077
0.000838
def find_exe(name, filepath=None): """Find an executable. Args: name: Name of the program, eg 'python'. filepath: Path to executable, a search is performed if None. Returns: Path to the executable if found, otherwise an error is raised. """ if filepath: if not os.pa...
[ "def", "find_exe", "(", "name", ",", "filepath", "=", "None", ")", ":", "if", "filepath", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "open", "(", "filepath", ")", "# raise IOError", "elif", "not", "os", ".", "path"...
29.761905
0.00155
def tparse(instring, lenout=_default_len_out): """ Parse a time string and return seconds past the J2000 epoch on a formal calendar. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html :param instring: Input time string, UTC. :type instring: str :param lenout: Available s...
[ "def", "tparse", "(", "instring", ",", "lenout", "=", "_default_len_out", ")", ":", "errmsg", "=", "stypes", ".", "stringToCharP", "(", "lenout", ")", "lenout", "=", "ctypes", ".", "c_int", "(", "lenout", ")", "instring", "=", "stypes", ".", "stringToCharP...
36.9
0.001321
def bundle_of_tubes(shape: List[int], spacing: int): r""" Create a 3D image of a bundle of tubes, in the form of a rectangular plate with randomly sized holes through it. Parameters ---------- shape : list The size the image, with the 3rd dimension indicating the plate thickness...
[ "def", "bundle_of_tubes", "(", "shape", ":", "List", "[", "int", "]", ",", "spacing", ":", "int", ")", ":", "shape", "=", "sp", ".", "array", "(", "shape", ")", "if", "sp", ".", "size", "(", "shape", ")", "==", "1", ":", "shape", "=", "sp", "."...
36.083333
0.000562
def sync(config, group, accounts=(), dryrun=False, region=None): """sync last recorded export to actual Use --dryrun to check status. """ config = validate.callback(config) destination = config.get('destination') client = boto3.Session().client('s3') for account in config.get('accounts', (...
[ "def", "sync", "(", "config", ",", "group", ",", "accounts", "=", "(", ")", ",", "dryrun", "=", "False", ",", "region", "=", "None", ")", ":", "config", "=", "validate", ".", "callback", "(", "config", ")", "destination", "=", "config", ".", "get", ...
34.488636
0.000961
def not_send_status(func): """ Do not send process status package back to scheduler. It's used by callbacks like on_message, on_result etc... """ @functools.wraps(func) def wrapper(self, response, task): self._extinfo['not_send_status'] = True function = func.__get__(self, self....
[ "def", "not_send_status", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "response", ",", "task", ")", ":", "self", ".", "_extinfo", "[", "'not_send_status'", "]", "=", "True", "function", "...
32.833333
0.002469
def lookup(self, label): ''' take a field_name_label and return the id''' if self.is_child: try: return self._children[label] except KeyError: self._children[label] = ChildFieldPicklist(self.parent, ...
[ "def", "lookup", "(", "self", ",", "label", ")", ":", "if", "self", ".", "is_child", ":", "try", ":", "return", "self", ".", "_children", "[", "label", "]", "except", "KeyError", ":", "self", ".", "_children", "[", "label", "]", "=", "ChildFieldPicklis...
43.416667
0.009398
def toroidal(target, mode='max', r_toroid=5e-6, target_Pc=None, num_points=1e2, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', throat_diameter='throat.diameter', touch_length='throat.touc...
[ "def", "toroidal", "(", "target", ",", "mode", "=", "'max'", ",", "r_toroid", "=", "5e-6", ",", "target_Pc", "=", "None", ",", "num_points", "=", "1e2", ",", "surface_tension", "=", "'pore.surface_tension'", ",", "contact_angle", "=", "'pore.contact_angle'", "...
42.091954
0.000133
def _invert(self, tempdir, catch_output=True, **kwargs): """Internal function than runs an inversion using CRTomo. Parameters ---------- tempdir : string directory which to use as a tomodir catch_output : bool, optional if True, catch all outputs of the C...
[ "def", "_invert", "(", "self", ",", "tempdir", ",", "catch_output", "=", "True", ",", "*", "*", "kwargs", ")", ":", "nr_cores", "=", "kwargs", ".", "get", "(", "'cores'", ",", "2", ")", "print", "(", "'attempting inversion in directory: {0}'", ".", "format...
31.255814
0.001443
def chunk(self, lenient=False): """ Read the next PNG chunk from the input file; returns a (*type*, *data*) tuple. *type* is the chunk's type as a byte string (all PNG chunk types are 4 bytes long). *data* is the chunk's data content, as a byte string. If the opt...
[ "def", "chunk", "(", "self", ",", "lenient", "=", "False", ")", ":", "self", ".", "validate_signature", "(", ")", "# http://www.w3.org/TR/PNG/#5Chunk-layout", "if", "not", "self", ".", "atchunk", ":", "self", ".", "atchunk", "=", "self", ".", "_chunk_len_type"...
38.408163
0.001036
def build_native_type_dictionary(fields, respect_required=False, wrap_field=True, name=''): """ This function takes a list of type summaries and builds a dictionary with native representations of each entry. Useful for dynamically building native class records from summaries. """ # a...
[ "def", "build_native_type_dictionary", "(", "fields", ",", "respect_required", "=", "False", ",", "wrap_field", "=", "True", ",", "name", "=", "''", ")", ":", "# a place to start when building the input field attributes", "input_fields", "=", "{", "}", "# go over every ...
37.209302
0.002436
def use_defaults(self, data): """ Combine data with defaults and set aesthetics from parameters geoms should not override this method. Parameters ---------- data : dataframe Data used for drawing the geom. Returns ------- out : dataf...
[ "def", "use_defaults", "(", "self", ",", "data", ")", ":", "missing_aes", "=", "(", "self", ".", "DEFAULT_AES", ".", "keys", "(", ")", "-", "self", ".", "aes_params", ".", "keys", "(", ")", "-", "set", "(", "data", ".", "columns", ")", ")", "# Not ...
30.410256
0.001634
def _neuron_states(self, inputs, t, argv): """! @brief Returns new value of the neuron (oscillator). @param[in] inputs (list): Initial values (current) of the neuron - excitatory. @param[in] t (double): Current time of simulation. @param[in] argv (tuple): Extra arg...
[ "def", "_neuron_states", "(", "self", ",", "inputs", ",", "t", ",", "argv", ")", ":", "xi", "=", "inputs", "[", "0", "]", "index", "=", "argv", "# own impact\r", "impact", "=", "self", ".", "_weight", "[", "index", "]", "[", "index", "]", "*", "sel...
34.357143
0.023256
def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a PUT request to url with optional authentication """ res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) return ...
[ "def", "rest_put", "(", "self", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "auth", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ")", ":", "res", "=", "requests", ".", "put", "(", "url", ",", ...
48.428571
0.011594
def randstring(length=1): """ Generate a random string consisting of letters, digits and punctuation :type length: integer :param length: The length of the generated string. """ charstouse = string.ascii_letters + string.digits + string.punctuation newpass = '' for _ in range(length): ...
[ "def", "randstring", "(", "length", "=", "1", ")", ":", "charstouse", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "string", ".", "punctuation", "newpass", "=", "''", "for", "_", "in", "range", "(", "length", ")", ":", "newpa...
33.416667
0.002427
def cummedian(expr, sort=None, ascending=True, unique=False, preceding=None, following=None): """ Calculate cumulative median of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order ...
[ "def", "cummedian", "(", "expr", ",", "sort", "=", "None", ",", "ascending", "=", "True", ",", "unique", "=", "False", ",", "preceding", "=", "None", ",", "following", "=", "None", ")", ":", "data_type", "=", "_stats_type", "(", "expr", ")", "return", ...
43.176471
0.001333
def fold_string(input_string, max_width): """ Fold a string within a maximum width. Parameters: input_string: The string of data to go into the cell max_width: Maximum width of cell. Data is folded into multiple lines to fit into this width. Return: ...
[ "def", "fold_string", "(", "input_string", ",", "max_width", ")", ":", "new_string", "=", "input_string", "if", "isinstance", "(", "input_string", ",", "six", ".", "string_types", ")", ":", "if", "max_width", "<", "len", "(", "input_string", ")", ":", "# use...
27.727273
0.001585
def getDataPath(_system=thisSystem, _FilePath=FilePath): """Gets an appropriate path for storing some local data, such as TLS credentials. If the path doesn't exist, it is created. """ if _system == "Windows": pathName = "~/Crypto101/" else: pathName = "~/.crypto101/" path...
[ "def", "getDataPath", "(", "_system", "=", "thisSystem", ",", "_FilePath", "=", "FilePath", ")", ":", "if", "_system", "==", "\"Windows\"", ":", "pathName", "=", "\"~/Crypto101/\"", "else", ":", "pathName", "=", "\"~/.crypto101/\"", "path", "=", "_FilePath", "...
23.823529
0.002375
def parse_validated_field(fld, selectable): """ Converts a validated field to sqlalchemy. Field references are looked up in selectable """ aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']] field = find_column(selectable, fld['value']) for operator in fld.get('operators', []): ...
[ "def", "parse_validated_field", "(", "fld", ",", "selectable", ")", ":", "aggr_fn", "=", "IngredientValidator", ".", "aggregation_lookup", "[", "fld", "[", "'aggregation'", "]", "]", "field", "=", "find_column", "(", "selectable", ",", "fld", "[", "'value'", "...
36.473684
0.001406
def _write_vmx_file(self): """ Writes pairs to the VMware VMX file corresponding to this VM. """ try: self.manager.write_vmx_file(self._vmx_path, self._vmx_pairs) except OSError as e: raise VMwareError('Could not write VMware VMX file "{}": {}'.format(sel...
[ "def", "_write_vmx_file", "(", "self", ")", ":", "try", ":", "self", ".", "manager", ".", "write_vmx_file", "(", "self", ".", "_vmx_path", ",", "self", ".", "_vmx_pairs", ")", "except", "OSError", "as", "e", ":", "raise", "VMwareError", "(", "'Could not wr...
36.444444
0.008929
def tag_instance(instance_id, **tags): """Tag a single ec2 instance.""" logger.debug("Got request to add tags %s to instance %s." % (str(tags), instance_id)) ec2 = boto3.resource('ec2') instance = ec2.Instance(instance_id) # Remove None's from `tags` filtered_tags = {k: v for k...
[ "def", "tag_instance", "(", "instance_id", ",", "*", "*", "tags", ")", ":", "logger", ".", "debug", "(", "\"Got request to add tags %s to instance %s.\"", "%", "(", "str", "(", "tags", ")", ",", "instance_id", ")", ")", "ec2", "=", "boto3", ".", "resource", ...
38.407407
0.000941
def do_bm(self, arg): """ [~process] bm <address-address> - set memory breakpoint """ pid = self.get_process_id_from_prefix() if not self.debug.is_debugee(pid): raise CmdError("target process is not being debugged") process = self.get_process(pid) ...
[ "def", "do_bm", "(", "self", ",", "arg", ")", ":", "pid", "=", "self", ".", "get_process_id_from_prefix", "(", ")", "if", "not", "self", ".", "debug", ".", "is_debugee", "(", "pid", ")", ":", "raise", "CmdError", "(", "\"target process is not being debugged\...
43.363636
0.008214
def parseImpl(self, instring, loc, *args, **kwargs): """Wrapper around ParseElementEnhance.parseImpl.""" with self.wrapper(self, instring, loc): return super(Wrap, self).parseImpl(instring, loc, *args, **kwargs)
[ "def", "parseImpl", "(", "self", ",", "instring", ",", "loc", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "wrapper", "(", "self", ",", "instring", ",", "loc", ")", ":", "return", "super", "(", "Wrap", ",", "self", ")...
59
0.008368
def filter_(predicate, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc, too-many-branches """Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to correspo...
[ "def", "filter_", "(", "predicate", ",", "*", "structures", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=differing-param-doc,missing-param-doc, too-many-branches", "# Named keyword arguments are not allowed after *args in Python 2.", "flatten", "=", "kwargs", ".", "pop...
43.676923
0.009301
def register(self, app, route, endpoint=None): # type: (Flask, str, str) -> None """Method to register the routing on the app at provided route. This is a utility method, that can be used for registering the ``dispatch_request`` on the provided :py:class:`flask.Flask` applicatio...
[ "def", "register", "(", "self", ",", "app", ",", "route", ",", "endpoint", "=", "None", ")", ":", "# type: (Flask, str, str) -> None", "if", "app", "is", "None", "or", "not", "isinstance", "(", "app", ",", "Flask", ")", ":", "raise", "TypeError", "(", "\...
42.206897
0.002396
def eval(thunk, env): """Evaluate a thunk in an environment. Will defer the actual evaluation to the thunk itself, but adds two things: caching and recursion detection. Since we have to use a global evaluation stack (because there is a variety of functions that may be invoked, not just eval() but also __get...
[ "def", "eval", "(", "thunk", ",", "env", ")", ":", "key", "=", "Activation", ".", "key", "(", "thunk", ",", "env", ")", "if", "Activation", ".", "activated", "(", "key", ")", ":", "raise", "exceptions", ".", "RecursionError", "(", "'Reference cycle'", ...
44.461538
0.010161
def _handle_minion_event(self, load): ''' Act on specific events from minions ''' id_ = load['id'] if load.get('tag', '') == '_salt_error': log.error( 'Received minion error from [%s]: %s', id_, load['data']['message'] ) ...
[ "def", "_handle_minion_event", "(", "self", ",", "load", ")", ":", "id_", "=", "load", "[", "'id'", "]", "if", "load", ".", "get", "(", "'tag'", ",", "''", ")", "==", "'_salt_error'", ":", "log", ".", "error", "(", "'Received minion error from [%s]: %s'", ...
35.333333
0.001837
def finish_displayhook(self): """Finish up all displayhook activities.""" io.stdout.write(self.shell.separate_out2) io.stdout.flush()
[ "def", "finish_displayhook", "(", "self", ")", ":", "io", ".", "stdout", ".", "write", "(", "self", ".", "shell", ".", "separate_out2", ")", "io", ".", "stdout", ".", "flush", "(", ")" ]
38.5
0.012739
def avail_images(call=None): ''' Return a dict of all available VM images on the cloud provider. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = ...
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_images function must be called with '", "'-f or --function, or with the --list-images option'", ")", "ret", "=", "{", "}", "c...
33.5
0.001451
def do_alarm_history(mc, args): '''Alarm state transition history.''' fields = {} fields['alarm_id'] = args.id if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history(**fields) except (osc_exc.ClientExc...
[ "def", "do_alarm_history", "(", "mc", ",", "args", ")", ":", "fields", "=", "{", "}", "fields", "[", "'alarm_id'", "]", "=", "args", ".", "id", "if", "args", ".", "limit", ":", "fields", "[", "'limit'", "]", "=", "args", ".", "limit", "if", "args",...
33
0.002105
def get_stats_of_series_in_dir(self, study_id=None): """ Dicom series staticstics, input is dcmdir, not dirpath Information is generated from dicomdir.pkl and first files of series """ if study_id is not None: logger.error("study_id tag is not implemented yet") re...
[ "def", "get_stats_of_series_in_dir", "(", "self", ",", "study_id", "=", "None", ")", ":", "if", "study_id", "is", "not", "None", ":", "logger", ".", "error", "(", "\"study_id tag is not implemented yet\"", ")", "return", "import", "numpy", "as", "np", "dcmdir", ...
36.878049
0.001933
def add_check(self, check_item): """Adds a check universally.""" self.checks.append(check_item) for other in self.others: other.add_check(check_item)
[ "def", "add_check", "(", "self", ",", "check_item", ")", ":", "self", ".", "checks", ".", "append", "(", "check_item", ")", "for", "other", "in", "self", ".", "others", ":", "other", ".", "add_check", "(", "check_item", ")" ]
36.2
0.010811
def lazyread(f, delimiter): """ Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the contents of ``f`` without loading the entire file into memory. :param f: Any file-like object which has a ``.read()`` method. :param ...
[ "def", "lazyread", "(", "f", ",", "delimiter", ")", ":", "# Get an empty string to start with. We need to make sure that if the", "# file is opened in binary mode, we're using byte strings, and similar", "# for Unicode. Otherwise trying to update the running string will", "# hit a TypeError....
35.333333
0.000656
def _is_second_run(): """Returns `True` when we know that `fuck` called second time.""" tracker_path = _get_not_configured_usage_tracker_path() if not tracker_path.exists(): return False current_pid = _get_shell_pid() with tracker_path.open('r') as tracker: try: info = j...
[ "def", "_is_second_run", "(", ")", ":", "tracker_path", "=", "_get_not_configured_usage_tracker_path", "(", ")", "if", "not", "tracker_path", ".", "exists", "(", ")", ":", "return", "False", "current_pid", "=", "_get_shell_pid", "(", ")", "with", "tracker_path", ...
32.944444
0.001639
def add_configuration(self, configuration, collect_another_source, done, result, src): """Used to add a file to the configuration, result here is the yaml.load of the src""" if "includes" in result: for include in result["includes"]: collect_another_source(include) co...
[ "def", "add_configuration", "(", "self", ",", "configuration", ",", "collect_another_source", ",", "done", ",", "result", ",", "src", ")", ":", "if", "\"includes\"", "in", "result", ":", "for", "include", "in", "result", "[", "\"includes\"", "]", ":", "colle...
58.833333
0.011173
def plot_pipeline(self, pipeline, *args, **kwargs): ''' Plots the light curve for the target de-trended with a given pipeline. :param str pipeline: The name of the pipeline (lowercase). Options \ are 'everest2', 'everest1', and other mission-specific \ pipelines. F...
[ "def", "plot_pipeline", "(", "self", ",", "pipeline", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "pipeline", "!=", "'everest2'", ":", "return", "getattr", "(", "missions", ",", "self", ".", "mission", ")", ".", "pipelines", ".", "plot",...
36.355263
0.000705
def inspect_build(self, module, modname=None, path=None): """build astroid from a living module (i.e. using inspect) this is used when there is no python source code available (either because it's a built-in module or because the .py is not available) """ self._module = module ...
[ "def", "inspect_build", "(", "self", ",", "module", ",", "modname", "=", "None", ",", "path", "=", "None", ")", ":", "self", ".", "_module", "=", "module", "if", "modname", "is", "None", ":", "modname", "=", "module", ".", "__name__", "try", ":", "no...
42.2
0.002317
def duration(self): """The duration of this stimulus :returns: float -- duration in seconds """ durs = [] for track in self._segments: durs.append(sum([comp.duration() for comp in track])) return max(durs)
[ "def", "duration", "(", "self", ")", ":", "durs", "=", "[", "]", "for", "track", "in", "self", ".", "_segments", ":", "durs", ".", "append", "(", "sum", "(", "[", "comp", ".", "duration", "(", ")", "for", "comp", "in", "track", "]", ")", ")", "...
27
0.010753
def _validate_params(priors, means, covars): """ Validation Check for M.L. paramateres """ for i,(p,m,cv) in enumerate(zip(priors, means, covars)): if np.any(np.isinf(p)) or np.any(np.isnan(p)): raise ValueError("Component %d of priors is not valid " % i) if np.any(np.isinf(m))...
[ "def", "_validate_params", "(", "priors", ",", "means", ",", "covars", ")", ":", "for", "i", ",", "(", "p", ",", "m", ",", "cv", ")", "in", "enumerate", "(", "zip", "(", "priors", ",", "means", ",", "covars", ")", ")", ":", "if", "np", ".", "an...
43.75
0.008392
def create_groups(self, *names, **kwargs): """Convenience method to create multiple groups in a single call.""" return tuple(self.create_group(name, **kwargs) for name in names)
[ "def", "create_groups", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "return", "tuple", "(", "self", ".", "create_group", "(", "name", ",", "*", "*", "kwargs", ")", "for", "name", "in", "names", ")" ]
63.666667
0.010363
def lookup(self, h): '''Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a ...
[ "def", "lookup", "(", "self", ",", "h", ")", ":", "for", "(", "_", ",", "k1", ",", "k2", ")", "in", "self", ".", "client", ".", "scan_keys", "(", "HASH_TF_INDEX_TABLE", ",", "(", "(", "h", ",", ")", ",", "(", "h", ",", ")", ")", ")", ":", "...
42.76
0.00183
def combine_proximals(*factory_list): r"""Combine proximal operators into a diagonal product space operator. This assumes the functional to be separable across variables in order to make use of the separable sum property of proximal operators. Parameters ---------- factory_list : sequence of c...
[ "def", "combine_proximals", "(", "*", "factory_list", ")", ":", "def", "diag_op_factory", "(", "sigma", ")", ":", "\"\"\"Diagonal matrix of operators.\n\n Parameters\n ----------\n sigma : positive float or sequence of positive floats\n Step size parameter(s...
31.083333
0.00065
def create_refund(self, refund_deets): """Creates a new refund transaction.""" request = self._post('transactions/refunds', refund_deets) return self.responder(request)
[ "def", "create_refund", "(", "self", ",", "refund_deets", ")", ":", "request", "=", "self", ".", "_post", "(", "'transactions/refunds'", ",", "refund_deets", ")", "return", "self", ".", "responder", "(", "request", ")" ]
47.25
0.010417
def _get_options(ret=None): ''' Get the redis options from salt. ''' attrs = {'host': 'host', 'port': 'port', 'unix_socket_path': 'unix_socket_path', 'db': 'db', 'password': 'password', 'cluster_mode': 'cluster_mode', 'startup...
[ "def", "_get_options", "(", "ret", "=", "None", ")", ":", "attrs", "=", "{", "'host'", ":", "'host'", ",", "'port'", ":", "'port'", ",", "'unix_socket_path'", ":", "'unix_socket_path'", ",", "'db'", ":", "'db'", ",", "'password'", ":", "'password'", ",", ...
42.875
0.001426
def make_docs(*args, **kwargs): """Make the documents for a `Request` or `Reply`. Takes a variety of argument styles, returns a list of dicts. Used by `make_prototype_request` and `make_reply`, which are in turn used by `MockupDB.receives`, `Request.replies`, and so on. See examples in tutorial. ...
[ "def", "make_docs", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "err_msg", "=", "\"Can't interpret args: \"", "if", "not", "args", "and", "not", "kwargs", ":", "return", "[", "]", "if", "not", "args", ":", "# OpReply(ok=1, ismaster=True).", "return"...
31.581818
0.001117