text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def run_profilers(run_object, prof_config, verbose=False): """Runs profilers on run_object. Args: run_object: An object (string or tuple) for profiling. prof_config: A string with profilers configuration. verbose: True if info about running profilers should be shown. Returns: ...
[ "def", "run_profilers", "(", "run_object", ",", "prof_config", ",", "verbose", "=", "False", ")", ":", "if", "len", "(", "prof_config", ")", ">", "len", "(", "set", "(", "prof_config", ")", ")", ":", "raise", "AmbiguousConfigurationError", "(", "'Profiler co...
40.266667
0.000808
def plate_exchanger_identifier(self): '''Method to create an identifying string in format 'L' + wavelength + 'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and amplitude are specified in units of mm and rounded to two decimal places. ''' s = ('L' + str(round(se...
[ "def", "plate_exchanger_identifier", "(", "self", ")", ":", "s", "=", "(", "'L'", "+", "str", "(", "round", "(", "self", ".", "wavelength", "*", "1000", ",", "2", ")", ")", "+", "'A'", "+", "str", "(", "round", "(", "self", ".", "amplitude", "*", ...
53.111111
0.010288
def getFingerprintsForTexts(self, strings, sparsity=1.0): """Bulk get Fingerprint for text. Args: strings, list(str): A list of texts to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: list of F...
[ "def", "getFingerprintsForTexts", "(", "self", ",", "strings", ",", "sparsity", "=", "1.0", ")", ":", "body", "=", "[", "{", "\"text\"", ":", "s", "}", "for", "s", "in", "strings", "]", "return", "self", ".", "_text", ".", "getRepresentationsForBulkText", ...
46.5
0.00703
def playbook_treeview(playbook): """ Creates a fake filesystem with playbook files and uses generate_tree() to recurse and return a JSON structure suitable for bootstrap-treeview. """ fs = fake_filesystem.FakeFilesystem() mock_os = fake_filesystem.FakeOsModule(fs) files = models.File.query....
[ "def", "playbook_treeview", "(", "playbook", ")", ":", "fs", "=", "fake_filesystem", ".", "FakeFilesystem", "(", ")", "mock_os", "=", "fake_filesystem", ".", "FakeOsModule", "(", "fs", ")", "files", "=", "models", ".", "File", ".", "query", ".", "filter", ...
33.444444
0.001616
def variables(names, **kwargs): """ Convenience function for the creation of multiple variables. For more control, consider using ``symbols(names, cls=Variable, **kwargs)`` directly. :param names: string of variable names. Example: x, y = variables('x, y') :param kwargs: kwargs to be passed...
[ "def", "variables", "(", "names", ",", "*", "*", "kwargs", ")", ":", "return", "symbols", "(", "names", ",", "cls", "=", "Variable", ",", "seq", "=", "True", ",", "*", "*", "kwargs", ")" ]
44.454545
0.004008
def synchronize(self, status): """Synchronize snapserver.""" self._version = status.get('server').get('version') self._groups = {} self._clients = {} self._streams = {} for stream in status.get('server').get('streams'): self._streams[stream.get('id')] = Snapst...
[ "def", "synchronize", "(", "self", ",", "status", ")", ":", "self", ".", "_version", "=", "status", ".", "get", "(", "'server'", ")", ".", "get", "(", "'version'", ")", "self", ".", "_groups", "=", "{", "}", "self", ".", "_clients", "=", "{", "}", ...
53.533333
0.003672
def record_asciinema(): '''a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status. ''' import asciinema.conf...
[ "def", "record_asciinema", "(", ")", ":", "import", "asciinema", ".", "config", "as", "aconfig", "from", "asciinema", ".", "api", "import", "Api", "# Load the API class", "cfg", "=", "aconfig", ".", "load", "(", ")", "api", "=", "Api", "(", "cfg", ".", "...
33.863636
0.006527
def get_resource_by_key(self, resource_key): """Return resource by quick_key/folder_key. key -- quick_key or folder_key """ # search for quick_key by default lookup_order = ["quick_key", "folder_key"] if len(resource_key) == FOLDER_KEY_LENGTH: lookup_order ...
[ "def", "get_resource_by_key", "(", "self", ",", "resource_key", ")", ":", "# search for quick_key by default", "lookup_order", "=", "[", "\"quick_key\"", ",", "\"folder_key\"", "]", "if", "len", "(", "resource_key", ")", "==", "FOLDER_KEY_LENGTH", ":", "lookup_order",...
30.787879
0.001908
def gradient(self): r"""Gradient of the KL functional. The gradient of `KullbackLeibler` with ``prior`` :math:`g` is given as .. math:: \nabla F(x) = 1 - \frac{g}{x}. The gradient is not defined in points where one or more components are non-positive. ...
[ "def", "gradient", "(", "self", ")", ":", "functional", "=", "self", "class", "KLGradient", "(", "Operator", ")", ":", "\"\"\"The gradient operator of this functional.\"\"\"", "def", "__init__", "(", "self", ")", ":", "\"\"\"Initialize a new instance.\"\"\"", "super", ...
30.028571
0.001843
def duration(self): """ The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). """ self._check_ps() rstar = self.system.central.radius k = self.r/rstar dur = self.period / np.pi arg = rstar/self.a * np.s...
[ "def", "duration", "(", "self", ")", ":", "self", ".", "_check_ps", "(", ")", "rstar", "=", "self", ".", "system", ".", "central", ".", "radius", "k", "=", "self", ".", "r", "/", "rstar", "dur", "=", "self", ".", "period", "/", "np", ".", "pi", ...
30.941176
0.005535
def get_genericpage(cls, kb_app): """ Return the one class if configured, otherwise default """ # Presumes the registry has been committed q = dectate.Query('genericpage') klasses = sorted(q(kb_app), key=lambda args: args[0].order) if not klasses: # The site doesn't ...
[ "def", "get_genericpage", "(", "cls", ",", "kb_app", ")", ":", "# Presumes the registry has been committed", "q", "=", "dectate", ".", "Query", "(", "'genericpage'", ")", "klasses", "=", "sorted", "(", "q", "(", "kb_app", ")", ",", "key", "=", "lambda", "arg...
37.454545
0.004739
def pairwise_cos_distance(A, B): """Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B. """ normalized_A = tf.nn.l2_normalize(A, dim=1) normalized_B = tf.nn.l2_normalize(B, dim=1) prod = tf.ma...
[ "def", "pairwise_cos_distance", "(", "A", ",", "B", ")", ":", "normalized_A", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "A", ",", "dim", "=", "1", ")", "normalized_B", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "B", ",", "dim", "=", "1",...
34.363636
0.002577
def propget(self, prop, rev, path=None): """Get Subversion property value of the path""" rev, prefix = self._maprev(rev) if path is None: return self._propget(prop, str(rev), None) else: path = type(self).cleanPath(_join(prefix, path)) return self._pro...
[ "def", "propget", "(", "self", ",", "prop", ",", "rev", ",", "path", "=", "None", ")", ":", "rev", ",", "prefix", "=", "self", ".", "_maprev", "(", "rev", ")", "if", "path", "is", "None", ":", "return", "self", ".", "_propget", "(", "prop", ",", ...
42.375
0.00578
def load_config(self): """ Load configuration for the service Args: config_file: Configuration file path """ logger.debug('loading config file: %s', self.config_file) if os.path.exists(self.config_file): with open(self.config_file) as file_handle:...
[ "def", "load_config", "(", "self", ")", ":", "logger", ".", "debug", "(", "'loading config file: %s'", ",", "self", ".", "config_file", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "config_file", ")", ":", "with", "open", "(", "self", ...
36.352941
0.003155
def Glob(self, pathname, ondisk=True, source=True, strings=False, exclude=None, cwd=None): """ Globs This is mainly a shim layer """ if cwd is None: cwd = self.getcwd() return cwd.glob(pathname, ondisk, source, strings, exclude)
[ "def", "Glob", "(", "self", ",", "pathname", ",", "ondisk", "=", "True", ",", "source", "=", "True", ",", "strings", "=", "False", ",", "exclude", "=", "None", ",", "cwd", "=", "None", ")", ":", "if", "cwd", "is", "None", ":", "cwd", "=", "self",...
31.222222
0.010381
def setExtention(self, ext): """ Deprecated: use :meth:`setExtension`. Args: ext (str): """ import warnings msg = "the setExtention method is deprecated, please use setExtension" warnings.warn(msg) self.setExtension(ext)
[ "def", "setExtention", "(", "self", ",", "ext", ")", ":", "import", "warnings", "msg", "=", "\"the setExtention method is deprecated, please use setExtension\"", "warnings", ".", "warn", "(", "msg", ")", "self", ".", "setExtension", "(", "ext", ")" ]
26.090909
0.006734
def location(hexgrid_type, coord): """ Returns a formatted string representing the coordinate. The format depends on the coordinate type. Tiles look like: 1, 12 Nodes look like: (1 NW), (12 S) Edges look like: (1 NW), (12 SE) :param hexgrid_type: hexgrid.TILE, hexgrid.NODE, hexgrid.EDGE ...
[ "def", "location", "(", "hexgrid_type", ",", "coord", ")", ":", "if", "hexgrid_type", "==", "TILE", ":", "return", "str", "(", "coord", ")", "elif", "hexgrid_type", "==", "NODE", ":", "tile_id", "=", "nearest_tile_to_node", "(", "coord", ")", "dirn", "=", ...
38.269231
0.002941
def _orientation(self, edge, point): """ Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. """ v1 = self.pts[point] - self.pts[edge[0]] v2 = self.pts[edge[1]] - self.pts[edge[0]] c = np.cross(v1, v2) # positive i...
[ "def", "_orientation", "(", "self", ",", "edge", ",", "point", ")", ":", "v1", "=", "self", ".", "pts", "[", "point", "]", "-", "self", ".", "pts", "[", "edge", "[", "0", "]", "]", "v2", "=", "self", ".", "pts", "[", "edge", "[", "1", "]", ...
47.875
0.007692
def userinfo_claims_only_specified_when_access_token_is_issued(authentication_request): """ According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST also use a response_typ...
[ "def", "userinfo_claims_only_specified_when_access_token_is_issued", "(", "authentication_request", ")", ":", "will_issue_access_token", "=", "authentication_request", "[", "'response_type'", "]", "!=", "[", "'id_token'", "]", "contains_userinfo_claims_request", "=", "'claims'", ...
71.8125
0.007732
def color_from_hex(value): """ Takes an HTML hex code and converts it to a proper hue value """ if "#" in value: value = value[1:] try: unhexed = bytes.fromhex(value) except: unhexed = binascii.unhexlify(value) # Fallback for 2.7 compatibility return color_from_r...
[ "def", "color_from_hex", "(", "value", ")", ":", "if", "\"#\"", "in", "value", ":", "value", "=", "value", "[", "1", ":", "]", "try", ":", "unhexed", "=", "bytes", ".", "fromhex", "(", "value", ")", "except", ":", "unhexed", "=", "binascii", ".", "...
31.181818
0.014164
def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/newFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder """ return DXHTTPRequest('/%s/newF...
[ "def", "project_new_folder", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/newFolder'", "%", "object_id", ",", "input_params", ",", "always_retry...
54.857143
0.010256
def info(self, uuid): """ Get info about a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) return self._client.json('kvm.i...
[ "def", "info", "(", "self", ",", "uuid", ")", ":", "args", "=", "{", "'uuid'", ":", "uuid", ",", "}", "self", ".", "_domain_action_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'kvm.info'", ",", "args", ...
26.666667
0.006042
def walk_dn(start_dir, depth=10): ''' Walk down a directory tree. Same as os.walk but allows for a depth limit via depth argument ''' start_depth = len(os.path.split(start_dir)) end_depth = start_depth + depth for root, subdirs, files in os.walk(start_dir): yield root, subdirs, fil...
[ "def", "walk_dn", "(", "start_dir", ",", "depth", "=", "10", ")", ":", "start_depth", "=", "len", "(", "os", ".", "path", ".", "split", "(", "start_dir", ")", ")", "end_depth", "=", "start_depth", "+", "depth", "for", "root", ",", "subdirs", ",", "fi...
27
0.002558
def contains(self, assertion): """ Returns `True` if `assertion` is contained in this `Independencies`-object, otherwise `False`. Parameters ---------- assertion: IndependenceAssertion()-object Examples -------- >>> from pgmpy.independencies impo...
[ "def", "contains", "(", "self", ",", "assertion", ")", ":", "if", "not", "isinstance", "(", "assertion", ",", "IndependenceAssertion", ")", ":", "raise", "TypeError", "(", "\"' in <Independencies()>' requires IndependenceAssertion\"", "+", "\" as left operand, not {0}\"",...
37.888889
0.00572
def handle_compressed_input(inputfq, file_type="fastq"): """Return handles from compressed files according to extension. Check for which fastq input is presented and open a handle accordingly Can read from compressed files (gz, bz2, bgz) or uncompressed Relies on file extensions to recognize compressio...
[ "def", "handle_compressed_input", "(", "inputfq", ",", "file_type", "=", "\"fastq\"", ")", ":", "ut", ".", "check_existance", "(", "inputfq", ")", "if", "inputfq", ".", "endswith", "(", "(", "'.gz'", ",", "'bgz'", ")", ")", ":", "import", "gzip", "logging"...
49
0.00455
def subscribe_list(self, list_id): """ Subscribe to a list :param list_id: list ID number :return: :class:`~responsebot.models.List` object """ return List(tweepy_list_to_json(self._client.subscribe_list(list_id=list_id)))
[ "def", "subscribe_list", "(", "self", ",", "list_id", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "subscribe_list", "(", "list_id", "=", "list_id", ")", ")", ")" ]
33
0.01107
def domain_list(auth=None, **kwargs): ''' List domains CLI Example: .. code-block:: bash salt '*' keystoneng.domain_list ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.list_domains(**kwargs)
[ "def", "domain_list", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "list_domains", "(", "*", "*"...
19.769231
0.003717
def check_reference_label(y, ref_label): ''' :param list y: label :param ref_label: reference label ''' set_y = set(y) if ref_label not in set_y: raise ValueError('There is not reference label in dataset. ' "Reference label: '%s' " 'Label...
[ "def", "check_reference_label", "(", "y", ",", "ref_label", ")", ":", "set_y", "=", "set", "(", "y", ")", "if", "ref_label", "not", "in", "set_y", ":", "raise", "ValueError", "(", "'There is not reference label in dataset. '", "\"Reference label: '%s' \"", "'Labels ...
35
0.002786
def content(self, path=None, overwrite=True, encoding='utf-8'): """ Downloads file to the specified path or as temporary file and reads the file content in memory. Should not be used on very large files. :param path: Path for file download If omitted tmp file will be used. ...
[ "def", "content", "(", "self", ",", "path", "=", "None", ",", "overwrite", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "path", ":", "self", ".", "download", "(", "wait", "=", "True", ",", "path", "=", "path", ",", "overwrite", "="...
43.9
0.00223
def nav_creators(self, article): """ Frontiers method. Given an Article class instance, this is responsible for returning the names for creators of the article. For our purposes, it is sufficient to list only the authors, returning their name, role=aut, and file-as name. ...
[ "def", "nav_creators", "(", "self", ",", "article", ")", ":", "creator_list", "=", "[", "]", "for", "contrib_group", "in", "article", ".", "metadata", ".", "front", ".", "article_meta", ".", "contrib_group", ":", "for", "contrib", "in", "contrib_group", ".",...
44.923077
0.002793
def reset(self): """ Reseting duration for throttling """ if self._call_later_handler is not None: self._call_later_handler.cancel() self._call_later_handler = None self._wait_done_cb()
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "_call_later_handler", "is", "not", "None", ":", "self", ".", "_call_later_handler", ".", "cancel", "(", ")", "self", ".", "_call_later_handler", "=", "None", "self", ".", "_wait_done_cb", "(", ")" ...
38.666667
0.008439
def worker_process(params, channel): """The worker process routines.""" signal(SIGINT, SIG_IGN) if params.initializer is not None: if not run_initializer(params.initializer, params.initargs): os._exit(1) try: for task in worker_get_next_task(channel, params.max_tasks): ...
[ "def", "worker_process", "(", "params", ",", "channel", ")", ":", "signal", "(", "SIGINT", ",", "SIG_IGN", ")", "if", "params", ".", "initializer", "is", "not", "None", ":", "if", "not", "run_initializer", "(", "params", ".", "initializer", ",", "params", ...
36.222222
0.001495
def send_exit_status(self, status): """ Send the exit status of an executed command to the client. (This really only makes sense in server mode.) Many clients expect to get some sort of status code back from an executed command after it completes. @param status...
[ "def", "send_exit_status", "(", "self", ",", "status", ")", ":", "# in many cases, the channel will not still be open here.", "# that's fine.", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "chr", "(", "MSG_CHANNEL_REQUEST", ")", ")", "m", ".", "add_in...
34.619048
0.005355
def update_tax_rate_by_id(cls, tax_rate_id, tax_rate, **kwargs): """Update TaxRate Update attributes of TaxRate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_tax_rate_by_id(tax_rate_i...
[ "def", "update_tax_rate_by_id", "(", "cls", ",", "tax_rate_id", ",", "tax_rate", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "...
44.363636
0.005015
def noun_phrases_as_tokens(text): '''Generate a bag of lists of unnormalized tokens representing noun phrases from ``text``. This is built around python's nltk library for getting Noun Phrases (NPs). This is all documented in the NLTK Book http://www.nltk.org/book/ch03.html and blog posts that cite...
[ "def", "noun_phrases_as_tokens", "(", "text", ")", ":", "## from NLTK Book:", "sentence_re", "=", "r'''(?x) # set flag to allow verbose regexps\n ([A-Z])(\\.[A-Z])+\\.? # abbreviations, e.g. U.S.A.\n | \\w+(-\\w+)* # words with optional internal hyphens\n | ...
33.590164
0.00569
def _annotated_unpack_infer(stmt, context=None): """ Recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements. Returns an iterator which yields tuples in the format ('original node', 'infered node'). """ if isinstance(stm...
[ "def", "_annotated_unpack_infer", "(", "stmt", ",", "context", "=", "None", ")", ":", "if", "isinstance", "(", "stmt", ",", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ")", ")", ":", "for", "elt", "in", "stmt", ".", "elts", ":", "infer...
38.882353
0.001477
def parse_exiobase2(path, charact=True, popvector='exio2'): """ Parse the exiobase 2.2.2 source files for the IOSystem The function parse product by product and industry by industry source file in the coefficient form (A and S). Filenames are hardcoded in the parser - for any other function the code h...
[ "def", "parse_exiobase2", "(", "path", ",", "charact", "=", "True", ",", "popvector", "=", "'exio2'", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normpath", "(", "str", "(", "path", ")", ")", ")", "exio_f...
42.489899
0.000348
def fix_paths(project_data, rel_path, extensions): """ Fix paths for extension list """ norm_func = lambda path : os.path.normpath(os.path.join(rel_path, path)) for key in extensions: if type(project_data[key]) is dict: for k,v in project_data[key].items(): project_data[k...
[ "def", "fix_paths", "(", "project_data", ",", "rel_path", ",", "extensions", ")", ":", "norm_func", "=", "lambda", "path", ":", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "rel_path", ",", "path", ")", ")", "for", "k...
49
0.007286
def _topo_sort(self, forward=True): """ Topological sort. Returns a list of nodes where the successors (based on outgoing and incoming edges selected by the forward parameter) of any given node appear in the sequence after that node. """ topo_list = [] qu...
[ "def", "_topo_sort", "(", "self", ",", "forward", "=", "True", ")", ":", "topo_list", "=", "[", "]", "queue", "=", "deque", "(", ")", "indeg", "=", "{", "}", "# select the operation that will be performed", "if", "forward", ":", "get_edges", "=", "self", "...
30.043478
0.001402
def downsample_completeness_table(comp_table, sample_width=0.1, mmax=None): """ Re-sample the completeness table to a specified sample_width """ new_comp_table = [] for i in range(comp_table.shape[0] - 1): mvals = np.arange(comp_table[i, 1], comp_table[i + 1, 1], d_...
[ "def", "downsample_completeness_table", "(", "comp_table", ",", "sample_width", "=", "0.1", ",", "mmax", "=", "None", ")", ":", "new_comp_table", "=", "[", "]", "for", "i", "in", "range", "(", "comp_table", ".", "shape", "[", "0", "]", "-", "1", ")", "...
45.866667
0.002849
def import_committees_from_legislators(current_term, abbr): """ create committees from legislators that have committee roles """ # for all current legislators for legislator in db.legislators.find({'roles': {'$elemMatch': { 'term': current_term, settings.LEVEL_FIELD: abbr}}}): # for al...
[ "def", "import_committees_from_legislators", "(", "current_term", ",", "abbr", ")", ":", "# for all current legislators", "for", "legislator", "in", "db", ".", "legislators", ".", "find", "(", "{", "'roles'", ":", "{", "'$elemMatch'", ":", "{", "'term'", ":", "c...
43.291667
0.000471
def _process_response(self, response): """Parse response""" forward_raw = False content_type = response.headers['Content-Type'] if content_type != 'application/json': logger.debug("headers: %s", response.headers) # API BUG: text/xml content-type with json payload...
[ "def", "_process_response", "(", "self", ",", "response", ")", ":", "forward_raw", "=", "False", "content_type", "=", "response", ".", "headers", "[", "'Content-Type'", "]", "if", "content_type", "!=", "'application/json'", ":", "logger", ".", "debug", "(", "\...
35.875
0.001357
def to_value(self, variables_mapping=None): """ parse lazy data with evaluated variables mapping. Notice: variables_mapping should not contain any variable or function. """ variables_mapping = variables_mapping or {} args = parse_lazy_data(self._args, variables_mapping) ...
[ "def", "to_value", "(", "self", ",", "variables_mapping", "=", "None", ")", ":", "variables_mapping", "=", "variables_mapping", "or", "{", "}", "args", "=", "parse_lazy_data", "(", "self", ".", "_args", ",", "variables_mapping", ")", "kwargs", "=", "parse_lazy...
53.222222
0.00616
def extent_size(self, units="MiB"): """ Returns the volume group extent size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_vg_get_extent_size(self.handle)...
[ "def", "extent_size", "(", "self", ",", "units", "=", "\"MiB\"", ")", ":", "self", ".", "open", "(", ")", "size", "=", "lvm_vg_get_extent_size", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "size_convert", "(", "size", ","...
30.916667
0.010471
def _get_drug_target_interactions(manager: Optional['bio2bel_drugbank.manager'] = None) -> Mapping[str, List[str]]: """Get a mapping from drugs to their list of gene.""" if manager is None: import bio2bel_drugbank manager = bio2bel_drugbank.Manager() if not manager.is_populated(): m...
[ "def", "_get_drug_target_interactions", "(", "manager", ":", "Optional", "[", "'bio2bel_drugbank.manager'", "]", "=", "None", ")", "->", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", ":", "if", "manager", "is", "None", ":", "import", "bio2bel_dru...
37.5
0.005208
def record(self, pipeline_name, from_study): """ Returns the provenance record for a given pipeline Parameters ---------- pipeline_name : str The name of the pipeline that generated the record from_study : str The name of the study that the pipeli...
[ "def", "record", "(", "self", ",", "pipeline_name", ",", "from_study", ")", ":", "try", ":", "return", "self", ".", "_records", "[", "(", "pipeline_name", ",", "from_study", ")", "]", "except", "KeyError", ":", "found", "=", "[", "]", "for", "sname", "...
38.84375
0.00157
def add_month(t: datetime, n: int=1) -> datetime: """ Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime """ t2 = t for count in range(abs(n)): if n > 0: t2 = datetime(year=t2.year, month=t2....
[ "def", "add_month", "(", "t", ":", "datetime", ",", "n", ":", "int", "=", "1", ")", "->", "datetime", ":", "t2", "=", "t", "for", "count", "in", "range", "(", "abs", "(", "n", ")", ")", ":", "if", "n", ">", "0", ":", "t2", "=", "datetime", ...
33.25
0.00731
def updateCurrentView(self, oldWidget, newWidget): """ Updates the current view widget. :param oldWidget | <QtGui.QWidget> newWidget | <QtGui.QWidget> """ view = projexui.ancestor(newWidget, XView) if view is not None: view.se...
[ "def", "updateCurrentView", "(", "self", ",", "oldWidget", ",", "newWidget", ")", ":", "view", "=", "projexui", ".", "ancestor", "(", "newWidget", ",", "XView", ")", "if", "view", "is", "not", "None", ":", "view", ".", "setCurrent", "(", ")" ]
32.1
0.009091
def submit_async_work(self, work, workunit_parent=None, on_success=None, on_failure=None): """Submit work to be executed in the background. :param work: The work to execute. :param workunit_parent: If specified, work is accounted for under this workunit. :param on_success: If specified, a callable taki...
[ "def", "submit_async_work", "(", "self", ",", "work", ",", "workunit_parent", "=", "None", ",", "on_success", "=", "None", ",", "on_failure", "=", "None", ")", ":", "if", "work", "is", "None", "or", "len", "(", "work", ".", "args_tuples", ")", "==", "0...
52.541667
0.010125
def process_word(word: str, to_lower: bool = False, append_case: Optional[str] = None) -> Tuple[str]: """Converts word to a tuple of symbols, optionally converts it to lowercase and adds capitalization label. Args: word: input word to_lower: whether to lowercase app...
[ "def", "process_word", "(", "word", ":", "str", ",", "to_lower", ":", "bool", "=", "False", ",", "append_case", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Tuple", "[", "str", "]", ":", "if", "all", "(", "x", ".", "isupper", "(", "...
32.058824
0.00089
def createLoadableModuleBuilder(env): """This is a utility function that creates the LoadableModule Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: ld_module = env['BUILDERS']['LoadableModule'] except KeyError: ...
[ "def", "createLoadableModuleBuilder", "(", "env", ")", ":", "try", ":", "ld_module", "=", "env", "[", "'BUILDERS'", "]", "[", "'LoadableModule'", "]", "except", "KeyError", ":", "import", "SCons", ".", "Defaults", "action_list", "=", "[", "SCons", ".", "Defa...
43.708333
0.015858
def check_custom_concurrency(default, forced, logger=None): """ Get the proper concurrency value according to the default one and the one specified by the crawler. :param int default: default tasks concurrency :param forced: concurrency asked by crawler :return: concurrency to u...
[ "def", "check_custom_concurrency", "(", "default", ",", "forced", ",", "logger", "=", "None", ")", ":", "logger", "=", "logger", "or", "LOGGER", "cmc_msg", "=", "'Invalid \"max_concurrent_tasks: '", "if", "not", "isinstance", "(", "forced", ",", "int", ")", ":...
27.666667
0.001294
def _split_str(s, n): """ split string into list of strings by specified number. """ length = len(s) return [s[i:i + n] for i in range(0, length, n)]
[ "def", "_split_str", "(", "s", ",", "n", ")", ":", "length", "=", "len", "(", "s", ")", "return", "[", "s", "[", "i", ":", "i", "+", "n", "]", "for", "i", "in", "range", "(", "0", ",", "length", ",", "n", ")", "]" ]
27.333333
0.005917
def do_loadmacros(parser, token): """ The function taking a parsed tag and returning a LoadMacrosNode object, while also loading the macros into the page. """ try: tag_name, filename = token.split_contents() except ValueError: raise template.TemplateSyntaxError( "'{0}...
[ "def", "do_loadmacros", "(", "parser", ",", "token", ")", ":", "try", ":", "tag_name", ",", "filename", "=", "token", ".", "split_contents", "(", ")", "except", "ValueError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"'{0}' tag requires exactl...
37.705882
0.00076
def insert(self, task, args=[], kwargs={}, delay_seconds=0): """ Insert a task into an existing queue. """ body = { "payload": task.payload(), "queueName": self._queue_name, "groupByTag": True, "tag": task.__class__.__name__ } def cloud_insertion(api): api.insert(b...
[ "def", "insert", "(", "self", ",", "task", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ",", "delay_seconds", "=", "0", ")", ":", "body", "=", "{", "\"payload\"", ":", "task", ".", "payload", "(", ")", ",", "\"queueName\"", ":", "sel...
22
0.008715
def remove_useless_start_nucleotides(self): '''Removes duplicated nucleotides at the start of REF and ALT. But always leaves at least one nucleotide in each of REF and ALT. eg if variant is at position 42, REF=GCTGA, ALT=GCA, then sets position=41, REF=CTGA, ALT=CA. Assumes only ...
[ "def", "remove_useless_start_nucleotides", "(", "self", ")", ":", "if", "len", "(", "self", ".", "REF", ")", "==", "1", "or", "len", "(", "self", ".", "ALT", ")", "!=", "1", ":", "return", "i", "=", "0", "while", "i", "<", "len", "(", "self", "."...
40.176471
0.004292
def expand(self, name): """Expand config for `name` by adding a sub-configuration for every dot-separated collection "below" the given one (or all, if none given). For example, for a database 'mydb' with collections ['spiderman.amazing', 'spiderman.spectacular', 'spiderman2'] ...
[ "def", "expand", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_is_pattern", "(", "name", ")", ":", "expr", "=", "re", ".", "compile", "(", "self", ".", "_pattern_to_regex", "(", "name", ")", ")", "for", "cfg_name", "in", "self", ".", "_d...
43.086957
0.001974
def hset(self, key, value): """Create key/value pair in Redis. Args: key (string): The key to create in Redis. value (any): The value to store in Redis. Returns: (string): The response from Redis. """ return self.r.hset(self.hash, key, value)
[ "def", "hset", "(", "self", ",", "key", ",", "value", ")", ":", "return", "self", ".", "r", ".", "hset", "(", "self", ".", "hash", ",", "key", ",", "value", ")" ]
28.181818
0.00625
def update(self, new_labels, departure_time_backup=None): """ Update the profile with the new labels. Each new label should have the same departure_time. Parameters ---------- new_labels: list[LabelTime] Returns ------- added: bool wh...
[ "def", "update", "(", "self", ",", "new_labels", ",", "departure_time_backup", "=", "None", ")", ":", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "\"Profile is closed, no updates can be made\"", ")", "try", ":", "departure_time", "=", "next", ...
38.609756
0.003081
def save_source(driver, name): """ Save the rendered HTML of the browser. The location of the source can be configured by the environment variable `SAVED_SOURCE_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled...
[ "def", "save_source", "(", "driver", ",", "name", ")", ":", "source", "=", "driver", ".", "page_source", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", ".", "get", "(", "'SAVED_SOURCE_DIR'", ")", ",", "'{name}.html'", ".", ...
34.269231
0.002183
def _load_instr(ctx, name: str, mount: str, *args, **kwargs) -> InstrumentContext: """ Build an instrument in a backwards-compatible way. You should almost certainly not be calling this function from a protocol; if you want to create a...
[ "def", "_load_instr", "(", "ctx", ",", "name", ":", "str", ",", "mount", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "InstrumentContext", ":", "return", "ctx", ".", "load_instrument", "(", "name", ",", "Mount", "[", "mount", "."...
46.833333
0.008726
def integrate_gamma(v, v0, gamma0, q0, q1, theta0): """ internal function to calculate Debye temperature :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param q0: logarithmic derivative of Gruneisen parameter :param ...
[ "def", "integrate_gamma", "(", "v", ",", "v0", ",", "gamma0", ",", "q0", ",", "q1", ",", "theta0", ")", ":", "def", "f_integrand", "(", "v", ")", ":", "gamma", "=", "gamma0", "*", "np", ".", "exp", "(", "q0", "/", "q1", "*", "(", "(", "v", "/...
34.944444
0.001548
def _compute_radii(self): """Generate RBF radii""" # use supplied radii if present radii = self._get_user_components('radii') # compute radii if (radii is None): centers = self.components_['centers'] n_centers = centers.shape[0] max_dist = n...
[ "def", "_compute_radii", "(", "self", ")", ":", "# use supplied radii if present", "radii", "=", "self", ".", "_get_user_components", "(", "'radii'", ")", "# compute radii", "if", "(", "radii", "is", "None", ")", ":", "centers", "=", "self", ".", "components_", ...
30.333333
0.004264
def writeToCheckpoint(self, checkpointDir): """Serializes model using capnproto and writes data to ``checkpointDir``""" proto = self.getSchema().new_message() self.write(proto) checkpointPath = self._getModelCheckpointFilePath(checkpointDir) # Clean up old saved state, if any if os.path.exist...
[ "def", "writeToCheckpoint", "(", "self", ",", "checkpointDir", ")", ":", "proto", "=", "self", ".", "getSchema", "(", ")", ".", "new_message", "(", ")", "self", ".", "write", "(", "proto", ")", "checkpointPath", "=", "self", ".", "_getModelCheckpointFilePath...
39.037037
0.010185
def with_dependencies(cls, model_expr, dependency_model, **init_kwargs): """ Initiate a model whose components depend on another model. For example:: >>> x, y, z = variables('x, y, z') >>> dependency_model = Model({y: x**2}) >>> model_dict = {z: y**2} >>>...
[ "def", "with_dependencies", "(", "cls", ",", "model_expr", ",", "dependency_model", ",", "*", "*", "init_kwargs", ")", ":", "model", "=", "cls", "(", "model_expr", ",", "*", "*", "init_kwargs", ")", "# Initiate model instance.", "if", "any", "(", "var", "in"...
54.795918
0.001464
def cmd(send, msg, args): """Chooses between multiple choices. Syntax: {command} <object> or <object> (or <object>...) """ if not msg: send("Choose what?") return choices = msg.split(' or ') action = [ 'draws a slip of paper from a hat and gets...', 'says eenie, menie, ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Choose what?\"", ")", "return", "choices", "=", "msg", ".", "split", "(", "' or '", ")", "action", "=", "[", "'draws a slip of paper from a hat and gets....
37.8
0.005164
def _merge_apis(collector): """ Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API definition wins because that conveys clear intent that the API is backed by a function. This method will merge two such list of Apis with the right or...
[ "def", "_merge_apis", "(", "collector", ")", ":", "implicit_apis", "=", "[", "]", "explicit_apis", "=", "[", "]", "# Store implicit and explicit APIs separately in order to merge them later in the correct order", "# Implicit APIs are defined on a resource with logicalID ServerlessRestA...
47.857143
0.00585
def update(ctx, name, description, tags): """Update build. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon build -b 2 update --description="new description for my build" ``` """ user, project_name, _build = get_build_or_local(ctx.obj.get('project')...
[ "def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get",...
28
0.002655
def spancount(args): """ %prog spancount list_of_fillingMetrics Count span support for each gap. A file with paths of all fillingMetrics can be built with Linux `find`. $ (find assembly -name "fillingMetrics.json" -print > list_of_fillMetrics 2> /dev/null &) """ import json p = Op...
[ "def", "spancount", "(", "args", ")", ":", "import", "json", "p", "=", "OptionParser", "(", "spancount", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ...
24.84375
0.003632
def get_random_password(self, length=32, chars=None): """Helper function that gets a random password. :param length: The length of the random password. :type length: int :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits. :type ch...
[ "def", "get_random_password", "(", "self", ",", "length", "=", "32", ",", "chars", "=", "None", ")", ":", "if", "chars", "is", "None", ":", "chars", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "return", "''", ".", "join", "(", ...
43.727273
0.00611
def _load_rsa_private_key(pem): """PEM encoded PKCS#8 private key -> rsa.PrivateKey.""" # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support # them natively. Do some ASN unwrapping to extract naked RSA key # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt. # Al...
[ "def", "_load_rsa_private_key", "(", "pem", ")", ":", "# ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support", "# them natively. Do some ASN unwrapping to extract naked RSA key", "# (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.", "# Also http://superuser.co...
53.375
0.001151
def __write_docker_compose(path, docker_compose, already_existed): ''' Write docker-compose to a path in order to use it with docker-compose ( config check ) :param path: docker_compose contains the docker-compose file :return: ''' if path.lower().endswith(('.yml', '.yaml')): ...
[ "def", "__write_docker_compose", "(", "path", ",", "docker_compose", ",", "already_existed", ")", ":", "if", "path", ".", "lower", "(", ")", ".", "endswith", "(", "(", "'.yml'", ",", "'.yaml'", ")", ")", ":", "file_path", "=", "path", "dir_name", "=", "o...
31.939394
0.000921
def associate_keys(user_dict, client): """ This whole function is black magic, had to however cause of the way we keep key-machine association """ added_keys = user_dict['keypairs'] print ">>>Updating Keys-Machines association" for key in added_keys: machines = added_keys[key]['machines...
[ "def", "associate_keys", "(", "user_dict", ",", "client", ")", ":", "added_keys", "=", "user_dict", "[", "'keypairs'", "]", "print", "\">>>Updating Keys-Machines association\"", "for", "key", "in", "added_keys", ":", "machines", "=", "added_keys", "[", "key", "]",...
39.151515
0.002266
def delete_changed(self, settings, key, user_data): """If the gconf var compat_delete be changed, this method will be called and will change the binding configuration in all terminals open. """ for i in self.guake.notebook_manager.iter_terminals(): i.set_delete_bindin...
[ "def", "delete_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "i", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "i", ".", "set_delete_binding", "(", "self", ".", "getEr...
51.857143
0.00813
def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None): """ Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finally load the snapsh...
[ "def", "load", "(", "self", ",", "dump_fn", "=", "''", ",", "prep_only", "=", "0", ",", "force_upload", "=", "0", ",", "from_local", "=", "0", ",", "name", "=", "None", ",", "site", "=", "None", ",", "dest_dir", "=", "None", ")", ":", "r", "=", ...
39.65
0.004308
def get_and_alter(self, function): """ Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a ...
[ "def", "get_and_alter", "(", "self", ",", "function", ")", ":", "check_not_none", "(", "function", ",", "\"function can't be None\"", ")", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_get_and_alter_codec", ",", "function", "=", "self", ".", "_to_d...
54.461538
0.009722
def parse_eep(self, rorg_func=None, rorg_type=None, direction=None, command=None): ''' Parse EEP based on FUNC and TYPE ''' # set EEP profile, if demanded if rorg_func is not None and rorg_type is not None: self.select_eep(rorg_func, rorg_type, direction, command) # parse dat...
[ "def", "parse_eep", "(", "self", ",", "rorg_func", "=", "None", ",", "rorg_type", "=", "None", ",", "direction", "=", "None", ",", "command", "=", "None", ")", ":", "# set EEP profile, if demanded", "if", "rorg_func", "is", "not", "None", "and", "rorg_type",...
52.666667
0.008299
def containing_simplex_and_bcc(self, lons, lats): """ Returns the simplices containing (lons,lats) and the local barycentric, normalised coordinates. Parameters ---------- lons : 1D array of longitudinal coordinates in radians lats : 1D array of latitudinal coo...
[ "def", "containing_simplex_and_bcc", "(", "self", ",", "lons", ",", "lats", ")", ":", "pts", "=", "np", ".", "array", "(", "lonlat2xyz", "(", "lons", ",", "lats", ")", ")", ".", "T", "tri", "=", "np", ".", "empty", "(", "(", "pts", ".", "shape", ...
31.378378
0.007519
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
[ "def", "_guess_name", "(", "desc", ",", "taken", "=", "None", ")", ":", "taken", "=", "taken", "or", "[", "]", "name", "=", "\"\"", "# Try to find the shortest name based on the given description.", "for", "word", "in", "desc", ".", "split", "(", ")", ":", "...
29.277778
0.001838
def click_window(self, window, button): """ Send a click for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is ...
[ "def", "click_window", "(", "self", ",", "window", ",", "button", ")", ":", "_libxdo", ".", "xdo_click_window", "(", "self", ".", "_xdo", ",", "window", ",", "button", ")" ]
39.181818
0.004535
def hasKey(self, key, notNone=False): '''Return entries where the key is present. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name...
[ "def", "hasKey", "(", "self", ",", "key", ",", "notNone", "=", "False", ")", ":", "result", "=", "[", "]", "result_tracker", "=", "[", "]", "for", "counter", ",", "row", "in", "enumerate", "(", "self", ".", "table", ")", ":", "(", "target", ",", ...
39.090909
0.006807
def perform_create(self, serializer): """Create a resource.""" with transaction.atomic(): instance = serializer.save() # Assign all permissions to the object contributor. assign_contributor_permissions(instance)
[ "def", "perform_create", "(", "self", ",", "serializer", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "instance", "=", "serializer", ".", "save", "(", ")", "# Assign all permissions to the object contributor.", "assign_contributor_permissions", "(", ...
36.857143
0.007576
def force_leave(self, node): """Force a failed gossip member into the left state. https://www.nomadproject.io/docs/http/agent-force-leave.html returns: 200 status code raises: - nomad.api.exceptions.BaseNomadException - nomad.api.exceptions.URLNo...
[ "def", "force_leave", "(", "self", ",", "node", ")", ":", "params", "=", "{", "\"node\"", ":", "node", "}", "return", "self", ".", "request", "(", "\"force-leave\"", ",", "params", "=", "params", ",", "method", "=", "\"post\"", ")", ".", "status_code" ]
38.166667
0.006397
def parse_url_to_dict(url): """Parse a url and return a dict with keys for all of the parts. The urlparse function() returns a wacky combination of a namedtuple with properties. """ p = urlparse(url) return { 'scheme': p.scheme, 'netloc': p.netloc, 'path': p.path, ...
[ "def", "parse_url_to_dict", "(", "url", ")", ":", "p", "=", "urlparse", "(", "url", ")", "return", "{", "'scheme'", ":", "p", ".", "scheme", ",", "'netloc'", ":", "p", ".", "netloc", ",", "'path'", ":", "p", ".", "path", ",", "'params'", ":", "p", ...
24.095238
0.001901
def train_agent(self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Trains the specified agent. Operation <response: ``google.protobuf.Em...
[ "def", "train_agent", "(", "self", ",", "parent", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata...
42.442857
0.002632
def create_exchange(self): """ Creates MQ exchange for this channel Needs to be defined only once. """ mq_channel = self._connect_mq() mq_channel.exchange_declare(exchange=self.code_name, exchange_type='fanout', ...
[ "def", "create_exchange", "(", "self", ")", ":", "mq_channel", "=", "self", ".", "_connect_mq", "(", ")", "mq_channel", ".", "exchange_declare", "(", "exchange", "=", "self", ".", "code_name", ",", "exchange_type", "=", "'fanout'", ",", "durable", "=", "True...
37.444444
0.005797
def ls(self, path, offset=None, amount=None): """ Return list of files/directories. Each item is a dict. Keys: 'path', 'creationdate', 'displayname', 'length', 'lastmodified', 'isDir'. """ def parseContent(content): result = [] root = ET.fromstri...
[ "def", "ls", "(", "self", ",", "path", ",", "offset", "=", "None", ",", "amount", "=", "None", ")", ":", "def", "parseContent", "(", "content", ")", ":", "result", "=", "[", "]", "root", "=", "ET", ".", "fromstring", "(", "content", ")", "for", "...
58.09375
0.008466
def _post_run_hook(self, runtime): ''' generates a report showing nine slices, three per axis, of an arbitrary volume of `in_files`, with the resulting segmentation overlaid ''' outputs = self.aggregate_outputs(runtime=runtime) self._melodic_dir = outputs.out_dir NIWORKF...
[ "def", "_post_run_hook", "(", "self", ",", "runtime", ")", ":", "outputs", "=", "self", ".", "aggregate_outputs", "(", "runtime", "=", "runtime", ")", "self", ".", "_melodic_dir", "=", "outputs", ".", "out_dir", "NIWORKFLOWS_LOG", ".", "info", "(", "'Generat...
42.1
0.004651
def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.from_float( value).to_integral_value(decimal.ROUND_HALF_EVEN))
[ "def", "intround", "(", "value", ")", ":", "return", "int", "(", "decimal", ".", "Decimal", ".", "from_float", "(", "value", ")", ".", "to_integral_value", "(", "decimal", ".", "ROUND_HALF_EVEN", ")", ")" ]
30.714286
0.004525
def logout(self, client_id, return_to, federated=False): """Logout Use this endpoint to logout a user. If you want to navigate the user to a specific URL after the logout, set that URL at the returnTo parameter. The URL should be included in any the appropriate Allowed Logout URLs list:...
[ "def", "logout", "(", "self", ",", "client_id", ",", "return_to", ",", "federated", "=", "False", ")", ":", "return_to", "=", "quote_plus", "(", "return_to", ")", "if", "federated", "is", "True", ":", "return", "self", ".", "get", "(", "'https://{}/v2/logo...
42.285714
0.004955
def respond(self, request, view, newsitems, extra_context={}): """A helper that takes some news items and returns an HttpResponse""" context = self.get_context(request, view=view) context.update(self.paginate_newsitems(request, newsitems)) context.update(extra_context) template =...
[ "def", "respond", "(", "self", ",", "request", ",", "view", ",", "newsitems", ",", "extra_context", "=", "{", "}", ")", ":", "context", "=", "self", ".", "get_context", "(", "request", ",", "view", "=", "view", ")", "context", ".", "update", "(", "se...
58.857143
0.004785
def parse_assessor_content(experiment_config): '''Validate whether assessor in experiment_config is valid''' if experiment_config.get('assessor'): if experiment_config['assessor'].get('builtinAssessorName'): experiment_config['assessor']['className'] = experiment_config['assessor']['builtinA...
[ "def", "parse_assessor_content", "(", "experiment_config", ")", ":", "if", "experiment_config", ".", "get", "(", "'assessor'", ")", ":", "if", "experiment_config", "[", "'assessor'", "]", ".", "get", "(", "'builtinAssessorName'", ")", ":", "experiment_config", "["...
58.428571
0.004819
def ekf_ok(self): """ ``True`` if the EKF status is considered acceptable, ``False`` otherwise (``boolean``). """ # legacy check for dronekit-python for solo # use same check that ArduCopter::system.pde::position_ok() is using if self.armed: return self._ekf_p...
[ "def", "ekf_ok", "(", "self", ")", ":", "# legacy check for dronekit-python for solo", "# use same check that ArduCopter::system.pde::position_ok() is using", "if", "self", ".", "armed", ":", "return", "self", ".", "_ekf_poshorizabs", "and", "not", "self", ".", "_ekf_constp...
43.6
0.006742
def clean(self): """ Remove empty values """ for key, value in self.values.copy().items(): if value is None: del self.values[key]
[ "def", "clean", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "values", ".", "copy", "(", ")", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "del", "self", ".", "values", "[", "key", "]" ]
26.142857
0.010582
def get_by_wiki(citiao): ''' Get the wiki record by title. ''' q_res = TabWiki.select().where(TabWiki.title == citiao) the_count = q_res.count() if the_count == 0 or the_count > 1: return None else: MWiki.update_view_count(citiao) ...
[ "def", "get_by_wiki", "(", "citiao", ")", ":", "q_res", "=", "TabWiki", ".", "select", "(", ")", ".", "where", "(", "TabWiki", ".", "title", "==", "citiao", ")", "the_count", "=", "q_res", ".", "count", "(", ")", "if", "the_count", "==", "0", "or", ...
30.090909
0.005865
def exists(instance_id=None, name=None, tags=None, region=None, key=None, keyid=None, profile=None, in_states=None, filters=None): ''' Given an instance id, check to see if the given instance id exists. Returns True if the given instance with the given id, name, or tags exists; otherwise, Fa...
[ "def", "exists", "(", "instance_id", "=", "None", ",", "name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "in_states", "=", "None", ",", ...
34.869565
0.002427
def save(self, designName=""): # type: (ASaveDesign) -> None """Save the current design to file""" self.try_stateful_function( ss.SAVING, ss.READY, self.do_save, designName)
[ "def", "save", "(", "self", ",", "designName", "=", "\"\"", ")", ":", "# type: (ASaveDesign) -> None", "self", ".", "try_stateful_function", "(", "ss", ".", "SAVING", ",", "ss", ".", "READY", ",", "self", ".", "do_save", ",", "designName", ")" ]
41
0.014354
def addSlider2D(sliderfunc, xmin, xmax, value=None, pos=4, s=.04, title='', c=None, showValue=True): """Add a slider widget which can call an external custom function. :param sliderfunc: external function to be called by the widget :param float xmin: lower value :param float xmax: upp...
[ "def", "addSlider2D", "(", "sliderfunc", ",", "xmin", ",", "xmax", ",", "value", "=", "None", ",", "pos", "=", "4", ",", "s", "=", ".04", ",", "title", "=", "''", ",", "c", "=", "None", ",", "showValue", "=", "True", ")", ":", "vp", "=", "setti...
42.598214
0.000615
def err(r): """ Input: { return - return code error - error text } Output: Nothing; quits program """ import sys rc=r['return'] re=r['error'] out('Error: '+re) sys.exit(rc)
[ "def", "err", "(", "r", ")", ":", "import", "sys", "rc", "=", "r", "[", "'return'", "]", "re", "=", "r", "[", "'error'", "]", "out", "(", "'Error: '", "+", "re", ")", "sys", ".", "exit", "(", "rc", ")" ]
13.941176
0.011858
def get_or_create_instance(self, id=None, application=None, revision=None, environment=None, name=None, parameters=None, submodules=None, destroyInterval=None): """ Get instance by id or name. If not found: create with given parameters """ try: ...
[ "def", "get_or_create_instance", "(", "self", ",", "id", "=", "None", ",", "application", "=", "None", ",", "revision", "=", "None", ",", "environment", "=", "None", ",", "name", "=", "None", ",", "parameters", "=", "None", ",", "submodules", "=", "None"...
51.076923
0.007396