text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_activity_lookup_session_for_objective_bank(self, objective_bank_id, proxy, *args, **kwargs): """Gets the ``OsidSession`` associated with the activity lookup service for the given objective bank. :param objective_bank_id: the ``Id`` of the objective bank :type objective_bank_id: ``osid.i...
[ "def", "get_activity_lookup_session_for_objective_bank", "(", "self", ",", "objective_bank_id", ",", "proxy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "objective_bank_id", ":", "raise", "NullArgument", "if", "not", "self", ".", "supports...
48.451613
0.005222
def __add_parameter(self, param, path_parameters, params): """Adds all parameters in a field to a method parameters descriptor. Simple fields will only have one parameter, but a message field 'x' that corresponds to a message class with fields 'y' and 'z' will result in parameters 'x.y' and 'x.z', for ...
[ "def", "__add_parameter", "(", "self", ",", "param", ",", "path_parameters", ",", "params", ")", ":", "# If this is a simple field, just build the descriptor and append it.", "# Otherwise, build a schema and assign it to this descriptor", "descriptor", "=", "None", "if", "not", ...
43.846154
0.006293
def read_cs_raw_symmetrized_tensors(self): """ Parse the matrix form of NMR tensor before corrected to table. Returns: nsymmetrized tensors list in the order of atoms. """ header_pattern = r"\s+-{50,}\s+" \ r"\s+Absolute Chemical Shift tensors\s+...
[ "def", "read_cs_raw_symmetrized_tensors", "(", "self", ")", ":", "header_pattern", "=", "r\"\\s+-{50,}\\s+\"", "r\"\\s+Absolute Chemical Shift tensors\\s+\"", "r\"\\s+-{50,}$\"", "first_part_pattern", "=", "r\"\\s+UNSYMMETRIZED TENSORS\\s+$\"", "row_pattern", "=", "r\"\\s+\"", ".",...
47.5
0.001965
def zset_example(): """ Example sorted set pagination. """ from uuid import uuid4 from redis import StrictRedis from zato.redis_paginator import ZSetPaginator conn = StrictRedis() key = 'paginator:{}'.format(uuid4().hex) # 97-114 is 'a' to 'r' in ASCII for x in range(1, 18)...
[ "def", "zset_example", "(", ")", ":", "from", "uuid", "import", "uuid4", "from", "redis", "import", "StrictRedis", "from", "zato", ".", "redis_paginator", "import", "ZSetPaginator", "conn", "=", "StrictRedis", "(", ")", "key", "=", "'paginator:{}'", ".", "form...
25.4
0.013657
def detach(gandi, resource, background, force): """Detach an ip from it's currently attached vm. resource can be an ip id or ip. """ if not force: proceed = click.confirm('Are you sure you want to detach ip %s?' % resource) if not proceed: ret...
[ "def", "detach", "(", "gandi", ",", "resource", ",", "background", ",", "force", ")", ":", "if", "not", "force", ":", "proceed", "=", "click", ".", "confirm", "(", "'Are you sure you want to detach ip %s?'", "%", "resource", ")", "if", "not", "proceed", ":",...
30.75
0.002632
def purge_data(self, which_sites=None, never_delete=False): """ Remove uploaded files, postgres db, solr index, venv """ # Default to the set of all sites if not exists(self.datadir + '/.version'): format_version = 1 else: with open(self.datadir + ...
[ "def", "purge_data", "(", "self", ",", "which_sites", "=", "None", ",", "never_delete", "=", "False", ")", ":", "# Default to the set of all sites", "if", "not", "exists", "(", "self", ".", "datadir", "+", "'/.version'", ")", ":", "format_version", "=", "1", ...
38.471429
0.00181
def get_host(self, retry_count=3): """ The function for retrieving host information for an IP address. Args: retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3...
[ "def", "get_host", "(", "self", ",", "retry_count", "=", "3", ")", ":", "try", ":", "default_timeout_set", "=", "False", "if", "not", "socket", ".", "getdefaulttimeout", "(", ")", ":", "socket", ".", "setdefaulttimeout", "(", "self", ".", "timeout", ")", ...
30.672131
0.001554
def getEncodableAttributes(self, obj, **kwargs): """ Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}. """ attrs = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) if not self.exclude_sa_key: # primary_key_from_inst...
[ "def", "getEncodableAttributes", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "pyamf", ".", "ClassAlias", ".", "getEncodableAttributes", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", "if", "not", "self", ".", "excl...
34.318182
0.002577
def gcs(line, cell=None): """Implements the gcs cell magic for ipython notebooks. Args: line: the contents of the gcs line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser(prog='%gcs', description=""" Execute various Google Cloud Storage related op...
[ "def", "gcs", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%gcs'", ",", "description", "=", "\"\"\"\nExecute various Google Cloud Storage rela...
55.116883
0.015046
def create_healthcheck(ip_addr=None, fqdn=None, region=None, key=None, keyid=None, profile=None, port=53, hc_type='TCP', resource_path='', string_match=None, request_interval=30, failure_threshold=3, retry_on_errors=True, error_retries=5): ''' Create a Route53 healthc...
[ "def", "create_healthcheck", "(", "ip_addr", "=", "None", ",", "fqdn", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "port", "=", "53", ",", "hc_type", "=", "'TCP'", "...
30.96
0.004695
def _process_requirements(requirements, cmd, cwd, saltenv, user): ''' Process the requirements argument ''' cleanup_requirements = [] if requirements is not None: if isinstance(requirements, six.string_types): requirements = [r.strip() for r in requirements.split(',')] e...
[ "def", "_process_requirements", "(", "requirements", ",", "cmd", ",", "cwd", ",", "saltenv", ",", "user", ")", ":", "cleanup_requirements", "=", "[", "]", "if", "requirements", "is", "not", "None", ":", "if", "isinstance", "(", "requirements", ",", "six", ...
37.607477
0.000969
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]: """ Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n`` """ for i in range(0, len(l), n): yield l[i:i + n]
[ "def", "chunks", "(", "l", ":", "List", "[", "Any", "]", ",", "n", ":", "int", ")", "->", "Iterable", "[", "List", "[", "Any", "]", "]", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", ":", "yield", "l"...
19.928571
0.006849
def _start_loop(self): """Starts main event handler loop, run in handler thread t.""" # Create our main loop, get our bus, and add the signal handler loop = GObject.MainLoop() bus = SystemBus() manager = bus.get(".NetworkManager") manager.onPropertiesChanged = self._vpn_s...
[ "def", "_start_loop", "(", "self", ")", ":", "# Create our main loop, get our bus, and add the signal handler", "loop", "=", "GObject", ".", "MainLoop", "(", ")", "bus", "=", "SystemBus", "(", ")", "manager", "=", "bus", ".", "get", "(", "\".NetworkManager\"", ")"...
36.7
0.005319
def set_version(version): """Set version.""" global UNIVERSION global UNIVERSION_INFO if version is None: version = unicodedata.unidata_version UNIVERSION = version UNIVERSION_INFO = tuple([int(x) for x in UNIVERSION.split('.')])
[ "def", "set_version", "(", "version", ")", ":", "global", "UNIVERSION", "global", "UNIVERSION_INFO", "if", "version", "is", "None", ":", "version", "=", "unicodedata", ".", "unidata_version", "UNIVERSION", "=", "version", "UNIVERSION_INFO", "=", "tuple", "(", "[...
23.090909
0.003788
def get_callable_name(c): """ Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode """ if hasattr(c, 'name'): return six.text_type(c.name) elif hasattr(c, '__name__'): return six.text_type(c.__name__) ...
[ "def", "get_callable_name", "(", "c", ")", ":", "if", "hasattr", "(", "c", ",", "'name'", ")", ":", "return", "six", ".", "text_type", "(", "c", ".", "name", ")", "elif", "hasattr", "(", "c", ",", "'__name__'", ")", ":", "return", "six", ".", "text...
27.461538
0.00271
def get_template_for_path(path, use_cache=True): ''' Convenience method that retrieves a template given a direct path to it. ''' dmp = apps.get_app_config('django_mako_plus') app_path, template_name = os.path.split(path) return dmp.engine.get_template_loader_for_path(app_path, use_cache=use_cach...
[ "def", "get_template_for_path", "(", "path", ",", "use_cache", "=", "True", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "app_path", ",", "template_name", "=", "os", ".", "path", ".", "split", "(", "path", ")", "retu...
49.142857
0.005714
def exception(self, timeout=None): """If the operation raised an exception, return the `Exception` object. Otherwise returns None. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is do...
[ "def", "exception", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_clear_tb_log", "(", ")", "if", "self", ".", "_exc_info", "is", "not", "None", ":", "return", "self", ".", "_exc_info", "[", "1", "]", "else", ":", "self", ".", "...
37.857143
0.003683
def make(self): """ Creates this directory and any of the missing directories in the path. Any errors that may occur are eaten. """ try: if not self.exists: logger.info("Creating %s" % self.path) os.makedirs(self.path) except os...
[ "def", "make", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "exists", ":", "logger", ".", "info", "(", "\"Creating %s\"", "%", "self", ".", "path", ")", "os", ".", "makedirs", "(", "self", ".", "path", ")", "except", "os", ".", "e...
29.416667
0.005495
def get_dataset_meta(label): """Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be do...
[ "def", "get_dataset_meta", "(", "label", ")", ":", "data_url", "=", "data_urls", "[", "label", "]", "if", "type", "(", "data_url", ")", "==", "str", ":", "# back compatibility", "data_url", "=", "[", "data_url", "]", "if", "type", "(", "data_url", ")", "...
41.75
0.004684
def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ with self.__index_cache_lock...
[ "def", "_purge_index", "(", "self", ",", "database_name", ",", "collection_name", "=", "None", ",", "index_name", "=", "None", ")", ":", "with", "self", ".", "__index_cache_lock", ":", "if", "not", "database_name", "in", "self", ".", "__index_cache", ":", "r...
35.44
0.007692
def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: ...
[ "def", "delete_beacon", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_get_beacons", "(", "include_opts", "=", "False", ")", ":", "comment", "=", "'Cannot delete beacon item {0}, '", "'it is configured in pillar.'", ".", "format", "(", "n...
38.25
0.002125
def shrink(self, fraction=0.85): """Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,...
[ "def", "shrink", "(", "self", ",", "fraction", "=", "0.85", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "shrink", "=", "vtk", ".", "vtkShrinkPolyData", "(", ")", "shrink", ".", "SetInputData", "(", "poly", ")", "shrink", ".", "S...
32.157895
0.004769
def search(self, s, stype=1, offset=0, total='true', limit=60): """get songs list from search keywords""" action = uri + '/search/get' data = { 's': s, 'type': stype, 'offset': offset, 'total': total, 'limit': 60 } resp ...
[ "def", "search", "(", "self", ",", "s", ",", "stype", "=", "1", ",", "offset", "=", "0", ",", "total", "=", "'true'", ",", "limit", "=", "60", ")", ":", "action", "=", "uri", "+", "'/search/get'", "data", "=", "{", "'s'", ":", "s", ",", "'type'...
31.142857
0.004454
def rename_event_type(self, name, new_name): """Rename event type.""" if name not in self.event_types: lg.info('Event type ' + name + ' was not found.') events = self.rater.find('events') for e in list(events): if e.get('type') == name: e.set('t...
[ "def", "rename_event_type", "(", "self", ",", "name", ",", "new_name", ")", ":", "if", "name", "not", "in", "self", ".", "event_types", ":", "lg", ".", "info", "(", "'Event type '", "+", "name", "+", "' was not found.'", ")", "events", "=", "self", ".", ...
26.461538
0.005618
def get_structure_by_formula(self, formula, **kwargs): """ Queries the COD for structures by formula. Requires mysql executable to be in the path. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure...
[ "def", "get_structure_by_formula", "(", "self", ",", "formula", ",", "*", "*", "kwargs", ")", ":", "structures", "=", "[", "]", "sql", "=", "'select file, sg from data where formula=\"- %s -\"'", "%", "Composition", "(", "formula", ")", ".", "hill_formula", "text"...
38.617647
0.002972
def _cgc_extended_application_handler(self, cfg, irsb, irsb_addr, stmt_idx, data_addr, max_size): # pylint:disable=unused-argument """ Identifies the extended application (a PDF file) associated with the CGC binary. :param angr.analyses.CFG cfg: The control flow graph. :param pyvex.IRS...
[ "def", "_cgc_extended_application_handler", "(", "self", ",", "cfg", ",", "irsb", ",", "irsb_addr", ",", "stmt_idx", ",", "data_addr", ",", "max_size", ")", ":", "# pylint:disable=unused-argument", "if", "max_size", "<", "100", ":", "return", "None", ",", "None"...
33.512195
0.004243
def _apply_to_data(data, func, unpack_dict=False): """Apply a function to data, trying to unpack different data types. """ apply_ = partial(_apply_to_data, func=func, unpack_dict=unpack_dict) if isinstance(data, dict): if unpack_dict: return [apply_(v) for v in data.values()] ...
[ "def", "_apply_to_data", "(", "data", ",", "func", ",", "unpack_dict", "=", "False", ")", ":", "apply_", "=", "partial", "(", "_apply_to_data", ",", "func", "=", "func", ",", "unpack_dict", "=", "unpack_dict", ")", "if", "isinstance", "(", "data", ",", "...
28.55
0.001695
def dedupe_and_sort(sequence, first=None, last=None): """ De-dupe and partially sort a sequence. The `first` argument should contain all the items that might appear in `sequence` and for which the order (relative to each other) is important. The `last` argument is the same, but matching items will...
[ "def", "dedupe_and_sort", "(", "sequence", ",", "first", "=", "None", ",", "last", "=", "None", ")", ":", "first", "=", "first", "or", "[", "]", "last", "=", "last", "or", "[", "]", "# Add items that should be sorted first.", "new_sequence", "=", "[", "i",...
38.75
0.000787
def digest_size(self): "Returns the size (in bytes) of the resulting digest." if getattr(self, '_fobj', None) is not None: return self._fobj.digest_size else: return hashlib.new(self._algorithms[-1]).digest_size
[ "def", "digest_size", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_fobj'", ",", "None", ")", "is", "not", "None", ":", "return", "self", ".", "_fobj", ".", "digest_size", "else", ":", "return", "hashlib", ".", "new", "(", "self", ".",...
42.333333
0.007722
def _collate(self, batch): """ Puts each data field into a tensor. :param batch: The input data batch. :type batch: list of (features, feature_weights) pair :return: Preprocessed data. :rtype: list of torch.Tensor with torch.Tensor (Optional) """ Y_batch...
[ "def", "_collate", "(", "self", ",", "batch", ")", ":", "Y_batch", "=", "None", "if", "isinstance", "(", "batch", "[", "0", "]", ",", "tuple", ")", ":", "batch", ",", "Y_batch", "=", "list", "(", "zip", "(", "*", "batch", ")", ")", "Y_batch", "="...
29.62963
0.002421
def parse(cls, version_string): """Parses a ``version_string`` and returns a :py:class:`~Version` object. """ match = RE.match(version_string) if match: major_str, minor_str, patch_str, postrelease_alpha, \ postrelease_digit, prerelease_str, build_meta...
[ "def", "parse", "(", "cls", ",", "version_string", ")", ":", "match", "=", "RE", ".", "match", "(", "version_string", ")", "if", "match", ":", "major_str", ",", "minor_str", ",", "patch_str", ",", "postrelease_alpha", ",", "postrelease_digit", ",", "prerelea...
30.355556
0.001418
def certify_set( value, certifier=None, min_len=None, max_len=None, include_collections=False, required=True, ): """ Certifier for a set. :param set value: The set to be certified. :param func certifier: A function to be called on each value in the list to check that it is valid...
[ "def", "certify_set", "(", "value", ",", "certifier", "=", "None", ",", "min_len", "=", "None", ",", "max_len", "=", "None", ",", "include_collections", "=", "False", ",", "required", "=", "True", ",", ")", ":", "certify_bool", "(", "include_collections", ...
31.447368
0.00487
def _jinja_sub(self, st): """Create a Jina template engine, then perform substitutions on a string""" if isinstance(st, string_types): from jinja2 import Template try: for i in range(5): # Only do 5 recursive substitutions. st = Template(st)...
[ "def", "_jinja_sub", "(", "self", ",", "st", ")", ":", "if", "isinstance", "(", "st", ",", "string_types", ")", ":", "from", "jinja2", "import", "Template", "try", ":", "for", "i", "in", "range", "(", "5", ")", ":", "# Only do 5 recursive substitutions.", ...
35.444444
0.007634
def set_params(self, **params): """ add/update solr query parameters """ if self._solr_locked: raise Exception("Query already executed, no changes can be made." "%s %s" % (self._solr_query, self._solr_params) ) s...
[ "def", "set_params", "(", "self", ",", "*", "*", "params", ")", ":", "if", "self", ".", "_solr_locked", ":", "raise", "Exception", "(", "\"Query already executed, no changes can be made.\"", "\"%s %s\"", "%", "(", "self", ".", "_solr_query", ",", "self", ".", ...
38.111111
0.005698
def ConvertToTemplate(self,visibility,description=None,password=None): """Converts existing server to a template. visibility is one of private or shared. >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').ConvertToTemplate("private","my template") 0 """ if visibility not in...
[ "def", "ConvertToTemplate", "(", "self", ",", "visibility", ",", "description", "=", "None", ",", "password", "=", "None", ")", ":", "if", "visibility", "not", "in", "(", "'private'", ",", "'shared'", ")", ":", "raise", "(", "clc", ".", "CLCException", "...
41.1
0.041617
def _landsat_get_mtl(sceneid): """ Get Landsat-8 MTL metadata. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. Returns ------- out : dict returns a JSON like object with the metadata. ""...
[ "def", "_landsat_get_mtl", "(", "sceneid", ")", ":", "scene_params", "=", "_landsat_parse_scene_id", "(", "sceneid", ")", "meta_file", "=", "\"http://landsat-pds.s3.amazonaws.com/{}_MTL.txt\"", ".", "format", "(", "scene_params", "[", "\"key\"", "]", ")", "metadata", ...
25.454545
0.001721
def mdownload(args): """ %prog mdownload links.txt Multiple download a list of files. Use formats.html.links() to extract the links file. """ from jcvi.apps.grid import Jobs p = OptionParser(mdownload.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not...
[ "def", "mdownload", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "grid", "import", "Jobs", "p", "=", "OptionParser", "(", "mdownload", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", ...
22.894737
0.002208
def sender(self) -> Optional[Sequence[SingleAddressHeader]]: """The ``Sender`` header.""" try: return cast(Sequence[SingleAddressHeader], self[b'sender']) except KeyError: return None
[ "def", "sender", "(", "self", ")", "->", "Optional", "[", "Sequence", "[", "SingleAddressHeader", "]", "]", ":", "try", ":", "return", "cast", "(", "Sequence", "[", "SingleAddressHeader", "]", ",", "self", "[", "b'sender'", "]", ")", "except", "KeyError", ...
37.666667
0.008658
def command_ls(self, list_what): """Lists the available/mounted/unmounted sftp systems. Usage: sftpman ls {what} Where {what} is one of: available, mounted, unmounted """ if list_what in ('available', 'mounted', 'unmounted'): callback = getattr(self.environment, 'get_...
[ "def", "command_ls", "(", "self", ",", "list_what", ")", ":", "if", "list_what", "in", "(", "'available'", ",", "'mounted'", ",", "'unmounted'", ")", ":", "callback", "=", "getattr", "(", "self", ".", "environment", ",", "'get_%s_ids'", "%", "list_what", "...
37.916667
0.004292
def run_setup(setup_script, args): """Run a distutils setup script, sandboxed in its directory""" setup_dir = os.path.abspath(os.path.dirname(setup_script)) with setup_context(setup_dir): try: sys.argv[:] = [setup_script] + list(args) sys.path.insert(0, setup_dir) ...
[ "def", "run_setup", "(", "setup_script", ",", "args", ")", ":", "setup_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "setup_script", ")", ")", "with", "setup_context", "(", "setup_dir", ")", ":", "try", ":",...
40.125
0.001014
def save_aggregate_reports_to_splunk(self, aggregate_reports): """ Saves aggregate DMARC reports to Splunk Args: aggregate_reports: A list of aggregate report dictionaries to save in Splunk """ logger.debug("Saving aggregate reports to Splunk") i...
[ "def", "save_aggregate_reports_to_splunk", "(", "self", ",", "aggregate_reports", ")", ":", "logger", ".", "debug", "(", "\"Saving aggregate reports to Splunk\"", ")", "if", "type", "(", "aggregate_reports", ")", "==", "dict", ":", "aggregate_reports", "=", "[", "ag...
43.515152
0.000681
def on_add_cols(self, event): """ Show simple dialog that allows user to add a new column name """ col_labels = self.grid.col_labels # do not list headers that are already column labels in the grid er_items = [head for head in self.grid_headers[self.grid_type]['er'][2] if...
[ "def", "on_add_cols", "(", "self", ",", "event", ")", ":", "col_labels", "=", "self", ".", "grid", ".", "col_labels", "# do not list headers that are already column labels in the grid", "er_items", "=", "[", "head", "for", "head", "in", "self", ".", "grid_headers", ...
49.714286
0.003758
def cells(self): """A dictionary of dictionaries containing all cells. """ return {row_key: {column_key:cell for column_key, cell in zip(self._column_keys, cells)} for row_key, cells in self._rows_mapping.items()}
[ "def", "cells", "(", "self", ")", ":", "return", "{", "row_key", ":", "{", "column_key", ":", "cell", "for", "column_key", ",", "cell", "in", "zip", "(", "self", ".", "_column_keys", ",", "cells", ")", "}", "for", "row_key", ",", "cells", "in", "self...
49.8
0.01581
def effective_len(self): """ Get the length of the sequence if N's are disregarded. """ if self._effective_len is None: self._effective_len = len([nuc for nuc in self.sequenceData if nuc != "N" and nuc != "n"]) return self._effective_len
[ "def", "effective_len", "(", "self", ")", ":", "if", "self", ".", "_effective_len", "is", "None", ":", "self", ".", "_effective_len", "=", "len", "(", "[", "nuc", "for", "nuc", "in", "self", ".", "sequenceData", "if", "nuc", "!=", "\"N\"", "and", "nuc"...
36.125
0.006757
def native(self, value, context=None): """Convert a value from a foriegn type (i.e. web-safe) to Python-native.""" if self.strip and hasattr(value, 'strip'): value = value.strip() if self.none and value == '': return None if self.encoding and isinstance(value, bytes): return value.decode(self....
[ "def", "native", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "if", "self", ".", "strip", "and", "hasattr", "(", "value", ",", "'strip'", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "if", "self", ".", "none", "an...
25.769231
0.051873
def uncontract_general(basis, use_copy=True): """ Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified. ...
[ "def", "uncontract_general", "(", "basis", ",", "use_copy", "=", "True", ")", ":", "if", "use_copy", ":", "basis", "=", "copy", ".", "deepcopy", "(", "basis", ")", "for", "k", ",", "el", "in", "basis", "[", "'elements'", "]", ".", "items", "(", ")", ...
32.128205
0.001549
def rotate(self, angle, center=(0, 0)): """ Rotate this object. Parameters ---------- angle : number The angle of rotation (in *radians*). center : array-like[2] Center point for the rotation. Returns ------- out : ``Path`...
[ "def", "rotate", "(", "self", ",", "angle", ",", "center", "=", "(", "0", ",", "0", ")", ")", ":", "ca", "=", "numpy", ".", "cos", "(", "angle", ")", "sa", "=", "numpy", ".", "sin", "(", "angle", ")", "sa", "=", "numpy", ".", "array", "(", ...
31.214286
0.00222
def selection_can_redo(self, name="default"): """Can selection name be redone?""" return (self.selection_history_indices[name] + 1) < len(self.selection_histories[name])
[ "def", "selection_can_redo", "(", "self", ",", "name", "=", "\"default\"", ")", ":", "return", "(", "self", ".", "selection_history_indices", "[", "name", "]", "+", "1", ")", "<", "len", "(", "self", ".", "selection_histories", "[", "name", "]", ")" ]
61
0.016216
def make_simple(data: Any) -> Any: """ Substitute all the references in the given data (typically a mapping or sequence) with the actual values. This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely. :param data: data to be made simple (dict instead of Comment...
[ "def", "make_simple", "(", "data", ":", "Any", ")", "->", "Any", ":", "return", "yaml", ".", "load", "(", "yaml", ".", "dump", "(", "data", ",", "Dumper", "=", "ruamel", ".", "yaml", ".", "RoundTripDumper", ")", ",", "Loader", "=", "ruamel", ".", "...
51.222222
0.008529
def quick_completer(cmd, completions): """ Easily create a trivial completer for a command. Takes either a list of completions, or all completions in string (that will be split on whitespace). Example:: [d:\ipython]|1> import ipy_completers [d:\ipython]|2> ipy_completers.quick_complet...
[ "def", "quick_completer", "(", "cmd", ",", "completions", ")", ":", "if", "isinstance", "(", "completions", ",", "basestring", ")", ":", "completions", "=", "completions", ".", "split", "(", ")", "def", "do_complete", "(", "self", ",", "event", ")", ":", ...
28.954545
0.012158
def Import(context, request, instrumentname='sysmex_xs_500i'): """ Sysmex XS - 500i analysis results """ # I don't really know how this file works, for this reason I added an 'Analysis Service selector'. # If non Analysis Service is selected, each 'data' column will be interpreted as a different Analysi...
[ "def", "Import", "(", "context", ",", "request", ",", "instrumentname", "=", "'sysmex_xs_500i'", ")", ":", "# I don't really know how this file works, for this reason I added an 'Analysis Service selector'.", "# If non Analysis Service is selected, each 'data' column will be interpreted as...
40.958904
0.003266
def get(self, action, default=None): """ Returns given action value. :param action: Action name. :type action: unicode :param default: Default value if action is not found. :type default: object :return: Action. :rtype: QAction """ try: ...
[ "def", "get", "(", "self", ",", "action", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", ".", "__getitem__", "(", "action", ")", "except", "KeyError", "as", "error", ":", "return", "default" ]
25.5
0.004728
def read_index(fn): """Reads index from file. Args: fn (str): the name of the file containing the index. Returns: pandas.DataFrame: the index of the file. Before reading the index, we check the first couple of bytes to see if it is a valid index file. """ index = None ...
[ "def", "read_index", "(", "fn", ")", ":", "index", "=", "None", "with", "open", "(", "fn", ",", "\"rb\"", ")", "as", "i_file", ":", "if", "i_file", ".", "read", "(", "len", "(", "_CHECK_STRING", ")", ")", "!=", "_CHECK_STRING", ":", "raise", "ValueEr...
26.086957
0.001608
def from_array(array): """ Deserialize a new SuccessfulPayment from a given dictionary. :return: new SuccessfulPayment instance. :rtype: SuccessfulPayment """ if array is None or not array: return None # end if assert_type_or_raise(array, dict...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "data", "=", "{", "}", "da...
46.454545
0.005753
def translate_aliases(kwargs, aliases): """Given a dict of keyword arguments and a dict mapping aliases to their canonical values, canonicalize the keys in the kwargs dict. :return: A dict continaing all the values in kwargs referenced by their canonical key. :raises: `AliasException`, if a can...
[ "def", "translate_aliases", "(", "kwargs", ",", "aliases", ")", ":", "result", "=", "{", "}", "for", "given_key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "canonical_key", "=", "aliases", ".", "get", "(", "given_key", ",", "given_key", ...
37.6
0.001037
async def send_offnetwork_invitation( self, send_offnetwork_invitation_request ): """Send an email to invite a non-Google contact to Hangouts.""" response = hangouts_pb2.SendOffnetworkInvitationResponse() await self._pb_request('devices/sendoffnetworkinvitation', ...
[ "async", "def", "send_offnetwork_invitation", "(", "self", ",", "send_offnetwork_invitation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SendOffnetworkInvitationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'devices/sendoffnetworkinvitation'"...
47.444444
0.006897
def process_gene_interaction(self, limit): """ The gene interaction file includes identified interactions, that are between two or more gene (products). In the case of interactions with >2 genes, this requires creating groups of genes that are involved in the interaction. ...
[ "def", "process_gene_interaction", "(", "self", ",", "limit", ")", ":", "raw", "=", "'/'", ".", "join", "(", "(", "self", ".", "rawdir", ",", "self", ".", "files", "[", "'gene_interaction'", "]", "[", "'file'", "]", ")", ")", "if", "self", ".", "test...
40.325843
0.001904
def triggers(self): """ Returns a list of available triggers. """ self._triggers, value = self.get_attr_set(self._triggers, 'trigger') return value
[ "def", "triggers", "(", "self", ")", ":", "self", ".", "_triggers", ",", "value", "=", "self", ".", "get_attr_set", "(", "self", ".", "_triggers", ",", "'trigger'", ")", "return", "value" ]
30.333333
0.010695
def updateFGDBfromSDE(fgdb, sde, logger=None): global changes """ fgdb: file geodatabase sde: sde geodatabase connection logger: agrc.logging.Logger (optional) returns: String[] - the list of errors Loops through the file geodatabase feature classes and looks for matches in the SDE dat...
[ "def", "updateFGDBfromSDE", "(", "fgdb", ",", "sde", ",", "logger", "=", "None", ")", ":", "global", "changes", "def", "log", "(", "msg", ")", ":", "if", "logger", ":", "logger", ".", "logMsg", "(", "msg", ")", "else", ":", "print", "msg", "def", "...
34.674797
0.001596
def vb_start_vm(name=None, timeout=10000, **kwargs): ''' Tells Virtualbox to start up a VM. Blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of started VM ''' ...
[ "def", "vb_start_vm", "(", "name", "=", "None", ",", "timeout", "=", "10000", ",", "*", "*", "kwargs", ")", ":", "# Time tracking", "start_time", "=", "time", ".", "time", "(", ")", "timeout_in_seconds", "=", "timeout", "/", "1000", "max_time", "=", "sta...
35
0.003475
def _fingerprint(jvm_options, classpath, java_version): """Compute a fingerprint for this invocation of a Java task. :param list jvm_options: JVM options passed to the java invocation :param list classpath: The -cp arguments passed to the java invocation :param Revision java_version: return va...
[ "def", "_fingerprint", "(", "jvm_options", ",", "classpath", ",", "java_version", ")", ":", "digest", "=", "hashlib", ".", "sha1", "(", ")", "# TODO(John Sirois): hash classpath contents?", "encoded_jvm_options", "=", "[", "option", ".", "encode", "(", "'utf-8'", ...
57.75
0.003195
def accel_move_tab_right(self, *args): # TODO KEYBINDINGS ONLY """ Callback to move a tab to the right """ pos = self.get_notebook().get_current_page() if pos != self.get_notebook().get_n_pages() - 1: self.move_tab(pos, pos + 1) return True
[ "def", "accel_move_tab_right", "(", "self", ",", "*", "args", ")", ":", "# TODO KEYBINDINGS ONLY", "pos", "=", "self", ".", "get_notebook", "(", ")", ".", "get_current_page", "(", ")", "if", "pos", "!=", "self", ".", "get_notebook", "(", ")", ".", "get_n_p...
40.857143
0.010274
def _walk(directory, enable_scandir=False, **kwargs): """ Internal function to return walk generator either from os or scandir :param directory: directory to traverse :param enable_scandir: on python < 3.5 enable external scandir package :param kwargs: arguments to pass to walk function :return...
[ "def", "_walk", "(", "directory", ",", "enable_scandir", "=", "False", ",", "*", "*", "kwargs", ")", ":", "walk", "=", "os", ".", "walk", "if", "python_version", "<", "(", "3", ",", "5", ")", "and", "enable_scandir", ":", "import", "scandir", "walk", ...
34.928571
0.001992
def calculate_heartbeats(shb, chb): """ Given a heartbeat string from the server, and a heartbeat tuple from the client, calculate what the actual heartbeat settings should be. :param (str,str) shb: server heartbeat numbers :param (int,int) chb: client heartbeat numbers :rtype: (int,int) "...
[ "def", "calculate_heartbeats", "(", "shb", ",", "chb", ")", ":", "(", "sx", ",", "sy", ")", "=", "shb", "(", "cx", ",", "cy", ")", "=", "chb", "x", "=", "0", "y", "=", "0", "if", "cx", "!=", "0", "and", "sy", "!=", "'0'", ":", "x", "=", "...
26.105263
0.003891
def beststr(*strings): """ Test if the output device can handle the desired strings. The options should be sorted by preference. Eg. beststr(unicode, ascii). """ for x in strings: try: x.encode(sys.stdout.encoding) except UnicodeEncodeError: pass else: ...
[ "def", "beststr", "(", "*", "strings", ")", ":", "for", "x", "in", "strings", ":", "try", ":", "x", ".", "encode", "(", "sys", ".", "stdout", ".", "encoding", ")", "except", "UnicodeEncodeError", ":", "pass", "else", ":", "return", "x", "raise", "Val...
33.636364
0.002632
def error(self, line_number, offset, text, check): """Report an error, according to options.""" code = text[:4] if self._ignore_code(code): return if code in self.counters: self.counters[code] += 1 else: self.counters[code] = 1 self...
[ "def", "error", "(", "self", ",", "line_number", ",", "offset", ",", "text", ",", "check", ")", ":", "code", "=", "text", "[", ":", "4", "]", "if", "self", ".", "_ignore_code", "(", "code", ")", ":", "return", "if", "code", "in", "self", ".", "co...
33.777778
0.0032
def new(self, string=None, *args, **kwargs): """Returns a `_ChainedHashAlgorithm` if the underlying tuple (specifying the list of algorithms) is not empty, otherwise a `_NopHashAlgorithm` instance is returned.""" if len(self): hobj = _ChainedHashAlgorithm(self, *args, **kwarg...
[ "def", "new", "(", "self", ",", "string", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "self", ")", ":", "hobj", "=", "_ChainedHashAlgorithm", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "...
42.090909
0.004228
def wrap_split_big_content(func_, *args, **kwargs): """ chunk the content into smaller binary blobs before inserting this function should chunk in such a way that this is completely transparent to the user. :param func_: :param args: :param kwargs: :return: <dict> RethinkDB dict from i...
[ "def", "wrap_split_big_content", "(", "func_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj_dict", "=", "args", "[", "0", "]", "if", "len", "(", "obj_dict", "[", "CONTENT_FIELD", "]", ")", "<", "MAX_PUT", ":", "obj_dict", "[", "PART_FIELD"...
29.333333
0.001835
async def exist(self, key, param=None): """see if specific identity exists""" identity = self._gen_identity(key, param) return await self.client.exists(identity)
[ "async", "def", "exist", "(", "self", ",", "key", ",", "param", "=", "None", ")", ":", "identity", "=", "self", ".", "_gen_identity", "(", "key", ",", "param", ")", "return", "await", "self", ".", "client", ".", "exists", "(", "identity", ")" ]
45.5
0.010811
def _getEnumValues(self, data): """ Returns a list of dictionary of valis value for this setting. """ enumstr = data.attrib.get('enumValues') if not enumstr: return None if ':' in enumstr: return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split...
[ "def", "_getEnumValues", "(", "self", ",", "data", ")", ":", "enumstr", "=", "data", ".", "attrib", ".", "get", "(", "'enumValues'", ")", "if", "not", "enumstr", ":", "return", "None", "if", "':'", "in", "enumstr", ":", "return", "{", "self", ".", "_...
44.25
0.00831
def check_shell(cmd, shell=None): """ Determine whether a command appears to involve shell process(es). The shell argument can be used to override the result of the check. :param str cmd: Command to investigate. :param bool shell: override the result of the check with this value. :return bool: ...
[ "def", "check_shell", "(", "cmd", ",", "shell", "=", "None", ")", ":", "if", "isinstance", "(", "shell", ",", "bool", ")", ":", "return", "shell", "return", "\"|\"", "in", "cmd", "or", "\">\"", "in", "cmd", "or", "r\"*\"", "in", "cmd" ]
39.833333
0.002045
def sequenceCategoryLengths(read, categories, defaultCategory=None, suppressedCategory='...', minLength=1): """ Summarize the nucleotides or AAs found in a read by assigning each to a category and reporting the lengths of the contiguous category classes found along the sequen...
[ "def", "sequenceCategoryLengths", "(", "read", ",", "categories", ",", "defaultCategory", "=", "None", ",", "suppressedCategory", "=", "'...'", ",", "minLength", "=", "1", ")", ":", "result", "=", "[", "]", "append", "=", "result", ".", "append", "get", "=...
39.136986
0.000341
def volume_oscillator(volume, short_period, long_period): """ Volume Oscillator. Formula: vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long)) """ catch_errors.check_for_period_error(volume, short_period) catch_errors.check_for_period_error(volume, long_period) vo = (100 * ((...
[ "def", "volume_oscillator", "(", "volume", ",", "short_period", ",", "long_period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "volume", ",", "short_period", ")", "catch_errors", ".", "check_for_period_error", "(", "volume", ",", "long_period", ")...
31.846154
0.002347
def create_tags(self, resource_ids, tags): """ Create new metadata tags for the specified resource ids. :type resource_ids: list :param resource_ids: List of strings :type tags: dict :param tags: A dictionary containing the name/value pairs. If you ...
[ "def", "create_tags", "(", "self", ",", "resource_ids", ",", "tags", ")", ":", "params", "=", "{", "}", "self", ".", "build_list_params", "(", "params", ",", "resource_ids", ",", "'ResourceId'", ")", "self", ".", "build_tag_param_list", "(", "params", ",", ...
36.166667
0.002994
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a target port into this object. ''' super(TargetPort, self).parse_xml_node(node) self.port_name = node.getAttributeNS(RTS_NS, 'portName') return self
[ "def", "parse_xml_node", "(", "self", ",", "node", ")", ":", "super", "(", "TargetPort", ",", "self", ")", ".", "parse_xml_node", "(", "node", ")", "self", ".", "port_name", "=", "node", ".", "getAttributeNS", "(", "RTS_NS", ",", "'portName'", ")", "retu...
33.5
0.007273
def group(self, id=None, **kwargs): """ Adds a group stage at aggregation query :param id: The group id. Default value is None and group merge all documents :param kwargs: The parameters-methods of group stage :return: The current object """ if type(id) == str: ...
[ "def", "group", "(", "self", ",", "id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "id", ")", "==", "str", ":", "if", "not", "id", ".", "startswith", "(", "'$'", ")", ":", "id", "=", "'$'", "+", "id", "query", "=", "...
29.789474
0.005137
def lock(self, timeout='default', requested_key=None): """Establish a shared lock to the resource. :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to ...
[ "def", "lock", "(", "self", ",", "timeout", "=", "'default'", ",", "requested_key", "=", "None", ")", ":", "timeout", "=", "self", ".", "timeout", "if", "timeout", "==", "'default'", "else", "timeout", "timeout", "=", "self", ".", "_cleanup_timeout", "(", ...
56.5625
0.004348
def trace_job(self, jobId): """ Get information about the specified remote job :param jobId: the job identifier :return: a dictionary with the information """ header = self.__check_authentication() status_url = self.address + "/jobs/" + jobId + "/trace" status_re...
[ "def", "trace_job", "(", "self", ",", "jobId", ")", ":", "header", "=", "self", ".", "__check_authentication", "(", ")", "status_url", "=", "self", ".", "address", "+", "\"/jobs/\"", "+", "jobId", "+", "\"/trace\"", "status_resp", "=", "requests", ".", "ge...
45
0.005445
def create(self): """ Create the link on the nodes """ node1 = self._nodes[0]["node"] adapter_number1 = self._nodes[0]["adapter_number"] port_number1 = self._nodes[0]["port_number"] node2 = self._nodes[1]["node"] adapter_number2 = self._nodes[1]["adapter_...
[ "def", "create", "(", "self", ")", ":", "node1", "=", "self", ".", "_nodes", "[", "0", "]", "[", "\"node\"", "]", "adapter_number1", "=", "self", ".", "_nodes", "[", "0", "]", "[", "\"adapter_number\"", "]", "port_number1", "=", "self", ".", "_nodes", ...
42.517857
0.003284
def set_meta_refresh_enabled(self, enabled): """ *Deprecated:* set :attr:`~.Cluster.schema_metadata_enabled` :attr:`~.Cluster.token_metadata_enabled` instead Sets a flag to enable (True) or disable (False) all metadata refresh queries. This applies to both schema and node topology. ...
[ "def", "set_meta_refresh_enabled", "(", "self", ",", "enabled", ")", ":", "warn", "(", "\"Cluster.set_meta_refresh_enabled is deprecated and will be removed in 4.0. Set \"", "\"Cluster.schema_metadata_enabled and Cluster.token_metadata_enabled instead.\"", ",", "DeprecationWarning", ")",...
51.3125
0.008373
def do_heavy_work(self, block): """ Note: Expects Compressor Block like objects """ destinations = self.destinations() ''' FIXME currently we return block whether it was correctly processed or not because MailSenders are chained and not doing that would mean other wo...
[ "def", "do_heavy_work", "(", "self", ",", "block", ")", ":", "destinations", "=", "self", ".", "destinations", "(", ")", "''' FIXME currently we return block whether it was correctly processed or not because MailSenders are chained\n and not doing that would mean other would...
45.956522
0.004634
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the specified host. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target ...
[ "def", "run_shell_command", "(", "state", ",", "host", ",", "command", ",", "get_pty", "=", "False", ",", "timeout", "=", "None", ",", "print_output", "=", "False", ",", "*", "*", "command_kwargs", ")", ":", "command", "=", "make_command", "(", "command", ...
33.506494
0.000377
def add_hook(self, pc, callback): """ Add a callback to be invoked on executing a program counter. Pass `None` for pc to invoke callback on every instruction. `callback` should be a callable that takes one :class:`~manticore.core.state.State` argument. :param pc: Address of inst...
[ "def", "add_hook", "(", "self", ",", "pc", ",", "callback", ")", ":", "if", "not", "(", "isinstance", "(", "pc", ",", "int", ")", "or", "pc", "is", "None", ")", ":", "raise", "TypeError", "(", "f\"pc must be either an int or None, not {pc.__class__.__name__}\"...
46.75
0.007864
def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2clien...
[ "def", "_from_p12_keyfile_contents", "(", "cls", ",", "service_account_email", ",", "private_key_pkcs12", ",", "private_key_password", "=", "None", ",", "scopes", "=", "''", ",", "token_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_URI", ",", "revoke_uri", "=", "oau...
50.731707
0.00283
def label_correcting_check_cycle(self, j, pred): ''' API: label_correcting_check_cycle(self, j, pred) Description: Checks if predecessor dictionary has a cycle, j represents the node that predecessor is recently updated. Pre: (1) predecesso...
[ "def", "label_correcting_check_cycle", "(", "self", ",", "j", ",", "pred", ")", ":", "labelled", "=", "{", "}", "for", "n", "in", "self", ".", "neighbors", ":", "labelled", "[", "n", "]", "=", "None", "current", "=", "j", "while", "current", "!=", "N...
35.148148
0.004103
def LOOPNZ(cpu, target): """ Loops if ECX counter is nonzero. :param cpu: current CPU. :param target: destination operand. """ counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size] counter = cpu.write_register(counter_name, cpu.read_register(count...
[ "def", "LOOPNZ", "(", "cpu", ",", "target", ")", ":", "counter_name", "=", "{", "16", ":", "'CX'", ",", "32", ":", "'ECX'", ",", "64", ":", "'RCX'", "}", "[", "cpu", ".", "address_bit_size", "]", "counter", "=", "cpu", ".", "write_register", "(", "...
47.7
0.00823
def simpleListFactory(list_type): """Used for simple parsers that support only one type of object""" def create(delegate, extra_args=None): """Create a Parser object for the specific tag type, on the fly""" return listParser(list_type, delegate, extra_args) return create
[ "def", "simpleListFactory", "(", "list_type", ")", ":", "def", "create", "(", "delegate", ",", "extra_args", "=", "None", ")", ":", "\"\"\"Create a Parser object for the specific tag type, on the fly\"\"\"", "return", "listParser", "(", "list_type", ",", "delegate", ","...
49
0.003344
def attachments(self): """Returns an object with: type = file content type file_name = the name of the file contents = base64 encoded file contents""" attachments = None if 'attachment-info' in self.payload: attachments = self._get_attachments(self.request) ...
[ "def", "attachments", "(", "self", ")", ":", "attachments", "=", "None", "if", "'attachment-info'", "in", "self", ".", "payload", ":", "attachments", "=", "self", ".", "_get_attachments", "(", "self", ".", "request", ")", "# Check if we have a raw message", "raw...
39.307692
0.003824
def set_loglevel(loggers, level): """Set logging levels for given loggers.""" if not loggers: return if 'all' in loggers: loggers = lognames.keys() for key in loggers: logging.getLogger(lognames[key]).setLevel(level)
[ "def", "set_loglevel", "(", "loggers", ",", "level", ")", ":", "if", "not", "loggers", ":", "return", "if", "'all'", "in", "loggers", ":", "loggers", "=", "lognames", ".", "keys", "(", ")", "for", "key", "in", "loggers", ":", "logging", ".", "getLogger...
31.125
0.003906
def frag2text(endpoint, stype, selector, clean=False, raw=False, verbose=False): """returns Markdown text of selected fragment. Args: endpoint: URL, file, or HTML string stype: { 'css' | 'xpath' } selector: CSS selector or XPath expression Returns: Markdown tex...
[ "def", "frag2text", "(", "endpoint", ",", "stype", ",", "selector", ",", "clean", "=", "False", ",", "raw", "=", "False", ",", "verbose", "=", "False", ")", ":", "try", ":", "return", "main", "(", "endpoint", ",", "stype", ",", "selector", ",", "clea...
31.736842
0.00161
def remove_all(self, other): """Remove all of the elems from other. Raises a ValueError if the multiplicity of any elem in other is greater than in self. """ if not self.is_superset(other): raise ValueError('Passed collection is not a subset of this bag') self.discard_all(other)
[ "def", "remove_all", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_superset", "(", "other", ")", ":", "raise", "ValueError", "(", "'Passed collection is not a subset of this bag'", ")", "self", ".", "discard_all", "(", "other", ")" ]
31.888889
0.030508
def merge_mutect(job, perchrom_rvs): """ This module will merge the per-chromosome mutect files created by spawn_mutect into a genome vcf. It will make 2 vcfs, one for PASSing non-germline calls, and one for all calls. ARGUMENTS 1. perchrom_rvs: REFER RETURN VALUE of spawn_mutect() RETURN VAL...
[ "def", "merge_mutect", "(", "job", ",", "perchrom_rvs", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Running merge_mutect'", ")", "work_dir", "=", "job", ".", "fileStore", ".", "getLocalTempDir", "(", ")", "# We need to squash the input dict of dict...
47.574074
0.00267
def configure(self, config): """ Configure all the blocks from an (horible) configuration dictionary this data are coming from a json client request and has to be parsed. It takes the default value if missing (for component selection and options). :param config: dictionary that...
[ "def", "configure", "(", "self", ",", "config", ")", ":", "##TODO use block configuration", "self", ".", "_logger", ".", "info", "(", "\"\\n\\n\\t\\t\\t ** ============= configure engine ============= ** \\n\"", ")", "# normalise input format", "for", "block_name", "in", "c...
43.539683
0.004278
def discovery_mqtt(self): """ Installs the MQTT discovery bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.discovery.mqtt").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery...
[ "def", "discovery_mqtt", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.discovery.mqtt\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", "ipopo...
34.944444
0.003096
def make_config_get(conf_path): """Return a function to get configuration options for a specific project Args: conf_path (path-like): path to project's conf file (i.e. foo.conf module) """ project_root = _get_project_root_from_conf_path(conf_path) config = load_config_in_dir(pro...
[ "def", "make_config_get", "(", "conf_path", ")", ":", "project_root", "=", "_get_project_root_from_conf_path", "(", "conf_path", ")", "config", "=", "load_config_in_dir", "(", "project_root", ")", "return", "partial", "(", "config_get", ",", "config", ")" ]
36
0.00271
def p_create_rop_statement(self, p): '''create_rop_statement : CREATE ROP REF_ID RELID FROM association_end TO association_end''' args = [p[4]] args.extend(p[6]) args.extend(p[8]) p[0] = CreateAssociationStmt(*args)
[ "def", "p_create_rop_statement", "(", "self", ",", "p", ")", ":", "args", "=", "[", "p", "[", "4", "]", "]", "args", ".", "extend", "(", "p", "[", "6", "]", ")", "args", ".", "extend", "(", "p", "[", "8", "]", ")", "p", "[", "0", "]", "=", ...
41.666667
0.011765
def replaceelement(oldelem, newelem): ''' Given a parent element, replace oldelem with newelem. ''' parent = oldelem.getparent() if parent is not None: size = len(parent.getchildren()) for x in range(0, size): if parent.getchildren()[x] == oldelem: parent....
[ "def", "replaceelement", "(", "oldelem", ",", "newelem", ")", ":", "parent", "=", "oldelem", ".", "getparent", "(", ")", "if", "parent", "is", "not", "None", ":", "size", "=", "len", "(", "parent", ".", "getchildren", "(", ")", ")", "for", "x", "in",...
33.363636
0.002653
def item_straat_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Straat` to json. """ return { 'id': obj.id, 'label': obj.label, 'namen': obj.namen, 'status': { 'id': obj.status.id, 'naam': obj.status.na...
[ "def", "item_straat_adapter", "(", "obj", ",", "request", ")", ":", "return", "{", "'id'", ":", "obj", ".", "id", ",", "'label'", ":", "obj", ".", "label", ",", "'namen'", ":", "obj", ".", "namen", ",", "'status'", ":", "{", "'id'", ":", "obj", "."...
32.457143
0.000855
def _get_type(self): """ Subclasses may override this method. """ point = self._point typ = point.type bType = None if point.smooth: if typ == "curve": bType = "curve" elif typ == "line": nextSegment = self._...
[ "def", "_get_type", "(", "self", ")", ":", "point", "=", "self", ".", "_point", "typ", "=", "point", ".", "type", "bType", "=", "None", "if", "point", ".", "smooth", ":", "if", "typ", "==", "\"curve\"", ":", "bType", "=", "\"curve\"", "elif", "typ", ...
31.826087
0.003979
def _mean_prediction(self,theta,Y,scores,h,t_params): """ Creates a h-step ahead mean prediction Parameters ---------- theta : np.array The past predicted values Y : np.array The past data scores : np.array The past scores h...
[ "def", "_mean_prediction", "(", "self", ",", "theta", ",", "Y", ",", "scores", ",", "h", ",", "t_params", ")", ":", "Y_exp", "=", "Y", ".", "copy", "(", ")", "theta_exp", "=", "theta", ".", "copy", "(", ")", "scores_exp", "=", "scores", ".", "copy"...
29.875
0.012966