text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def enable_loggly(graph): """ Enable loggly if it is configured and not debug/testing. """ if graph.metadata.debug or graph.metadata.testing: return False try: if not graph.config.logging.loggly.token: return False if not graph.config.logging.loggly.environment...
[ "def", "enable_loggly", "(", "graph", ")", ":", "if", "graph", ".", "metadata", ".", "debug", "or", "graph", ".", "metadata", ".", "testing", ":", "return", "False", "try", ":", "if", "not", "graph", ".", "config", ".", "logging", ".", "loggly", ".", ...
21.888889
20.888889
def dump_nodes(self): """ Dump tag,rule,id and value cache. For debug. example:: R = [ #dump_nodes ] """ print("DUMP NODE LOCAL INFOS") try: print("map Id->node name") for k, v in self.id_cache.items(): print("[%d]=%s" % (k, v)) ...
[ "def", "dump_nodes", "(", "self", ")", ":", "print", "(", "\"DUMP NODE LOCAL INFOS\"", ")", "try", ":", "print", "(", "\"map Id->node name\"", ")", "for", "k", ",", "v", "in", "self", ".", "id_cache", ".", "items", "(", ")", ":", "print", "(", "\"[%d]=%s...
28.5
13.794118
def run(self) -> None: """Starts or resumes the generator, running until it reaches a yield point that is not ready. """ if self.running or self.finished: return try: self.running = True while True: future = self.future ...
[ "def", "run", "(", "self", ")", "->", "None", ":", "if", "self", ".", "running", "or", "self", ".", "finished", ":", "return", "try", ":", "self", ".", "running", "=", "True", "while", "True", ":", "future", "=", "self", ".", "future", "if", "futur...
37.018868
13.792453
def world_command_examples(): """A few examples to showcase commands for manipulating the worlds.""" env = holodeck.make("MazeWorld") # This is the unaltered MazeWorld for _ in range(300): _ = env.tick() env.reset() # The set_day_time_command sets the hour between 0 and 23 (military ti...
[ "def", "world_command_examples", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"MazeWorld\"", ")", "# This is the unaltered MazeWorld", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "res...
32.111111
24.866667
def add_access_key_permissions(self, access_key_id, permissions): """ Adds to the existing list of permissions on this key with the contents of this list. Will not remove any existing permissions or modify the remainder of the key. :param access_key_id: the 'key' value of the access key...
[ "def", "add_access_key_permissions", "(", "self", ",", "access_key_id", ",", "permissions", ")", ":", "# Get current state via HTTPS.", "current_access_key", "=", "self", ".", "get_access_key", "(", "access_key_id", ")", "# Copy and only change the single parameter.", "payloa...
48.090909
25.454545
def punctuation_for_spaces_dict() -> Dict[int, str]: """ Provide a dictionary for removing punctuation, keeping spaces. Essential for scansion to keep stress patterns in alignment with original vowel positions in the verse. :return dict with punctuation from the unicode table >>> print("I'm ok! Oh...
[ "def", "punctuation_for_spaces_dict", "(", ")", "->", "Dict", "[", "int", ",", "str", "]", ":", "return", "dict", "(", "(", "i", ",", "\" \"", ")", "for", "i", "in", "range", "(", "sys", ".", "maxunicode", ")", "if", "unicodedata", ".", "category", "...
42.230769
20.846154
def _add_to_ref(self, rec_curr, line, lnum): """Add new fields to the current reference.""" # Written by DV Klopfenstein # Examples of record lines containing ':' include: # id: GO:0000002 # name: mitochondrial genome maintenance # namespace: biological_process ...
[ "def", "_add_to_ref", "(", "self", ",", "rec_curr", ",", "line", ",", "lnum", ")", ":", "# Written by DV Klopfenstein", "# Examples of record lines containing ':' include:", "# id: GO:0000002", "# name: mitochondrial genome maintenance", "# namespace: biological_process", "# ...
45.875
10.5625
def get_addon_module_name(addonxml_filename): '''Attempts to extract a module name for the given addon's addon.xml file. Looks for the 'xbmc.python.pluginsource' extension node and returns the addon's filename without the .py suffix. ''' try: xml = ET.parse(addonxml_filename).getroot() e...
[ "def", "get_addon_module_name", "(", "addonxml_filename", ")", ":", "try", ":", "xml", "=", "ET", ".", "parse", "(", "addonxml_filename", ")", ".", "getroot", "(", ")", "except", "IOError", ":", "sys", ".", "exit", "(", "'Cannot find an addon.xml file in the cur...
41.842105
25.105263
def configure(self): """ Enables the repository for a most current version on Debian systems. https://www.rabbitmq.com/install-debian.html """ os_version = self.os_version if not self.dryrun and os_version.distro != UBUNTU: raise NotImplementedError("OS ...
[ "def", "configure", "(", "self", ")", ":", "os_version", "=", "self", ".", "os_version", "if", "not", "self", ".", "dryrun", "and", "os_version", ".", "distro", "!=", "UBUNTU", ":", "raise", "NotImplementedError", "(", "\"OS %s is not supported.\"", "%", "os_v...
42.117647
29.176471
def set_filter_type(self, filter_type=None): """ Set(modify) filtering mode for better compression `filter_type` is number or name of filter type for better compression see http://www.w3.org/TR/PNG/#9Filter-types for details It's also possible to use adaptive strategy for choosi...
[ "def", "set_filter_type", "(", "self", ",", "filter_type", "=", "None", ")", ":", "if", "filter_type", "is", "None", ":", "filter_type", "=", "0", "elif", "isinstance", "(", "filter_type", ",", "basestring", ")", ":", "str_ftype", "=", "str", "(", "filter_...
43.875
12.458333
def get_collections_for_image(self, image_id): """Get identifier of all collections that contain a given image. Parameters ---------- image_id : string Unique identifierof image object Returns ------- List(string) List of image collection...
[ "def", "get_collections_for_image", "(", "self", ",", "image_id", ")", ":", "result", "=", "[", "]", "# Get all active collections that contain the image identifier", "for", "document", "in", "self", ".", "collection", ".", "find", "(", "{", "'active'", ":", "True",...
32.444444
19.944444
def get_wordset(poems): """get all words""" words = sorted(list(set(reduce(lambda x, y: x + y, poems)))) return words
[ "def", "get_wordset", "(", "poems", ")", ":", "words", "=", "sorted", "(", "list", "(", "set", "(", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "poems", ")", ")", ")", ")", "return", "words" ]
31.5
16.25
def scan(self, folder, sub=None, next_=None): """ Request immediate rescan of a folder, or a specific path within a folder. Args: folder (str): Folder ID. sub (str): Path relative to the folder root. If sub is omitted the entire folder is ...
[ "def", "scan", "(", "self", ",", "folder", ",", "sub", "=", "None", ",", "next_", "=", "None", ")", ":", "if", "not", "sub", ":", "sub", "=", "''", "assert", "isinstance", "(", "sub", ",", "string_types", ")", "assert", "isinstance", "(", "next_", ...
40
18.727273
def get_initial_beliefs(self): """ Returns the state, action and observation variables as a dictionary in the case of table type parameter and a nested structure in case of decision diagram parameter Examples -------- >>> reader = PomdpXReader('Test_PomdpX.xml') ...
[ "def", "get_initial_beliefs", "(", "self", ")", ":", "initial_state_belief", "=", "[", "]", "for", "variable", "in", "self", ".", "network", ".", "findall", "(", "'InitialStateBelief'", ")", ":", "for", "var", "in", "variable", ".", "findall", "(", "'CondPro...
36.828571
17.171429
def trcdep(): """ Return the number of modules in the traceback representation. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcdep_c.html :return: The number of modules in the traceback. :rtype: int """ depth = ctypes.c_int() libspice.trcdep_c(ctypes.byref(depth)) retur...
[ "def", "trcdep", "(", ")", ":", "depth", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "trcdep_c", "(", "ctypes", ".", "byref", "(", "depth", ")", ")", "return", "depth", ".", "value" ]
26.833333
19.666667
def correlation_vector(self, value): """The correlation_vector property. Args: value (string). the property value. """ if value == self._defaults['ai.operation.correlationVector'] and 'ai.operation.correlationVector' in self._values: del self._values['ai....
[ "def", "correlation_vector", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'ai.operation.correlationVector'", "]", "and", "'ai.operation.correlationVector'", "in", "self", ".", "_values", ":", "del", "self", ".", "_val...
42.1
22.7
def data_file(self): """ Gets the full path to the file in which to save/load configured data. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.data_filename
[ "def", "data_file", "(", "self", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "return", "path", "+", "self", ".", "data_filename" ]
49
7.75
def write(self, txt): """Write ``txt`` to file and output stream (StringIO). """ self.fp.write(to_unicode(txt)) if self.out: self.out.write(txt)
[ "def", "write", "(", "self", ",", "txt", ")", ":", "self", ".", "fp", ".", "write", "(", "to_unicode", "(", "txt", ")", ")", "if", "self", ".", "out", ":", "self", ".", "out", ".", "write", "(", "txt", ")" ]
30.5
8.333333
def set_color_in_session(intent, session): """ Sets the color in the session and prepares the speech to reply to the user. """ card_title = intent['name'] session_attributes = {} should_end_session = False if 'Color' in intent['slots']: favorite_color = intent['slots']['Color']['va...
[ "def", "set_color_in_session", "(", "intent", ",", "session", ")", ":", "card_title", "=", "intent", "[", "'name'", "]", "session_attributes", "=", "{", "}", "should_end_session", "=", "False", "if", "'Color'", "in", "intent", "[", "'slots'", "]", ":", "favo...
46.5
20.192308
def find_gate(nid=None): """ find gate according node ID. :param nid: node id :return: the gate if found or None if not found """ LOGGER.debug("GateService.find_gate") ret = None if nid is None or not nid: raise exceptions.ArianeCallParametersE...
[ "def", "find_gate", "(", "nid", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "\"GateService.find_gate\"", ")", "ret", "=", "None", "if", "nid", "is", "None", "or", "not", "nid", ":", "raise", "exceptions", ".", "ArianeCallParametersError", "(", "'id...
43.942857
22.8
def json_engine(self, req): # pylint: disable=R0201,W0613 """ Return torrent engine data. """ try: return stats.engine_data(config.engine) except (error.LoggableError, xmlrpc.ERRORS) as torrent_exc: raise exc.HTTPInternalServerError(str(torrent_exc))
[ "def", "json_engine", "(", "self", ",", "req", ")", ":", "# pylint: disable=R0201,W0613", "try", ":", "return", "stats", ".", "engine_data", "(", "config", ".", "engine", ")", "except", "(", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", ...
42.857143
15.142857
def create_hosting_device_resources(self, context, complementary_id, tenant_id, mgmt_context, max_hosted): """Create resources for a hosting device in a plugin specific way.""" mgmt_port = None if mgmt_context and mgmt_context.get('mgmt_nw_id') and tenant_...
[ "def", "create_hosting_device_resources", "(", "self", ",", "context", ",", "complementary_id", ",", "tenant_id", ",", "mgmt_context", ",", "max_hosted", ")", ":", "mgmt_port", "=", "None", "if", "mgmt_context", "and", "mgmt_context", ".", "get", "(", "'mgmt_nw_id...
53.892857
18
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
[ "def", "to_dict", "(", "self", ")", ":", "input_dict", "=", "super", "(", "Prod", ",", "self", ")", ".", "_save_to_input_dict", "(", ")", "input_dict", "[", "\"class\"", "]", "=", "str", "(", "\"GPy.kern.Prod\"", ")", "return", "input_dict" ]
35.25
26.25
def reload_handler(self, c, e): """This handles reloads.""" cmd = self.is_reload(e) cmdchar = self.config['core']['cmdchar'] if cmd is not None: # If we're in a minimal reload state, only the owner can do stuff, as we can't rely on the db working. if self.reload_e...
[ "def", "reload_handler", "(", "self", ",", "c", ",", "e", ")", ":", "cmd", "=", "self", ".", "is_reload", "(", "e", ")", "cmdchar", "=", "self", ".", "config", "[", "'core'", "]", "[", "'cmdchar'", "]", "if", "cmd", "is", "not", "None", ":", "# I...
49.04
17.96
def get_all_positions(dataset, num_workers=1): """ Extracts paragraph identifiers, and positions from a dataset in the NTCIR-11 Math-2, and NTCIR-12 MathIR XHTML5 format. Parameters ---------- dataset : Path A path to a dataset. num_workers : int, optional The number of proc...
[ "def", "get_all_positions", "(", "dataset", ",", "num_workers", "=", "1", ")", ":", "positions", "=", "[", "]", "identifiers", "=", "tqdm", "(", "list", "(", "get_all_identifiers", "(", "dataset", ")", ")", ",", "desc", "=", "\"get_all_positions(%s)\"", "%",...
39.653846
25.423077
def compile_graphql_to_sql(schema, graphql_string, compiler_metadata, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a SQL query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the Gr...
[ "def", "compile_graphql_to_sql", "(", "schema", ",", "graphql_string", ",", "compiler_metadata", ",", "type_equivalence_hints", "=", "None", ")", ":", "lowering_func", "=", "ir_lowering_sql", ".", "lower_ir", "query_emitter_func", "=", "emit_sql", ".", "emit_code_from_i...
65
34.419355
def check(self, regex): """ See what :meth:`scan` would return without advancing the pointer. >>> s = Scanner("test string") >>> s.check('test ') 'test ' >>> s.pos 0 """ return self.scan_full(regex, return_string=True, advance_...
[ "def", "check", "(", "self", ",", "regex", ")", ":", "return", "self", ".", "scan_full", "(", "regex", ",", "return_string", "=", "True", ",", "advance_pointer", "=", "False", ")" ]
29.454545
18.727273
def get(self, key): """ Get a key and its CAS value from server. If the value isn't cached, return (None, None). :param key: Key's name :type key: six.string_types :return: Returns (value, cas). :rtype: object """ logger.debug('Getting key %s', k...
[ "def", "get", "(", "self", ",", "key", ")", ":", "logger", ".", "debug", "(", "'Getting key %s'", ",", "key", ")", "data", "=", "struct", ".", "pack", "(", "self", ".", "HEADER_STRUCT", "+", "self", ".", "COMMANDS", "[", "'get'", "]", "[", "'struct'"...
38
22.540541
def is_child_of_objective_bank(self, id_, objective_bank_id): """Tests if an objective bank is a direct child of another. arg: id (osid.id.Id): an ``Id`` arg: objective_bank_id (osid.id.Id): the ``Id`` of an objective bank return: (boolean) - ``true`` if the ``id``...
[ "def", "is_child_of_objective_bank", "(", "self", ",", "id_", ",", "objective_bank_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.is_child_of_bin", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", "...
51.181818
21
def get_supported_unary_ops(): ''' Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol. ''' unary_ops = {} unary_ops[np.exp.__name__] = 'exp' unary_ops[np.log.__name__] = 'log' unary_ops[np.sqrt.__name__] = 'sqrt' return unary_ops
[ "def", "get_supported_unary_ops", "(", ")", ":", "unary_ops", "=", "{", "}", "unary_ops", "[", "np", ".", "exp", ".", "__name__", "]", "=", "'exp'", "unary_ops", "[", "np", ".", "log", ".", "__name__", "]", "=", "'log'", "unary_ops", "[", "np", ".", ...
32.444444
19.555556
def plot_eq_sym(fignum, DIblock, s, sym): """ plots directions with specified symbol Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name sym : matplotlib symbol (e.g., 'bo' for blue circle) """ # make the stereonet plt....
[ "def", "plot_eq_sym", "(", "fignum", ",", "DIblock", ",", "s", ",", "sym", ")", ":", "# make the stereonet", "plt", ".", "figure", "(", "num", "=", "fignum", ")", "if", "len", "(", "DIblock", ")", "<", "1", ":", "return", "# plt.clf()", "if", "not", ...
25.541667
16.625
def start(self): """Start server if not previously started.""" msg = '' if not self.running(): if self._port == 0: self._port = _port_not_in_use() self._process = start_server_background(self._port) else: msg = 'Server already started\n...
[ "def", "start", "(", "self", ")", ":", "msg", "=", "''", "if", "not", "self", ".", "running", "(", ")", ":", "if", "self", ".", "_port", "==", "0", ":", "self", ".", "_port", "=", "_port_not_in_use", "(", ")", "self", ".", "_process", "=", "start...
35.181818
15.090909
def read_numbers(numbers): """ Read the input data in the most optimal way """ if isiterable(numbers): for number in numbers: yield float(str(number).strip()) else: with open(numbers) as fh: for number in fh: yield float(number.strip())
[ "def", "read_numbers", "(", "numbers", ")", ":", "if", "isiterable", "(", "numbers", ")", ":", "for", "number", "in", "numbers", ":", "yield", "float", "(", "str", "(", "number", ")", ".", "strip", "(", ")", ")", "else", ":", "with", "open", "(", "...
27.454545
9.090909
def configure(self, config): """ Configures component by passing configuration parameters. :param config: configuration parameters to be set. """ self._level = LogLevelConverter.to_log_level(config.get_as_object("level")) self._source = config.get_as_string_with_default(...
[ "def", "configure", "(", "self", ",", "config", ")", ":", "self", ".", "_level", "=", "LogLevelConverter", ".", "to_log_level", "(", "config", ".", "get_as_object", "(", "\"level\"", ")", ")", "self", ".", "_source", "=", "config", ".", "get_as_string_with_d...
42
22.25
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should ...
[ "def", "make_map", "(", "config", ")", ":", "map", "=", "Mapper", "(", "directory", "=", "config", "[", "'pylons.paths'", "]", "[", "'controllers'", "]", ",", "always_scan", "=", "config", "[", "'debug'", "]", ")", "map", ".", "minimization", "=", "False...
35.1
20
def validate(datum, schema, field=None, raise_errors=True): """ Determine if a python datum is an instance of a schema. Parameters ---------- datum: Any Data being validated schema: dict Schema field: str, optional Record field being validated raise_errors: bool,...
[ "def", "validate", "(", "datum", ",", "schema", ",", "field", "=", "None", ",", "raise_errors", "=", "True", ")", ":", "record_type", "=", "extract_record_type", "(", "schema", ")", "result", "=", "None", "validator", "=", "VALIDATORS", ".", "get", "(", ...
28.363636
18.727273
def get_external_references(self): """ Iterator that returns all the external reference objects of the external references object @rtype: L{CexternalReference} @return: the external reference objects """ for ext_ref_node in self.node.findall('externalRef'): ex...
[ "def", "get_external_references", "(", "self", ")", ":", "for", "ext_ref_node", "in", "self", ".", "node", ".", "findall", "(", "'externalRef'", ")", ":", "ext_refs_obj", "=", "CexternalReference", "(", "ext_ref_node", ")", "for", "ref", "in", "ext_refs_obj", ...
41.9
13.3
def select(query, ts, mode='list', cast=True): """ Perform the TSQL selection query *query* on testsuite *ts*. Note: The `select`/`retrieve` part of the query is not included. Args: query (str): TSQL select query ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over mo...
[ "def", "select", "(", "query", ",", "ts", ",", "mode", "=", "'list'", ",", "cast", "=", "True", ")", ":", "queryobj", "=", "_parse_select", "(", "query", ")", "return", "_select", "(", "queryobj", "[", "'projection'", "]", ",", "queryobj", "[", "'table...
34.115385
19.961538
def option(func, *args, **attrs): """ Args: func (function): Function defining this option *args: Optional extra short flag name **attrs: Optional attr overrides provided by caller Returns: function: Click decorator """ if click is None: return func def ...
[ "def", "option", "(", "func", ",", "*", "args", ",", "*", "*", "attrs", ")", ":", "if", "click", "is", "None", ":", "return", "func", "def", "decorator", "(", "f", ")", ":", "name", "=", "attrs", ".", "pop", "(", "\"name\"", ",", "func", ".", "...
31.230769
15.923077
def transfer_file(cls, src_ep, dst_ep, src_path, dst_path): tc = globus_sdk.TransferClient(authorizer=cls.authorizer) td = globus_sdk.TransferData(tc, src_ep, dst_ep) td.add_item(src_path, dst_path) try: task = tc.submit_transfer(td) except Exception as e: ...
[ "def", "transfer_file", "(", "cls", ",", "src_ep", ",", "dst_ep", ",", "src_path", ",", "dst_path", ")", ":", "tc", "=", "globus_sdk", ".", "TransferClient", "(", "authorizer", "=", "cls", ".", "authorizer", ")", "td", "=", "globus_sdk", ".", "TransferData...
54.883721
26.55814
def _build_gui(self): """ Removes all existing sliders and rebuilds them based on the colormap. """ # remove all widgets (should destroy all children too) self._central_widget.deleteLater() # remove all references to other controls self._sliders = [...
[ "def", "_build_gui", "(", "self", ")", ":", "# remove all widgets (should destroy all children too)", "self", ".", "_central_widget", ".", "deleteLater", "(", ")", "# remove all references to other controls", "self", ".", "_sliders", "=", "[", "]", "self", ".", "_button...
49.333333
29.403509
def cached_property(getter): """ Decorator that converts a method into memoized property. The decorator works as expected only for classes with attribute '__dict__' and immutable properties. """ def decorator(self): key = "_cached_property_" + getter.__name__ if not hasattr(self...
[ "def", "cached_property", "(", "getter", ")", ":", "def", "decorator", "(", "self", ")", ":", "key", "=", "\"_cached_property_\"", "+", "getter", ".", "__name__", "if", "not", "hasattr", "(", "self", ",", "key", ")", ":", "setattr", "(", "self", ",", "...
28.789474
14.684211
def dispatch_non_api_requests(self, request, start_response): """Dispatch this request if this is a request to a reserved URL. If the request matches one of our reserved URLs, this calls start_response and returns the response body. This also handles OPTIONS CORS requests. Args: request: An...
[ "def", "dispatch_non_api_requests", "(", "self", ",", "request", ",", "start_response", ")", ":", "for", "path_regex", ",", "dispatch_function", "in", "self", ".", "_dispatchers", ":", "if", "path_regex", ".", "match", "(", "request", ".", "relative_url", ")", ...
39.296296
22.148148
def start_container(self, image, container_name: str, repo_path: Path): """ Starts a container with the image and name ``container_name`` and copies the repository into the container. :type image: docker.models.images.Image :rtype: docker.models.container.Container """ command =...
[ "def", "start_container", "(", "self", ",", "image", ",", "container_name", ":", "str", ",", "repo_path", ":", "Path", ")", ":", "command", "=", "\"bash -i\"", "if", "self", ".", "inherit_image", ":", "command", "=", "\"sh -i\"", "container", "=", "self", ...
43.85
26.35
def obo(self): """str: the `Relationship` serialized in an ``[Typedef]`` stanza. Note: The following guide was used: ftp://ftp.geneontology.org/pub/go/www/GO.format.obo-1_4.shtml """ lines = [ "[Typedef]", "id: {}".format(self.obo_name), ...
[ "def", "obo", "(", "self", ")", ":", "lines", "=", "[", "\"[Typedef]\"", ",", "\"id: {}\"", ".", "format", "(", "self", ".", "obo_name", ")", ",", "\"name: {}\"", ".", "format", "(", "self", ".", "obo_name", ")", "]", "if", "self", ".", "complementary"...
39
18.083333
def AutorizarAnticipo(self): "Autorizar Anticipo de una Liquidación Primaria Electrónica de Granos" # extraer y adaptar los campos para el anticipo anticipo = {"liquidacion": self.liquidacion} liq = anticipo["liquidacion"] liq["campaniaPpal"] = self.liquidacion["campaniaPPal"] ...
[ "def", "AutorizarAnticipo", "(", "self", ")", ":", "# extraer y adaptar los campos para el anticipo", "anticipo", "=", "{", "\"liquidacion\"", ":", "self", ".", "liquidacion", "}", "liq", "=", "anticipo", "[", "\"liquidacion\"", "]", "liq", "[", "\"campaniaPpal\"", ...
37.46875
19.71875
def user(self, username=None): """gets the user's content. If None is passed, the current user is used. Input: username - name of the login for a given user on a site. """ if username is None: username = self.__getUsername() url = "%s/%s" % (self.r...
[ "def", "user", "(", "self", ",", "username", "=", "None", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "__getUsername", "(", ")", "url", "=", "\"%s/%s\"", "%", "(", "self", ".", "root", ",", "username", ")", "return", ...
33.6875
14.8125
def t_STRING(self, t): r'"[^"\n]*"' t.endlexpos = t.lexpos + len(t.value) return t
[ "def", "t_STRING", "(", "self", ",", "t", ")", ":", "t", ".", "endlexpos", "=", "t", ".", "lexpos", "+", "len", "(", "t", ".", "value", ")", "return", "t" ]
25.75
16.75
def _get_column_by_db_name(cls, name): """ Returns the column, mapped by db_field name """ return cls._columns.get(cls._db_map.get(name, name))
[ "def", "_get_column_by_db_name", "(", "cls", ",", "name", ")", ":", "return", "cls", ".", "_columns", ".", "get", "(", "cls", ".", "_db_map", ".", "get", "(", "name", ",", "name", ")", ")" ]
34.2
6.6
def _upload_dists(self, repo, dists): """Upload a given component to pypi The pypi username and password must either be specified in a ~/.pypirc file or in environment variables PYPI_USER and PYPI_PASS """ from twine.commands.upload import upload if 'PYPI_USER' in os.e...
[ "def", "_upload_dists", "(", "self", ",", "repo", ",", "dists", ")", ":", "from", "twine", ".", "commands", ".", "upload", "import", "upload", "if", "'PYPI_USER'", "in", "os", ".", "environ", "and", "'PYPI_PASS'", "in", "os", ".", "environ", ":", "pypi_u...
39.777778
25
def clear(self): """ 直接把现在的清空 """ if not self.timer: return # 不阻塞 try: self.timer.kill(block=False) except: pass self.timer = None
[ "def", "clear", "(", "self", ")", ":", "if", "not", "self", ".", "timer", ":", "return", "# 不阻塞", "try", ":", "self", ".", "timer", ".", "kill", "(", "block", "=", "False", ")", "except", ":", "pass", "self", ".", "timer", "=", "None" ]
16.846154
18.692308
def cloudtrail_policy(original, bucket_name, account_id, bucket_region): '''add CloudTrail permissions to an S3 policy, preserving existing''' ct_actions = [ { 'Action': 's3:GetBucketAcl', 'Effect': 'Allow', 'Principal': {'Service': 'cloudtrail.amazonaws.com'}, ...
[ "def", "cloudtrail_policy", "(", "original", ",", "bucket_name", ",", "account_id", ",", "bucket_region", ")", ":", "ct_actions", "=", "[", "{", "'Action'", ":", "'s3:GetBucketAcl'", ",", "'Effect'", ":", "'Allow'", ",", "'Principal'", ":", "{", "'Service'", "...
36.243243
18.459459
def list_pkgs(installed=True, attributes=True): ''' Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``. :param bool installed: list only installed packages. This can be a very long list (12,000+ elements), so caution is advised. Default:...
[ "def", "list_pkgs", "(", "installed", "=", "True", ",", "attributes", "=", "True", ")", ":", "# We don't use -Q here, as it obfuscates the attribute names on full package listings.", "cmd", "=", "_nix_env", "(", ")", "cmd", ".", "append", "(", "'--query'", ")", "if", ...
36.488372
28.255814
def get_arp_output_arp_entry_age(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_arp = ET.Element("get_arp") config = get_arp output = ET.SubElement(get_arp, "output") arp_entry = ET.SubElement(output, "arp-entry") ip_address_...
[ "def", "get_arp_output_arp_entry_age", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_arp", "=", "ET", ".", "Element", "(", "\"get_arp\"", ")", "config", "=", "get_arp", "output", "=", "E...
38.6
10.933333
def modify_ip(self, ip_addr, ptr_record): """ Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string). """ body = { 'ip_address': { 'ptr_record': ptr_record } } res = ...
[ "def", "modify_ip", "(", "self", ",", "ip_addr", ",", "ptr_record", ")", ":", "body", "=", "{", "'ip_address'", ":", "{", "'ptr_record'", ":", "ptr_record", "}", "}", "res", "=", "self", ".", "request", "(", "'PUT'", ",", "'/ip_address/'", "+", "str", ...
30.642857
19.785714
def marshall(self, registry): """Marshalls a full registry (various collectors)""" blocks = [] for i in registry.get_all(): blocks.append(self.marshall_collector(i)) # Sort? used in tests blocks = sorted(blocks) # Needs EOF blocks.append("") ...
[ "def", "marshall", "(", "self", ",", "registry", ")", ":", "blocks", "=", "[", "]", "for", "i", "in", "registry", ".", "get_all", "(", ")", ":", "blocks", ".", "append", "(", "self", ".", "marshall_collector", "(", "i", ")", ")", "# Sort? used in tests...
25.857143
20.428571
def export_metrics(self, metrics): """ Exports given metrics to target metric service. """ metric_protos = [] for metric in metrics: metric_protos.append(_get_metric_proto(metric)) self._rpc_handler.send( metrics_service_pb2.ExportMetricsServiceRequest( ...
[ "def", "export_metrics", "(", "self", ",", "metrics", ")", ":", "metric_protos", "=", "[", "]", "for", "metric", "in", "metrics", ":", "metric_protos", ".", "append", "(", "_get_metric_proto", "(", "metric", ")", ")", "self", ".", "_rpc_handler", ".", "sen...
34.9
11.9
def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unp...
[ "def", "register_unpack_format", "(", "name", ",", "extensions", ",", "function", ",", "extra_args", "=", "None", ",", "description", "=", "''", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "[", "]", "_check_unpack_options", "(", "exte...
41.904762
21.380952
def _set_switch_attributes(self, v, load=False): """ Setter method for switch_attributes, mapped from YANG variable /rbridge_id/switch_attributes (container) If this variable is read-only (config: false) in the source YANG file, then _set_switch_attributes is considered as a private method. Backends...
[ "def", "_set_switch_attributes", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",",...
84.545455
39.454545
def statics(self) -> typing.Iterator['Static']: """ Returns: generator over all statics in this coalition """ for country in self.countries: for static in country.statics: yield static
[ "def", "statics", "(", "self", ")", "->", "typing", ".", "Iterator", "[", "'Static'", "]", ":", "for", "country", "in", "self", ".", "countries", ":", "for", "static", "in", "country", ".", "statics", ":", "yield", "static" ]
26.444444
13.777778
def camelcase_to_underscores(word): """Converts a CamelCase word into an under_score word. >>> camelcase_to_underscores("CamelCaseCase") 'camel_case_case' >>> camelcase_to_underscores("getHTTPResponseCode") 'get_http_response_code' """ s1 = _FIRST_CAP_RE.sub(r'\1_\2', word) ...
[ "def", "camelcase_to_underscores", "(", "word", ")", ":", "s1", "=", "_FIRST_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "word", ")", "return", "_ALL_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
35.9
11
def load(self, data_file = None): """ Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load. """ if not data_file: data_file = '' elif data_file[-1] != '/': data_file += '/' if data_file[-6:] !=...
[ "def", "load", "(", "self", ",", "data_file", "=", "None", ")", ":", "if", "not", "data_file", ":", "data_file", "=", "''", "elif", "data_file", "[", "-", "1", "]", "!=", "'/'", ":", "data_file", "+=", "'/'", "if", "data_file", "[", "-", "6", ":", ...
24.947368
15.789474
async def register_callback(self, cb): """ Allows the caller to register a callback, and returns a closure that can be used to unregister the provided callback """ self._callbacks.add(cb) def unregister(): self._callbacks.remove(cb) return unregister
[ "async", "def", "register_callback", "(", "self", ",", "cb", ")", ":", "self", ".", "_callbacks", ".", "add", "(", "cb", ")", "def", "unregister", "(", ")", ":", "self", ".", "_callbacks", ".", "remove", "(", "cb", ")", "return", "unregister" ]
30.3
14.3
def batch_market_order(self, share_counts): """Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from asset to number of shares to order for that asset. Returns ------- order_ids : pd.Ind...
[ "def", "batch_market_order", "(", "self", ",", "share_counts", ")", ":", "style", "=", "MarketOrder", "(", ")", "order_args", "=", "[", "(", "asset", ",", "amount", ",", "style", ")", "for", "(", "asset", ",", "amount", ")", "in", "iteritems", "(", "sh...
30.1
17.25
def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. Copyright: https://docs.djangoproject.com/en/1...
[ "def", "slugify", "(", "value", ",", "allow_unicode", "=", "False", ")", ":", "value", "=", "force_text", "(", "value", ")", "if", "allow_unicode", ":", "value", "=", "unicodedata", ".", "normalize", "(", "'NFKC'", ",", "value", ")", "value", "=", "re", ...
53.3125
21.1875
def add_text(self, text): """Add text to combo box: add a new item if text is not found in combo box items.""" index = self.findText(text) while index != -1: self.removeItem(index) index = self.findText(text) self.insertItem(0, text) index ...
[ "def", "add_text", "(", "self", ",", "text", ")", ":", "index", "=", "self", ".", "findText", "(", "text", ")", "while", "index", "!=", "-", "1", ":", "self", ".", "removeItem", "(", "index", ")", "index", "=", "self", ".", "findText", "(", "text",...
33.333333
7.833333
def mkstemp(*args, **kwargs): """ Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath is returned .. warnings:: Unlike tempfile.mkstemp, this is not secure """ fd, filename = tempfile.mkstemp(*args, **kwargs) os.close(fd) try: yield f...
[ "def", "mkstemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", "os", ".", "close", "(", "fd", ")", "try", ":", "yield", "filename", ...
29.25
22.916667
def parse_sync_points(names, tests): """ Slice list of test names on sync points. If test is test file find full path to file. Returns: A list of test file sets and sync point strings. Examples: ['test_hard_reboot'] [set('test1', 'test2')] [set('test1', 'test2'), 't...
[ "def", "parse_sync_points", "(", "names", ",", "tests", ")", ":", "test_files", "=", "[", "]", "section", "=", "set", "(", ")", "for", "name", "in", "names", ":", "if", "name", "in", "SYNC_POINTS", ":", "if", "section", ":", "test_files", ".", "append"...
25.033333
17.966667
def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
[ "def", "text_to_url", "(", "self", ",", "text", ")", ":", "if", "text", ".", "startswith", "(", "'/'", ")", ":", "text", "=", "text", "[", "1", ":", "]", "return", "QUrl", "(", "self", ".", "home_url", ".", "toString", "(", ")", "+", "text", "+",...
40
9.6
def version(self): """Return version from installed packages """ if self.find: return self.meta.sp + split_package(self.find)[1] return ""
[ "def", "version", "(", "self", ")", ":", "if", "self", ".", "find", ":", "return", "self", ".", "meta", ".", "sp", "+", "split_package", "(", "self", ".", "find", ")", "[", "1", "]", "return", "\"\"" ]
29.5
14.166667
def name_build(self, name, is_policy=False, prefix=True): """ Build name from prefix and name + type :param name: Name of the role/policy :param is_policy: True if policy should be added as suffix :param prefix: True if prefix should be added :return: Joined name ...
[ "def", "name_build", "(", "self", ",", "name", ",", "is_policy", "=", "False", ",", "prefix", "=", "True", ")", ":", "str", "=", "name", "# Add prefix", "if", "prefix", ":", "str", "=", "self", ".", "__role_name_prefix", "+", "str", "# Add policy suffix", ...
27.263158
17.368421
def list_keys(self, pattern='*', db=0): """ Run the ``KEYS`` command and return the list of matching keys. :param pattern: the pattern to filter keys by (default ``*``) :param db: the db number to query (default ``0``) """ lines = output_lines(self.exec_redis_cli('KEYS',...
[ "def", "list_keys", "(", "self", ",", "pattern", "=", "'*'", ",", "db", "=", "0", ")", ":", "lines", "=", "output_lines", "(", "self", ".", "exec_redis_cli", "(", "'KEYS'", ",", "[", "pattern", "]", ",", "db", "=", "db", ")", ")", "return", "[", ...
41.888889
17.444444
def _one_cycle_mult(areg, breg, rem_bits, sum_sf=0, curr_bit=0): """ returns a WireVector sum of rem_bits multiplies (in one clock cycle) note: this method requires a lot of area because of the indexing in the else statement """ if rem_bits == 0: return sum_sf else: a_curr_val = areg[cur...
[ "def", "_one_cycle_mult", "(", "areg", ",", "breg", ",", "rem_bits", ",", "sum_sf", "=", "0", ",", "curr_bit", "=", "0", ")", ":", "if", "rem_bits", "==", "0", ":", "return", "sum_sf", "else", ":", "a_curr_val", "=", "areg", "[", "curr_bit", "]", "."...
49
18.666667
def set_filters(self, filters): """ set and validate filters dict """ if not isinstance(filters, dict): raise Exception("filters must be a dict") self.filters = {} for key in filters.keys(): value = filters[key] self.add_filter(key,valu...
[ "def", "set_filters", "(", "self", ",", "filters", ")", ":", "if", "not", "isinstance", "(", "filters", ",", "dict", ")", ":", "raise", "Exception", "(", "\"filters must be a dict\"", ")", "self", ".", "filters", "=", "{", "}", "for", "key", "in", "filte...
31.3
5.7
def move_column(column=1, file=sys.stdout): """ Move the cursor to the specified column, default 1. Esc[<column>G """ move.column(column).write(file=file)
[ "def", "move_column", "(", "column", "=", "1", ",", "file", "=", "sys", ".", "stdout", ")", ":", "move", ".", "column", "(", "column", ")", ".", "write", "(", "file", "=", "file", ")" ]
28.333333
10.333333
def set_rule_name(self, rule_name): """ Add the matched centralized sampling rule name if a segment is sampled because of that rule. This method should be only used by the recorder. """ if not self.aws.get('xray', None): self.aws['xray'] = {} self.aws[...
[ "def", "set_rule_name", "(", "self", ",", "rule_name", ")", ":", "if", "not", "self", ".", "aws", ".", "get", "(", "'xray'", ",", "None", ")", ":", "self", ".", "aws", "[", "'xray'", "]", "=", "{", "}", "self", ".", "aws", "[", "'xray'", "]", "...
39.222222
8.333333
def getTypedValueOrException(self, row): 'Returns the properly-typed value for the given row at this column, or an Exception object.' return wrapply(self.type, wrapply(self.getValue, row))
[ "def", "getTypedValueOrException", "(", "self", ",", "row", ")", ":", "return", "wrapply", "(", "self", ".", "type", ",", "wrapply", "(", "self", ".", "getValue", ",", "row", ")", ")" ]
67.333333
27.333333
def clear_db(self): """ Clear the Main Database of all samples and worker output. Args: None Returns: Nothing """ self.data_store.clear_db() # Have the plugin manager reload all the plugins self.plugin_manager.load_all_plug...
[ "def", "clear_db", "(", "self", ")", ":", "self", ".", "data_store", ".", "clear_db", "(", ")", "# Have the plugin manager reload all the plugins", "self", ".", "plugin_manager", ".", "load_all_plugins", "(", ")", "# Store information about commands and workbench", "self"...
28.857143
16.571429
def write_transparency(selection): """writes transparency as rgba to ~/.Xresources""" global themefile, transparency, prefix if themefile == "": return lines = themefile.split('\n') for line in lines: if 'background' in line.lower(): try: background = l...
[ "def", "write_transparency", "(", "selection", ")", ":", "global", "themefile", ",", "transparency", ",", "prefix", "if", "themefile", "==", "\"\"", ":", "return", "lines", "=", "themefile", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":...
27.058824
18.666667
def load_matrix_sparse(filename): coo = np.load(filename) """Check if coo is (M, 3) ndarray""" if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] values = coo[:, 2] """Check if imaginary part of row and col is zero""" if np.all(np.isreal(r...
[ "def", "load_matrix_sparse", "(", "filename", ")", ":", "coo", "=", "np", ".", "load", "(", "filename", ")", "if", "len", "(", "coo", ".", "shape", ")", "==", "2", "and", "coo", ".", "shape", "[", "1", "]", "==", "3", ":", "row", "=", "coo", "[...
35.633333
20.033333
def _print(pass_through_tensor, values): """Wrapper for tf.Print which supports lists and namedtuples for printing.""" flat_values = [] for value in values: # Checks if it is a namedtuple. if hasattr(value, '_fields'): for field in value._fields: flat_values.extend([field, _to_str(getattr(va...
[ "def", "_print", "(", "pass_through_tensor", ",", "values", ")", ":", "flat_values", "=", "[", "]", "for", "value", "in", "values", ":", "# Checks if it is a namedtuple.", "if", "hasattr", "(", "value", ",", "'_fields'", ")", ":", "for", "field", "in", "valu...
36.866667
12.133333
def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False...
[ "def", "replace", "(", "path", ",", "pattern", ",", "repl", ",", "count", "=", "0", ",", "flags", "=", "8", ",", "bufsize", "=", "1", ",", "append_if_not_found", "=", "False", ",", "prepend_if_not_found", "=", "False", ",", "not_found_content", "=", "Non...
40.868421
23.136842
def calc_glmelt_in_v1(self): """Calculate melting from glaciers which are actually not covered by a snow layer and add it to the water release of the snow module. Required control parameters: |NmbZones| |ZoneType| |GMelt| Required state sequence: |SP| Required flux sequenc...
[ "def", "calc_glmelt_in_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", "....
29.040541
20.810811
def show(key=None, display_toolbar=True): """Shows the current context figure in the output area. Parameters ---------- key : hashable, optional Any variable that can be used as a key for a dictionary. display_toolbar: bool (default: True) If True, a toolbar for different mouse int...
[ "def", "show", "(", "key", "=", "None", ",", "display_toolbar", "=", "True", ")", ":", "if", "key", "is", "None", ":", "figure", "=", "current_figure", "(", ")", "else", ":", "figure", "=", "_context", "[", "'figure_registry'", "]", "[", "key", "]", ...
24.725
20.925
def get_styles(self, names=None, workspaces=None): ''' names and workspaces can be provided as a comma delimited strings or as arrays, and are used for filtering. If no workspaces are provided, will return all styles in the catalog (global and workspace specific). Will always return an a...
[ "def", "get_styles", "(", "self", ",", "names", "=", "None", ",", "workspaces", "=", "None", ")", ":", "all_styles", "=", "[", "]", "if", "workspaces", "is", "None", ":", "# Add global styles", "url", "=", "\"{}/styles.xml\"", ".", "format", "(", "self", ...
39.847826
25.23913
def find_pingback_urls(self, urls): """ Find the pingback URL for each URLs. """ pingback_urls = {} for url in urls: try: page = urlopen(url) headers = page.info() server_url = headers.get('X-Pingback') ...
[ "def", "find_pingback_urls", "(", "self", ",", "urls", ")", ":", "pingback_urls", "=", "{", "}", "for", "url", "in", "urls", ":", "try", ":", "page", "=", "urlopen", "(", "url", ")", "headers", "=", "page", ".", "info", "(", ")", "server_url", "=", ...
37.580645
18.032258
def _get_cloud_foundry_config(self): """ Reads the local cf CLI cache stored in the users home directory. """ config = os.path.expanduser(self.config_file) if not os.path.exists(config): raise CloudFoundryLoginError('You must run `cf login` to authenticate') ...
[ "def", "_get_cloud_foundry_config", "(", "self", ")", ":", "config", "=", "os", ".", "path", ".", "expanduser", "(", "self", ".", "config_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "raise", "CloudFoundryLoginError",...
34.909091
12.909091
def instance_get(plugin, opts, url_file_input, out): """ Return an instance dictionary for an individual plugin. @see Scan._instances_get. """ inst = plugin() hp, func, enabled_func = inst._general_init(opts, out) name = inst._meta.label kwargs = { 'hide_progressbar': hp, ...
[ "def", "instance_get", "(", "plugin", ",", "opts", ",", "url_file_input", ",", "out", ")", ":", "inst", "=", "plugin", "(", ")", "hp", ",", "func", ",", "enabled_func", "=", "inst", ".", "_general_init", "(", "opts", ",", "out", ")", "name", "=", "in...
22.954545
18.954545
def escape_shell_arg(shell_arg): """Escape shell argument shell_arg by placing it within single-quotes. Any single quotes found within the shell argument string will be escaped. @param shell_arg: The shell argument to be escaped. @type shell_arg: string @return: The single-quote-escaped value ...
[ "def", "escape_shell_arg", "(", "shell_arg", ")", ":", "if", "isinstance", "(", "shell_arg", ",", "six", ".", "text_type", ")", ":", "msg", "=", "\"ERROR: escape_shell_arg() expected string argument but \"", "\"got '%s' of type '%s'.\"", "%", "(", "repr", "(", "shell_...
40.210526
20.736842
def new_log_file(logger, suffix, file_type='tcl'): """ Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param su...
[ "def", "new_log_file", "(", "logger", ",", "suffix", ",", "file_type", "=", "'tcl'", ")", ":", "file_handler", "=", "None", "for", "handler", "in", "logger", ".", "handlers", ":", "if", "isinstance", "(", "handler", ",", "logging", ".", "FileHandler", ")",...
42.291667
22.5
def first(self): """ Return the first element of an array """ from bolt.local.array import BoltArrayLocal rdd = self._rdd if self._ordered else self._rdd.sortByKey() return BoltArrayLocal(rdd.values().first())
[ "def", "first", "(", "self", ")", ":", "from", "bolt", ".", "local", ".", "array", "import", "BoltArrayLocal", "rdd", "=", "self", ".", "_rdd", "if", "self", ".", "_ordered", "else", "self", ".", "_rdd", ".", "sortByKey", "(", ")", "return", "BoltArray...
35.857143
11
def get_closest_sibling_state(state_m, from_logical_port=None): """ Calculate the closest sibling also from optional logical port of handed state model :param StateModel state_m: Reference State model the closest sibling state should be find for :param str from_logical_port: The logical port of handed stat...
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", ...
46.767442
27.465116
def load_command_line_configuration(self, args=None): """Override configuration according to command line parameters return additional arguments """ with _patch_optparse(): if args is None: args = sys.argv[1:] else: args = list(arg...
[ "def", "load_command_line_configuration", "(", "self", ",", "args", "=", "None", ")", ":", "with", "_patch_optparse", "(", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "else", ":", "args", "=", "list...
38.105263
11.631579
def copy_group(from_file, to_file, key): """Recursively copy all groups/datasets/attributes from from_file[key] to to_file. Datasets are not overwritten, attributes are. """ if not key in to_file: from_file.copy(key, to_file, key) else: # also make sure any additional attributes are ...
[ "def", "copy_group", "(", "from_file", ",", "to_file", ",", "key", ")", ":", "if", "not", "key", "in", "to_file", ":", "from_file", ".", "copy", "(", "key", ",", "to_file", ",", "key", ")", "else", ":", "# also make sure any additional attributes are copied", ...
42.357143
12.5
def render(self, name, value, attrs=None, **kwargs): """Widget render method.""" min_score = zxcvbn_min_score() message_title = _('Warning') message_body = _( 'This password would take ' '<em class="password_strength_time"></em> to crack.') strength_marku...
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "min_score", "=", "zxcvbn_min_score", "(", ")", "message_title", "=", "_", "(", "'Warning'", ")", "message_body", "=", "_", "(", "'...
35.818182
15.386364
def from_frequency(cls, freq): """ Construct a :class:`Tone` from a frequency specified in `Hz`_ which must be a positive floating-point value in the range 0 < freq <= 20000. .. _Hz: https://en.wikipedia.org/wiki/Hertz """ if 0 < freq <= 20000: return super(T...
[ "def", "from_frequency", "(", "cls", ",", "freq", ")", ":", "if", "0", "<", "freq", "<=", "20000", ":", "return", "super", "(", "Tone", ",", "cls", ")", ".", "__new__", "(", "cls", ",", "freq", ")", "raise", "ValueError", "(", "'invalid frequency: %.2f...
39.8
17.8
def genes_by_alias(self, build='37', genes=None): """Return a dictionary with hgnc symbols as keys and a list of hgnc ids as value. If a gene symbol is listed as primary the list of ids will only consist of that entry if not the gene can not be determined so the result is a list ...
[ "def", "genes_by_alias", "(", "self", ",", "build", "=", "'37'", ",", "genes", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"Fetching all genes by alias\"", ")", "# Collect one entry for each alias symbol that exists", "alias_genes", "=", "{", "}", "# Loop over...
37.711111
17.8
def convert_meas(direction, Rec): """ converts measurments tables from magic 2 to 3 (direction=magic3) or from model 3 to 2.5 (direction=magic2) [not available] """ if direction == 'magic3': columns = meas_magic2_2_magic3_map MeasRec = {} for key in columns: if ke...
[ "def", "convert_meas", "(", "direction", ",", "Rec", ")", ":", "if", "direction", "==", "'magic3'", ":", "columns", "=", "meas_magic2_2_magic3_map", "MeasRec", "=", "{", "}", "for", "key", "in", "columns", ":", "if", "key", "in", "list", "(", "Rec", ".",...
35.066667
12.666667
def _BYTES_TO_BITS(): """Generate a table to convert a whole byte to binary. This code was taken from the Python Cookbook, 2nd edition - O'Reilly.""" the_table = 256*[None] bits_per_byte = list(range(7, -1, -1)) for n in range(256): l = n bits = 8*[None] for i in bits_per_byt...
[ "def", "_BYTES_TO_BITS", "(", ")", ":", "the_table", "=", "256", "*", "[", "None", "]", "bits_per_byte", "=", "list", "(", "range", "(", "7", ",", "-", "1", ",", "-", "1", ")", ")", "for", "n", "in", "range", "(", "256", ")", ":", "l", "=", "...
32.461538
12
def _update_offset_file(self): """ Update the offset file with the current inode and offset. """ if self.on_update: self.on_update() offset = self._filehandle().tell() inode = stat(self.filename).st_ino fh = open(self._offset_file, "w") fh.writ...
[ "def", "_update_offset_file", "(", "self", ")", ":", "if", "self", ".", "on_update", ":", "self", ".", "on_update", "(", ")", "offset", "=", "self", ".", "_filehandle", "(", ")", ".", "tell", "(", ")", "inode", "=", "stat", "(", "self", ".", "filenam...
32.5
8.666667