text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def new_session(self, session): ''' Clear out the current session on the remote and setup a new one. :return: A response from having expired the current session. :rtype: requests.Response ''' response = self.__get('/Home/SessionExpire') self.session = update_sess...
[ "def", "new_session", "(", "self", ",", "session", ")", ":", "response", "=", "self", ".", "__get", "(", "'/Home/SessionExpire'", ")", "self", ".", "session", "=", "update_session_headers", "(", "session", ")", "return", "response" ]
32.272727
0.005479
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlpars...
[ "def", "prepend_scheme_if_needed", "(", "url", ",", "new_scheme", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ",", "new_scheme", ")", "# urlparse is a finicky beast, and sometimes decid...
41.933333
0.001555
def knit(self, input_file, opts_chunk='eval=FALSE'): """Use Knitr to convert the r-markdown input_file into markdown, returning a file object. """ # use temporary files at both ends to allow stdin / stdout tmp_in = tempfile.NamedTemporaryFile(mode='w+') tmp_out = tempfile...
[ "def", "knit", "(", "self", ",", "input_file", ",", "opts_chunk", "=", "'eval=FALSE'", ")", ":", "# use temporary files at both ends to allow stdin / stdout", "tmp_in", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w+'", ")", "tmp_out", "=", "tempf...
36.6
0.003552
def rename(args): """Supply two names: Existing instance name or ID, and new name to assign to the instance.""" old_name, new_name = args.names add_tags(resources.ec2.Instance(resolve_instance_id(old_name)), Name=new_name, dry_run=args.dry_run)
[ "def", "rename", "(", "args", ")", ":", "old_name", ",", "new_name", "=", "args", ".", "names", "add_tags", "(", "resources", ".", "ec2", ".", "Instance", "(", "resolve_instance_id", "(", "old_name", ")", ")", ",", "Name", "=", "new_name", ",", "dry_run"...
63.25
0.011719
def _update_port_locations(self, initial_coordinates): """Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the loca...
[ "def", "_update_port_locations", "(", "self", ",", "initial_coordinates", ")", ":", "particles", "=", "list", "(", "self", ".", "particles", "(", ")", ")", "for", "port", "in", "self", ".", "all_ports", "(", ")", ":", "if", "port", ".", "anchor", ":", ...
43.181818
0.00206
def error_received(self, exception): """Datagram error callback.""" if exception is None: pass else: import pprint pprint.pprint(exception) _LOGGER.error('Error received: %s', exception)
[ "def", "error_received", "(", "self", ",", "exception", ")", ":", "if", "exception", "is", "None", ":", "pass", "else", ":", "import", "pprint", "pprint", ".", "pprint", "(", "exception", ")", "_LOGGER", ".", "error", "(", "'Error received: %s'", ",", "exc...
31.375
0.007752
def clone_replace_name(self, new_name): """Instantiate a BucketStorageUri from the current BucketStorageUri, but replacing the object_name. @type new_name: string @param new_name: new object name """ if not self.bucket_name: raise InvalidUriError('clone_repla...
[ "def", "clone_replace_name", "(", "self", ",", "new_name", ")", ":", "if", "not", "self", ".", "bucket_name", ":", "raise", "InvalidUriError", "(", "'clone_replace_name() on bucket-less URI %s'", "%", "self", ".", "uri", ")", "return", "BucketStorageUri", "(", "se...
42.307692
0.005338
def _nemo_accpars(self,vo,ro): """ NAME: _nemo_accpars PURPOSE: return the accpars potential parameters for use of this potential with NEMO INPUT: vo - velocity unit in km/s ro - length unit in kpc OUTPUT: accpars str...
[ "def", "_nemo_accpars", "(", "self", ",", "vo", ",", "ro", ")", ":", "ampl", "=", "self", ".", "_amp", "*", "vo", "**", "2.", "*", "ro", "**", "(", "self", ".", "alpha", "-", "2.", ")", "return", "\"0,%s,%s,%s\"", "%", "(", "ampl", ",", "self", ...
17.925926
0.015686
def inventory(self, inventory_name): """ Decorator to register filters for given inventory. For a function "abc", it has the same effect :param inventory_name: :return: .. code-block:: python tic = CtsTextInventoryCollection() latin = CtsTextInventoryMetadata("...
[ "def", "inventory", "(", "self", ",", "inventory_name", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "add", "(", "func", "=", "f", ",", "inventory_name", "=", "inventory_name", ")", "return", "f", "return", "decorator" ]
34.75
0.004667
def check(self): """Check for validity. :raises ValueError: - if not all lines are as long as the :attr:`number of needles <AYABInterface.machines.Machine.number_of_needles>` - if the contents of the rows are not :attr:`needle positions <AYABInterface.machin...
[ "def", "check", "(", "self", ")", ":", "# TODO: This violates the law of demeter.", "# The architecture should be changed that this check is either", "# performed by the machine or by the unity of machine and", "# carriage.", "expected_positions", "=", "self", ".", "_ma...
49.148148
0.001478
def unlock(self): """Unlock the doors and extend handles where applicable.""" if self.__lock_state: data = self._controller.command(self._id, 'door_unlock', wake_if_asleep=True) if data['response']['result']: self.__lock...
[ "def", "unlock", "(", "self", ")", ":", "if", "self", ".", "__lock_state", ":", "data", "=", "self", ".", "_controller", ".", "command", "(", "self", ".", "_id", ",", "'door_unlock'", ",", "wake_if_asleep", "=", "True", ")", "if", "data", "[", "'respon...
47.375
0.005181
def load_path(self, path): """ Loads given path. :param path: Path to load. :type path: unicode :return: Method success. :rtype: bool """ if not foundations.common.path_exists(path): return False if os.path.isfile(path): ...
[ "def", "load_path", "(", "self", ",", "path", ")", ":", "if", "not", "foundations", ".", "common", ".", "path_exists", "(", "path", ")", ":", "return", "False", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "if", "path", "in", "sel...
25.045455
0.005245
def traverse_depth_first_post_order(self, callback): """Visits the internal "nodes" of the enhanced suffix array in depth-first post-order. Kasai et. al. (2001), Abouelhoda et al. (2004). """ # a. Reimplement without python lists?.. # b. Interface will require it to have not int...
[ "def", "traverse_depth_first_post_order", "(", "self", ",", "callback", ")", ":", "# a. Reimplement without python lists?..", "# b. Interface will require it to have not internal nodes only?..", "# (but actually this implementation gives a ~2x gain of performance)", "last_interval", "=", ...
43.413793
0.002331
def includes_missingalt(data): """ As of GATK 4.1.0.0, variants with missing alts are generated (see https://github.com/broadinstitute/gatk/issues/5650) """ MISSINGALT_VERSION = LooseVersion("4.1.0.0") version = LooseVersion(broad.get_gatk_version(config=dd.get_config(data))) return version ...
[ "def", "includes_missingalt", "(", "data", ")", ":", "MISSINGALT_VERSION", "=", "LooseVersion", "(", "\"4.1.0.0\"", ")", "version", "=", "LooseVersion", "(", "broad", ".", "get_gatk_version", "(", "config", "=", "dd", ".", "get_config", "(", "data", ")", ")", ...
41.75
0.002933
def sha256sum(filename): """Return SHA256 hash of file.""" sha256 = hashlib.sha256() mem_view = memoryview(bytearray(128*1024)) with open(filename, 'rb', buffering=0) as stream: for i in iter(lambda: stream.readinto(mem_view), 0): sha256.update(mem_view[:i]) return sha256.hexdige...
[ "def", "sha256sum", "(", "filename", ")", ":", "sha256", "=", "hashlib", ".", "sha256", "(", ")", "mem_view", "=", "memoryview", "(", "bytearray", "(", "128", "*", "1024", ")", ")", "with", "open", "(", "filename", ",", "'rb'", ",", "buffering", "=", ...
39.625
0.003086
def license_is_oa(license): """Return True if license is compatible with Open Access""" for oal in OA_LICENSES: if re.search(oal, license): return True return False
[ "def", "license_is_oa", "(", "license", ")", ":", "for", "oal", "in", "OA_LICENSES", ":", "if", "re", ".", "search", "(", "oal", ",", "license", ")", ":", "return", "True", "return", "False" ]
31.833333
0.005102
def subscribe(self, event, handler): """ Subscribes a Handler for the given Event. @param event: (str|see.Event) event to react to. @param handler: (callable) function or method to subscribe. """ self._handlers.sync_handlers[event].append(handler)
[ "def", "subscribe", "(", "self", ",", "event", ",", "handler", ")", ":", "self", ".", "_handlers", ".", "sync_handlers", "[", "event", "]", ".", "append", "(", "handler", ")" ]
36.125
0.006757
def plot_gender(data, options): """Plots the gender. :param data: the data to plot. :param options: the options. :type data: numpy.recarray :type options: argparse.Namespace Plots the summarized intensities of the markers on the Y chromosomes in function of the markers on the X chromosome...
[ "def", "plot_gender", "(", "data", ",", "options", ")", ":", "if", "data", "is", "None", ":", "# there is a problem...", "msg", "=", "(", "\"no data: specify either '--bfile' and '--intensities', or \"", "\"'--summarized-intensities'\"", ")", "raise", "ProgramError", "(",...
37.567164
0.000194
def fetch_all_kernels(self): r""" Returns a generator that yields all of the kernels available to the droplet :rtype: generator of `Kernel`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for kern in api.pagin...
[ "def", "fetch_all_kernels", "(", "self", ")", ":", "api", "=", "self", ".", "doapi_manager", "for", "kern", "in", "api", ".", "paginate", "(", "self", ".", "url", "+", "'/kernels'", ",", "'kernels'", ")", ":", "yield", "Kernel", "(", "kern", ",", "doap...
36.181818
0.004902
def setup_app_scope(name, scope): """activate plugins accordingly to config""" # load plugins plugins = [] for plugin_name, active in get('settings').get('rw.plugins', {}).items(): plugin = __import__(plugin_name) plugin_path = plugin_name.split('.')[1:] + ['plugin'] for sub in ...
[ "def", "setup_app_scope", "(", "name", ",", "scope", ")", ":", "# load plugins", "plugins", "=", "[", "]", "for", "plugin_name", ",", "active", "in", "get", "(", "'settings'", ")", ".", "get", "(", "'rw.plugins'", ",", "{", "}", ")", ".", "items", "(",...
33.571429
0.00207
def create_transition(self, from_state_id, from_outcome, to_state_id, to_outcome, transition_id): """ Creates a new transition. Lookout: Check the parameters first before creating a new transition :param from_state_id: The source state of the transition :param from_outcome: The outcome...
[ "def", "create_transition", "(", "self", ",", "from_state_id", ",", "from_outcome", ",", "to_state_id", ",", "to_outcome", ",", "transition_id", ")", ":", "# get correct states", "if", "from_state_id", "is", "not", "None", ":", "if", "from_state_id", "==", "self",...
49.133333
0.004878
def Hash(self): """ Get the hash of the transaction. Returns: UInt256: """ if not self.__hash: ba = bytearray(binascii.unhexlify(self.GetHashData())) hash = Crypto.Hash256(ba) self.__hash = UInt256(data=hash) return self.__...
[ "def", "Hash", "(", "self", ")", ":", "if", "not", "self", ".", "__hash", ":", "ba", "=", "bytearray", "(", "binascii", ".", "unhexlify", "(", "self", ".", "GetHashData", "(", ")", ")", ")", "hash", "=", "Crypto", ".", "Hash256", "(", "ba", ")", ...
26.083333
0.006173
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = {'initial': self.get_initial(), 'instance': self.object} if self.request.method in ('POST', 'PUT') and self.can_submit: kwargs.update({ ...
[ "def", "get_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'initial'", ":", "self", ".", "get_initial", "(", ")", ",", "'instance'", ":", "self", ".", "object", "}", "if", "self", ".", "request", ".", "method", "in", "(", "'POST'", ",", "'...
32.307692
0.00463
def after_unassign(duplicate_analysis): """Removes the duplicate from the system """ analysis_events.after_unassign(duplicate_analysis) parent = duplicate_analysis.aq_parent logger.info("Removing duplicate '{}' from '{}'" .format(duplicate_analysis.getId(), parent.getId())) paren...
[ "def", "after_unassign", "(", "duplicate_analysis", ")", ":", "analysis_events", ".", "after_unassign", "(", "duplicate_analysis", ")", "parent", "=", "duplicate_analysis", ".", "aq_parent", "logger", ".", "info", "(", "\"Removing duplicate '{}' from '{}'\"", ".", "form...
45.25
0.00271
def __do_parse(self, pattern_str): """ Parses the given pattern and returns the antlr parse tree. :param pattern_str: The STIX pattern :return: The parse tree :raises ParseException: If there is a parse error """ in_ = antlr4.InputStream(pattern_str) lexe...
[ "def", "__do_parse", "(", "self", ",", "pattern_str", ")", ":", "in_", "=", "antlr4", ".", "InputStream", "(", "pattern_str", ")", "lexer", "=", "STIXPatternLexer", "(", "in_", ")", "lexer", ".", "removeErrorListeners", "(", ")", "# remove the default \"console\...
45.451613
0.001042
def read_json_file(fpath): """ Read a JSON file from ``fpath``; raise an exception if it doesn't exist. :param fpath: path to file to read :type fpath: str :return: deserialized JSON :rtype: dict """ if not os.path.exists(fpath): raise Exception('ERROR: file %s does not exist.' ...
[ "def", "read_json_file", "(", "fpath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":", "raise", "Exception", "(", "'ERROR: file %s does not exist.'", "%", "fpath", ")", "with", "open", "(", "fpath", ",", "'r'", ")", "as",...
27.466667
0.002347
def load_replacements(self, file_path): """ Populate self.replacements using the specified file. """ with open(file_path, encoding='utf-8') as f: for line in map(lambda x: x.strip(), f): if line: line = line.split('\t') self.replacements[line[0]] = line[1]
[ "def", "load_replacements", "(", "self", ",", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "for", "line", "in", "map", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "f",...
30.333333
0.035587
def get_all_by_product_id(self, product_id, **kwargs): """ Gets all Build Configurations of a Product This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the respo...
[ "def", "get_all_by_product_id", "(", "self", ",", "product_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_by_produc...
42.551724
0.004754
def find_resources(self, rsrc_type, sort=None, yield_pages=False, **kwargs): """Find instances of `rsrc_type` that match the filter in `**kwargs`""" return rsrc_type.find(self, sort=sort, yield_pages=yield_pages, **kwargs)
[ "def", "find_resources", "(", "self", ",", "rsrc_type", ",", "sort", "=", "None", ",", "yield_pages", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "rsrc_type", ".", "find", "(", "self", ",", "sort", "=", "sort", ",", "yield_pages", "=", ...
78.666667
0.012605
def encode_sub(self, validator, value): # type: (bv.Validator, typing.Any) -> typing.Any """ Callback intended to be called by other ``encode`` methods to delegate encoding of sub-values. Arguments have the same semantics as with the ``encode`` method. """ if isi...
[ "def", "encode_sub", "(", "self", ",", "validator", ",", "value", ")", ":", "# type: (bv.Validator, typing.Any) -> typing.Any", "if", "isinstance", "(", "validator", ",", "bv", ".", "List", ")", ":", "# Because Lists are mutable, we always validate them during", "# serial...
45.773585
0.003228
def collect(self): """ Collect memory stats of LXCs. """ lxc_metrics = ["memory.usage_in_bytes", "memory.limit_in_bytes"] if os.path.isdir(self.config["sys_path"]) is False: self.log.debug("sys_path '%s' isn't directory.", self.config["sys_p...
[ "def", "collect", "(", "self", ")", ":", "lxc_metrics", "=", "[", "\"memory.usage_in_bytes\"", ",", "\"memory.limit_in_bytes\"", "]", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "config", "[", "\"sys_path\"", "]", ")", "is", "False", ":", "sel...
39.138889
0.001385
def remove_locations(node): """ Removes locations from the given AST tree completely """ def fix(node): if 'lineno' in node._attributes and hasattr(node, 'lineno'): del node.lineno if 'col_offset' in node._attributes and hasattr(node, 'col_offset'): del node.col...
[ "def", "remove_locations", "(", "node", ")", ":", "def", "fix", "(", "node", ")", ":", "if", "'lineno'", "in", "node", ".", "_attributes", "and", "hasattr", "(", "node", ",", "'lineno'", ")", ":", "del", "node", ".", "lineno", "if", "'col_offset'", "in...
24.75
0.002433
def predict(model_id, image_files, resize, show_image): """Predict using a deployed (online) model.""" import google.datalab.ml as ml images = _util.load_images(image_files, resize=resize) parts = model_id.split('.') if len(parts) != 2: raise ValueError('Invalid model name for cloud predict...
[ "def", "predict", "(", "model_id", ",", "image_files", ",", "resize", ",", "show_image", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "images", "=", "_util", ".", "load_images", "(", "image_files", ",", "resize", "=", "resize", ")...
36.75
0.007457
def _spectrum(self, photon_energy): """Compute differential bremsstrahlung spectrum for energies in ``photon_energy``. Parameters ---------- photon_energy : :class:`~astropy.units.Quantity` instance Photon energy array. """ Eph = _validate_ene(photon...
[ "def", "_spectrum", "(", "self", ",", "photon_energy", ")", ":", "Eph", "=", "_validate_ene", "(", "photon_energy", ")", "spec", "=", "self", ".", "n0", "*", "(", "self", ".", "weight_ee", "*", "self", ".", "_emiss_ee", "(", "Eph", ")", "+", "self", ...
26.111111
0.004107
def init(cls, repo_dir=None, temp=False, initial_commit=False): """Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is ...
[ "def", "init", "(", "cls", ",", "repo_dir", "=", "None", ",", "temp", "=", "False", ",", "initial_commit", "=", "False", ")", ":", "if", "temp", ":", "suffix", "=", "'.temp_simpl_GitRepo'", "repo_dir", "=", "create_tempdir", "(", "suffix", "=", "suffix", ...
44.633333
0.001462
def FromResponse(cls, response): """Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1 """ # device_code, user_code, and verification_url are require...
[ "def", "FromResponse", "(", "cls", ",", "response", ")", ":", "# device_code, user_code, and verification_url are required.", "kwargs", "=", "{", "'device_code'", ":", "response", "[", "'device_code'", "]", ",", "'user_code'", ":", "response", "[", "'user_code'", "]",...
41.533333
0.001569
def _permute(self, ordering: np.ndarray) -> None: """ Permute all the attributes in the collection Remarks: This permutes the order of the values for each attribute in the file """ for key in self.keys(): self[key] = self[key][ordering]
[ "def", "_permute", "(", "self", ",", "ordering", ":", "np", ".", "ndarray", ")", "->", "None", ":", "for", "key", "in", "self", ".", "keys", "(", ")", ":", "self", "[", "key", "]", "=", "self", "[", "key", "]", "[", "ordering", "]" ]
27.222222
0.035573
def update(self,*flags): """Update Flags registry with a list of :class:`Flag` instances.""" super(Flags,self).update([(flag.name,flag) for flag in flags])
[ "def", "update", "(", "self", ",", "*", "flags", ")", ":", "super", "(", "Flags", ",", "self", ")", ".", "update", "(", "[", "(", "flag", ".", "name", ",", "flag", ")", "for", "flag", "in", "flags", "]", ")" ]
56.333333
0.02924
def push_results(self, kill_event): """ Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die. """ # We set this timeout so that the thread...
[ "def", "push_results", "(", "self", ",", "kill_event", ")", ":", "# We set this timeout so that the thread checks the kill_event and does not", "# block forever on the internal result queue", "timeout", "=", "0.1", "# timer = time.time()", "logger", ".", "debug", "(", "\"[RESULT_...
37.03125
0.004112
def _set_django_attributes(span, request): """Set the django related attributes.""" django_user = getattr(request, 'user', None) if django_user is None: return user_id = django_user.pk try: user_name = django_user.get_username() except AttributeError: # AnonymousUser in...
[ "def", "_set_django_attributes", "(", "span", ",", "request", ")", ":", "django_user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "django_user", "is", "None", ":", "return", "user_id", "=", "django_user", ".", "pk", "try", ":", ...
30.47619
0.001515
def create_pool(batch_service_client, pool_id, resource_files, publisher, offer, sku, task_file, vm_size, node_count): """Creates a pool of compute nodes with the specified OS settings. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.b...
[ "def", "create_pool", "(", "batch_service_client", ",", "pool_id", ",", "resource_files", ",", "publisher", ",", "offer", ",", "sku", ",", "task_file", ",", "vm_size", ",", "node_count", ")", ":", "_log", ".", "info", "(", "'Creating pool [{}]...'", ".", "form...
47.805556
0.000854
def pairwise_dists_on_cols(df_in, earth_mover_dist=True, energy_dist=True): """Computes pairwise statistical distance measures. parameters ---------- df_in: pandas data frame Columns represent estimators and rows represent runs. Each data frane element is an array of values which are us...
[ "def", "pairwise_dists_on_cols", "(", "df_in", ",", "earth_mover_dist", "=", "True", ",", "energy_dist", "=", "True", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", ")", "for", "col", "in", "df_in", ".", "columns", ":", "df", "[", "col", "]", "=", ...
35.083333
0.001156
def create_fwrule(kwargs=None, call=None): ''' Create a GCE firewall rule. The 'default' network is used if not specified. CLI Example: .. code-block:: bash salt-cloud -f create_fwrule gce name=allow-http allow=tcp:80 ''' if call != 'function': raise SaltCloudSystemExit( ...
[ "def", "create_fwrule", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_fwrule function must be called with -f or --function.'", ")", "if", "not", "kwargs", "or"...
26.4
0.000487
def predict(self, inputs: np.ndarray) -> np.ndarray: """Run on multiple inputs""" return self.sess.run(self.out_var, {self.inp_var: inputs})
[ "def", "predict", "(", "self", ",", "inputs", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "return", "self", ".", "sess", ".", "run", "(", "self", ".", "out_var", ",", "{", "self", ".", "inp_var", ":", "inputs", "}", ")" ]
51.333333
0.012821
def get_plugin(self, name): """ Get a plugin by its name from the plugins loaded for the current namespace :param name: :return: """ for p in self._plugins: if p.name == name: return p return None
[ "def", "get_plugin", "(", "self", ",", "name", ")", ":", "for", "p", "in", "self", ".", "_plugins", ":", "if", "p", ".", "name", "==", "name", ":", "return", "p", "return", "None" ]
27.1
0.010714
def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = ReadHoldingRegisters() instance.starting_address = start...
[ "def", "create_from_request_pdu", "(", "pdu", ")", ":", "_", ",", "starting_address", ",", "quantity", "=", "struct", ".", "unpack", "(", "'>BHH'", ",", "pdu", ")", "instance", "=", "ReadHoldingRegisters", "(", ")", "instance", ".", "starting_address", "=", ...
29.307692
0.005089
def get_transform_vector(self, resx, resy): """ Given resolution it returns a transformation vector :param resx: Resolution in x direction :type resx: float or int :param resy: Resolution in y direction :type resy: float or int :return: A tuple with 6 numbers representin...
[ "def", "get_transform_vector", "(", "self", ",", "resx", ",", "resy", ")", ":", "return", "self", ".", "x_min", ",", "self", ".", "_parse_resolution", "(", "resx", ")", ",", "0", ",", "self", ".", "y_max", ",", "0", ",", "-", "self", ".", "_parse_res...
43.545455
0.006135
def set_color(self, light_id, hex_value, brightness=None): ''' This will set the light color based on a hex value ''' light = self.get_light(light_id) xy = get_xy_from_hex(hex_value) data = { 'xy': [xy.x, xy.y], } if brightness is not None: ...
[ "def", "set_color", "(", "self", ",", "light_id", ",", "hex_value", ",", "brightness", "=", "None", ")", ":", "light", "=", "self", ".", "get_light", "(", "light_id", ")", "xy", "=", "get_xy_from_hex", "(", "hex_value", ")", "data", "=", "{", "'xy'", "...
26.4
0.004878
def render(self, context): '''Evaluates the code in the page and returns the result''' modules = { 'pyjade': __import__('pyjade') } context['false'] = False context['true'] = True try: return six.text_type(eval('pyjade.runtime.attrs(%s)'%self.code,modules,context)) except NameE...
[ "def", "render", "(", "self", ",", "context", ")", ":", "modules", "=", "{", "'pyjade'", ":", "__import__", "(", "'pyjade'", ")", "}", "context", "[", "'false'", "]", "=", "False", "context", "[", "'true'", "]", "=", "True", "try", ":", "return", "si...
30.272727
0.014577
def get_name(self): """ Return the name of the instruction :rtype: string """ if self.OP > 0xff: if self.OP >= 0xf2ff: return DALVIK_OPCODES_OPTIMIZED[self.OP][1][0] return DALVIK_OPCODES_EXTENDED_WIDTH[self.OP][1][0] return DALVIK...
[ "def", "get_name", "(", "self", ")", ":", "if", "self", ".", "OP", ">", "0xff", ":", "if", "self", ".", "OP", ">=", "0xf2ff", ":", "return", "DALVIK_OPCODES_OPTIMIZED", "[", "self", ".", "OP", "]", "[", "1", "]", "[", "0", "]", "return", "DALVIK_OP...
30.909091
0.005714
def if_json_contain(left_json, right_json, op='strict'): """ 判断一个 json 是否包含另外一个 json 的 key,并且 value 相等; :param: * left_json: (dict) 需要判断的 json,我们称之为 left * right_json: (dict) 需要判断的 json,我们称之为 right,目前是判断 left 是否包含在 right 中 * op: (string) 判断操作符,目前只有一种,默认为 strict,向后兼容 :return: ...
[ "def", "if_json_contain", "(", "left_json", ",", "right_json", ",", "op", "=", "'strict'", ")", ":", "key_list", "=", "left_json", ".", "keys", "(", ")", "if", "op", "==", "'strict'", ":", "for", "key", "in", "key_list", ":", "if", "not", "right_json", ...
25.205882
0.004494
def create(self, chatRoomInfo): """ 创建聊天室方法 方法 @param chatRoomInfo:id:要创建的聊天室的id;name:要创建的聊天室的name。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fi...
[ "def", "create", "(", "self", ",", "chatRoomInfo", ")", ":", "desc", "=", "{", "\"name\"", ":", "\"CodeSuccessReslut\"", ",", "\"desc\"", ":", "\" http 成功返回结果\",", "", "\"fields\"", ":", "[", "{", "\"name\"", ":", "\"code\"", ",", "\"type\"", ":", "\"Integer...
28.129032
0.008869
def delete_before(self, segment_info): """ Delete all base backups and WAL before a given segment This is the most commonly-used deletion operator; to delete old backups and WAL. """ # This will delete all base backup data before segment_info. self._delete_base...
[ "def", "delete_before", "(", "self", ",", "segment_info", ")", ":", "# This will delete all base backup data before segment_info.", "self", ".", "_delete_base_backups_before", "(", "segment_info", ")", "# This will delete all WAL segments before segment_info.", "self", ".", "_del...
29.705882
0.003839
def _get_matplot_dict(self, option, prop, defdict): """Returns a copy of the settings dictionary for the specified option in curargs with update values where the value is replaced by the key from the relevant default dictionary. :arg option: the key in self.curargs to update. ...
[ "def", "_get_matplot_dict", "(", "self", ",", "option", ",", "prop", ",", "defdict", ")", ":", "cargs", "=", "self", ".", "curargs", "[", "option", "]", "result", "=", "cargs", ".", "copy", "(", ")", "for", "varname", "in", "cargs", ":", "if", "prop"...
40.526316
0.007614
def _fetch_messages(self): """ Get an input message from the socket """ try: [_, msg] = self.socket.recv_multipart(flags=zmq.NOBLOCK) if Global.CONFIG_MANAGER.tracing_mode: Global.LOGGER.debug("fetched a new message") self.fetched = se...
[ "def", "_fetch_messages", "(", "self", ")", ":", "try", ":", "[", "_", ",", "msg", "]", "=", "self", ".", "socket", ".", "recv_multipart", "(", "flags", "=", "zmq", ".", "NOBLOCK", ")", "if", "Global", ".", "CONFIG_MANAGER", ".", "tracing_mode", ":", ...
32.944444
0.003279
def subset_bbox(da, lon_bnds=None, lat_bnds=None, start_yr=None, end_yr=None): """Subset a datarray or dataset spatially (and temporally) using a lat lon bounding box and years selection. Return a subsetted data array for grid points falling within a spatial bounding box defined by longitude and latitudina...
[ "def", "subset_bbox", "(", "da", ",", "lon_bnds", "=", "None", ",", "lat_bnds", "=", "None", ",", "start_yr", "=", "None", ",", "end_yr", "=", "None", ")", ":", "if", "lon_bnds", ":", "lon_bnds", "=", "np", ".", "asarray", "(", "lon_bnds", ")", "if",...
41
0.005161
def get_terms(self, sort='weight', cache=True): """Get the terms associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. sort (str): A string...
[ "def", "get_terms", "(", "self", ",", "sort", "=", "'weight'", ",", "cache", "=", "True", ")", ":", "if", "cache", "and", "(", "'terms'", "in", "self", ".", "cache", ")", "and", "sort", "==", "'weight'", ":", "return", "self", ".", "cache", "[", "'...
36.155172
0.005571
def __field_to_parameter_type_and_format(self, field): """Converts the field variant type into a tuple describing the parameter. Args: field: An instance of a subclass of messages.Field. Returns: A tuple with the type and format of the field, respectively. Raises: TypeError: if the ...
[ "def", "__field_to_parameter_type_and_format", "(", "self", ",", "field", ")", ":", "# We use lowercase values for types (e.g. 'string' instead of 'STRING').", "variant", "=", "field", ".", "variant", "if", "variant", "==", "messages", ".", "Variant", ".", "MESSAGE", ":",...
40.555556
0.001338
def get_vaults(self): """Gets the vault list resulting from the search. return: (osid.authorization.VaultList) - the vault list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: ...
[ "def", "get_vaults", "(", "self", ")", ":", "if", "self", ".", "retrieved", ":", "raise", "errors", ".", "IllegalState", "(", "'List has already been retrieved.'", ")", "self", ".", "retrieved", "=", "True", "return", "objects", ".", "VaultList", "(", "self", ...
39.916667
0.004082
def numericise(value, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty...
[ "def", "numericise", "(", "value", ",", "empty2zero", "=", "False", ",", "default_blank", "=", "\"\"", ",", "allow_underscores_in_numeric_literals", "=", "False", ")", ":", "if", "value", "is", "not", "None", ":", "if", "\"_\"", "in", "value", "and", "not", ...
28.625
0.001407
def banner(cls, content_="Well Come"): """生成占3行的字符串""" # char def sp_char = "#" # length calc itsays = content_.strip() effective_length = int(len(itsays)) # gen contents side_space = ' ' * int(effective_length * ((1 - 0.618) / 0.618) / 2) content_...
[ "def", "banner", "(", "cls", ",", "content_", "=", "\"Well Come\"", ")", ":", "# char def", "sp_char", "=", "\"#\"", "# length calc", "itsays", "=", "content_", ".", "strip", "(", ")", "effective_length", "=", "int", "(", "len", "(", "itsays", ")", ")", ...
41.769231
0.003604
def check_data(cls, name, dims, is_unstructured): """ A validation method for the data shape Parameters ---------- name: list of str with length 2 The variable names (one for the first, two for the second array) dims: list with length 2 of lists with length 1...
[ "def", "check_data", "(", "cls", ",", "name", ",", "dims", ",", "is_unstructured", ")", ":", "if", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", "or", "not", "is_iterable", "(", "name", ")", ":", "name", "=", "[", "name", "]", "dim...
40.121212
0.001475
def derive_single_object_url_pattern(slug_url_kwarg, path, action): """ Utility function called by class methods for single object views """ if slug_url_kwarg: return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg) else: return r'^%s/%s/(?P<pk>\d+)/$' % (path, action)
[ "def", "derive_single_object_url_pattern", "(", "slug_url_kwarg", ",", "path", ",", "action", ")", ":", "if", "slug_url_kwarg", ":", "return", "r'^%s/%s/(?P<%s>[^/]+)/$'", "%", "(", "path", ",", "action", ",", "slug_url_kwarg", ")", "else", ":", "return", "r'^%s/%...
38.5
0.003175
def _get_elements(self, source): """ Returns the list of HtmlElements for the source :param source: The source list to parse :type source: list :returns: A list of HtmlElements :rtype: list """ return list(chain(*[self.tree.xpath(xpath) for xpath in sourc...
[ "def", "_get_elements", "(", "self", ",", "source", ")", ":", "return", "list", "(", "chain", "(", "*", "[", "self", ".", "tree", ".", "xpath", "(", "xpath", ")", "for", "xpath", "in", "source", "]", ")", ")" ]
31.5
0.006173
def load_dale_chall(self): """Create the dictionary of words, and grade dictionary, for the Dale-Chall readability test.""" self.dale_chall_dict = os.path.join(self.base_dir, 'dicts', 'dale_chall.txt') with open(self.dale_chall_dict) as words_file: data = words_file.read() se...
[ "def", "load_dale_chall", "(", "self", ")", ":", "self", ".", "dale_chall_dict", "=", "os", ".", "path", ".", "join", "(", "self", ".", "base_dir", ",", "'dicts'", ",", "'dale_chall.txt'", ")", "with", "open", "(", "self", ".", "dale_chall_dict", ")", "a...
59.833333
0.010989
def run(self, synchronous=True, **kwargs): """Helper to run existing job template :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. ...
[ "def", "run", "(", "self", ",", "synchronous", "=", "True", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "kwargs", ".", "copy", "(", ")", "# shadow the passed-in kwargs", "kwargs", ".", "update", "(", "self", ".", "_server_config", ".", "get_client_kw...
48.214286
0.003388
def __calculate_total_wce(self): """! @brief Calculate total within cluster errors that is depend on metric that was chosen for K-Means algorithm. """ dataset_differences = self.__calculate_dataset_difference(len(self.__clusters)) self.__total_wce = 0 for inde...
[ "def", "__calculate_total_wce", "(", "self", ")", ":", "dataset_differences", "=", "self", ".", "__calculate_dataset_difference", "(", "len", "(", "self", ".", "__clusters", ")", ")", "self", ".", "__total_wce", "=", "0", "for", "index_cluster", "in", "range", ...
41.583333
0.009804
def skip_first(pipe, items=1): ''' this is an alias for skip to parallel the dedicated skip_last function to provide a little more readability to the code. the action of actually skipping does not occur until the first iteration is done ''' pipe = iter(pipe) for i in skip(pipe, items): ...
[ "def", "skip_first", "(", "pipe", ",", "items", "=", "1", ")", ":", "pipe", "=", "iter", "(", "pipe", ")", "for", "i", "in", "skip", "(", "pipe", ",", "items", ")", ":", "yield", "i" ]
40.875
0.005988
def count_async(self, limit=None, **q_options): """Count the number of query results, up to a limit. This is the asynchronous version of Query.count(). """ qry = self._fix_namespace() return qry._count_async(limit=limit, **q_options)
[ "def", "count_async", "(", "self", ",", "limit", "=", "None", ",", "*", "*", "q_options", ")", ":", "qry", "=", "self", ".", "_fix_namespace", "(", ")", "return", "qry", ".", "_count_async", "(", "limit", "=", "limit", ",", "*", "*", "q_options", ")"...
35.428571
0.003937
def on_lstHazardCategories_itemSelectionChanged(self): """Update hazard category description label. .. note:: This is an automatic Qt slot executed when the category selection changes. """ self.clear_further_steps() # Set widgets hazard_category = self.selecte...
[ "def", "on_lstHazardCategories_itemSelectionChanged", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "hazard_category", "=", "self", ".", "selected_hazard_category", "(", ")", "# Exit if no selection", "if", "not", "hazard_category",...
37.1875
0.003279
def postprocess_link(self, entry): """ Attempt to load full-text content from resource. """ if not self.follow_links: return if type(entry.link) is not list: entry.link = [entry.link] for link in list(entry.link): if not os.path.exis...
[ "def", "postprocess_link", "(", "self", ",", "entry", ")", ":", "if", "not", "self", ".", "follow_links", ":", "return", "if", "type", "(", "entry", ".", "link", ")", "is", "not", "list", ":", "entry", ".", "link", "=", "[", "entry", ".", "link", "...
31.5
0.002431
def ls(ctx, available): "List installed datasets on path" path = ctx.obj['path'] global_ = ctx.obj['global_'] _ls(available=available, **ctx.obj)
[ "def", "ls", "(", "ctx", ",", "available", ")", ":", "path", "=", "ctx", ".", "obj", "[", "'path'", "]", "global_", "=", "ctx", ".", "obj", "[", "'global_'", "]", "_ls", "(", "available", "=", "available", ",", "*", "*", "ctx", ".", "obj", ")" ]
22.428571
0.006135
def access_request(pid, record, template, **kwargs): """Create an access request.""" recid = int(pid.pid_value) datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) # Record must be in restricted access mode. if record.get('access_right') != 'restricted' or \ ...
[ "def", "access_request", "(", "pid", ",", "record", ",", "template", ",", "*", "*", "kwargs", ")", ":", "recid", "=", "int", "(", "pid", ".", "pid_value", ")", "datastore", "=", "LocalProxy", "(", "lambda", ":", "current_app", ".", "extensions", "[", "...
33.189655
0.000505
def run_preprocessor(self, files_to_download): """ Run file_download_pre_processor for each file we are about to download. :param files_to_download: [ProjectFile]: files that will be downloaded """ for project_file in files_to_download: self.file_download_pre_processo...
[ "def", "run_preprocessor", "(", "self", ",", "files_to_download", ")", ":", "for", "project_file", "in", "files_to_download", ":", "self", ".", "file_download_pre_processor", ".", "run", "(", "self", ".", "remote_store", ".", "data_service", ",", "project_file", "...
52.142857
0.008086
def index( self, symbol='000001', market='sh', category='9', start='0', offset='100'): ''' 获取指数k线 K线种类: - 0 5分钟K线 - 1 15分钟K线 - 2 30分钟K线 - 3 1小时K线 - 4 日K线 - 5 周K线 - 6 月K线 - 7 1分钟 ...
[ "def", "index", "(", "self", ",", "symbol", "=", "'000001'", ",", "market", "=", "'sh'", ",", "category", "=", "'9'", ",", "start", "=", "'0'", ",", "offset", "=", "'100'", ")", ":", "market", "=", "1", "if", "market", "==", "'sh'", "else", "0", ...
21.756757
0.003567
def elapsed(self): """elapsed time since initial submission""" if self.ready(): return self.wall_time now = submitted = datetime.now() for msg_id in self.msg_ids: if msg_id in self._client.metadata: stamp = self._client.metadata[msg_id]['s...
[ "def", "elapsed", "(", "self", ")", ":", "if", "self", ".", "ready", "(", ")", ":", "return", "self", ".", "wall_time", "now", "=", "submitted", "=", "datetime", ".", "now", "(", ")", "for", "msg_id", "in", "self", ".", "msg_ids", ":", "if", "msg_i...
37.5
0.006508
def run_actions(self, actions): """ Runs the given lists of attached actions and instance actions on the client. :param actions: Actions to apply. :type actions: list[dockermap.map.action.ItemAction] :return: Where the result is not ``None``, returns the output from the client. ...
[ "def", "run_actions", "(", "self", ",", "actions", ")", ":", "policy", "=", "self", ".", "_policy", "for", "action", "in", "actions", ":", "config_id", "=", "action", ".", "config_id", "config_type", "=", "config_id", ".", "config_type", "client_config", "="...
54.431373
0.004954
def consume(self, consumer_callback, exclusive=False, recover=False): """ Initialize consuming of messages from an AMQP queue. Messages will be consumed after start_consuming() is called. Calling this method multiple times with exclusive active will result in a pika.exceptions.ChannelClosed Error. Parameters ...
[ "def", "consume", "(", "self", ",", "consumer_callback", ",", "exclusive", "=", "False", ",", "recover", "=", "False", ")", ":", "if", "recover", ":", "self", ".", "logger", ".", "info", "(", "\"Asking server to requeue all unacknowledged messages\"", ")", "self...
37.935484
0.028192
def _spawn(self): """ Initialize the queue and the threads. """ self.queue = Queue(maxsize=self.num_threads * 10) for i in range(self.num_threads): t = Thread(target=self._consume) t.daemon = True t.start()
[ "def", "_spawn", "(", "self", ")", ":", "self", ".", "queue", "=", "Queue", "(", "maxsize", "=", "self", ".", "num_threads", "*", "10", ")", "for", "i", "in", "range", "(", "self", ".", "num_threads", ")", ":", "t", "=", "Thread", "(", "target", ...
37.142857
0.007519
def set(self, header, value=None): """Set header to the value""" if value is None: for k, v in header.items(): self.headers[k] = v else: self.headers[header] = value
[ "def", "set", "(", "self", ",", "header", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "for", "k", ",", "v", "in", "header", ".", "items", "(", ")", ":", "self", ".", "headers", "[", "k", "]", "=", "v", "else", ":", ...
31.857143
0.008734
def _set_ospf(self, v, load=False): """ Setter method for ospf, mapped from YANG variable /rbridge_id/ipv6/router/ospf (list) If this variable is read-only (config: false) in the source YANG file, then _set_ospf is considered as a private method. Backends looking to populate this variable should ...
[ "def", "_set_ospf", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
135.818182
0.003323
def AddContract(self, contract): """ Add a contract to the database. Args: contract(neo.SmartContract.Contract): a Contract instance. """ super(UserWallet, self).AddContract(contract) try: db_contract = Contract.get(ScriptHash=contract.ScriptHash...
[ "def", "AddContract", "(", "self", ",", "contract", ")", ":", "super", "(", "UserWallet", ",", "self", ")", ".", "AddContract", "(", "contract", ")", "try", ":", "db_contract", "=", "Contract", ".", "get", "(", "ScriptHash", "=", "contract", ".", "Script...
37.5
0.003714
def assign_bus_results(grid, bus_data): """ Write results obtained from PF to graph Parameters ---------- grid: ding0.network bus_data: pandas.DataFrame DataFrame containing voltage levels obtained from PF analysis """ # iterate of nodes and assign voltage obtained from power f...
[ "def", "assign_bus_results", "(", "grid", ",", "bus_data", ")", ":", "# iterate of nodes and assign voltage obtained from power flow analysis", "for", "node", "in", "grid", ".", "_graph", ".", "nodes", "(", ")", ":", "# check if node is connected to graph", "if", "(", "...
42.148148
0.000859
def parse_command_line() -> Namespace: """Parse command line options and set them to ``config``. This function skips unknown command line options. After parsing options, set log level and set options in ``tornado.options``. """ import tornado.options parser.parse_known_args(namespace=config) ...
[ "def", "parse_command_line", "(", ")", "->", "Namespace", ":", "import", "tornado", ".", "options", "parser", ".", "parse_known_args", "(", "namespace", "=", "config", ")", "set_loglevel", "(", ")", "# set new log level based on commanline option", "for", "k", ",", ...
39.538462
0.001901
def wr_txt(self, fout_txt="gos_depth01.txt", title=None): """write text table of depth-01 GO terms and their letter representation.""" with open(fout_txt, 'w') as prt: self.prt_header(prt, title) data_nts = self.prt_txt(prt) sys.stdout.write(" {N:>5} items WROTE: {TX...
[ "def", "wr_txt", "(", "self", ",", "fout_txt", "=", "\"gos_depth01.txt\"", ",", "title", "=", "None", ")", ":", "with", "open", "(", "fout_txt", ",", "'w'", ")", "as", "prt", ":", "self", ".", "prt_header", "(", "prt", ",", "title", ")", "data_nts", ...
53.571429
0.007874
def clear_cache(self): ''' Completely clear cache ''' errors = [] for rdir in (self.cache_root, self.file_list_cachedir): if os.path.exists(rdir): try: shutil.rmtree(rdir) except OSError as exc: e...
[ "def", "clear_cache", "(", "self", ")", ":", "errors", "=", "[", "]", "for", "rdir", "in", "(", "self", ".", "cache_root", ",", "self", ".", "file_list_cachedir", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "rdir", ")", ":", "try", ":", ...
31
0.004474
def process_bind_param(self, obj, dialect): """Get a flask_cloudy.Object and save it as a dict""" value = obj or {} if isinstance(obj, flask_cloudy.Object): value = {} for k in self.DEFAULT_KEYS: value[k] = getattr(obj, k) return super(self.__clas...
[ "def", "process_bind_param", "(", "self", ",", "obj", ",", "dialect", ")", ":", "value", "=", "obj", "or", "{", "}", "if", "isinstance", "(", "obj", ",", "flask_cloudy", ".", "Object", ")", ":", "value", "=", "{", "}", "for", "k", "in", "self", "."...
39.666667
0.005479
def check_tool(command): """ Checks that a tool can be invoked by 'command'. If command is not an absolute path, checks if it can be found in 'path'. If comand is absolute path, check that it exists. Returns 'command' if ok and empty string otherwise. """ assert is_iterable_typed(com...
[ "def", "check_tool", "(", "command", ")", ":", "assert", "is_iterable_typed", "(", "command", ",", "basestring", ")", "#FIXME: why do we check the first and last elements????", "if", "check_tool_aux", "(", "command", "[", "0", "]", ")", "or", "check_tool_aux", "(", ...
47.7
0.006173
def message(self): ''' Override this to provide failure message''' name = self.__class__.__name__ return "{0} {1}".format(humanize(name), pp(*self.expectedArgs, **self.expectedKwArgs))
[ "def", "message", "(", "self", ")", ":", "name", "=", "self", ".", "__class__", ".", "__name__", "return", "\"{0} {1}\"", ".", "format", "(", "humanize", "(", "name", ")", ",", "pp", "(", "*", "self", ".", "expectedArgs", ",", "*", "*", "self", ".", ...
47.2
0.008333
def calls_sorted(self): """ calls sorted in z """ def _z(call): if isinstance(call.z.value, np.ndarray): return np.mean(call.z.value.flatten()) elif isinstance(call.z.value, float) or isinstance(call.z.value, int): return call.z.val...
[ "def", "calls_sorted", "(", "self", ")", ":", "def", "_z", "(", "call", ")", ":", "if", "isinstance", "(", "call", ".", "z", ".", "value", ",", "np", ".", "ndarray", ")", ":", "return", "np", ".", "mean", "(", "call", ".", "z", ".", "value", "....
36.421053
0.004225
def check(self, request, consumer, token, signature): """ Returns whether the given signature is the correct signature for the given consumer and token signing the given request. """ built = self.sign(request, consumer, token) if isinstance(signature, STRING_TYPES): ...
[ "def", "check", "(", "self", ",", "request", ",", "consumer", ",", "token", ",", "signature", ")", ":", "built", "=", "self", ".", "sign", "(", "request", ",", "consumer", ",", "token", ")", "if", "isinstance", "(", "signature", ",", "STRING_TYPES", ")...
43.222222
0.005038
def _blockread(self, fname): """ Generator yields bsize lines from gdf file. Hidden method. Parameters ---------- fname : str Name of gdf-file. Yields ------ list file contents ""...
[ "def", "_blockread", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "a", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "bsize", ")", ":", "line", "=", "...
22.851852
0.010886
def compile_glob(spec): """Convert the given glob `spec` to a compiled regex.""" parsed = "".join(parse_glob(spec)) regex = "^{0}$".format(parsed) return re.compile(regex)
[ "def", "compile_glob", "(", "spec", ")", ":", "parsed", "=", "\"\"", ".", "join", "(", "parse_glob", "(", "spec", ")", ")", "regex", "=", "\"^{0}$\"", ".", "format", "(", "parsed", ")", "return", "re", ".", "compile", "(", "regex", ")" ]
36.6
0.005348
def _ensure_running(name, no_start=False, path=None): ''' If the container is not currently running, start it. This function returns the state that the container was in before changing path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: ...
[ "def", "_ensure_running", "(", "name", ",", "no_start", "=", "False", ",", "path", "=", "None", ")", ":", "_ensure_exists", "(", "name", ",", "path", "=", "path", ")", "pre", "=", "state", "(", "name", ",", "path", "=", "path", ")", "if", "pre", "=...
32.862069
0.001019
def apply_type_shim(cls, _context=None) -> Iterator: """ Morphs model fields to representative type """ if cls.name in ["IntField", "SmallIntField"]: base_nodes = scoped_nodes.builtin_lookup("int") elif cls.name in ["CharField", "TextField"]: base_nodes = scoped_nodes.builtin_lookup(...
[ "def", "apply_type_shim", "(", "cls", ",", "_context", "=", "None", ")", "->", "Iterator", ":", "if", "cls", ".", "name", "in", "[", "\"IntField\"", ",", "\"SmallIntField\"", "]", ":", "base_nodes", "=", "scoped_nodes", ".", "builtin_lookup", "(", "\"int\"",...
43.357143
0.002417
def _solidAngleMMD(self): """ Compute solid angle within the mask annulus (deg^2) as a function of mag_1 and mag_2 """ # Take upper corner of the magnitude bin mag_2,mag_1 = np.meshgrid(self.roi.bins_mag[1:],self.roi.bins_mag[1:]) # Havent tested since adding fra...
[ "def", "_solidAngleMMD", "(", "self", ")", ":", "# Take upper corner of the magnitude bin", "mag_2", ",", "mag_1", "=", "np", ".", "meshgrid", "(", "self", ".", "roi", ".", "bins_mag", "[", "1", ":", "]", ",", "self", ".", "roi", ".", "bins_mag", "[", "1...
43.526316
0.015385
def _symlink_local_src(self, gopath, go_local_src, required_links): """Creates symlinks from the given gopath to the source files of the given local package. Also duplicates directory structure leading to source files of package within gopath, in order to provide isolation to the package. Adds the sym...
[ "def", "_symlink_local_src", "(", "self", ",", "gopath", ",", "go_local_src", ",", "required_links", ")", ":", "source_list", "=", "[", "os", ".", "path", ".", "join", "(", "get_buildroot", "(", ")", ",", "src", ")", "for", "src", "in", "go_local_src", "...
52.076923
0.004354
def get_string(self): """A string representation of the junction :return: string represnetation :rtype: string """ return self.left.chr+':'+str(self.left.end)+'-'+self.right.chr+':'+str(self.right.start)
[ "def", "get_string", "(", "self", ")", ":", "return", "self", ".", "left", ".", "chr", "+", "':'", "+", "str", "(", "self", ".", "left", ".", "end", ")", "+", "'-'", "+", "self", ".", "right", ".", "chr", "+", "':'", "+", "str", "(", "self", ...
31.142857
0.008929
def find_links(cls, root_plot): """ Traverses the supplied plot and searches for any Links on the plotted objects. """ plot_fn = lambda x: isinstance(x, GenericElementPlot) and not isinstance(x, GenericOverlayPlot) plots = root_plot.traverse(lambda x: x, [plot_fn]) ...
[ "def", "find_links", "(", "cls", ",", "root_plot", ")", ":", "plot_fn", "=", "lambda", "x", ":", "isinstance", "(", "x", ",", "GenericElementPlot", ")", "and", "not", "isinstance", "(", "x", ",", "GenericOverlayPlot", ")", "plots", "=", "root_plot", ".", ...
45.380952
0.004111
def _remove_dep(self, dep): """ Decrement the reference count for *dep*. If the reference count reaches 0, then the dependency is removed and its *changed* event is disconnected. """ refcount = self._deps[dep] if refcount == 1: self._deps.pop(dep) ...
[ "def", "_remove_dep", "(", "self", ",", "dep", ")", ":", "refcount", "=", "self", ".", "_deps", "[", "dep", "]", "if", "refcount", "==", "1", ":", "self", ".", "_deps", ".", "pop", "(", "dep", ")", "dep", ".", "_dependents", ".", "pop", "(", "sel...
34.818182
0.007634