text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def compare(items, params, rank=False): """Generate a comparison outcome that follows Luce's axiom. This function samples an outcome for the comparison of a subset of items, from a model parametrized by ``params``. If ``rank`` is True, it returns a ranking over the items, otherwise it returns a single ...
[ "def", "compare", "(", "items", ",", "params", ",", "rank", "=", "False", ")", ":", "probs", "=", "probabilities", "(", "items", ",", "params", ")", "if", "rank", ":", "return", "np", ".", "random", ".", "choice", "(", "items", ",", "size", "=", "l...
32.615385
21.769231
def sign_data(self, name, hash_input, key_version=None, hash_algorithm="sha2-256", context="", prehashed=False, signature_algorithm="pss", mount_point=DEFAULT_MOUNT_POINT): """Return the cryptographic signature of the given data using the named key and the specified hash algorithm. Th...
[ "def", "sign_data", "(", "self", ",", "name", ",", "hash_input", ",", "key_version", "=", "None", ",", "hash_algorithm", "=", "\"sha2-256\"", ",", "context", "=", "\"\"", ",", "prehashed", "=", "False", ",", "signature_algorithm", "=", "\"pss\"", ",", "mount...
58.515152
30.939394
def split_template_path(template): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in template.split('/'): if path.sep in piece \ or (path.altsep and path.altsep in piece)...
[ "def", "split_template_path", "(", "template", ")", ":", "pieces", "=", "[", "]", "for", "piece", "in", "template", ".", "split", "(", "'/'", ")", ":", "if", "path", ".", "sep", "in", "piece", "or", "(", "path", ".", "altsep", "and", "path", ".", "...
36.846154
10
def values(self): """ TimeSeries of values. """ # if accessing and stale - update first if self._needupdate or self.now != self.parent.now: self.update(self.root.now) if self.root.stale: self.root.update(self.root.now, None) return self._va...
[ "def", "values", "(", "self", ")", ":", "# if accessing and stale - update first", "if", "self", ".", "_needupdate", "or", "self", ".", "now", "!=", "self", ".", "parent", ".", "now", ":", "self", ".", "update", "(", "self", ".", "root", ".", "now", ")",...
33
8.6
def _finalize_step(self): """Finalize simulation step after all agents have acted for the current step. """ t = time.time() if self._callback is not None: self._callback(self.age) t2 = time.time() self._step_processing_time += t2 - t self._log(...
[ "def", "_finalize_step", "(", "self", ")", ":", "t", "=", "time", ".", "time", "(", ")", "if", "self", ".", "_callback", "is", "not", "None", ":", "self", ".", "_callback", "(", "self", ".", "age", ")", "t2", "=", "time", ".", "time", "(", ")", ...
41.928571
12.785714
def read_config(config_path=default_config_path): """ Read configuration file and produce a dictionary of the following structure: {'<instance1>': {'username': '<user>', 'password': '<pass>', 'verify': <True/False>, 'cert': '<path-to-cert>'} '<instance2>': {...}, ...}...
[ "def", "read_config", "(", "config_path", "=", "default_config_path", ")", ":", "config_path", "=", "os", ".", "path", ".", "expanduser", "(", "config_path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "config_path", ")", ":", "raise", "OSErro...
37.318182
21.772727
def volumes(self): """ Returns a `list` of all the `Volume` known to the cluster. Updates every time - no caching. :return: a `list` of all the `Volume` known to the cluster. :rtype: list """ self.connection._check_login() response = self.connection._do_get("{}/{...
[ "def", "volumes", "(", "self", ")", ":", "self", ".", "connection", ".", "_check_login", "(", ")", "response", "=", "self", ".", "connection", ".", "_do_get", "(", "\"{}/{}\"", ".", "format", "(", "self", ".", "connection", ".", "_api_url", ",", "\"types...
39.357143
20.5
def watch_one_event(event_filter, callback, timeout_callback, timeout, args, start_time=None): """ Start to watch one event. :param event_filter: :param callback: :param timeout_callback: :param timeout: :param args: :param start_t...
[ "def", "watch_one_event", "(", "event_filter", ",", "callback", ",", "timeout_callback", ",", "timeout", ",", "args", ",", "start_time", "=", "None", ")", ":", "if", "timeout", "and", "not", "start_time", ":", "start_time", "=", "int", "(", "datetime", ".", ...
30.051282
16.923077
def update_node(availability=str, node_name=str, role=str, node_id=str, version=int): ''' Updates docker swarm nodes/needs to target a manager node/minion availability Drain or Active node_name minion/node role ...
[ "def", "update_node", "(", "availability", "=", "str", ",", "node_name", "=", "str", ",", "role", "=", "str", ",", "node_id", "=", "str", ",", "version", "=", "int", ")", ":", "client", "=", "docker", ".", "APIClient", "(", "base_url", "=", "'unix://va...
28.113636
23.522727
def manager_view(request, managerTitle): ''' View the details of a manager position. Parameters: request is an HTTP request managerTitle is the URL title of the manager. ''' targetManager = get_object_or_404(Manager, url_title=managerTitle) if not targetManager.active: messa...
[ "def", "manager_view", "(", "request", ",", "managerTitle", ")", ":", "targetManager", "=", "get_object_or_404", "(", "Manager", ",", "url_title", "=", "managerTitle", ")", "if", "not", "targetManager", ".", "active", ":", "messages", ".", "add_message", "(", ...
43.5
21.375
def get_queryset(self, **kwargs): """ Gets our queryset. This takes care of filtering if there are any fields to filter by. """ queryset = self.derive_queryset(**kwargs) return self.order_queryset(queryset)
[ "def", "get_queryset", "(", "self", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "self", ".", "derive_queryset", "(", "*", "*", "kwargs", ")", "return", "self", ".", "order_queryset", "(", "queryset", ")" ]
31.125
13.125
def connect(self, addr): """Initiate a connection request to the peer router.""" if _debug: RouterToRouterService._debug("connect %r", addr) # make a connection conn = ConnectionState(addr) self.multiplexer.connections[addr] = conn # associate with this service, but it ...
[ "def", "connect", "(", "self", ",", "addr", ")", ":", "if", "_debug", ":", "RouterToRouterService", ".", "_debug", "(", "\"connect %r\"", ",", "addr", ")", "# make a connection", "conn", "=", "ConnectionState", "(", "addr", ")", "self", ".", "multiplexer", "...
31.347826
21.304348
def import_words_from_file(self, inputfile: str, is_diceware: bool) -> None: """Import words for the wordlist from a given file. The file can have a single column with words or be diceware-like (two columns). Keyword argumen...
[ "def", "import_words_from_file", "(", "self", ",", "inputfile", ":", "str", ",", "is_diceware", ":", "bool", ")", "->", "None", ":", "if", "not", "Aux", ".", "isfile_notempty", "(", "inputfile", ")", ":", "raise", "FileNotFoundError", "(", "'Input file does no...
40.347826
22
def list_overview_fmt_gen(self): """Generator for the LIST OVERVIEW.FMT See list_overview_fmt() for more information. Yields: An element in the list returned by list_overview_fmt(). """ code, message = self.command("LIST OVERVIEW.FMT") if code != 215: ...
[ "def", "list_overview_fmt_gen", "(", "self", ")", ":", "code", ",", "message", "=", "self", ".", "command", "(", "\"LIST OVERVIEW.FMT\"", ")", "if", "code", "!=", "215", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "for", "line", "in",...
36
16.045455
def distance_calc(s1, s2): """ Calculate Levenshtein distance between two words. :param s1: first word :type s1 : str :param s2: second word :type s2 : str :return: distance between two word References : 1- https://stackoverflow.com/questions/2460177/edit-distance-in-python 2- ...
[ "def", "distance_calc", "(", "s1", ",", "s2", ")", ":", "if", "len", "(", "s1", ")", ">", "len", "(", "s2", ")", ":", "s1", ",", "s2", "=", "s2", ",", "s1", "distances", "=", "range", "(", "len", "(", "s1", ")", "+", "1", ")", "for", "i2", ...
28.607143
17.035714
def _set_arp_entry(self, v, load=False): """ Setter method for arp_entry, mapped from YANG variable /rbridge_id/arp_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_arp_entry is considered as a private method. Backends looking to populate this variable sh...
[ "def", "_set_arp_entry", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
131.772727
63.227273
def export_envars(self, env): """Export the environment variables contained in the dict env.""" for k, v in env.items(): self.export_envar(k, v)
[ "def", "export_envars", "(", "self", ",", "env", ")", ":", "for", "k", ",", "v", "in", "env", ".", "items", "(", ")", ":", "self", ".", "export_envar", "(", "k", ",", "v", ")" ]
42.25
6
def from_api_repr(cls, resource): """Factory: construct instance from the JSON repr. :type resource: dict :param resource: JSON representation of the entry :rtype: :class:`QueryPlanEntryStep` :return: new instance built from the resource """ return cls(kind=reso...
[ "def", "from_api_repr", "(", "cls", ",", "resource", ")", ":", "return", "cls", "(", "kind", "=", "resource", ".", "get", "(", "\"kind\"", ")", ",", "substeps", "=", "resource", ".", "get", "(", "\"substeps\"", ",", "(", ")", ")", ")" ]
36.7
17.6
def getIfStats(self): """Return dictionary of Traffic Stats for Network Interfaces. @return: Nested dictionary of statistics for each interface. """ info_dict = {} try: fp = open(ifaceStatsFile, 'r') data = fp.read() fp.close(...
[ "def", "getIfStats", "(", "self", ")", ":", "info_dict", "=", "{", "}", "try", ":", "fp", "=", "open", "(", "ifaceStatsFile", ",", "'r'", ")", "data", "=", "fp", ".", "read", "(", ")", "fp", ".", "close", "(", ")", "except", ":", "raise", "IOErro...
39.111111
17.259259
def kron_dot(A, B, C, out=None): r""" Kronecker product followed by dot product. Let :math:`\mathrm A`, :math:`\mathrm B`, and :math:`\mathrm C` be matrices of dimensions :math:`p\times p`, :math:`n\times d`, and :math:`d\times p`. It computes .. math:: \text{unvec}((\mathrm A\otimes\mat...
[ "def", "kron_dot", "(", "A", ",", "B", ",", "C", ",", "out", "=", "None", ")", ":", "from", "numpy", "import", "dot", ",", "zeros", ",", "asarray", "A", "=", "asarray", "(", "A", ")", "B", "=", "asarray", "(", "B", ")", "C", "=", "asarray", "...
23.02439
24
def is_constraint(self): """ returns the expression of the constraint that constrains this parameter """ if self._is_constraint is None: return None return self._bundle.get_parameter(context='constraint', uniqueid=self._is_constraint)
[ "def", "is_constraint", "(", "self", ")", ":", "if", "self", ".", "_is_constraint", "is", "None", ":", "return", "None", "return", "self", ".", "_bundle", ".", "get_parameter", "(", "context", "=", "'constraint'", ",", "uniqueid", "=", "self", ".", "_is_co...
40
18
def load_exon_bulk(self, exon_objs): """Load a bulk of exon objects to the database Arguments: exon_objs(iterable(scout.models.hgnc_exon)) """ try: result = self.exon_collection.insert_many(transcript_objs) except (DuplicateKeyError, BulkWriteError) as e...
[ "def", "load_exon_bulk", "(", "self", ",", "exon_objs", ")", ":", "try", ":", "result", "=", "self", ".", "exon_collection", ".", "insert_many", "(", "transcript_objs", ")", "except", "(", "DuplicateKeyError", ",", "BulkWriteError", ")", "as", "err", ":", "r...
29.230769
19.307692
def run_and_measure(self, quil_program: Program, qubits: List[int] = None, trials: int = 1, memory_map: Any = None) -> np.ndarray: """ Run a Quil program once to determine the final wavefunction, and measure multiple times. Alternatively, consider using ``wavefunction`` ...
[ "def", "run_and_measure", "(", "self", ",", "quil_program", ":", "Program", ",", "qubits", ":", "List", "[", "int", "]", "=", "None", ",", "trials", ":", "int", "=", "1", ",", "memory_map", ":", "Any", "=", "None", ")", "->", "np", ".", "ndarray", ...
59.022727
37.068182
def safe_file_dump(filename, payload='', mode='w'): """Write a string to a file. This method is "safe" to the extent that `safe_open` is "safe". See the explanation on the method doc there. When `payload` is an empty string (the default), this method can be used as a concise way to create an empty file alon...
[ "def", "safe_file_dump", "(", "filename", ",", "payload", "=", "''", ",", "mode", "=", "'w'", ")", ":", "with", "safe_open", "(", "filename", ",", "mode", "=", "mode", ")", "as", "f", ":", "f", ".", "write", "(", "payload", ")" ]
44.625
28.4375
def identify_image(image): """Provides a tuple of image's UNIQUE_IMAGE_ATTRIBUTES. Note: this is not guaranteed to be unique (and will often not be) for pre-1.1 metadata, as subvariant did not exist. Provided as a function so consumers can use it on plain image dicts read from the metadata or PDC. ...
[ "def", "identify_image", "(", "image", ")", ":", "try", ":", "# Image instance case", "attrs", "=", "tuple", "(", "getattr", "(", "image", ",", "attr", ")", "for", "attr", "in", "UNIQUE_IMAGE_ATTRIBUTES", ")", "except", "AttributeError", ":", "# Plain dict case"...
45.210526
23.105263
def bend_rounded(Di, angle, fd=None, rc=None, bend_diameters=5.0, Re=None, roughness=0.0, L_unimpeded=None, method='Rennels'): r'''Returns loss coefficient for rounded bend in a pipe of diameter `Di`, `angle`, with a specified either radius of curvature `rc` or curvature defined by `bend_d...
[ "def", "bend_rounded", "(", "Di", ",", "angle", ",", "fd", "=", "None", ",", "rc", "=", "None", ",", "bend_diameters", "=", "5.0", ",", "Re", "=", "None", ",", "roughness", "=", "0.0", ",", "L_unimpeded", "=", "None", ",", "method", "=", "'Rennels'",...
44.2
24.955556
def save_graph(cn_topo, filename, showintfs=False, showaddrs=False): ''' Save the topology to an image file ''' __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs) pyp.savefig(filename)
[ "def", "save_graph", "(", "cn_topo", ",", "filename", ",", "showintfs", "=", "False", ",", "showaddrs", "=", "False", ")", ":", "__do_draw", "(", "cn_topo", ",", "showintfs", "=", "showintfs", ",", "showaddrs", "=", "showaddrs", ")", "pyp", ".", "savefig",...
35
22.333333
def send_action(action, params=None): """ helper method for sending actions """ data={"msg_type":"action", "action":action} if params is not None: data['params']=params _comm.send(data)
[ "def", "send_action", "(", "action", ",", "params", "=", "None", ")", ":", "data", "=", "{", "\"msg_type\"", ":", "\"action\"", ",", "\"action\"", ":", "action", "}", "if", "params", "is", "not", "None", ":", "data", "[", "'params'", "]", "=", "params"...
23.25
8.75
def encode(self, sequence): """Returns a tuple (binary reprensentation, default sequence, polymorphisms list)""" polymorphisms = [] defaultSequence = '' binSequence = array.array(self.forma.typecode) b = 0 i = 0 trueI = 0 #not inc in case if poly poly = set() while i < len(sequence)-1: b = b | ...
[ "def", "encode", "(", "self", ",", "sequence", ")", ":", "polymorphisms", "=", "[", "]", "defaultSequence", "=", "''", "binSequence", "=", "array", ".", "array", "(", "self", ".", "forma", ".", "typecode", ")", "b", "=", "0", "i", "=", "0", "trueI", ...
23.829268
19.341463
def _exit_gracefully(self, signum, frame): """ Helper method to clean up DAG file processors to avoid leaving orphan processes. """ self.log.info("Exiting gracefully upon receiving signal %s", signum) self.terminate() self.end() self.log.debug("Finished terminatin...
[ "def", "_exit_gracefully", "(", "self", ",", "signum", ",", "frame", ")", ":", "self", ".", "log", ".", "info", "(", "\"Exiting gracefully upon receiving signal %s\"", ",", "signum", ")", "self", ".", "terminate", "(", ")", "self", ".", "end", "(", ")", "s...
39.777778
17.777778
def check_dependencies(): """ Check that dependencies are installed: - require git 2.7+, so that credential-cache--daemon ignores SIGHUP https://github.com/git/git/blob/v2.7.0/credential-cache--daemon.c """ # Check that git is installed if not shutil.which("git"): raise Error(_(...
[ "def", "check_dependencies", "(", ")", ":", "# Check that git is installed", "if", "not", "shutil", ".", "which", "(", "\"git\"", ")", ":", "raise", "Error", "(", "_", "(", "\"You don't have git. Install git, then re-run!\"", ")", ")", "# Check that git --version > 2.7"...
46.625
25.125
def redhat_release(rh_release, un): """ .. warning:: This combiner methode is deprecated, please use :py:class:`insights.combiners.redhat_release.RedHatRelease` instead. Combiner method to check uname and redhat-release for rhel major/minor version. Prefer uname to redhat-release. ...
[ "def", "redhat_release", "(", "rh_release", ",", "un", ")", ":", "deprecated", "(", "redhat_release", ",", "\"Use the `RedHatRelease` class instead.\"", ")", "if", "un", "and", "un", ".", "release_tuple", "[", "0", "]", "!=", "-", "1", ":", "return", "Release"...
25.641026
23.384615
def get_historic_trades(self, start, end, granularity, product_id='BTC-USD'): """`<https://docs.exchange.coinbase.com/#get-historic-rates>`_ :param start: either datetime.datetime or str in ISO 8601 :param end: either datetime.datetime or str in ISO 8601 :pram int granularity: desired timeslice in seco...
[ "def", "get_historic_trades", "(", "self", ",", "start", ",", "end", ",", "granularity", ",", "product_id", "=", "'BTC-USD'", ")", ":", "params", "=", "{", "'start'", ":", "self", ".", "_format_iso_time", "(", "start", ")", ",", "'end'", ":", "self", "."...
36.866667
19.333333
def create_networking_resource_from_context(shell_name, supported_os, context): """ Creates an instance of Networking Resource by given context :param shell_name: Shell Name :type shell_name: str :param supported_os: list of supported OS :type supported_os: list :param context: cloudshell.sh...
[ "def", "create_networking_resource_from_context", "(", "shell_name", ",", "supported_os", ",", "context", ")", ":", "result", "=", "GenericNetworkingResource", "(", "shell_name", "=", "shell_name", ",", "name", "=", "context", ".", "resource", ".", "name", ",", "s...
38.904762
21.952381
def list(self, **kwargs): """Return a list of roles. =====API DOCS===== Retrieve a list of objects. :param all_pages: Flag that if set, collect all pages of content from the API when returning results. :type all_pages: bool :param page: The page to show. Ignored if all_...
[ "def", "list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "data", ",", "self", ".", "endpoint", "=", "self", ".", "data_endpoint", "(", "kwargs", ")", "r", "=", "super", "(", "Resource", ",", "self", ")", ".", "list", "(", "*", "*", "data", ...
40.041667
26.666667
def check_exists(name, path): ''' Check if the given path is an alternative for a name. .. versionadded:: 2015.8.4 CLI Example: .. code-block:: bash salt '*' alternatives.check_exists name path ''' cmd = [_get_cmd(), '--display', name] out = __salt__['cmd.run_all'](cmd, pytho...
[ "def", "check_exists", "(", "name", ",", "path", ")", ":", "cmd", "=", "[", "_get_cmd", "(", ")", ",", "'--display'", ",", "name", "]", "out", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "if", "out"...
24.684211
25.421053
def write(filename, f): """Write a function `f` defined in terms of spherical coordinates to a file. """ import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], ...
[ "def", "write", "(", "filename", ",", "f", ")", ":", "import", "meshio", "import", "meshzoo", "points", ",", "cells", "=", "meshzoo", ".", "iso_sphere", "(", "5", ")", "# get spherical coordinates from points", "polar", "=", "numpy", ".", "arccos", "(", "poi...
34.076923
15.692308
def cis(x: float) -> complex: r""" Implements Euler's formula :math:`\text{cis}(x) = e^{i \pi x} = \cos(x) + i \sin(x)` """ return np.cos(x) + 1.0j * np.sin(x)
[ "def", "cis", "(", "x", ":", "float", ")", "->", "complex", ":", "return", "np", ".", "cos", "(", "x", ")", "+", "1.0j", "*", "np", ".", "sin", "(", "x", ")" ]
29
7.166667
def describe_db_instances(name=None, filters=None, jmespath='DBInstances', region=None, key=None, keyid=None, profile=None): ''' Return a detailed listing of some, or all, DB Instances visible in the current scope. Arbitrary subelements or subsections of the returned dataset c...
[ "def", "describe_db_instances", "(", "name", "=", "None", ",", "filters", "=", "None", ",", "jmespath", "=", "'DBInstances'", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn",...
41.807692
26.884615
def main(): """Create coverage reports and open them in the browser.""" usage = "Usage: %prog PATH_TO_PACKAGE" parser = optparse.OptionParser(usage=usage) parser.add_option( "-v", "--verbose", action="store_true", dest="verbose", default=False, help="Show debug output") parse...
[ "def", "main", "(", ")", ":", "usage", "=", "\"Usage: %prog PATH_TO_PACKAGE\"", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "usage", ")", "parser", ".", "add_option", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true...
38.210526
15.77193
def from_val(val_schema): """Serialize a val schema to teleport.""" definition = getattr(val_schema, "definition", val_schema) if isinstance( val_schema, BaseSchema) else val_schema if isinstance(definition, dict): return _dict_to_teleport(definition) if isinstance(definition, list): ...
[ "def", "from_val", "(", "val_schema", ")", ":", "definition", "=", "getattr", "(", "val_schema", ",", "\"definition\"", ",", "val_schema", ")", "if", "isinstance", "(", "val_schema", ",", "BaseSchema", ")", "else", "val_schema", "if", "isinstance", "(", "defin...
36.294118
15.529412
def _rpt_unused_sections(self, prt): """Report unused sections.""" sections_unused = set(self.sections_seen).difference(self.section2goids.keys()) for sec in sections_unused: prt.write(" UNUSED SECTION: {SEC}\n".format(SEC=sec))
[ "def", "_rpt_unused_sections", "(", "self", ",", "prt", ")", ":", "sections_unused", "=", "set", "(", "self", ".", "sections_seen", ")", ".", "difference", "(", "self", ".", "section2goids", ".", "keys", "(", ")", ")", "for", "sec", "in", "sections_unused"...
52.2
16.4
def get_relationship_query_session_for_family(self, family_id=None, proxy=None): """Gets the ``OsidSession`` associated with the relationship query service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the family arg: proxy (osid.proxy.Proxy): a proxy return: (o...
[ "def", "get_relationship_query_session_for_family", "(", "self", ",", "family_id", "=", "None", ",", "proxy", "=", "None", ")", ":", "if", "not", "family_id", ":", "raise", "NullArgument", "if", "not", "self", ".", "supports_relationship_query", "(", ")", ":", ...
45.515152
21.727273
def setMovie( self, movie ): """ Sets the movie for this loader to the inputed movie. :param movie | <QMovie> """ self._movieLabel.setMovie(movie) self._smallMovieLabel.setMovie(movie)
[ "def", "setMovie", "(", "self", ",", "movie", ")", ":", "self", ".", "_movieLabel", ".", "setMovie", "(", "movie", ")", "self", ".", "_smallMovieLabel", ".", "setMovie", "(", "movie", ")" ]
30.75
9
def insert(queue, items, backend='sqlite'): ''' Add an item or items to a queue CLI Example: .. code-block:: bash salt-run queue.insert myqueue myitem salt-run queue.insert myqueue "['item1', 'item2', 'item3']" salt-run queue.insert myqueue myitem backend=sqlite salt-r...
[ "def", "insert", "(", "queue", ",", "items", ",", "backend", "=", "'sqlite'", ")", ":", "queue_funcs", "=", "salt", ".", "loader", ".", "queues", "(", "__opts__", ")", "cmd", "=", "'{0}.insert'", ".", "format", "(", "backend", ")", "if", "cmd", "not", ...
33.894737
22.210526
def set_db_application_prefix(prefix, sep=None): """Set the global app prefix and separator.""" global _APPLICATION_PREFIX, _APPLICATION_SEP _APPLICATION_PREFIX = prefix if (sep is not None): _APPLICATION_SEP = sep
[ "def", "set_db_application_prefix", "(", "prefix", ",", "sep", "=", "None", ")", ":", "global", "_APPLICATION_PREFIX", ",", "_APPLICATION_SEP", "_APPLICATION_PREFIX", "=", "prefix", "if", "(", "sep", "is", "not", "None", ")", ":", "_APPLICATION_SEP", "=", "sep" ...
38.833333
8.166667
def _default_json_default(obj): """ Coerce everything to strings. All objects representing time get output as ISO8601. """ if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return obj.isoformat() else: return str(obj)
[ "def", "_default_json_default", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "datetime", ".", "time", ")", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "else",...
30
13.777778
def get_dataset(self, remote_id): '''Get or create a dataset given its remote ID (and its source) We first try to match `source_id` to be source domain independent ''' dataset = Dataset.objects(__raw__={ 'extras.harvest:remote_id': remote_id, '$or': [ ...
[ "def", "get_dataset", "(", "self", ",", "remote_id", ")", ":", "dataset", "=", "Dataset", ".", "objects", "(", "__raw__", "=", "{", "'extras.harvest:remote_id'", ":", "remote_id", ",", "'$or'", ":", "[", "{", "'extras.harvest:domain'", ":", "self", ".", "sou...
41.333333
19.5
def _perform_async_update_rule(context, id, db_sg_group, rule_id, action): """Updates a SG rule async and return the job information. Only happens if the security group has associated ports. If the async connection fails the update continues (legacy mode). """ rpc_reply = None sg_rpc = sg_rpc_a...
[ "def", "_perform_async_update_rule", "(", "context", ",", "id", ",", "db_sg_group", ",", "rule_id", ",", "action", ")", ":", "rpc_reply", "=", "None", "sg_rpc", "=", "sg_rpc_api", ".", "QuarkSGAsyncProcessClient", "(", ")", "ports", "=", "db_api", ".", "sg_gat...
43.625
19.8125
def up_to(self, key): '''Gets the recently inserted values up to a key''' for okey, ovalue in reversed(self.history): if okey == key: break else: yield ovalue
[ "def", "up_to", "(", "self", ",", "key", ")", ":", "for", "okey", ",", "ovalue", "in", "reversed", "(", "self", ".", "history", ")", ":", "if", "okey", "==", "key", ":", "break", "else", ":", "yield", "ovalue" ]
32
16.571429
def _traverse_parent_objs(self, p2cs, goobj_child, goids_seen): """Traverse from source GO up parents.""" # Update public(go2obj p2cs), private(goids_seen) child_id = goobj_child.id # mark child as seen goids_seen.add(child_id) ##A self.go2obj[child_id] = goobj_child ...
[ "def", "_traverse_parent_objs", "(", "self", ",", "p2cs", ",", "goobj_child", ",", "goids_seen", ")", ":", "# Update public(go2obj p2cs), private(goids_seen)", "child_id", "=", "goobj_child", ".", "id", "# mark child as seen", "goids_seen", ".", "add", "(", "child_id", ...
48.578947
11.473684
def get_event_canned_questions(self, id, **data): """ GET /events/:id/canned_questions/ This endpoint returns canned questions of a single event (examples: first name, last name, company, prefix, etc.). This endpoint will return :format:`question`. """ return self.get("/...
[ "def", "get_event_canned_questions", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/canned_questions/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
52.285714
29.714286
def _set_hostname_domain(self): """Extract hostname and domain""" self._hostname, _, self._domain = str(self._fqdn).partition('.') log.debug('Hostname: %s, Domain: %s' % (self._hostname, self._domain))
[ "def", "_set_hostname_domain", "(", "self", ")", ":", "self", ".", "_hostname", ",", "_", ",", "self", ".", "_domain", "=", "str", "(", "self", ".", "_fqdn", ")", ".", "partition", "(", "'.'", ")", "log", ".", "debug", "(", "'Hostname: %s, Domain: %s'", ...
55.5
19.75
def revoke_user_token(self, user_id): """ Revoke user token Erases user token on file forcing them to re-login and obtain a new one. :param user_id: int :return: """ user = self.get(user_id) user._token = None self.save(user)
[ "def", "revoke_user_token", "(", "self", ",", "user_id", ")", ":", "user", "=", "self", ".", "get", "(", "user_id", ")", "user", ".", "_token", "=", "None", "self", ".", "save", "(", "user", ")" ]
28.8
13.4
def get_metric_type(measure, aggregation): """Get the corresponding metric type for the given stats type. :type measure: (:class: '~opencensus.stats.measure.BaseMeasure') :param measure: the measure for which to find a metric type :type aggregation: (:class: '~opencensus.stats.aggregation.BaseAggr...
[ "def", "get_metric_type", "(", "measure", ",", "aggregation", ")", ":", "if", "aggregation", ".", "aggregation_type", "==", "aggregation_module", ".", "Type", ".", "NONE", ":", "raise", "ValueError", "(", "\"aggregation type must not be NONE\"", ")", "assert", "isin...
49.171429
24
def set_logging(self, log_level=logging.ERROR, file_path_name=None): """ This function allows to change the logging backend, either output or file as backend It also allows to set the logging level (whether to display only critical/error/info/debug. for example:: yag = yagma...
[ "def", "set_logging", "(", "self", ",", "log_level", "=", "logging", ".", "ERROR", ",", "file_path_name", "=", "None", ")", ":", "self", ".", "log", "=", "get_logger", "(", "log_level", ",", "file_path_name", ")" ]
39.25
29.625
def visit_With(self, node): """ with describe(thing) as it: ... | v class TestThing(TestCase): ... """ withitem, = node.items context = withitem.context_expr if context.func.id == "describe": descr...
[ "def", "visit_With", "(", "self", ",", "node", ")", ":", "withitem", ",", "=", "node", ".", "items", "context", "=", "withitem", ".", "context_expr", "if", "context", ".", "func", ".", "id", "==", "\"describe\"", ":", "describes", "=", "context", ".", ...
22.772727
20.045455
def parse_delta(filename): """Returns (alignment length, similarity errors) tuple from passed .delta. - filename - path to the input .delta file Extracts the aligned length and number of similarity errors for each aligned uniquely-matched region, and returns the cumulative total for each as a tupl...
[ "def", "parse_delta", "(", "filename", ")", ":", "aln_length", ",", "sim_errors", "=", "0", ",", "0", "for", "line", "in", "[", "l", ".", "strip", "(", ")", ".", "split", "(", ")", "for", "l", "in", "open", "(", "filename", ",", "\"r\"", ")", "."...
40.666667
18.611111
def _search_chimera(binary, directories, prefix, search_all=False): """ Try running ``chimera --root`` if Chimera happens to be in PATH, otherwise traverse usual installation locations to find the Chimera root path. Parameters ---------- binary : str Name of the chimera executable in th...
[ "def", "_search_chimera", "(", "binary", ",", "directories", ",", "prefix", ",", "search_all", "=", "False", ")", ":", "# First, check if environment variable is already present", "try", ":", "return", "os", ".", "path", ".", "expanduser", "(", "os", ".", "environ...
34.795918
22.020408
def push_cluster_configuration(self, scaleioobj, noUpload = False, noInstall= False, noConfigure = False): """ Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM) Method: POST Attach JSON cluster con...
[ "def", "push_cluster_configuration", "(", "self", ",", "scaleioobj", ",", "noUpload", "=", "False", ",", "noInstall", "=", "False", ",", "noConfigure", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"push_cluster_configuration(\"", "+", "\...
50.2
28.533333
def purge_all(self, rate_limit_delay=60): '''Purge all pending URLs, waiting for API rate-limits if necessary!''' for batch, response in self.purge(): if response.status_code == 507: details = response.json().get('detail', '<response did not contain "detail">') ...
[ "def", "purge_all", "(", "self", ",", "rate_limit_delay", "=", "60", ")", ":", "for", "batch", ",", "response", "in", "self", ".", "purge", "(", ")", ":", "if", "response", ".", "status_code", "==", "507", ":", "details", "=", "response", ".", "json", ...
54.222222
23.111111
def GetRootFileEntry(self): """Retrieves the root file entry. Returns: APFSFileEntry: file entry. """ path_spec = apfs_path_spec.APFSPathSpec( location=self.LOCATION_ROOT, identifier=self.ROOT_DIRECTORY_IDENTIFIER, parent=self._path_spec.parent) return self.GetFileEntryByPathS...
[ "def", "GetRootFileEntry", "(", "self", ")", ":", "path_spec", "=", "apfs_path_spec", ".", "APFSPathSpec", "(", "location", "=", "self", ".", "LOCATION_ROOT", ",", "identifier", "=", "self", ".", "ROOT_DIRECTORY_IDENTIFIER", ",", "parent", "=", "self", ".", "_...
32.5
14.3
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, explicit_eoc = self.find_cell_end(lines) # Metadata to dict if self.start_code_re.match(lines[0]) or se...
[ "def", "find_cell_content", "(", "self", ",", "lines", ")", ":", "cell_end_marker", ",", "next_cell_start", ",", "explicit_eoc", "=", "self", ".", "find_cell_end", "(", "lines", ")", "# Metadata to dict", "if", "self", ".", "start_code_re", ".", "match", "(", ...
37.633333
23.566667
def threshold_monitor_hidden_threshold_monitor_sfp_policy_area_alert_above_above_highthresh_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-th...
[ "def", "threshold_monitor_hidden_threshold_monitor_sfp_policy_area_alert_above_above_highthresh_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "threshold_monitor_hidden", "=", "ET", ".", "SubElement", ...
55.227273
21.727273
def export_dse_home_in_dse_env_sh(self): ''' Due to the way CCM lays out files, separating the repository from the node(s) confs, the `dse-env.sh` script of each node needs to have its DSE_HOME var set and exported. Since DSE 4.5.x, the stock `dse-env.sh` file includes a commente...
[ "def", "export_dse_home_in_dse_env_sh", "(", "self", ")", ":", "with", "open", "(", "self", ".", "get_bin_dir", "(", ")", "+", "\"/dse-env.sh\"", ",", "\"r\"", ")", "as", "dse_env_sh", ":", "buf", "=", "dse_env_sh", ".", "readlines", "(", ")", "with", "ope...
51
25
def periodic_hann(window_length): """Calculate a "periodic" Hann window. The classic Hann window is defined as a raised cosine that starts and ends on zero, and where every value appears twice, except the middle point for an odd-length window. Matlab calls this a "symmetric" window and np.hanning() returns ...
[ "def", "periodic_hann", "(", "window_length", ")", ":", "return", "0.5", "-", "(", "0.5", "*", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "/", "window_length", "*", "np", ".", "arange", "(", "window_length", ")", ")", ")" ]
44.761905
24.52381
def major_tick_mark(self): """ Read/write :ref:`XlTickMark` value specifying the type of major tick mark to display on this axis. """ majorTickMark = self._element.majorTickMark if majorTickMark is None: return XL_TICK_MARK.CROSS return majorTickMark.v...
[ "def", "major_tick_mark", "(", "self", ")", ":", "majorTickMark", "=", "self", ".", "_element", ".", "majorTickMark", "if", "majorTickMark", "is", "None", ":", "return", "XL_TICK_MARK", ".", "CROSS", "return", "majorTickMark", ".", "val" ]
34.888889
9.111111
def ac(d, key, **kwarg): """Alias of :meth:`self.add_children()<DictTree.add_children>`. """ if kwarg: d[key] = {_meta: kwarg} else: d[key] = dict()
[ "def", "ac", "(", "d", ",", "key", ",", "*", "*", "kwarg", ")", ":", "if", "kwarg", ":", "d", "[", "key", "]", "=", "{", "_meta", ":", "kwarg", "}", "else", ":", "d", "[", "key", "]", "=", "dict", "(", ")" ]
28.285714
12
def _extract_definitions(alist, level=None): """ Since we couldn't be bothered to register models elsewhere our definitions need to be extracted from the parameters. We require an 'id' field for the schema to be correctly added to the definitions list. """ def _extract_array_defs(source): ...
[ "def", "_extract_definitions", "(", "alist", ",", "level", "=", "None", ")", ":", "def", "_extract_array_defs", "(", "source", ")", ":", "# extract any definitions that are within arrays", "# this occurs recursively", "ret", "=", "[", "]", "items", "=", "source", "....
35.058824
17.490196
def job_monitor(job, interval=None, monitor_async=False, quiet=False, output=sys.stdout): """Monitor the status of a IBMQJob instance. Args: job (BaseJob): Job to monitor. interval (int): Time interval between status queries. monitor_async (bool): Monitor asyncronously (in Jupyter only)...
[ "def", "job_monitor", "(", "job", ",", "interval", "=", "None", ",", "monitor_async", "=", "False", ",", "quiet", "=", "False", ",", "output", "=", "sys", ".", "stdout", ")", ":", "if", "interval", "is", "None", ":", "_interval_set", "=", "False", "int...
40.340426
24.106383
def _download_libraries(self, libname): """ download enrichr libraries.""" self._logger.info("Downloading and generating Enrichr library gene sets......") s = retry(5) # queery string ENRICHR_URL = 'http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary' query_string = '?mode=t...
[ "def", "_download_libraries", "(", "self", ",", "libname", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Downloading and generating Enrichr library gene sets......\"", ")", "s", "=", "retry", "(", "5", ")", "# queery string", "ENRICHR_URL", "=", "'http://am...
44.5
19.115385
def get_version(): """Get version and version_info without importing the entire module.""" path = os.path.join(os.path.dirname(__file__), 'backrefs') fp, pathname, desc = imp.find_module('__meta__', [path]) try: vi = imp.load_module('__meta__', fp, pathname, desc).__version_info__ retur...
[ "def", "get_version", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'backrefs'", ")", "fp", ",", "pathname", ",", "desc", "=", "imp", ".", "find_module", "(", "'__met...
37
21.75
def check(self, line_info): "Check if the initial word/function is callable and autocall is on." if not self.shell.autocall: return None oinfo = line_info.ofind(self.shell) # This can mutate state via getattr if not oinfo['found']: return None if callabl...
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "if", "not", "self", ".", "shell", ".", "autocall", ":", "return", "None", "oinfo", "=", "line_info", ".", "ofind", "(", "self", ".", "shell", ")", "# This can mutate state via getattr", "if", "not",...
38.133333
23.6
def replace_persistent_volume_status(self, name, body, **kwargs): # noqa: E501 """replace_persistent_volume_status # noqa: E501 replace status of the specified PersistentVolume # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request,...
[ "def", "replace_persistent_volume_status", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retur...
59.625
32.791667
def move(src_parent, src_idx, dest_parent, dest_idx): """Move an item.""" copy(src_parent, src_idx, dest_parent, dest_idx) remove(src_parent, src_idx)
[ "def", "move", "(", "src_parent", ",", "src_idx", ",", "dest_parent", ",", "dest_idx", ")", ":", "copy", "(", "src_parent", ",", "src_idx", ",", "dest_parent", ",", "dest_idx", ")", "remove", "(", "src_parent", ",", "src_idx", ")" ]
38.25
8.5
def _generate_examples( self, image_dir, annotation_dir, split_type, has_annotation=True): """Generate examples as dicts. Args: image_dir: `str`, directory containing the images annotation_dir: `str`, directory containing split_type: `str`, <split_name><year> (ex: train2014) has_a...
[ "def", "_generate_examples", "(", "self", ",", "image_dir", ",", "annotation_dir", ",", "split_type", ",", "has_annotation", "=", "True", ")", ":", "if", "has_annotation", ":", "instance_filename", "=", "\"instances_{}.json\"", "else", ":", "instance_filename", "=",...
34.147059
18.882353
def update(self, message, content, branch=None, committer=None, author=None): """Update this file. :param str message: (required), commit message to describe the update :param str content: (required), content to update the file with :param str branch: (optional), branch w...
[ "def", "update", "(", "self", ",", "message", ",", "content", ",", "branch", "=", "None", ",", "committer", "=", "None", ",", "author", "=", "None", ")", ":", "if", "content", "and", "not", "isinstance", "(", "content", ",", "bytes", ")", ":", "raise...
47.323529
21.470588
def to_bytes(s): '''Return s as a bytes type, using utf-8 encoding if necessary. @param s string or bytes @return bytes ''' if isinstance(s, six.binary_type): return s if isinstance(s, six.string_types): return s.encode('utf-8') raise TypeError('want string or bytes, got {}',...
[ "def", "to_bytes", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "binary_type", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", ":", "return", "s", ".", "encode", "(", "'utf-8'", ")"...
32
17.4
def get_xref_graph(ont): """ Creates a basic graph object corresponding to a remote ontology """ g = networkx.MultiGraph() for (c,x) in fetchall_xrefs(ont): g.add_edge(c,x,source=c) return g
[ "def", "get_xref_graph", "(", "ont", ")", ":", "g", "=", "networkx", ".", "MultiGraph", "(", ")", "for", "(", "c", ",", "x", ")", "in", "fetchall_xrefs", "(", "ont", ")", ":", "g", ".", "add_edge", "(", "c", ",", "x", ",", "source", "=", "c", "...
26.875
11.625
def serialize(self, value, entity=None, request=None): """ Validate and serialize the value. This is the default implementation """ ret = self.from_python(value) self.validate(ret) self.run_validators(value) return ret
[ "def", "serialize", "(", "self", ",", "value", ",", "entity", "=", "None", ",", "request", "=", "None", ")", ":", "ret", "=", "self", ".", "from_python", "(", "value", ")", "self", ".", "validate", "(", "ret", ")", "self", ".", "run_validators", "(",...
23.9
15.7
def append(self, position, array): """Append an array to the end of the map. The position must be greater than any positions in the map""" if not Gauged.map_append(self.ptr, position, array.ptr): raise MemoryError
[ "def", "append", "(", "self", ",", "position", ",", "array", ")", ":", "if", "not", "Gauged", ".", "map_append", "(", "self", ".", "ptr", ",", "position", ",", "array", ".", "ptr", ")", ":", "raise", "MemoryError" ]
49
8.2
def write(self, message, autoerase=True): """Send something for stdout and erased after delay""" super(Animation, self).write(message) self.last_message = message if autoerase: time.sleep(self.interval) self.erase(message)
[ "def", "write", "(", "self", ",", "message", ",", "autoerase", "=", "True", ")", ":", "super", "(", "Animation", ",", "self", ")", ".", "write", "(", "message", ")", "self", ".", "last_message", "=", "message", "if", "autoerase", ":", "time", ".", "s...
38.857143
6
def Write(self, grr_message): """Write the message into the transaction log. Args: grr_message: A GrrMessage instance. """ grr_message = grr_message.SerializeToString() try: winreg.SetValueEx(_GetServiceKey(), "Transaction", 0, winreg.REG_BINARY, grr_message) ...
[ "def", "Write", "(", "self", ",", "grr_message", ")", ":", "grr_message", "=", "grr_message", ".", "SerializeToString", "(", ")", "try", ":", "winreg", ".", "SetValueEx", "(", "_GetServiceKey", "(", ")", ",", "\"Transaction\"", ",", "0", ",", "winreg", "."...
27.846154
17.769231
def _homogenize_waves(wave_a, wave_b): """ Generate combined independent variable vector. The combination is from two waveforms and the (possibly interpolated) dependent variable vectors of these two waveforms """ indep_vector = _get_indep_vector(wave_a, wave_b) dep_vector_a = _interp_dep_v...
[ "def", "_homogenize_waves", "(", "wave_a", ",", "wave_b", ")", ":", "indep_vector", "=", "_get_indep_vector", "(", "wave_a", ",", "wave_b", ")", "dep_vector_a", "=", "_interp_dep_vector", "(", "wave_a", ",", "indep_vector", ")", "dep_vector_b", "=", "_interp_dep_v...
41
14.636364
def ensure_tuple(obj): """Try and make the given argument into a tuple.""" if obj is None: return tuple() if isinstance(obj, Iterable) and not isinstance(obj, six.string_types): return tuple(obj) return obj,
[ "def", "ensure_tuple", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "tuple", "(", ")", "if", "isinstance", "(", "obj", ",", "Iterable", ")", "and", "not", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "return...
33.285714
18.857143
def _lincomb(self, a, x1, b, x2, out): """Raw linear combination.""" self.tspace._lincomb(a, x1.tensor, b, x2.tensor, out.tensor)
[ "def", "_lincomb", "(", "self", ",", "a", ",", "x1", ",", "b", ",", "x2", ",", "out", ")", ":", "self", ".", "tspace", ".", "_lincomb", "(", "a", ",", "x1", ".", "tensor", ",", "b", ",", "x2", ".", "tensor", ",", "out", ".", "tensor", ")" ]
47.666667
10
def natural_sorted(l): """ sorts a sortable in human order (0 < 20 < 100) """ ll = copy(l) ll.sort(key=_natural_keys) return ll
[ "def", "natural_sorted", "(", "l", ")", ":", "ll", "=", "copy", "(", "l", ")", "ll", ".", "sort", "(", "key", "=", "_natural_keys", ")", "return", "ll" ]
27.8
15.8
def _es_margin(settings): """ Extract margin formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_MARGIN, ConsoleWidget.SETTING_MARGIN_LEFT, ConsoleWidget....
[ "def", "_es_margin", "(", "settings", ")", ":", "return", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "(", "ConsoleWidget", ".", "SETTING_MARGIN", ",", "ConsoleWidget", ".", "SETTING_MARGIN_LEFT", ",", "ConsoleWidget", ".", "SETTING_MARGIN_RIGH...
51.375
22.375
def get_time_variables(ds): ''' Returns a list of variables describing the time coordinate :param netCDF4.Dataset ds: An open netCDF4 Dataset ''' time_variables = set() for variable in ds.get_variables_by_attributes(standard_name='time'): time_variables.add(variable.name) for varia...
[ "def", "get_time_variables", "(", "ds", ")", ":", "time_variables", "=", "set", "(", ")", "for", "variable", "in", "ds", ".", "get_variables_by_attributes", "(", "standard_name", "=", "'time'", ")", ":", "time_variables", ".", "add", "(", "variable", ".", "n...
38.1
24.9
def getStore(self) : """get the inner store as dictionary""" res = {} res.update(self.store) for k, v in self.subStores.items() : res[k] = v.getStore() return res
[ "def", "getStore", "(", "self", ")", ":", "res", "=", "{", "}", "res", ".", "update", "(", "self", ".", "store", ")", "for", "k", ",", "v", "in", "self", ".", "subStores", ".", "items", "(", ")", ":", "res", "[", "k", "]", "=", "v", ".", "g...
27
14.875
def delete(self, ids): """ Method to delete ipv4's by their ids :param ids: Identifiers of ipv4's :return: None """ url = build_uri_with_ids('api/v4/ipv4/%s/', ids) return super(ApiV4IPv4, self).delete(url)
[ "def", "delete", "(", "self", ",", "ids", ")", ":", "url", "=", "build_uri_with_ids", "(", "'api/v4/ipv4/%s/'", ",", "ids", ")", "return", "super", "(", "ApiV4IPv4", ",", "self", ")", ".", "delete", "(", "url", ")" ]
25.5
14.7
def retryable_http_error( e ): """ Determine if an error encountered during an HTTP download is likely to go away if we try again. """ if isinstance( e, urllib.error.HTTPError ) and e.code in ('503', '408', '500'): # The server returned one of: # 503 Service Unavailable # 408 Req...
[ "def", "retryable_http_error", "(", "e", ")", ":", "if", "isinstance", "(", "e", ",", "urllib", ".", "error", ".", "HTTPError", ")", "and", "e", ".", "code", "in", "(", "'503'", ",", "'408'", ",", "'500'", ")", ":", "# The server returned one of:", "# 50...
36.428571
16
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a CNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :...
[ "def", "from_fp", "(", "self", ",", "file_pointer", ",", "comment_lead", "=", "[", "'c'", "]", ")", ":", "self", ".", "nv", "=", "0", "self", ".", "clauses", "=", "[", "]", "self", ".", "atmosts", "=", "[", "]", "self", ".", "comments", "=", "[",...
37.622642
20
def update_hook(self, auth, repo_name, hook_id, update, organization=None): """ Updates hook with id ``hook_id`` according to ``update``. :param auth.Authentication auth: authentication object :param str repo_name: repo of the hook to update :param int hook_id: id of the hook to...
[ "def", "update_hook", "(", "self", ",", "auth", ",", "repo_name", ",", "hook_id", ",", "update", ",", "organization", "=", "None", ")", ":", "if", "organization", "is", "not", "None", ":", "path", "=", "\"/repos/{o}/{r}/hooks/{i}\"", ".", "format", "(", "o...
52.55
24.35
def spur(image, mask=None, iterations=1): '''Remove spur pixels from an image 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 1 0 0 ? ''' global spur_table_1,spur_table_2 if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~...
[ "def", "spur", "(", "image", ",", "mask", "=", "None", ",", "iterations", "=", "1", ")", ":", "global", "spur_table_1", ",", "spur_table_2", "if", "mask", "is", "None", ":", "masked_image", "=", "image", "else", ":", "masked_image", "=", "image", ".", ...
35.68
17.36
def profile(self, query_id, timeout=10): """ Get the profile of the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result """ result = ...
[ "def", "profile", "(", "self", ",", "query_id", ",", "timeout", "=", "10", ")", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", "*", "{", "'method'", ":", "'GET'", ",", "'url'", ":", "'/profiles/{0}.json'", ".", "forma...
33.6875
17.1875
def get_message(zelf): """ get one message if available else return None if message is available returns the result of handler(message) does not block! if you would like to call your handler manually, this is the way to go. don't pass in a handler to Listener() and the d...
[ "def", "get_message", "(", "zelf", ")", ":", "try", ":", "message", "=", "zelf", ".", "r", ".", "master", ".", "rpoplpush", "(", "zelf", ".", "lijst", ",", "zelf", ".", "_processing", ")", "if", "message", ":", "# NOTE(tr3buchet): got a message, process it",...
41.444444
19.666667
def _setChoiceDict(self): """Create dictionary for choice list""" # value is name of choice parameter (same as key) self.choiceDict = {} for c in self.choice: self.choiceDict[c] = c
[ "def", "_setChoiceDict", "(", "self", ")", ":", "# value is name of choice parameter (same as key)", "self", ".", "choiceDict", "=", "{", "}", "for", "c", "in", "self", ".", "choice", ":", "self", ".", "choiceDict", "[", "c", "]", "=", "c" ]
41.8
11.2
def figure(self,forceNew=False): """make sure a figure is ready.""" if plt._pylab_helpers.Gcf.get_num_fig_managers()>0 and forceNew is False: self.log.debug("figure already seen, not creating one.") return if self.subplot: self.log.debug("subplot mode enabled...
[ "def", "figure", "(", "self", ",", "forceNew", "=", "False", ")", ":", "if", "plt", ".", "_pylab_helpers", ".", "Gcf", ".", "get_num_fig_managers", "(", ")", ">", "0", "and", "forceNew", "is", "False", ":", "self", ".", "log", ".", "debug", "(", "\"f...
42.909091
23.272727
def mnl_utility_transform(sys_utility_array, *args, **kwargs): """ Parameters ---------- sys_utility_array : ndarray. Should have 1D or 2D. Should have been created by the dot product of a design matrix and an array of index coefficients. Returns ------- systematic_utili...
[ "def", "mnl_utility_transform", "(", "sys_utility_array", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Return a 2D array of systematic utility values", "if", "len", "(", "sys_utility_array", ".", "shape", ")", "==", "1", ":", "systematic_utilities", "=", ...
34.363636
19