text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def related(self): """ Yields a list of all chunks in the sentence with the same relation id. """ return [ch for ch in self.sentence.chunks if ch != self and intersects(unzip(0, ch.relations), unzip(0, self.relations))]
[ "def", "related", "(", "self", ")", ":", "return", "[", "ch", "for", "ch", "in", "self", ".", "sentence", ".", "chunks", "if", "ch", "!=", "self", "and", "intersects", "(", "unzip", "(", "0", ",", "ch", ".", "relations", ")", ",", "unzip", "(", "...
52
18.2
def partial(cls, prefix, source): """Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs.""" match = prefix + "." matches = cls([(key[len(match):], source[key]) for key in source if key.startswith(match)]) if not ...
[ "def", "partial", "(", "cls", ",", "prefix", ",", "source", ")", ":", "match", "=", "prefix", "+", "\".\"", "matches", "=", "cls", "(", "[", "(", "key", "[", "len", "(", "match", ")", ":", "]", ",", "source", "[", "key", "]", ")", "for", "key",...
38.2
21.9
def agent_delete(self, agent_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/agents#delete-agent" api_path = "/api/v2/agents/{agent_id}" api_path = api_path.format(agent_id=agent_id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "agent_delete", "(", "self", ",", "agent_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/agents/{agent_id}\"", "api_path", "=", "api_path", ".", "format", "(", "agent_id", "=", "agent_id", ")", "return", "self", ".", "call", "(", ...
56.2
16.2
def clean_networks(networks: Iterable[str] = None) -> Optional[Iterable[str]]: """ Cleans the values inside `networks` Returns a new list """ if not networks: return networks if not isinstance(networks, list): raise TypeError("networks parameter must be a list.") result = []...
[ "def", "clean_networks", "(", "networks", ":", "Iterable", "[", "str", "]", "=", "None", ")", "->", "Optional", "[", "Iterable", "[", "str", "]", "]", ":", "if", "not", "networks", ":", "return", "networks", "if", "not", "isinstance", "(", "networks", ...
27
16.25
def _delete_handler(self, handler_class): """Delete a specific handler from our logger.""" to_remove = self._get_handler(handler_class) if not to_remove: logging.warning('Error we should have an element to remove') else: self.handlers.remove(to_remove) ...
[ "def", "_delete_handler", "(", "self", ",", "handler_class", ")", ":", "to_remove", "=", "self", ".", "_get_handler", "(", "handler_class", ")", "if", "not", "to_remove", ":", "logging", ".", "warning", "(", "'Error we should have an element to remove'", ")", "els...
43.75
12.25
def on_lstUnits_itemSelectionChanged(self): """Update unit description label and field widgets. .. note:: This is an automatic Qt slot executed when the unit selection changes. """ self.clear_further_steps() # Set widgets unit = self.selected_unit() # ...
[ "def", "on_lstUnits_itemSelectionChanged", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "unit", "=", "self", ".", "selected_unit", "(", ")", "# Exit if no selection", "if", "not", "unit", ":", "return", "self", ".", "lblD...
33.466667
11.466667
def build_timeout_circuit(tor_state, reactor, path, timeout, using_guards=False): """ Build a new circuit within a timeout. CircuitBuildTimedOutError will be raised unless we receive a circuit build result (success or failure) within the `timeout` duration. :returns: a Deferred which fires whe...
[ "def", "build_timeout_circuit", "(", "tor_state", ",", "reactor", ",", "path", ",", "timeout", ",", "using_guards", "=", "False", ")", ":", "timed_circuit", "=", "[", "]", "d", "=", "tor_state", ".", "build_circuit", "(", "routers", "=", "path", ",", "usin...
29.848485
21.545455
def reads_supporting_variants(variants, samfile, **kwargs): """ Given a SAM/BAM file and a collection of variants, generates a sequence of variants paired with reads which support each variant. """ for variant, allele_reads in reads_overlapping_variants( variants=variants, sa...
[ "def", "reads_supporting_variants", "(", "variants", ",", "samfile", ",", "*", "*", "kwargs", ")", ":", "for", "variant", ",", "allele_reads", "in", "reads_overlapping_variants", "(", "variants", "=", "variants", ",", "samfile", "=", "samfile", ",", "*", "*", ...
42.7
17.3
def create_user(self, user): """ Create a user on the local system """ self.run("useradd -m %s" % user) usr = getpwnam(user) return usr
[ "def", "create_user", "(", "self", ",", "user", ")", ":", "self", ".", "run", "(", "\"useradd -m %s\"", "%", "user", ")", "usr", "=", "getpwnam", "(", "user", ")", "return", "usr" ]
25.428571
6.571429
def fit_transform(self, X, y): """Encode categorical columns into average target values. Args: X (pandas.DataFrame): categorical columns to encode y (pandas.Series): the target column Returns: X (pandas.DataFrame): encoded columns """ self.targ...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", ")", ":", "self", ".", "target_encoders", "=", "[", "None", "]", "*", "X", ".", "shape", "[", "1", "]", "self", ".", "target_mean", "=", "y", ".", "mean", "(", ")", "for", "i", ",", "col"...
36.235294
21.176471
def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) ...
[ "def", "calculate_unaryop", "(", "self", ",", "node", ",", "next_node", ")", ":", "position", "=", "(", "next_node", ".", "first_line", ",", "next_node", ".", "first_col", "+", "1", ")", "possible", "=", "[", "]", "for", "ch", "in", "OPERATORS", "[", "...
35.733333
16.6
def process(self, sched, coro): """Add the given coroutine in the scheduler.""" super(AddCoro, self).process(sched, coro) self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP) if self.prio & priority.CORO: return self, coro else: ...
[ "def", "process", "(", "self", ",", "sched", ",", "coro", ")", ":", "super", "(", "AddCoro", ",", "self", ")", ".", "process", "(", "sched", ",", "coro", ")", "self", ".", "result", "=", "sched", ".", "add", "(", "self", ".", "coro", ",", "self",...
44.75
14.25
def send_msg(self, message): """Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send """ packet = self.driver.send(message) self.send_bytes(packet)
[ "def", "send_msg", "(", "self", ",", "message", ")", ":", "packet", "=", "self", ".", "driver", ".", "send", "(", "message", ")", "self", ".", "send_bytes", "(", "packet", ")" ]
32.428571
11.857143
def create(self, emails, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Create a new user account for a given organization Only an admin can create a new user account. Args: ...
[ "def", "create", "(", "self", ",", "emails", ",", "displayName", "=", "None", ",", "firstName", "=", "None", ",", "lastName", "=", "None", ",", "avatar", "=", "None", ",", "orgId", "=", "None", ",", "roles", "=", "None", ",", "licenses", "=", "None",...
39.789474
20.807018
def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente): "Realiza la consulta remota a ARBA, estableciendo los resultados" self.limpiar() try: self.xml = SimpleXMLElement(XML_ENTRADA_BASE) self.xml.fechaDesde = fecha_desde self.xml.fec...
[ "def", "ConsultarContribuyentes", "(", "self", ",", "fecha_desde", ",", "fecha_hasta", ",", "cuit_contribuyente", ")", ":", "self", ".", "limpiar", "(", ")", "try", ":", "self", ".", "xml", "=", "SimpleXMLElement", "(", "XML_ENTRADA_BASE", ")", "self", ".", ...
50.642857
23.75
def add_category(self, category): """ Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately....
[ "def", "add_category", "(", "self", ",", "category", ")", ":", "assert", "isinstance", "(", "category", ",", "list", ")", ",", "'Category input was expecting list.'", "from", "smc", ".", "elements", ".", "other", "import", "Category", "for", "tag", "in", "cate...
40.125
17.791667
def import_from_string(self, text, title=None): """Import data from string""" data = self.model.get_data() # Check if data is a dict if not hasattr(data, "keys"): return editor = ImportWizard(self, text, title=title, contents_title...
[ "def", "import_from_string", "(", "self", ",", "text", ",", "title", "=", "None", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "# Check if data is a dict\r", "if", "not", "hasattr", "(", "data", ",", "\"keys\"", ")", ":", "retu...
47.461538
14.538462
def age(self, now=None): """ Returns an integer which is the difference in seconds from 'now' to when this circuit was created. Returns None if there is no created-time. """ if not self.time_created: return None if now is None: now = datet...
[ "def", "age", "(", "self", ",", "now", "=", "None", ")", ":", "if", "not", "self", ".", "time_created", ":", "return", "None", "if", "now", "is", "None", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "return", "(", "now", "-", "self", "."...
30.833333
12.666667
def open(self, fname, mode='r', psw=None): """Returns file-like object (:class:`RarExtFile`) from where the data can be read. The object implements :class:`io.RawIOBase` interface, so it can be further wrapped with :class:`io.BufferedReader` and :class:`io.TextIOWrapper`. On ol...
[ "def", "open", "(", "self", ",", "fname", ",", "mode", "=", "'r'", ",", "psw", "=", "None", ")", ":", "if", "mode", "!=", "'r'", ":", "raise", "NotImplementedError", "(", "\"RarFile.open() supports only mode=r\"", ")", "# entry lookup", "inf", "=", "self", ...
33.536585
22.780488
def order_by_next_occurrence(self): """ :return: A list of events in order of minimum occurrence greater than now (or overlapping now in the case of drop-in events). This is an expensive operation - use with as small a source queryset as possible. ...
[ "def", "order_by_next_occurrence", "(", "self", ")", ":", "qs", "=", "self", ".", "prefetch_related", "(", "'occurrences'", ")", "def", "_sort", "(", "x", ")", ":", "try", ":", "# If there's an upcoming occurrence, use it.", "return", "x", ".", "get_next_occurrenc...
40.875
22.625
def _get_attr_list(self, attr): """Return user's attribute/attributes""" a = self._attrs.get(attr) if not a: return [] if type(a) is list: r = [i.decode('utf-8', 'ignore') for i in a] else: r = [a.decode('utf-8', 'ignore')] return r
[ "def", "_get_attr_list", "(", "self", ",", "attr", ")", ":", "a", "=", "self", ".", "_attrs", ".", "get", "(", "attr", ")", "if", "not", "a", ":", "return", "[", "]", "if", "type", "(", "a", ")", "is", "list", ":", "r", "=", "[", "i", ".", ...
30.7
14.3
def RegisterDecompressor(cls, decompressor): """Registers a decompressor for a specific compression method. Args: decompressor (type): decompressor class. Raises: KeyError: if the corresponding decompressor is already set. """ compression_method = decompressor.COMPRESSION_METHOD.lower(...
[ "def", "RegisterDecompressor", "(", "cls", ",", "decompressor", ")", ":", "compression_method", "=", "decompressor", ".", "COMPRESSION_METHOD", ".", "lower", "(", ")", "if", "compression_method", "in", "cls", ".", "_decompressors", ":", "raise", "KeyError", "(", ...
35
20.3125
def is_url(value): "Must start with http:// or https:// and contain JUST a URL" if not isinstance(value, str): return False if not value.startswith('http://') and not value.startswith('https://'): return False # Any whitespace at all is invalid if whitespace_re.search(value): ...
[ "def", "is_url", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "False", "if", "not", "value", ".", "startswith", "(", "'http://'", ")", "and", "not", "value", ".", "startswith", "(", "'https://'", ")",...
34
18
def _trigger_event( self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any ) -> None: """Triggers an event on the associated Observable object. The Holder is the object this property is a member of, alt_name is used as the event name when self.event is not set, actio...
[ "def", "_trigger_event", "(", "self", ",", "holder", ":", "T", ".", "Any", ",", "alt_name", ":", "str", ",", "action", ":", "str", ",", "*", "event_args", ":", "T", ".", "Any", ")", "->", "None", ":", "if", "isinstance", "(", "self", ".", "observab...
45.538462
19.961538
def set_tag(tag, value): """ Set the tag 'tag' to the value True or False. :param value: should be a boolean :param tag: should be the id of the tag. Can not starts with '*auto-tag-' """ if not tag.startswith("*auto-tag-"): rdict = load_feedback() tests = rdict.setdefault("te...
[ "def", "set_tag", "(", "tag", ",", "value", ")", ":", "if", "not", "tag", ".", "startswith", "(", "\"*auto-tag-\"", ")", ":", "rdict", "=", "load_feedback", "(", ")", "tests", "=", "rdict", ".", "setdefault", "(", "\"tests\"", ",", "{", "}", ")", "te...
35
8.636364
async def stop_tasks(self, address): """Clear all tasks pertaining to a tile. This coroutine will synchronously cancel all running tasks that were attached to the given tile and wait for them to stop before returning. Args: address (int): The address of the tile we should s...
[ "async", "def", "stop_tasks", "(", "self", ",", "address", ")", ":", "tasks", "=", "self", ".", "_tasks", ".", "get", "(", "address", ",", "[", "]", ")", "for", "task", "in", "tasks", ":", "task", ".", "cancel", "(", ")", "asyncio", ".", "gather", ...
31.875
21.5625
def execute(self, fragment, pretty_format=True): """ Run or aggregate a query fragment Concat the fragment to any stored fragments. If they form a complete query, run it and return the result. If not, store them and return None. """ self.fragments = (self.fragme...
[ "def", "execute", "(", "self", ",", "fragment", ",", "pretty_format", "=", "True", ")", ":", "self", ".", "fragments", "=", "(", "self", ".", "fragments", "+", "\"\\n\"", "+", "fragment", ")", ".", "lstrip", "(", ")", "try", ":", "line_parser", ".", ...
34.315789
21.157895
def get_chunk(self, chunk_id): """ Returns the chunk object for the supplied identifier @type chunk_id: string @param chunk_id: chunk identifier """ if chunk_id in self.idx: return Cchunk(self.idx[chunk_id], self.type) else: return None
[ "def", "get_chunk", "(", "self", ",", "chunk_id", ")", ":", "if", "chunk_id", "in", "self", ".", "idx", ":", "return", "Cchunk", "(", "self", ".", "idx", "[", "chunk_id", "]", ",", "self", ".", "type", ")", "else", ":", "return", "None" ]
30.7
10.9
def config_examples(dest, user_dir): """ Copy the example workflows to a directory. \b DEST: Path to which the examples should be copied. """ examples_path = Path(lightflow.__file__).parents[1] / 'examples' if examples_path.exists(): dest_path = Path(dest).resolve() if not user_...
[ "def", "config_examples", "(", "dest", ",", "user_dir", ")", ":", "examples_path", "=", "Path", "(", "lightflow", ".", "__file__", ")", ".", "parents", "[", "1", "]", "/", "'examples'", "if", "examples_path", ".", "exists", "(", ")", ":", "dest_path", "=...
36.25
20.625
def get_inst_info(qry_string): """Get details for instances that match the qry_string. Execute a query against the AWS EC2 client object, that is based on the contents of qry_string. Args: qry_string (str): the query to be used against the aws ec2 client. Returns: qry_results (dict...
[ "def", "get_inst_info", "(", "qry_string", ")", ":", "qry_prefix", "=", "\"EC2C.describe_instances(\"", "qry_real", "=", "qry_prefix", "+", "qry_string", "+", "\")\"", "qry_results", "=", "eval", "(", "qry_real", ")", "# pylint: disable=eval-used", "return", "qry_resu...
33
19.75
async def start_store(app, url, workers=0, **kw): '''Equivalent to :func:`.create_store` for most cases excepts when the ``url`` is for a pulsar store not yet started. In this case, a :class:`.PulsarDS` is started. ''' store = create_store(url, **kw) if store.name == 'pulsar': client = s...
[ "async", "def", "start_store", "(", "app", ",", "url", ",", "workers", "=", "0", ",", "*", "*", "kw", ")", ":", "store", "=", "create_store", "(", "url", ",", "*", "*", "kw", ")", "if", "store", ".", "name", "==", "'pulsar'", ":", "client", "=", ...
37.9
11.6
def find_window(className = None, windowName = None): """ Find the first top-level window in the current desktop to match the given class name and/or window name. If neither are provided any top-level window will match. @see: L{get_window_at} @type className: str ...
[ "def", "find_window", "(", "className", "=", "None", ",", "windowName", "=", "None", ")", ":", "# I'd love to reverse the order of the parameters", "# but that might create some confusion. :(", "hWnd", "=", "win32", ".", "FindWindow", "(", "className", ",", "windowName", ...
41.357143
23
def add_marshaller(self, marshallers): """ Add a marshaller/s to the user provided list. Adds a marshaller or a list of them to the user provided set of marshallers. Note that the builtin marshallers take priority when choosing the right marshaller. .. versionchanged::...
[ "def", "add_marshaller", "(", "self", ",", "marshallers", ")", ":", "if", "not", "isinstance", "(", "marshallers", ",", "collections", ".", "Iterable", ")", ":", "marshallers", "=", "[", "marshallers", "]", "for", "m", "in", "marshallers", ":", "if", "not"...
33.767442
19.906977
def Split(axis, a, n): """ Split op with n splits. """ return tuple(np.split(np.copy(a), n, axis=axis))
[ "def", "Split", "(", "axis", ",", "a", ",", "n", ")", ":", "return", "tuple", "(", "np", ".", "split", "(", "np", ".", "copy", "(", "a", ")", ",", "n", ",", "axis", "=", "axis", ")", ")" ]
23
8.6
def change_pin(ctx, pin, new_pin): """ Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended. """ controller = ctx.obj['controller'] if not pin: p...
[ "def", "change_pin", "(", "ctx", ",", "pin", ",", "new_pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "pin", ":", "pin", "=", "_prompt_pin", "(", "ctx", ",", "prompt", "=", "'Enter your current PIN'", ")", ...
32.027778
21.138889
def decimal_field_data(field, **kwargs): """ Return random value for DecimalField >>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2)) >>> type(result) <type 'str'> >>> from decimal import Decimal >>> Decimal(result) >= 11, Decimal(r...
[ "def", "decimal_field_data", "(", "field", ",", "*", "*", "kwargs", ")", ":", "min_value", "=", "0", "max_value", "=", "10", "from", "django", ".", "core", ".", "validators", "import", "MinValueValidator", ",", "MaxValueValidator", "for", "elem", "in", "fiel...
39.83871
18.483871
def solve(self): """ Solves AC optimal power flow. """ case = self.om.case self._base_mva = case.base_mva # TODO: Find an explanation for this value. self.opt["cost_mult"] = 1e-4 # Unpack the OPF model. self._bs, self._ln, self._gn, _ = self._unpack_model...
[ "def", "solve", "(", "self", ")", ":", "case", "=", "self", ".", "om", ".", "case", "self", ".", "_base_mva", "=", "case", ".", "base_mva", "# TODO: Find an explanation for this value.", "self", ".", "opt", "[", "\"cost_mult\"", "]", "=", "1e-4", "# Unpack t...
34.326531
20.244898
def plot(*args, ax=None, **kwargs): """ Plots but automatically resizes x axis. .. versionadded:: 1.4 Parameters ---------- args Passed on to :meth:`matplotlib.axis.Axis.plot`. ax : :class:`matplotlib.axis.Axis`, optional The axis to plot to. kwargs Passed on to...
[ "def", "plot", "(", "*", "args", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "_setup_axes", "(", ")", "pl", "=", "ax", ".", "plot", "(", "*", "args", ",", "*", "*", "kwarg...
21.892857
18.678571
def emit_edge(self, name1, name2, **props): """emit an edge from <name1> to <name2>. edge properties: see http://www.graphviz.org/doc/info/attrs.html """ attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()] n_from, n_to = normalize_node_id(name1), normalize_node_i...
[ "def", "emit_edge", "(", "self", ",", "name1", ",", "name2", ",", "*", "*", "props", ")", ":", "attrs", "=", "[", "'%s=\"%s\"'", "%", "(", "prop", ",", "value", ")", "for", "prop", ",", "value", "in", "props", ".", "items", "(", ")", "]", "n_from...
57.285714
20.285714
def get_agent_queues_by_names(self, queue_names, project=None, action_filter=None): """GetAgentQueuesByNames. [Preview API] Get a list of agent queues by their names :param [str] queue_names: A comma-separated list of agent names to retrieve :param str project: Project ID or project name...
[ "def", "get_agent_queues_by_names", "(", "self", ",", "queue_names", ",", "project", "=", "None", ",", "action_filter", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", ...
58.391304
24.391304
def bisine_wave(frequency): """Emit two sine waves, in stereo at different octaves.""" # # We can first our existing sine generator to generate two different # waves. f_hi = frequency f_lo = frequency / 2.0 with tf.name_scope('hi'): sine_hi = sine_wave(f_hi) with tf.name_scope('lo'): sine_lo = s...
[ "def", "bisine_wave", "(", "frequency", ")", ":", "#", "# We can first our existing sine generator to generate two different", "# waves.", "f_hi", "=", "frequency", "f_lo", "=", "frequency", "/", "2.0", "with", "tf", ".", "name_scope", "(", "'hi'", ")", ":", "sine_h...
33.5625
20.1875
def _generate_docker_image_version(layers, runtime): """ Generate the Docker TAG that will be used to create the image Parameters ---------- layers list(samcli.commands.local.lib.provider.Layer) List of the layers runtime str Runtime of the image...
[ "def", "_generate_docker_image_version", "(", "layers", ",", "runtime", ")", ":", "# Docker has a concept of a TAG on an image. This is plus the REPOSITORY is a way to determine", "# a version of the image. We will produced a TAG for a combination of the runtime with the layers", "# specified in...
43.88
31.32
def show_heatmap(self, blocking=True, output_file=None, enable_scroll=False): """Method to actually display the heatmap created. @param blocking: When set to False makes an unblocking plot show. @param output_file: If not None the heatmap image is output to this file. Suppor...
[ "def", "show_heatmap", "(", "self", ",", "blocking", "=", "True", ",", "output_file", "=", "None", ",", "enable_scroll", "=", "False", ")", ":", "if", "output_file", "is", "None", ":", "if", "enable_scroll", ":", "# Add a new axes which will be used as scroll bar....
44.04
20.2
def find_module(self, fullname, path=None): """ Find the appropriate loader for module ``name`` :param fullname: ``__name__`` of the module to import :type fullname: str :param path: ``__path__`` of the *parent* package already imported :type path: str or None ""...
[ "def", "find_module", "(", "self", ",", "fullname", ",", "path", "=", "None", ")", ":", "# path points to the top-level package path if any", "# and we can only import sub-modules/-packages", "if", "path", "is", "None", ":", "return", "if", "fullname", ".", "startswith"...
33.941176
16.294118
def make_article_info_dates(self): """ Makes the section containing important dates for the article: typically Received, Accepted, and Published. """ dates_div = etree.Element('div', {'id': 'article-dates'}) d = './front/article-meta/history/date' received = self...
[ "def", "make_article_info_dates", "(", "self", ")", ":", "dates_div", "=", "etree", ".", "Element", "(", "'div'", ",", "{", "'id'", ":", "'article-dates'", "}", ")", "d", "=", "'./front/article-meta/history/date'", "received", "=", "self", ".", "article", ".",...
46.419355
19.322581
def dstationarystate(self, k, param): """See docs for `Model` abstract base class.""" assert param not in self.distributionparams assert param in self.freeparams or param == self.distributedparam ds = self._models[k].dstationarystate(param) return ds
[ "def", "dstationarystate", "(", "self", ",", "k", ",", "param", ")", ":", "assert", "param", "not", "in", "self", ".", "distributionparams", "assert", "param", "in", "self", ".", "freeparams", "or", "param", "==", "self", ".", "distributedparam", "ds", "="...
47.5
13.666667
def complete_value_catching_error( self, return_type: GraphQLOutputType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: """Complete a value while catching an error. This is a small ...
[ "def", "complete_value_catching_error", "(", "self", ",", "return_type", ":", "GraphQLOutputType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "info", ":", "GraphQLResolveInfo", ",", "path", ":", "ResponsePath", ",", "result", ":", "Any", ",", ...
35.166667
15.333333
def syslog_generate(str_processName, str_pid): ''' Returns a string similar to: Tue Oct 9 10:49:53 2012 pretoria message.py[26873]: where 'pretoria' is the hostname, 'message.py' is the current process name and 26873 is the current process id. ''' localtime = time.asct...
[ "def", "syslog_generate", "(", "str_processName", ",", "str_pid", ")", ":", "localtime", "=", "time", ".", "asctime", "(", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", ")", ")", "hostname", "=", "os", ".", "uname", "(", ")", "[", "1"...
36.846154
24.384615
def estimate_achievable_tmid_precision(snr, t_ingress_min=10, t_duration_hr=2.14): '''Using Carter et al. 2009's estimate, calculate the theoretical optimal precision on mid-transit time measurement possible given a transit of a particular SNR. The relation used i...
[ "def", "estimate_achievable_tmid_precision", "(", "snr", ",", "t_ingress_min", "=", "10", ",", "t_duration_hr", "=", "2.14", ")", ":", "t_ingress", "=", "t_ingress_min", "*", "u", ".", "minute", "t_duration", "=", "t_duration_hr", "*", "u", ".", "hour", "theta...
32.018182
26.709091
def write_main_jobwrappers(self): ''' Writes out 'jobs' as wrapped toil objects in preparation for calling. :return: A string representing this. ''' main_section = '' # toil cannot technically start with multiple jobs, so an empty # 'initialize_jobs' function is...
[ "def", "write_main_jobwrappers", "(", "self", ")", ":", "main_section", "=", "''", "# toil cannot technically start with multiple jobs, so an empty", "# 'initialize_jobs' function is always called first to get around this", "main_section", "=", "main_section", "+", "'\\n job0 = ...
53.37931
33.586207
def file_exists(path, saltenv=None): ''' .. versionadded:: 2016.3.0 This is a master-only function. Calling from the minion is not supported. Use the given path and search relative to the pillar environments to see if a file exists at that path. If the ``saltenv`` argument is given, restrict ...
[ "def", "file_exists", "(", "path", ",", "saltenv", "=", "None", ")", ":", "pillar_roots", "=", "__opts__", ".", "get", "(", "'pillar_roots'", ")", "if", "not", "pillar_roots", ":", "raise", "CommandExecutionError", "(", "'No pillar_roots found. Are you running '", ...
28.326087
26.543478
def result(self): ''' :return: None if the result is not ready, the result from set_result, or raise the exception from set_exception. If the result can be None, it is not possible to tell if the result is available; use done() to determine that. ''' try...
[ "def", "result", "(", "self", ")", ":", "try", ":", "r", "=", "getattr", "(", "self", ",", "'_result'", ")", "except", "AttributeError", ":", "return", "None", "else", ":", "if", "hasattr", "(", "self", ",", "'_exception'", ")", ":", "raise", "self", ...
36.133333
23.466667
def build_disease_term(disease_info, alias_genes={}): """Build a disease phenotype object Args: disease_info(dict): Dictionary with phenotype information alias_genes(dict): { <alias_symbol>: { 'true': hgnc_id or None, ...
[ "def", "build_disease_term", "(", "disease_info", ",", "alias_genes", "=", "{", "}", ")", ":", "try", ":", "disease_nr", "=", "int", "(", "disease_info", "[", "'mim_number'", "]", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "\"Diseases has to hav...
33.561644
20.356164
def to_json_file(self, path, file_name=None): """Writes output to a JSON file with the given file name""" if bool(path) and os.path.isdir(path): self.write_to_json(path, file_name) else: self.write_to_json(os.getcwd(), file_name)
[ "def", "to_json_file", "(", "self", ",", "path", ",", "file_name", "=", "None", ")", ":", "if", "bool", "(", "path", ")", "and", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "self", ".", "write_to_json", "(", "path", ",", "file_name", ")...
45.333333
9.833333
def save_as_png(self, filename, width=300, height=250, render_time=1): """Open saved html file in an virtual browser and save a screen shot to PNG format.""" self.driver.set_window_size(width, height) self.driver.get('file://{path}/{filename}'.format( path=os.getcwd(), filename=filen...
[ "def", "save_as_png", "(", "self", ",", "filename", ",", "width", "=", "300", ",", "height", "=", "250", ",", "render_time", "=", "1", ")", ":", "self", ".", "driver", ".", "set_window_size", "(", "width", ",", "height", ")", "self", ".", "driver", "...
59.428571
14.285714
def del_restriction(self, command, user, event_types): """ Removes restriction for given `command`. :param command: command on which the restriction should be removed. :type command: str :param user: username for which restriction should be removed. :type user: str ...
[ "def", "del_restriction", "(", "self", ",", "command", ",", "user", ",", "event_types", ")", ":", "if", "user", ".", "lower", "(", ")", "in", "self", ".", "commands_rights", "[", "command", "]", ":", "for", "event_type", "in", "event_types", ":", "try", ...
43.052632
18.947368
def _get_path(fname: str) -> str: """ :meth: download get path of file from pythainlp-corpus :param str fname: file name :return: path to downloaded file """ path = get_corpus_path(fname) if not path: download(fname) path = get_corpus_path(fname) return path
[ "def", "_get_path", "(", "fname", ":", "str", ")", "->", "str", ":", "path", "=", "get_corpus_path", "(", "fname", ")", "if", "not", "path", ":", "download", "(", "fname", ")", "path", "=", "get_corpus_path", "(", "fname", ")", "return", "path" ]
26.909091
10.363636
def reload_repo_cache(i): """ Input: { (force) - if 'yes', force recaching } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } ...
[ "def", "reload_repo_cache", "(", "i", ")", ":", "global", "cache_repo_uoa", ",", "cache_repo_info", ",", "paths_repos_all", ",", "cache_repo_init", "if", "i", ".", "get", "(", "'force'", ",", "''", ")", "==", "'yes'", ":", "# pragma: no cover", "cache_repo_init"...
31.363636
20.363636
def set_focus_to_state_model(self, state_m, ratio_requested=0.8): """ Focus a state view of respective state model :param rafcon.gui.model.state state_m: Respective state model of state view to be focused :param ratio_requested: Minimum ratio of the screen which is requested, so can be more ...
[ "def", "set_focus_to_state_model", "(", "self", ",", "state_m", ",", "ratio_requested", "=", "0.8", ")", ":", "state_machine_m", "=", "self", ".", "model", "state_v", "=", "self", ".", "canvas", ".", "get_view_for_model", "(", "state_m", ")", "if", "state_v", ...
67.411765
33
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64): """Returns a key derived using the scrypt key-derivarion function N must be a power of two larger than 1 but no larger than 2 ** 63 (insane) r and p must be positive numbers such that r * p < 2 ** 30 The default values are: N...
[ "def", "scrypt", "(", "password", ",", "salt", ",", "N", "=", "SCRYPT_N", ",", "r", "=", "SCRYPT_r", ",", "p", "=", "SCRYPT_p", ",", "olen", "=", "64", ")", ":", "check_args", "(", "password", ",", "salt", ",", "N", ",", "r", ",", "p", ",", "ol...
37.178571
25.821429
def put_script(self, id, body, context=None, params=None): """ Create a script in given language with specified ID. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_ :arg id: Script ID :arg body: The document """ for param...
[ "def", "put_script", "(", "self", ",", "id", ",", "body", ",", "context", "=", "None", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "id", ",", "body", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(...
41.285714
20.428571
def bookmark_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/bookmarks#create-bookmark" api_path = "/api/v2/bookmarks.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "bookmark_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/bookmarks.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", "*",...
59.75
19.75
def get_terms(desc, geneset, assoc, obo_dag, log): """Get the terms in the study group """ _chk_gene2go(assoc) term2itemids = defaultdict(set) genes = [g for g in geneset if g in assoc] for gene in genes: for goid in assoc[gene]: if goid in obo_dag: term2itemi...
[ "def", "get_terms", "(", "desc", ",", "geneset", ",", "assoc", ",", "obo_dag", ",", "log", ")", ":", "_chk_gene2go", "(", "assoc", ")", "term2itemids", "=", "defaultdict", "(", "set", ")", "genes", "=", "[", "g", "for", "g", "in", "geneset", "if", "g...
38.294118
13.588235
def _is_type_compatible(a, b): """helper for interval_range to check type compat of start/end/freq""" is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset)) is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset)) return ((is_number(a) and is_number(b)) or (is_ts_compat(a) an...
[ "def", "_is_type_compatible", "(", "a", ",", "b", ")", ":", "is_ts_compat", "=", "lambda", "x", ":", "isinstance", "(", "x", ",", "(", "Timestamp", ",", "DateOffset", ")", ")", "is_td_compat", "=", "lambda", "x", ":", "isinstance", "(", "x", ",", "(", ...
52.5
12.75
def update_records(self, domain, records): """ Modifies an existing records for a domain. """ if not isinstance(records, list): raise TypeError("Expected records of type list") uri = "/domains/%s/records" % utils.get_id(domain) resp, resp_body = self._async_ca...
[ "def", "update_records", "(", "self", ",", "domain", ",", "records", ")", ":", "if", "not", "isinstance", "(", "records", ",", "list", ")", ":", "raise", "TypeError", "(", "\"Expected records of type list\"", ")", "uri", "=", "\"/domains/%s/records\"", "%", "u...
43.363636
11.545455
def set_xy_color(self, color_x, color_y, *, index=0, transition_time=None): """Set xy color of the light.""" self._value_validate(color_x, RANGE_X, "X color") self._value_validate(color_y, RANGE_Y, "Y color") values = { ATTR_LIGHT_COLOR_X: color_x, ATTR_LIGHT_COL...
[ "def", "set_xy_color", "(", "self", ",", "color_x", ",", "color_y", ",", "*", ",", "index", "=", "0", ",", "transition_time", "=", "None", ")", ":", "self", ".", "_value_validate", "(", "color_x", ",", "RANGE_X", ",", "\"X color\"", ")", "self", ".", "...
34.5
19.5
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow...
[ "def", "do_urlize", "(", "eval_ctx", ",", "value", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ",", "target", "=", "None", ",", "rel", "=", "None", ")", ":", "policies", "=", "eval_ctx", ".", "environment", ".", "policies", "rel", ...
31.428571
19.914286
def _invertMapping(mapping): """Converts a protein to peptide or peptide to protein mapping. :param mapping: dict, for each key contains a set of entries :returns: an inverted mapping that each entry of the values points to a set of initial keys. """ invertedMapping = ddict(set) for ke...
[ "def", "_invertMapping", "(", "mapping", ")", ":", "invertedMapping", "=", "ddict", "(", "set", ")", "for", "key", ",", "values", "in", "viewitems", "(", "mapping", ")", ":", "for", "value", "in", "values", ":", "invertedMapping", "[", "value", "]", ".",...
33.846154
16.153846
def importFromPath(self, path, fqname): """Import a dotted-name package whose tail is at path. In other words, given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then bar from path/to/foo/bar, returning bar. """ # find the base dir of the package path_parts...
[ "def", "importFromPath", "(", "self", ",", "path", ",", "fqname", ")", ":", "# find the base dir of the package", "path_parts", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", ".", "split", "(", "os...
48.642857
10.142857
def coverage(self): """ Will return a DataFrame with coverage information (if available) for each repo in the project). If there is a .coverage file available, this will attempt to form a DataFrame with that information in it, which will contain the columns: * repository ...
[ "def", "coverage", "(", "self", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "columns", "=", "[", "'filename'", ",", "'lines_covered'", ",", "'total_lines'", ",", "'coverage'", ",", "'repository'", "]", ")", "for", "repo", "in", "self", ".", "repos"...
30.548387
27.387097
def unwrap_stream(stream_name): """ Temporarily unwraps a given stream (stdin, stdout, or stderr) to undo the effects of wrap_stdio_in_codecs(). """ wrapped_stream = None try: wrapped_stream = getattr(sys, stream_name) if hasattr(wrapped_stream, '_original_stream'): setat...
[ "def", "unwrap_stream", "(", "stream_name", ")", ":", "wrapped_stream", "=", "None", "try", ":", "wrapped_stream", "=", "getattr", "(", "sys", ",", "stream_name", ")", "if", "hasattr", "(", "wrapped_stream", ",", "'_original_stream'", ")", ":", "setattr", "(",...
36.076923
20.384615
def generate_edit_credentials(self): """ request an edit token and update the cookie_jar in order to add the session cookie :return: Returns a json with all relevant cookies, aka cookie jar """ params = { 'action': 'query', 'meta': 'tokens', 'f...
[ "def", "generate_edit_credentials", "(", "self", ")", ":", "params", "=", "{", "'action'", ":", "'query'", ",", "'meta'", ":", "'tokens'", ",", "'format'", ":", "'json'", "}", "response", "=", "self", ".", "s", ".", "get", "(", "self", ".", "base_url", ...
35.428571
19.714286
def _on_return(self, text): """Called when the user presses return on the send message widget.""" # Ignore if the user hasn't typed a message. if not text: return elif text.startswith('/image') and len(text.split(' ')) == 2: # Temporary UI for testing image upload...
[ "def", "_on_return", "(", "self", ",", "text", ")", ":", "# Ignore if the user hasn't typed a message.", "if", "not", "text", ":", "return", "elif", "text", ".", "startswith", "(", "'/image'", ")", "and", "len", "(", "text", ".", "split", "(", "' '", ")", ...
36.761905
14.333333
def multicore(function, cores, multiargs, **singleargs): """ wrapper for multicore process execution Parameters ---------- function individual function to be applied to each process item cores: int the number of subprocesses started/CPUs used; this value is reduced in ca...
[ "def", "multicore", "(", "function", ",", "cores", ",", "multiargs", ",", "*", "*", "singleargs", ")", ":", "tblib", ".", "pickling_support", ".", "install", "(", ")", "# compare the function arguments with the multi and single arguments and raise errors if mismatches occur...
41.298611
26.270833
def sndread(path:str) -> Tuple[np.ndarray, int]: """ Read a soundfile as a numpy array. This is a float array defined between -1 and 1, independently of the format of the soundfile Returns (data:ndarray, sr:int) """ backend = _getBackend(path) logger.debug(f"sndread: using backend {bac...
[ "def", "sndread", "(", "path", ":", "str", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "int", "]", ":", "backend", "=", "_getBackend", "(", "path", ")", "logger", ".", "debug", "(", "f\"sndread: using backend {backend.name}\"", ")", "return", "back...
35.3
14.3
def by_phone(self, phone, **kwargs): """ Fetch messages from chat with specified phone number. :Example: chat = client.chats.by_phone(phone="447624800500") :param str phone: Phone number in E.164 format. :param int page: Fetch specified results page. Default=1 ...
[ "def", "by_phone", "(", "self", ",", "phone", ",", "*", "*", "kwargs", ")", ":", "chat_messages", "=", "ChatMessages", "(", "self", ".", "base_uri", ",", "self", ".", "auth", ")", "return", "self", ".", "get_subresource_instances", "(", "uid", "=", "phon...
38.071429
23.214286
def from_events(self, instance, ev_args, ctx): """ Detect the object to instanciate from the arguments `ev_args` of the ``"start"`` event. The new object is stored at the corresponding descriptor attribute on `instance`. This method is suspendable. """ obj = yiel...
[ "def", "from_events", "(", "self", ",", "instance", ",", "ev_args", ",", "ctx", ")", ":", "obj", "=", "yield", "from", "self", ".", "_process", "(", "instance", ",", "ev_args", ",", "ctx", ")", "self", ".", "__set__", "(", "instance", ",", "obj", ")"...
37.181818
15.545455
def as_tuple(self, named=None): """ Create a structured schema that will pass stream tuples into callables as ``tuple`` instances. If this instance represents a common schema then it will be returned without modification. Stream tuples with common schemas are always passed accor...
[ "def", "as_tuple", "(", "self", ",", "named", "=", "None", ")", ":", "if", "not", "named", ":", "return", "self", ".", "_copy", "(", "tuple", ")", "if", "named", "==", "True", "or", "isinstance", "(", "named", ",", "basestring", ")", ":", "return", ...
41.637931
26.706897
def _file_in_next_patches(self, filename, patch): """ Checks if a backup file of the filename in the applied patches after patch exists """ if not self.db.is_patch(patch): # no patches applied return patches = self.db.patches_after(patch) for patch in pa...
[ "def", "_file_in_next_patches", "(", "self", ",", "filename", ",", "patch", ")", ":", "if", "not", "self", ".", "db", ".", "is_patch", "(", "patch", ")", ":", "# no patches applied", "return", "patches", "=", "self", ".", "db", ".", "patches_after", "(", ...
40.6
16.733333
def rsync(*args, **kwargs): """ wrapper around the rsync command. the ssh connection arguments are set automatically. any args are just passed directly to rsync. you can use {host_string} in place of the server. the kwargs are passed on the 'local' fabric command. if not s...
[ "def", "rsync", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'capture'", ",", "False", ")", "replacements", "=", "dict", "(", "host_string", "=", "\"{user}@{host}\"", ".", "format", "(", "user", "=", "env", "....
35.903226
15.709677
def _add_snps( self, snps, discrepant_snp_positions_threshold, discrepant_genotypes_threshold, save_output, ): """ Add SNPs to this Individual. Parameters ---------- snps : SNPs SNPs to add discrepant_snp_positions_threshol...
[ "def", "_add_snps", "(", "self", ",", "snps", ",", "discrepant_snp_positions_threshold", ",", "discrepant_genotypes_threshold", ",", "save_output", ",", ")", ":", "discrepant_positions", "=", "pd", ".", "DataFrame", "(", ")", "discrepant_genotypes", "=", "pd", ".", ...
36.579618
21.171975
def derivative(func, x0, dx=1.0, n=1, args=(), order=3): '''Reimplementation of SciPy's derivative function, with more cached coefficients and without using numpy. If new coefficients not cached are needed, they are only calculated once and are remembered. ''' if order < n + 1: raise ValueEr...
[ "def", "derivative", "(", "func", ",", "x0", ",", "dx", "=", "1.0", ",", "n", "=", "1", ",", "args", "=", "(", ")", ",", "order", "=", "3", ")", ":", "if", "order", "<", "n", "+", "1", ":", "raise", "ValueError", "if", "order", "%", "2", "=...
36.666667
19.866667
def cache_file(source): ''' Wrapper for cp.cache_file which raises an error if the file was unable to be cached. CLI Example: .. code-block:: bash salt myminion container_resource.cache_file salt://foo/bar/baz.txt ''' try: # Don't just use cp.cache_file for this. Docker ha...
[ "def", "cache_file", "(", "source", ")", ":", "try", ":", "# Don't just use cp.cache_file for this. Docker has its own code to", "# pull down images from the web.", "if", "source", ".", "startswith", "(", "'salt://'", ")", ":", "cached_source", "=", "__salt__", "[", "'cp....
31.916667
23.25
def __Logout(si): """ Disconnect (logout) service instance @param si: Service instance (returned from Connect) """ try: if si: content = si.RetrieveContent() content.sessionManager.Logout() except Exception as e: pass
[ "def", "__Logout", "(", "si", ")", ":", "try", ":", "if", "si", ":", "content", "=", "si", ".", "RetrieveContent", "(", ")", "content", ".", "sessionManager", ".", "Logout", "(", ")", "except", "Exception", "as", "e", ":", "pass" ]
23.181818
13.181818
def get_descendants(self): """ :returns: A queryset of all the node's descendants as DFS, doesn't include the node itself """ if self.is_leaf(): return get_result_class(self.__class__).objects.none() return self.__class__.get_tree(self).exclude(pk=self.pk)
[ "def", "get_descendants", "(", "self", ")", ":", "if", "self", ".", "is_leaf", "(", ")", ":", "return", "get_result_class", "(", "self", ".", "__class__", ")", ".", "objects", ".", "none", "(", ")", "return", "self", ".", "__class__", ".", "get_tree", ...
39.125
14.625
def phytozome10(args): """ %prog phytozome species Retrieve genomes and annotations from phytozome using Globus API. Available species listed below. Use comma to give a list of species to download. For example: $ %prog phytozome Athaliana,Vvinifera,Osativa,Sbicolor,Slycopersicum """ fr...
[ "def", "phytozome10", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "biomart", "import", "GlobusXMLParser", "p", "=", "OptionParser", "(", "phytozome10", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", ...
27.793103
19.793103
async def rpc_message(self, request, message): '''Publish a message via JSON-RPC''' await self.pubsub.publish(self.channel, message) return 'OK'
[ "async", "def", "rpc_message", "(", "self", ",", "request", ",", "message", ")", ":", "await", "self", ".", "pubsub", ".", "publish", "(", "self", ".", "channel", ",", "message", ")", "return", "'OK'" ]
41.25
11.75
def add_file(self, filename): """Add a file and all its immediate dependencies to the graph.""" assert not self.final, 'Trying to mutate a final graph.' self.add_source_file(filename) resolved, unresolved = self.get_file_deps(filename) self.graph.add_node(filename) for f...
[ "def", "add_file", "(", "self", ",", "filename", ")", ":", "assert", "not", "self", ".", "final", ",", "'Trying to mutate a final graph.'", "self", ".", "add_source_file", "(", "filename", ")", "resolved", ",", "unresolved", "=", "self", ".", "get_file_deps", ...
40.083333
11.666667
def getattrs(value, attrs, default=_no_default): """ Perform a chained application of ``getattr`` on ``value`` with the values in ``attrs``. If ``default`` is supplied, return it if any of the attribute lookups fail. Parameters ---------- value : object Root of the lookup chain. ...
[ "def", "getattrs", "(", "value", ",", "attrs", ",", "default", "=", "_no_default", ")", ":", "try", ":", "for", "attr", "in", "attrs", ":", "value", "=", "getattr", "(", "value", ",", "attr", ")", "except", "AttributeError", ":", "if", "default", "is",...
24.145833
19.895833
def BinToTri(self, a, b): ''' Turn an a-b coord to an x-y-z triangular coord . if z is negative, calc with its abs then return (a, -b). :param a,b: the numbers of the a-b coord :type a,b: float or double are both OK, just numbers :return: the corresponding x-y-z triangu...
[ "def", "BinToTri", "(", "self", ",", "a", ",", "b", ")", ":", "if", "(", "b", ">=", "0", ")", ":", "y", "=", "a", "-", "b", "/", "np", ".", "sqrt", "(", "3", ")", "z", "=", "b", "*", "2", "/", "np", ".", "sqrt", "(", "3", ")", "x", ...
32.571429
16.190476
def list(self, reservation_status=values.unset, limit=None, page_size=None): """ Lists ReservationInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param ReservationInstance.Status reser...
[ "def", "list", "(", "self", ",", "reservation_status", "=", "values", ".", "unset", ",", "limit", "=", "None", ",", "page_size", "=", "None", ")", ":", "return", "list", "(", "self", ".", "stream", "(", "reservation_status", "=", "reservation_status", ",",...
65.222222
38.222222
def check_credentials(self): """Verifies key/secret/host combination by making a balance inquiry""" try: return bool(self.mturk.get_account_balance()) except NoCredentialsError: raise MTurkServiceException("No AWS credentials set!") except ClientError: ...
[ "def", "check_credentials", "(", "self", ")", ":", "try", ":", "return", "bool", "(", "self", ".", "mturk", ".", "get_account_balance", "(", ")", ")", "except", "NoCredentialsError", ":", "raise", "MTurkServiceException", "(", "\"No AWS credentials set!\"", ")", ...
43.083333
15.75
def cmd_part(self, connection, sender, target, payload): """ Asks the bot to leave a channel """ if payload: connection.part(payload) else: raise ValueError("No channel given")
[ "def", "cmd_part", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "if", "payload", ":", "connection", ".", "part", "(", "payload", ")", "else", ":", "raise", "ValueError", "(", "\"No channel given\"", ")" ]
29.125
9.625
def shall_save(self, form, name, composite_form): """ Return ``True`` if the given ``composite_form`` (the nested form of this field) shall be saved. Return ``False`` if the form shall not be saved together with the super-form. By default it will return ``False`` if the form was...
[ "def", "shall_save", "(", "self", ",", "form", ",", "name", ",", "composite_form", ")", ":", "if", "composite_form", ".", "empty_permitted", "and", "not", "composite_form", ".", "has_changed", "(", ")", ":", "return", "False", "return", "True" ]
44.615385
21.846154
def init(self, context): """Initializes sitetree to handle new request. :param Context|None context: """ self.cache = Cache() self.current_page_context = context self.current_request = context.get('request', None) if context else None self.current_lang = get_lang...
[ "def", "init", "(", "self", ",", "context", ")", ":", "self", ".", "cache", "=", "Cache", "(", ")", "self", ".", "current_page_context", "=", "context", "self", ".", "current_request", "=", "context", ".", "get", "(", "'request'", ",", "None", ")", "if...
36.357143
14.571429
def get_notebook_status(self, name): """Get the running named Notebook status. :return: None if no notebook is running, otherwise context dictionary """ context = comm.get_context(self.get_pid(name)) if not context: return None return context
[ "def", "get_notebook_status", "(", "self", ",", "name", ")", ":", "context", "=", "comm", ".", "get_context", "(", "self", ".", "get_pid", "(", "name", ")", ")", "if", "not", "context", ":", "return", "None", "return", "context" ]
32.777778
16.333333
def confirm(self, msg, _timeout=-1): ''' Send a confirm prompt to the GUI Arguments: msg (string): The message to display to the user. _timeout (int): The optional amount of time for which the prompt should be displayed to...
[ "def", "confirm", "(", "self", ",", "msg", ",", "_timeout", "=", "-", "1", ")", ":", "return", "self", ".", "msgBox", "(", "'confirm'", ",", "_timeout", "=", "_timeout", ",", "msg", "=", "msg", ")" ]
38
21.846154
def ReadMessageHandlerRequests(self): """Reads all message handler requests from the database.""" res = [] leases = self.message_handler_leases for requests in itervalues(self.message_handler_requests): for r in itervalues(requests): res.append(r.Copy()) existing_lease = leases.get...
[ "def", "ReadMessageHandlerRequests", "(", "self", ")", ":", "res", "=", "[", "]", "leases", "=", "self", ".", "message_handler_leases", "for", "requests", "in", "itervalues", "(", "self", ".", "message_handler_requests", ")", ":", "for", "r", "in", "itervalues...
41.454545
15.181818
def dna(self, dna): """ Replace this chromosome's DNA with new DNA of equal length, assigning the new DNA to the chromosome's genes sequentially. For example, if a chromosome contains these genes... 1. 100100 2. 011011 ...and the new DNA...
[ "def", "dna", "(", "self", ",", "dna", ")", ":", "assert", "self", ".", "length", "==", "len", "(", "dna", ")", "i", "=", "0", "for", "gene", "in", "self", ".", "genes", ":", "gene", ".", "dna", "=", "dna", "[", "i", ":", "i", "+", "gene", ...
28.5
19.05
def check_in_bounds(self, date): '''Check that left and right bounds are sane :param date: date to validate left/right bounds for ''' dt = Timestamp(date) return ((self._lbound is None or dt >= self._lbound) and (self._rbound is None or dt <= self._rbound))
[ "def", "check_in_bounds", "(", "self", ",", "date", ")", ":", "dt", "=", "Timestamp", "(", "date", ")", "return", "(", "(", "self", ".", "_lbound", "is", "None", "or", "dt", ">=", "self", ".", "_lbound", ")", "and", "(", "self", ".", "_rbound", "is...
38.375
20.625