text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _collapse_addresses_internal(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse...
[ "def", "_collapse_addresses_internal", "(", "addresses", ")", ":", "# First merge", "to_merge", "=", "list", "(", "addresses", ")", "subnets", "=", "{", "}", "while", "to_merge", ":", "net", "=", "to_merge", ".", "pop", "(", ")", "supernet", "=", "net", "....
30.297872
0.00068
def get_ports_alert(self, port, header="", log=False): """Return the alert status relative to the port scan return value.""" ret = 'OK' if port['status'] is None: ret = 'CAREFUL' elif port['status'] == 0: ret = 'CRITICAL' elif (isinstance(port['status'], (...
[ "def", "get_ports_alert", "(", "self", ",", "port", ",", "header", "=", "\"\"", ",", "log", "=", "False", ")", ":", "ret", "=", "'OK'", "if", "port", "[", "'status'", "]", "is", "None", ":", "ret", "=", "'CAREFUL'", "elif", "port", "[", "'status'", ...
32.12
0.002418
def sigma(self): """ Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}` """ return _np.power(2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, 2)) , 0.25) * _np.sqrt(self.emit)
[ "def", "sigma", "(", "self", ")", ":", "return", "_np", ".", "power", "(", "2", "*", "_sltr", ".", "GeV2joule", "(", "self", ".", "E", ")", "*", "_spc", ".", "epsilon_0", "/", "(", "self", ".", "plasma", ".", "n_p", "*", "_np", ".", "power", "(...
62.6
0.015773
def main(args=sys.argv[1:]): '''Processes command line arguments and file i/o''' if not args: sys.stderr.write(_usage() + '\n') sys.exit(4) else: parsed = _parse_args(args) # Set delim based on whether or not regex is desired by user delim = parsed.delimiter if parsed.regex ...
[ "def", "main", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "if", "not", "args", ":", "sys", ".", "stderr", ".", "write", "(", "_usage", "(", ")", "+", "'\\n'", ")", "sys", ".", "exit", "(", "4", ")", "else", ":", "pa...
33.15873
0.00093
def set_block(arr, arr_block): """ Sets the diagonal blocks of an array to an given array Parameters ---------- arr : numpy ndarray the original array block_arr : numpy ndarray the block array for the new diagonal Returns ------- numpy ndarray (the modified array) ...
[ "def", "set_block", "(", "arr", ",", "arr_block", ")", ":", "nr_col", "=", "arr", ".", "shape", "[", "1", "]", "nr_row", "=", "arr", ".", "shape", "[", "0", "]", "nr_col_block", "=", "arr_block", ".", "shape", "[", "1", "]", "nr_row_block", "=", "a...
29.307692
0.000847
def getInstrumentsDisplayList(self): """Instruments capable to perform this method """ items = [(i.UID(), i.Title()) for i in self.getInstruments()] return DisplayList(list(items))
[ "def", "getInstrumentsDisplayList", "(", "self", ")", ":", "items", "=", "[", "(", "i", ".", "UID", "(", ")", ",", "i", ".", "Title", "(", ")", ")", "for", "i", "in", "self", ".", "getInstruments", "(", ")", "]", "return", "DisplayList", "(", "list...
41.6
0.009434
def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''record the topic data to the file ''' class TopicRecorder(object): def __init__(self, file_path, topic_names): self._topic_names = topic_names self._file_path = file_path...
[ "def", "record", "(", "file_path", ",", "topic_names", "=", "[", "]", ",", "host", "=", "jps", ".", "env", ".", "get_master_host", "(", ")", ",", "sub_port", "=", "jps", ".", "DEFAULT_SUB_PORT", ")", ":", "class", "TopicRecorder", "(", "object", ")", "...
39.113636
0.001134
def add_cable_distributor(self, cable_dist): """Adds a cable distributor to _cable_distributors if not already existing Args ---- cable_dist : float Desription #TODO """ if cable_dist not in self.cable_distributors() and isinstance(cable_dist, ...
[ "def", "add_cable_distributor", "(", "self", ",", "cable_dist", ")", ":", "if", "cable_dist", "not", "in", "self", ".", "cable_distributors", "(", ")", "and", "isinstance", "(", "cable_dist", ",", "MVCableDistributorDing0", ")", ":", "# add to array and graph", "s...
41
0.011009
def create_cells(self, blocks): """Turn the list of blocks into a list of notebook cells.""" cells = [] for block in blocks: if (block['type'] == self.code) and (block['IO'] == 'input'): code_cell = self.create_code_cell(block) cells.append(code_cell) ...
[ "def", "create_cells", "(", "self", ",", "blocks", ")", ":", "cells", "=", "[", "]", "for", "block", "in", "blocks", ":", "if", "(", "block", "[", "'type'", "]", "==", "self", ".", "code", ")", "and", "(", "block", "[", "'IO'", "]", "==", "'input...
38.772727
0.002288
def make_processitem_username(username, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/Username :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/Username' content_type = 'string' c...
[ "def", "make_processitem_username", "(", "username", ",", "condition", "=", "'contains'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'ProcessItem'", "search", "=", "'ProcessItem/Username'", "content_type", "=", "'s...
40.923077
0.009191
def fqn(self): ''' Returns a fully qualified name for this object ''' prefix = type(self).cls_key() return '{}:{}'.format(prefix, self.id)
[ "def", "fqn", "(", "self", ")", ":", "prefix", "=", "type", "(", "self", ")", ".", "cls_key", "(", ")", "return", "'{}:{}'", ".", "format", "(", "prefix", ",", "self", ".", "id", ")" ]
31.8
0.01227
def molecular_diameter(Tc=None, Pc=None, Vc=None, Zc=None, omega=None, Vm=None, Vb=None, CASRN='', AvailableMethods=False, Method=None): r'''This function handles the retrieval or calculation a chemical's L-J molecular diameter. Values are available from one source with lookup based on CASRNs, or ...
[ "def", "molecular_diameter", "(", "Tc", "=", "None", ",", "Pc", "=", "None", ",", "Vc", "=", "None", ",", "Zc", "=", "None", ",", "omega", "=", "None", ",", "Vm", "=", "None", ",", "Vb", "=", "None", ",", "CASRN", "=", "''", ",", "AvailableMethod...
35.024194
0.000448
async def load(self, file_path, locale=None, flags=None): """ Start the loading/watching process """ await self.start(file_path, locale, {'flags': flags})
[ "async", "def", "load", "(", "self", ",", "file_path", ",", "locale", "=", "None", ",", "flags", "=", "None", ")", ":", "await", "self", ".", "start", "(", "file_path", ",", "locale", ",", "{", "'flags'", ":", "flags", "}", ")" ]
30.333333
0.010695
def _fetch_router_info(self, router_ids=None, device_ids=None, all_routers=False): """Fetch router dict from the routing plugin. :param router_ids: List of router_ids of routers to fetch :param device_ids: List of device_ids whose routers to fetch :param all_r...
[ "def", "_fetch_router_info", "(", "self", ",", "router_ids", "=", "None", ",", "device_ids", "=", "None", ",", "all_routers", "=", "False", ")", ":", "try", ":", "if", "all_routers", ":", "LOG", ".", "debug", "(", "'Fetching all routers'", ")", "router_ids",...
48.62
0.00121
def gradients_X(self, dL_dK, X, X2, target): """Derivative of the covariance matrix with respect to X""" self._K_computations(X, X2) arg = self._K_poly_arg if X2 is None: target += 2*self.weight_variance*self.degree*self.variance*(((X[None,:, :])) *(arg**(self.degree-1))[:, :...
[ "def", "gradients_X", "(", "self", ",", "dL_dK", ",", "X", ",", "X2", ",", "target", ")", ":", "self", ".", "_K_computations", "(", "X", ",", "X2", ")", "arg", "=", "self", ".", "_K_poly_arg", "if", "X2", "is", "None", ":", "target", "+=", "2", "...
63.75
0.015474
def request_io(self, iocb): """Called by a client to start processing a request.""" if _debug: IOQController._debug("request_io %r", iocb) # bind the iocb to this controller iocb.ioController = self # if we're busy, queue it if (self.state != CTRL_IDLE): if ...
[ "def", "request_io", "(", "self", ",", "iocb", ")", ":", "if", "_debug", ":", "IOQController", ".", "_debug", "(", "\"request_io %r\"", ",", "iocb", ")", "# bind the iocb to this controller", "iocb", ".", "ioController", "=", "self", "# if we're busy, queue it", "...
33.1
0.008806
def _combine(self, x, y): """Combines two constraints, raising an error if they are not compatible.""" if x is None or y is None: return x or y if x != y: raise ValueError('Incompatible set of constraints provided.') return x
[ "def", "_combine", "(", "self", ",", "x", ",", "y", ")", ":", "if", "x", "is", "None", "or", "y", "is", "None", ":", "return", "x", "or", "y", "if", "x", "!=", "y", ":", "raise", "ValueError", "(", "'Incompatible set of constraints provided.'", ")", ...
35.285714
0.01581
def prep_pdf(qc_dir, config): """Create PDF from HTML summary outputs in QC directory. Requires wkhtmltopdf installed: http://www.msweet.org/projects.php?Z1 Thanks to: https://www.biostars.org/p/16991/ Works around issues with CSS conversion on CentOS by adjusting CSS. """ html_file = os.path....
[ "def", "prep_pdf", "(", "qc_dir", ",", "config", ")", ":", "html_file", "=", "os", ".", "path", ".", "join", "(", "qc_dir", ",", "\"fastqc\"", ",", "\"fastqc_report.html\"", ")", "html_fixed", "=", "\"%s-fixed%s\"", "%", "os", ".", "path", ".", "splitext",...
44.608696
0.001908
def delete(self): 'Delete this file and return the new, deleted JFSFile' #url = '%s?dl=true' % self.path r = self.jfs.post(url=self.path, params={'dl':'true'}) return r
[ "def", "delete", "(", "self", ")", ":", "#url = '%s?dl=true' % self.path", "r", "=", "self", ".", "jfs", ".", "post", "(", "url", "=", "self", ".", "path", ",", "params", "=", "{", "'dl'", ":", "'true'", "}", ")", "return", "r" ]
39.2
0.02
def dump(obj, fp, container_count=False, sort_keys=False, no_float32=True, default=None): """Writes the given object as UBJSON to the provided file-like object Args: obj: The object to encode fp: write([size])-able object container_count (bool): Specify length for container types (inclu...
[ "def", "dump", "(", "obj", ",", "fp", ",", "container_count", "=", "False", ",", "sort_keys", "=", "False", ",", "no_float32", "=", "True", ",", "default", "=", "None", ")", ":", "if", "not", "callable", "(", "fp", ".", "write", ")", ":", "raise", ...
56.479452
0.001192
def new_cast_status(self, status): """ Called when a new status received from the Chromecast. """ self.status = status if status: self.status_event.set()
[ "def", "new_cast_status", "(", "self", ",", "status", ")", ":", "self", ".", "status", "=", "status", "if", "status", ":", "self", ".", "status_event", ".", "set", "(", ")" ]
37
0.010582
def quick_layout_switch(self, index): """Switch to quick layout number *index*""" section = 'quick_layouts' try: settings = self.load_window_settings('layout_{}/'.format(index), section=section) (hexstate, window_si...
[ "def", "quick_layout_switch", "(", "self", ",", "index", ")", ":", "section", "=", "'quick_layouts'", "try", ":", "settings", "=", "self", ".", "load_window_settings", "(", "'layout_{}/'", ".", "format", "(", "index", ")", ",", "section", "=", "section", ")"...
51.487805
0.00093
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr( self, 'processed_language') and self.processed_language is not None: _dict['processed_language'] = self.processed_language if hasattr(self, 'word...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'processed_language'", ")", "and", "self", ".", "processed_language", "is", "not", "None", ":", "_dict", "[", "'processed_language'", "]", "=", "self", ...
52.413793
0.001938
def data(ctx, path): """List EDC data for [STUDY] [ENV] [SUBJECT]""" _rws = partial(rws_call, ctx) if len(path) == 0: _rws(ClinicalStudiesRequest(), default_attr='oid') elif len(path) == 1: _rws(StudySubjectsRequest(path[0], 'Prod'), default_attr='subjectkey') elif len(path) == 2: ...
[ "def", "data", "(", "ctx", ",", "path", ")", ":", "_rws", "=", "partial", "(", "rws_call", ",", "ctx", ")", "if", "len", "(", "path", ")", "==", "0", ":", "_rws", "(", "ClinicalStudiesRequest", "(", ")", ",", "default_attr", "=", "'oid'", ")", "eli...
37.833333
0.001433
def is_root(self): """Return True when the comment is a top level comment.""" sub_prefix = self.reddit_session.config.by_object[Submission] return self.parent_id.startswith(sub_prefix)
[ "def", "is_root", "(", "self", ")", ":", "sub_prefix", "=", "self", ".", "reddit_session", ".", "config", ".", "by_object", "[", "Submission", "]", "return", "self", ".", "parent_id", ".", "startswith", "(", "sub_prefix", ")" ]
51.25
0.009615
def dump(self, filename): """Dump the grammar tables to a pickle file.""" f = open(filename, "wb") pickle.dump(self.__dict__, f, 2) f.close()
[ "def", "dump", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "\"wb\"", ")", "pickle", ".", "dump", "(", "self", ".", "__dict__", ",", "f", ",", "2", ")", "f", ".", "close", "(", ")" ]
33.8
0.011561
def scms(self): """ Property for accessing :class:`SCMManager` instance, which is used to manage pluggable SCM materials. :rtype: yagocd.resources.scm.SCMManager """ if self._scm_manager is None: self._scm_manager = SCMManager(session=self._session) return se...
[ "def", "scms", "(", "self", ")", ":", "if", "self", ".", "_scm_manager", "is", "None", ":", "self", ".", "_scm_manager", "=", "SCMManager", "(", "session", "=", "self", ".", "_session", ")", "return", "self", ".", "_scm_manager" ]
36.333333
0.008955
def _integrate_direct_python(self,t,pot,**kwargs): """Integrate the snapshot using a direct force summation method \ written entirely in python""" #Prepare input for direct_nbody q= [] p= [] nq= len(self.orbits) dim= self.orbits[0].dim() if pot is None: ...
[ "def", "_integrate_direct_python", "(", "self", ",", "t", ",", "pot", ",", "*", "*", "kwargs", ")", ":", "#Prepare input for direct_nbody", "q", "=", "[", "]", "p", "=", "[", "]", "nq", "=", "len", "(", "self", ".", "orbits", ")", "dim", "=", "self",...
43.461538
0.019037
def compute_num_true_positives(ref_freqs, est_freqs, window=0.5, chroma=False): """Compute the number of true positives in an estimate given a reference. A frequency is correct if it is within a quartertone of the correct frequency. Parameters ---------- ref_freqs : list of np.ndarray r...
[ "def", "compute_num_true_positives", "(", "ref_freqs", ",", "est_freqs", ",", "window", "=", "0.5", ",", "chroma", "=", "False", ")", ":", "n_frames", "=", "len", "(", "ref_freqs", ")", "true_positives", "=", "np", ".", "zeros", "(", "(", "n_frames", ",", ...
33.075
0.000734
def _parse_logline_timestamp(t): """Parses a logline timestamp into a tuple. Args: t: Timestamp in logline format. Returns: An iterable of date and time elements in the order of month, day, hour, minute, second, microsecond. """ date, time = t.split(' ') month, day = da...
[ "def", "_parse_logline_timestamp", "(", "t", ")", ":", "date", ",", "time", "=", "t", ".", "split", "(", "' '", ")", "month", ",", "day", "=", "date", ".", "split", "(", "'-'", ")", "h", ",", "m", ",", "s", "=", "time", ".", "split", "(", "':'"...
27.4
0.002353
def send_tcp_message(): """send_tcp_message Send a ``TCP`` message to port 80 by default. """ need_response = os.getenv("NEED_RESPONSE", "0") == "1" msg = os.getenv( "MSG", "testing msg time={} - {}".format( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:...
[ "def", "send_tcp_message", "(", ")", ":", "need_response", "=", "os", ".", "getenv", "(", "\"NEED_RESPONSE\"", ",", "\"0\"", ")", "==", "\"1\"", "msg", "=", "os", ".", "getenv", "(", "\"MSG\"", ",", "\"testing msg time={} - {}\"", ".", "format", "(", "dateti...
23.653846
0.001563
def _hide_column(self, column): '''Hides a column by prefixing the name with \'__\'''' column = _ensure_string_from_expression(column) new_name = self._find_valid_name('__' + column) self._rename(column, new_name)
[ "def", "_hide_column", "(", "self", ",", "column", ")", ":", "column", "=", "_ensure_string_from_expression", "(", "column", ")", "new_name", "=", "self", ".", "_find_valid_name", "(", "'__'", "+", "column", ")", "self", ".", "_rename", "(", "column", ",", ...
48.2
0.008163
def get_activity_form_for_create(self, objective_id, activity_record_types): """Gets the activity form for creating new activities. A new form should be requested for each create transaction. arg: objective_id (osid.id.Id): the ``Id`` of the ``Objective`` arg: act...
[ "def", "get_activity_form_for_create", "(", "self", ",", "objective_id", ",", "activity_record_types", ")", ":", "# Implemented from template for", "# osid.learning.ActivityAdminSession.get_activity_form_for_create_template", "if", "not", "isinstance", "(", "objective_id", ",", "...
46.170213
0.001805
def check_archive_format (format, compression): """Make sure format and compression is known.""" if format not in ArchiveFormats: raise util.PatoolError("unknown archive format `%s'" % format) if compression is not None and compression not in ArchiveCompressions: raise util.PatoolError("unko...
[ "def", "check_archive_format", "(", "format", ",", "compression", ")", ":", "if", "format", "not", "in", "ArchiveFormats", ":", "raise", "util", ".", "PatoolError", "(", "\"unknown archive format `%s'\"", "%", "format", ")", "if", "compression", "is", "not", "No...
59.833333
0.008242
def add_license(key): ''' Add a license ''' result = { 'result': False, 'retcode': -1, 'output': '' } if not has_powerpath(): result['output'] = 'PowerPath is not installed' return result cmd = '/sbin/emcpreg -add {0}'.format(key) ret = __salt__[...
[ "def", "add_license", "(", "key", ")", ":", "result", "=", "{", "'result'", ":", "False", ",", "'retcode'", ":", "-", "1", ",", "'output'", ":", "''", "}", "if", "not", "has_powerpath", "(", ")", ":", "result", "[", "'output'", "]", "=", "'PowerPath ...
20.961538
0.001754
def _check_transition_id(self, transition): """Checks the validity of a transition id Checks whether the transition id is already used by another transition within the state :param rafcon.core.transition.Transition transition: The transition to be checked :return bool validity, str mes...
[ "def", "_check_transition_id", "(", "self", ",", "transition", ")", ":", "transition_id", "=", "transition", ".", "transition_id", "if", "transition_id", "in", "self", ".", "transitions", "and", "transition", "is", "not", "self", ".", "transitions", "[", "transi...
54.384615
0.008345
def plugins(self): """ :returns: [(plugin_name, plugin_package, plugin_config), ...] :rtype: list of tuple """ if not self._plugins: self._plugins = [ (plugin_name, plugin_cfg['package'], plugin_cfg) for plugin...
[ "def", "plugins", "(", "self", ")", ":", "if", "not", "self", ".", "_plugins", ":", "self", ".", "_plugins", "=", "[", "(", "plugin_name", ",", "plugin_cfg", "[", "'package'", "]", ",", "plugin_cfg", ")", "for", "plugin_name", ",", "plugin_cfg", "in", ...
39.75
0.008197
def thread_stopped(self): """ :meth:`.WThreadTask.thread_stopped` implementation. Register (if required) stop and termination event by a tracker storage :return: None """ tracker = self.tracker_storage() if tracker is not None: try: if self.ready_event().is_set() is True: if self.track_stop() i...
[ "def", "thread_stopped", "(", "self", ")", ":", "tracker", "=", "self", ".", "tracker_storage", "(", ")", "if", "tracker", "is", "not", "None", ":", "try", ":", "if", "self", ".", "ready_event", "(", ")", ".", "is_set", "(", ")", "is", "True", ":", ...
37.105263
0.027663
def pexpect_monkeypatch(): """Patch pexpect to prevent unhandled exceptions at VM teardown. Calling this function will monkeypatch the pexpect.spawn class and modify its __del__ method to make it more robust in the face of failures that can occur if it is called when the Python VM is shutting down. ...
[ "def", "pexpect_monkeypatch", "(", ")", ":", "if", "pexpect", ".", "__version__", "[", ":", "3", "]", ">=", "'2.2'", ":", "# No need to patch, fix is already the upstream version.", "return", "def", "__del__", "(", "self", ")", ":", "\"\"\"This makes sure that no syst...
40.53125
0.000753
def list(context, job_id, sort, limit, where, verbose): """list(context, sort, limit, where, verbose) List all files. >>> dcictl file-list job-id [OPTIONS] :param string sort: Field to apply sort :param integer limit: Max number of rows to return :param string where: An optional filter criter...
[ "def", "list", "(", "context", ",", "job_id", ",", "sort", ",", "limit", ",", "where", ",", "verbose", ")", ":", "result", "=", "job", ".", "list_files", "(", "context", ",", "id", "=", "job_id", ",", "sort", "=", "sort", ",", "limit", "=", "limit"...
37.466667
0.001736
def create_addon(name): """ Create a Skeleton AddOn (needs internet connection to github) """ try: full_name = "fab_addon_" + name dirname = "Flask-AppBuilder-Skeleton-AddOn-master" url = urlopen(ADDON_REPO_URL) zipfile = ZipFile(BytesIO(url.read())) zipfile.e...
[ "def", "create_addon", "(", "name", ")", ":", "try", ":", "full_name", "=", "\"fab_addon_\"", "+", "name", "dirname", "=", "\"Flask-AppBuilder-Skeleton-AddOn-master\"", "url", "=", "urlopen", "(", "ADDON_REPO_URL", ")", "zipfile", "=", "ZipFile", "(", "BytesIO", ...
38.291667
0.002123
def migration_exchange(self, *, users: List[str], **kwargs) -> SlackResponse: """For Enterprise Grid workspaces, map local user IDs to global user IDs Args: users (list): A list of user ids, up to 400 per request. e.g. ['W1234567890', 'U2345678901', 'U3456789012'] ""...
[ "def", "migration_exchange", "(", "self", ",", "*", ",", "users", ":", "List", "[", "str", "]", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "kwargs", ".", "update", "(", "{", "\"users\"", ":", "users", "}", ")", "return", "self", ".", ...
48.444444
0.009009
def We(self): """ Total energy in electrons used for the radiative calculation """ We = trapz_loglog(self._gam * self._nelec, self._gam * mec2) return We
[ "def", "We", "(", "self", ")", ":", "We", "=", "trapz_loglog", "(", "self", ".", "_gam", "*", "self", ".", "_nelec", ",", "self", ".", "_gam", "*", "mec2", ")", "return", "We" ]
36.2
0.010811
def append_or_dryrun(*args, **kwargs): """ Wrapper around Fabric's contrib.files.append() to give it a dryrun option. text filename http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.append """ from fabric.contrib.files import append dryrun = get_dryrun(kwargs.ge...
[ "def", "append_or_dryrun", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "fabric", ".", "contrib", ".", "files", "import", "append", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")", ")", "if", "'dryrun'", "in...
30.483871
0.002051
def bindex(start, stop=None, dim=1, sort="G", cross_truncation=1.): """ Generator for creating multi-indices. Args: start (int): The lower order of the indices stop (:py:data:typing.Optional[int]): the maximum shape included. If omitted: stop <- start; start <- 0 ...
[ "def", "bindex", "(", "start", ",", "stop", "=", "None", ",", "dim", "=", "1", ",", "sort", "=", "\"G\"", ",", "cross_truncation", "=", "1.", ")", ":", "if", "stop", "is", "None", ":", "start", ",", "stop", "=", "0", ",", "start", "start", "=", ...
31.584416
0.000797
def enable_cloud_integration(self, id, **kwargs): # noqa: E501 """Enable a specific cloud integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.enable_c...
[ "def", "enable_cloud_integration", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "ena...
43.238095
0.002155
def on_fork(): """ Should be called by any program integrating Mitogen each time the process is forked, in the context of the new child. """ reset_logging_framework() # Must be first! fixup_prngs() mitogen.core.Latch._on_fork() mitogen.core.Side._on_fork() mitogen.core.ExternalConte...
[ "def", "on_fork", "(", ")", ":", "reset_logging_framework", "(", ")", "# Must be first!", "fixup_prngs", "(", ")", "mitogen", ".", "core", ".", "Latch", ".", "_on_fork", "(", ")", "mitogen", ".", "core", ".", "Side", ".", "_on_fork", "(", ")", "mitogen", ...
34.642857
0.002008
def import_module_from_path(modpath, index=-1): """ Imports a module via its path Args: modpath (PathLike): path to the module on disk or within a zipfile. Returns: module: the imported module References: https://stackoverflow.com/questions/67631/import-module-given-path ...
[ "def", "import_module_from_path", "(", "modpath", ",", "index", "=", "-", "1", ")", ":", "import", "os", "if", "not", "os", ".", "path", ".", "exists", "(", "modpath", ")", ":", "import", "re", "import", "zipimport", "# We allow (if not prefer or force) the co...
39.301887
0.000234
def ask_yes_no(prompt,default=None): """Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an ...
[ "def", "ask_yes_no", "(", "prompt", ",", "default", "=", "None", ")", ":", "answers", "=", "{", "'y'", ":", "True", ",", "'n'", ":", "False", ",", "'yes'", ":", "True", ",", "'no'", ":", "False", "}", "ans", "=", "None", "while", "ans", "not", "i...
32.25
0.009677
def out_of_service(self, args): """ Set the Out_Of_Service property so the Present_Value of an I/O may be written. :param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ] """ if not self._started: raise ApplicationNotStarted("B...
[ "def", "out_of_service", "(", "self", ",", "args", ")", ":", "if", "not", "self", ".", "_started", ":", "raise", "ApplicationNotStarted", "(", "\"BACnet stack not running - use startApp()\"", ")", "# with self.this_application._lock: if use lock...won't be able to call read...\...
39.529412
0.010174
def _parse_game_data(self, game_data): """ Parses a value for every attribute. The function looks through every attribute with the exception of those listed below and retrieves the value according to the parsing scheme and index of the attribute from the passed HTML data. Once t...
[ "def", "_parse_game_data", "(", "self", ",", "game_data", ")", ":", "for", "field", "in", "self", ".", "__dict__", ":", "# Remove the leading '_' from the name", "short_name", "=", "str", "(", "field", ")", "[", "1", ":", "]", "if", "short_name", "==", "'dat...
39.193548
0.001606
def authentication(login, password): """ Authentication on vk.com. :param login: login on vk.com. :param password: password on vk.com. :returns: `requests.Session` session with cookies. """ session = requests.Session() response = session.get('https://m.vk.com') url = re.search(r'act...
[ "def", "authentication", "(", "login", ",", "password", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "response", "=", "session", ".", "get", "(", "'https://m.vk.com'", ")", "url", "=", "re", ".", "search", "(", "r'action=\"([^\\\"]+)\"'", ...
32.571429
0.002132
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): # pylint: disable=too-many-arguments """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for specification of input and result values. Implements the following eq...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# pylint: disable=too-many-arguments", "# obtain coefficients for required intensity measure type (IMT)", "coeffs", "=", "self", ".", "COEFFS_BA...
35.34375
0.00129
def sim_levenshtein(src, tar, mode='lev', cost=(1, 1, 1, 1)): """Return the Levenshtein similarity of two strings. This is a wrapper of :py:meth:`Levenshtein.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison mode : str...
[ "def", "sim_levenshtein", "(", "src", ",", "tar", ",", "mode", "=", "'lev'", ",", "cost", "=", "(", "1", ",", "1", ",", "1", ",", "1", ")", ")", ":", "return", "Levenshtein", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "mode", ",", "co...
30.627907
0.000736
def _get_proj_enclosing_polygon(self): """ See :meth:`Mesh._get_proj_enclosing_polygon`. :class:`RectangularMesh` contains an information about relative positions of points, so it allows to define the minimum polygon, containing the projection of the mesh, which doesn't necessar...
[ "def", "_get_proj_enclosing_polygon", "(", "self", ")", ":", "if", "self", ".", "lons", ".", "size", "<", "4", ":", "# the mesh doesn't contain even a single cell", "return", "self", ".", "_get_proj_convex_hull", "(", ")", "proj", "=", "geo_utils", ".", "Orthograp...
50.52459
0.000637
def _make_ssh_forward_server(self, remote_address, local_bind_address): """ Make SSH forward proxy Server class """ _Handler = self._make_ssh_forward_handler_class(remote_address) try: if isinstance(local_bind_address, string_types): forward_maker_clas...
[ "def", "_make_ssh_forward_server", "(", "self", ",", "remote_address", ",", "local_bind_address", ")", ":", "_Handler", "=", "self", ".", "_make_ssh_forward_handler_class", "(", "remote_address", ")", "try", ":", "if", "isinstance", "(", "local_bind_address", ",", "...
43.447368
0.001185
def coarsen_matrix(Z, xlevel=0, ylevel=0, method='average'): """ This returns a coarsened numpy matrix. method can be 'average', 'maximum', or 'minimum' """ # coarsen x if not ylevel: Z_coarsened = Z else: temp = [] for z in Z: temp.append(coarsen_array(z, ylevel, m...
[ "def", "coarsen_matrix", "(", "Z", ",", "xlevel", "=", "0", ",", "ylevel", "=", "0", ",", "method", "=", "'average'", ")", ":", "# coarsen x", "if", "not", "ylevel", ":", "Z_coarsened", "=", "Z", "else", ":", "temp", "=", "[", "]", "for", "z", "in"...
26.428571
0.008342
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing an execution context into this object. ''' self.id = node.getAttributeNS(RTS_NS, 'id') self.kind = node.getAttributeNS(RTS_NS, 'kind') if node.hasAttributeNS(RTS_NS, 'rate'): self.ra...
[ "def", "parse_xml_node", "(", "self", ",", "node", ")", ":", "self", ".", "id", "=", "node", ".", "getAttributeNS", "(", "RTS_NS", ",", "'id'", ")", "self", ".", "kind", "=", "node", ".", "getAttributeNS", "(", "RTS_NS", ",", "'kind'", ")", "if", "no...
43.473684
0.00237
def preprocess_for_eval(image, image_size=224, normalize=True): """Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A prepr...
[ "def", "preprocess_for_eval", "(", "image", ",", "image_size", "=", "224", ",", "normalize", "=", "True", ")", ":", "if", "normalize", ":", "image", "=", "tf", ".", "to_float", "(", "image", ")", "/", "255.0", "image", "=", "_do_scale", "(", "image", "...
34.352941
0.016667
def filter(self): """ Get a filtered list of file imports :return: A list of file imports, with only the id set (you need to refresh them if you want all the attributes to be filled in) :rtype: list of :class:`carto.file_import.FileImportJob` :raise: CartoExcept...
[ "def", "filter", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "send", "(", "self", ".", "get_collection_endpoint", "(", ")", ",", "\"get\"", ")", "if", "self", ".", "json_collection_attribute", "is", "not", "None", ":", "resource_ids", ...
34.735294
0.001647
def import_product_sets( self, parent, input_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Asynchronous API that imports a list of reference images to specified pro...
[ "def", "import_product_sets", "(", "self", ",", "parent", ",", "input_config", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", "."...
42.647619
0.002401
def group_resources_by_type(resources): """Group a list of `resources` by `type` with order""" groups = defaultdict(list) for resource in resources: groups[getattr(resource, 'type')].append(resource) ordered = OrderedDict() for rtype, rtype_label in RESOURCE_TYPES.items(): if groups[...
[ "def", "group_resources_by_type", "(", "resources", ")", ":", "groups", "=", "defaultdict", "(", "list", ")", "for", "resource", "in", "resources", ":", "groups", "[", "getattr", "(", "resource", ",", "'type'", ")", "]", ".", "append", "(", "resource", ")"...
39.5
0.002475
def wait_for_path_blocking(path: pathlib.Path, timeout: int=30) -> None: """ Waits up to ``timeout`` seconds for the path to appear at path ``path`` otherwise raises :exc:`TimeoutError`. """ start_at = time.monotonic() while time.monotonic() - start_at < timeout: if path.exists(): ...
[ "def", "wait_for_path_blocking", "(", "path", ":", "pathlib", ".", "Path", ",", "timeout", ":", "int", "=", "30", ")", "->", "None", ":", "start_at", "=", "time", ".", "monotonic", "(", ")", "while", "time", ".", "monotonic", "(", ")", "-", "start_at",...
34.769231
0.008621
def getTamilWords( tweet ): """" word needs to all be in the same tamil language """ tweet = TamilTweetParser.cleanupPunct( tweet ); nonETwords = filter( lambda x: len(x) > 0 , re.split(r'\s+',tweet) );#|"+|\'+|#+ tamilWords = filter( TamilTweetParser.isTamilPredicate, nonETwords ); ...
[ "def", "getTamilWords", "(", "tweet", ")", ":", "tweet", "=", "TamilTweetParser", ".", "cleanupPunct", "(", "tweet", ")", "nonETwords", "=", "filter", "(", "lambda", "x", ":", "len", "(", "x", ")", ">", "0", ",", "re", ".", "split", "(", "r'\\s+'", "...
56
0.052786
def contains_vasp_input(dir_name): """ Checks if a directory contains valid VASP input. Args: dir_name: Directory name to check. Returns: True if directory contains all four VASP input files (INCAR, POSCAR, KPOINTS and POTCAR). """ for f in ["INCAR", "POSCAR...
[ "def", "contains_vasp_input", "(", "dir_name", ")", ":", "for", "f", "in", "[", "\"INCAR\"", ",", "\"POSCAR\"", ",", "\"POTCAR\"", ",", "\"KPOINTS\"", "]", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", ...
29.705882
0.001919
def bk_white(cls): "Make the text background color white." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_GREY cls._set_text_attributes(wAttributes)
[ "def", "bk_white", "(", "cls", ")", ":", "wAttributes", "=", "cls", ".", "_get_text_attributes", "(", ")", "wAttributes", "&=", "~", "win32", ".", "BACKGROUND_MASK", "wAttributes", "|=", "win32", ".", "BACKGROUND_GREY", "cls", ".", "_set_text_attributes", "(", ...
41.333333
0.011858
def handle_triple(self, lhs, relation, rhs): """ Process triples before they are added to the graph. Note that *lhs* and *rhs* are as they originally appeared, and may be inverted. Inversions are detected by is_relation_inverted() and de-inverted by invert_relation(). B...
[ "def", "handle_triple", "(", "self", ",", "lhs", ",", "relation", ",", "rhs", ")", ":", "relation", "=", "relation", ".", "replace", "(", "':'", ",", "''", ",", "1", ")", "# remove leading :", "if", "self", ".", "is_relation_inverted", "(", "relation", "...
37.368421
0.001373
def diff( cobertura_file1, cobertura_file2, color, format, output, source1, source2, source_prefix1, source_prefix2, source): """compare coverage of two Cobertura reports""" cobertura1 = Cobertura( cobertura_file1, source=source1, source_prefix=source_prefix1 ...
[ "def", "diff", "(", "cobertura_file1", ",", "cobertura_file2", ",", "color", ",", "format", ",", "output", ",", "source1", ",", "source2", ",", "source_prefix1", ",", "source_prefix2", ",", "source", ")", ":", "cobertura1", "=", "Cobertura", "(", "cobertura_fi...
28.944444
0.000929
def fht(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH, zetaV, xdirect, fhtarg, use_ne_eval, msrc, mrec): r"""Hankel Transform using the Digital Linear Filter method. The *Digital Linear Filter* method was introduced to geophysics by [Ghos70]_, and made popular and wide-spread b...
[ "def", "fht", "(", "zsrc", ",", "zrec", ",", "lsrc", ",", "lrec", ",", "off", ",", "factAng", ",", "depth", ",", "ab", ",", "etaH", ",", "etaV", ",", "zetaH", ",", "zetaV", ",", "xdirect", ",", "fhtarg", ",", "use_ne_eval", ",", "msrc", ",", "mre...
32.885246
0.000484
def vector_poly_data(orig, vec): """ Creates a vtkPolyData object composed of vectors """ # shape, dimention checking if not isinstance(orig, np.ndarray): orig = np.asarray(orig) if not isinstance(vec, np.ndarray): vec = np.asarray(vec) if orig.ndim != 2: orig = orig.resha...
[ "def", "vector_poly_data", "(", "orig", ",", "vec", ")", ":", "# shape, dimention checking", "if", "not", "isinstance", "(", "orig", ",", "np", ".", "ndarray", ")", ":", "orig", "=", "np", ".", "asarray", "(", "orig", ")", "if", "not", "isinstance", "(",...
31
0.000569
def compound_statements(logical_line): r"""Compound statements (on the same line) are generally discouraged. While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! Always use a def statemen...
[ "def", "compound_statements", "(", "logical_line", ")", ":", "line", "=", "logical_line", "last_char", "=", "len", "(", "line", ")", "-", "1", "found", "=", "line", ".", "find", "(", "':'", ")", "prev_found", "=", "0", "counts", "=", "dict", "(", "(", ...
39.706897
0.000424
def parse_hyphen_range(self, value): """ Parse hyphen ranges such as: 2 - 5, -2 - -1, -3 - 5 """ values = value.strip().split('-') values = list(map(strip, values)) if len(values) == 1: lower = upper = value.strip() elif len(values) == 2: l...
[ "def", "parse_hyphen_range", "(", "self", ",", "value", ")", ":", "values", "=", "value", ".", "strip", "(", ")", ".", "split", "(", "'-'", ")", "values", "=", "list", "(", "map", "(", "strip", ",", "values", ")", ")", "if", "len", "(", "values", ...
33.354839
0.00188
def p_expression_uxnor(self, p): 'expression : XNOR expression %prec UXNOR' p[0] = Uxnor(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_uxnor", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Uxnor", "(", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", ...
41
0.011976
def run(*args): """Load given `envfile` and run `command` with `params`""" if not args: args = sys.argv[1:] if len(args) < 2: print('Usage: runenv <envfile> <command> <params>') sys.exit(0) os.environ.update(create_env(args[0])) os.environ['_RUNENV_WRAPPED'] = '1' runna...
[ "def", "run", "(", "*", "args", ")", ":", "if", "not", "args", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "len", "(", "args", ")", "<", "2", ":", "print", "(", "'Usage: runenv <envfile> <command> <params>'", ")", "sys", ".", "e...
30.08
0.001289
def get_short_string(self): """ Return a shorter formatted String which encodes this method. The returned name has the form: <classname> <methodname> ([arguments ...])<returntype> * All Class names are condensed to the actual name (no package). * Access flags are not ret...
[ "def", "get_short_string", "(", "self", ")", ":", "def", "_fmt_classname", "(", "cls", ")", ":", "arr", "=", "\"\"", "# Test for arrays", "while", "cls", ".", "startswith", "(", "\"[\"", ")", ":", "arr", "+=", "\"[\"", "cls", "=", "cls", "[", "1", ":",...
32.805556
0.002467
def fix_tree(tree, a_id_lookup, out): """ get the names for sequences in the raxml tree """ if check(out) is False and check(tree) is True: tree = open(tree).read() for line in open(a_id_lookup): id, name, header = line.strip().split('\t') tree = tree.replace(id+'...
[ "def", "fix_tree", "(", "tree", ",", "a_id_lookup", ",", "out", ")", ":", "if", "check", "(", "out", ")", "is", "False", "and", "check", "(", "tree", ")", "is", "True", ":", "tree", "=", "open", "(", "tree", ")", ".", "read", "(", ")", "for", "...
34
0.002387
def add_signature(name=None, inputs=None, outputs=None): """Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__c...
[ "def", "add_signature", "(", "name", "=", "None", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "\"default\"", "if", "inputs", "is", "None", ":", "inputs", "=", "{", "}", "if", "outputs", ...
38.352941
0.011219
def lowpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, cutoff_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :mat...
[ "def", "lowpass_filter", "(", "data", ":", "FLOATS_TYPE", ",", "sampling_freq_hz", ":", "float", ",", "cutoff_freq_hz", ":", "float", ",", "numtaps", ":", "int", ")", "->", "FLOATS_TYPE", ":", "coeffs", "=", "firwin", "(", "numtaps", "=", "numtaps", ",", "...
32.851852
0.001095
def get_public_ip(self, addr_family=None, *args, **kwargs): """Alias for get_ip('public')""" return self.get_ip('public', addr_family, *args, **kwargs)
[ "def", "get_public_ip", "(", "self", ",", "addr_family", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_ip", "(", "'public'", ",", "addr_family", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
55
0.011976
def preprocess_bel_stmt(stmt: str) -> str: """Clean up basic formatting of BEL statement Args: stmt: BEL statement as single string Returns: cleaned BEL statement """ stmt = stmt.strip() # remove newline at end of stmt stmt = re.sub(r",+", ",", stmt) # remove multiple commas...
[ "def", "preprocess_bel_stmt", "(", "stmt", ":", "str", ")", "->", "str", ":", "stmt", "=", "stmt", ".", "strip", "(", ")", "# remove newline at end of stmt", "stmt", "=", "re", ".", "sub", "(", "r\",+\"", ",", "\",\"", ",", "stmt", ")", "# remove multiple ...
28.125
0.002151
def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() return ageSorted[::-1]
[ "def", "sortedbyAge", "(", "self", ")", ":", "ageAll", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "for", "i", "in", "range", "(", "self", ".", "length", ")", ":", "ageAll", "[", "i", "]", "=", "self", ".", "Ind", "[", "i", "]"...
23.888889
0.044843
def get_context(request, model=None): """ Extracts ORB context information from the request. :param request: <pyramid.request.Request> :param model: <orb.Model> || None :return: {<str> key: <variant> value} values, <orb.Context> """ # convert request parameters to python param_values =...
[ "def", "get_context", "(", "request", ",", "model", "=", "None", ")", ":", "# convert request parameters to python", "param_values", "=", "get_param_values", "(", "request", ",", "model", "=", "model", ")", "# extract the full orb context if provided", "context", "=", ...
33.602564
0.001112
def check_schema_coverage(doc, schema): ''' FORWARD CHECK OF DOCUMENT This routine looks at each element in the doc, and makes sure there is a matching 'name' in the schema at that level. ''' error_list = [] to_delete = [] for entry in doc.list_tuples(): (name, value, index,...
[ "def", "check_schema_coverage", "(", "doc", ",", "schema", ")", ":", "error_list", "=", "[", "]", "to_delete", "=", "[", "]", "for", "entry", "in", "doc", ".", "list_tuples", "(", ")", ":", "(", "name", ",", "value", ",", "index", ",", "seq", ")", ...
36.409091
0.008516
def _get_default_jp2_boxes(self): """Create a default set of JP2 boxes.""" # Try to create a reasonable default. boxes = [JPEG2000SignatureBox(), FileTypeBox(), JP2HeaderBox(), ContiguousCodestreamBox()] height = self.codestream.segment[...
[ "def", "_get_default_jp2_boxes", "(", "self", ")", ":", "# Try to create a reasonable default.", "boxes", "=", "[", "JPEG2000SignatureBox", "(", ")", ",", "FileTypeBox", "(", ")", ",", "JP2HeaderBox", "(", ")", ",", "ContiguousCodestreamBox", "(", ")", "]", "heigh...
40.259259
0.001797
def filter_short(terms): ''' only keep if brute-force possibilities are greater than this word's rank in the dictionary ''' return [term for i, term in enumerate(terms) if 26**(len(term)) > i]
[ "def", "filter_short", "(", "terms", ")", ":", "return", "[", "term", "for", "i", ",", "term", "in", "enumerate", "(", "terms", ")", "if", "26", "**", "(", "len", "(", "term", ")", ")", ">", "i", "]" ]
40.8
0.009615
def string(value, allow_empty = False, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Validate that ``value`` is a valid string. :param value: The value to validate. :type value:...
[ "def", "string", "(", "value", ",", "allow_empty", "=", "False", ",", "coerce_value", "=", "False", ",", "minimum_length", "=", "None", ",", "maximum_length", "=", "None", ",", "whitespace_padding", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", ...
40.77027
0.008414
def AddPort(self,protocol,port,port_to=None): """Add and commit a single port. # Add single port >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='TCP',port='22').WaitUntilComplete() 0 # Add port range >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='UD...
[ "def", "AddPort", "(", "self", ",", "protocol", ",", "port", ",", "port_to", "=", "None", ")", ":", "self", ".", "ports", ".", "append", "(", "Port", "(", "self", ",", "protocol", ",", "port", ",", "port_to", ")", ")", "return", "(", "self", ".", ...
28
0.043197
def cardClass( self, record ): """ Returns the class that will be used by the createCard method to generate card widgets for records. :param record | <orb.Table> :return <XAbstractCardWidget> """ return self._cardClasses.get(typ...
[ "def", "cardClass", "(", "self", ",", "record", ")", ":", "return", "self", ".", "_cardClasses", ".", "get", "(", "type", "(", "record", ")", ",", "self", ".", "_cardClasses", "[", "None", "]", ")" ]
34.6
0.019718
def read_tabular(filename, dtype_conversion=None): """ Read a tabular data file which can be CSV, TSV, XLS or XLSX. Parameters ---------- filename : str or pathlib.Path The full file path. May be a compressed file. dtype_conversion : dict Column names as keys and corresponding t...
[ "def", "read_tabular", "(", "filename", ",", "dtype_conversion", "=", "None", ")", ":", "if", "dtype_conversion", "is", "None", ":", "dtype_conversion", "=", "{", "}", "name", ",", "ext", "=", "filename", ".", "split", "(", "\".\"", ",", "1", ")", "ext",...
35.694444
0.000758
def parse_project_and_dataset( project: str, dataset: Optional[str] = None ) -> Tuple[str, str, Optional[str]]: """Compute the billing project, data project, and dataset if available. This function figure out the project id under which queries will run versus the project of where the data live as well ...
[ "def", "parse_project_and_dataset", "(", "project", ":", "str", ",", "dataset", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Tuple", "[", "str", ",", "str", ",", "Optional", "[", "str", "]", "]", ":", "try", ":", "data_project", ",", "d...
26.018519
0.000686
def update(self, membershipId, isModerator=None, **request_parameters): """Update a team membership, by ID. Args: membershipId(basestring): The team membership ID. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional re...
[ "def", "update", "(", "self", ",", "membershipId", ",", "isModerator", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "membershipId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "isModerator", ...
37.4375
0.001627
def analyse_action(func): """Analyse a function.""" description = inspect.getdoc(func) or 'undocumented action' arguments = [] args, varargs, kwargs, defaults = inspect.getargspec(func) if varargs or kwargs: raise TypeError('variable length arguments for action not allowed.') if len(args...
[ "def", "analyse_action", "(", "func", ")", ":", "description", "=", "inspect", ".", "getdoc", "(", "func", ")", "or", "'undocumented action'", "arguments", "=", "[", "]", "args", ",", "varargs", ",", "kwargs", ",", "defaults", "=", "inspect", ".", "getargs...
42.75
0.000953
def subscribe(object_type: str, subscriber: str, callback_handler: Callable = None) -> EventQueue: """Subscribe to the specified object type. Returns an EventQueue object which can be used to query events associated with the object type for this subscriber. Args: object_type (str...
[ "def", "subscribe", "(", "object_type", ":", "str", ",", "subscriber", ":", "str", ",", "callback_handler", ":", "Callable", "=", "None", ")", "->", "EventQueue", ":", "key", "=", "_keys", ".", "subscribers", "(", "object_type", ")", "DB", ".", "remove_fro...
34
0.001431
def dequeue_pre_prepares(self): """ Dequeue any received PRE-PREPAREs that did not have finalized requests or the replica was missing any PRE-PREPAREs before it :return: """ ppsReady = [] # Check if any requests have become finalised belonging to any stashed ...
[ "def", "dequeue_pre_prepares", "(", "self", ")", ":", "ppsReady", "=", "[", "]", "# Check if any requests have become finalised belonging to any stashed", "# PRE-PREPAREs.", "for", "i", ",", "(", "pp", ",", "sender", ",", "reqIds", ")", "in", "enumerate", "(", "self...
43.189189
0.001836
def get_diff_idxs(array, rtol, atol): """ Given an array with (C, N, L) values, being the first the reference value, compute the relative differences and discard the one below the tolerance. :returns: indices where there are sensible differences. """ C, N, L = array.shape diff_idxs = set() ...
[ "def", "get_diff_idxs", "(", "array", ",", "rtol", ",", "atol", ")", ":", "C", ",", "N", ",", "L", "=", "array", ".", "shape", "diff_idxs", "=", "set", "(", ")", "# indices of the sites with differences", "for", "c", "in", "range", "(", "1", ",", "C", ...
42.153846
0.001786
def _process_phenotype_hpoa(self, raw, limit): """ see info on format here: http://www.human-phenotype-ontology.org/contao/index.php/annotation-guide.html :param raw: :param limit: :return: """ src_key = 'hpoa' if self.test_mode: gra...
[ "def", "_process_phenotype_hpoa", "(", "self", ",", "raw", ",", "limit", ")", ":", "src_key", "=", "'hpoa'", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "model", "=", "Mo...
37.329341
0.001406
def flatten_dir_tree(self, tree): """ Convert a file tree back into a flat dict """ result = {} def helper(tree, leading_path = ''): dirs = tree['dirs']; files = tree['files'] for name, file_info in files.iteritems(): file_info['path'] = leading_path + ...
[ "def", "flatten_dir_tree", "(", "self", ",", "tree", ")", ":", "result", "=", "{", "}", "def", "helper", "(", "tree", ",", "leading_path", "=", "''", ")", ":", "dirs", "=", "tree", "[", "'dirs'", "]", "files", "=", "tree", "[", "'files'", "]", "for...
37.071429
0.018797
def _record_to_struct(cur_rec, records): """Convert a CWL record into a WDL struct/Object. Work in progress to support changes to WDL Objects to be defined in structs. """ def to_camel_case(x): def uppercase_word(w): return w[0].upper() + w[1:] return "".join(uppercase_w...
[ "def", "_record_to_struct", "(", "cur_rec", ",", "records", ")", ":", "def", "to_camel_case", "(", "x", ")", ":", "def", "uppercase_word", "(", "w", ")", ":", "return", "w", "[", "0", "]", ".", "upper", "(", ")", "+", "w", "[", "1", ":", "]", "re...
41.941176
0.001372
def function_call_prepare_action(self, text, loc, fun): """Code executed after recognising a function call (type and function name)""" exshared.setpos(loc, text) if DEBUG > 0: print("FUN_PREP:",fun) if DEBUG == 2: self.symtab.display() if DEBUG > 2: retu...
[ "def", "function_call_prepare_action", "(", "self", ",", "text", ",", "loc", ",", "fun", ")", ":", "exshared", ".", "setpos", "(", "loc", ",", "text", ")", "if", "DEBUG", ">", "0", ":", "print", "(", "\"FUN_PREP:\"", ",", "fun", ")", "if", "DEBUG", "...
51.875
0.009467
def _generate_union_cstor_funcs(self, union): """Emits standard union constructor.""" for field in union.all_fields: enum_field_name = fmt_enum_name(field.name, union) func_args = [] if is_void_type( field.data_type) else fmt_func_args_from_fields([field]) ...
[ "def", "_generate_union_cstor_funcs", "(", "self", ",", "union", ")", ":", "for", "field", "in", "union", ".", "all_fields", ":", "enum_field_name", "=", "fmt_enum_name", "(", "field", ".", "name", ",", "union", ")", "func_args", "=", "[", "]", "if", "is_v...
46.722222
0.002331