text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update(self, prefixes): """Add a value to the list. Arguments: prefixes(list): A list to add the value """ if self.ip_prefix not in prefixes: prefixes.append(self.ip_prefix) self.log.info("announcing %s for %s", self.ip_prefix, self.name) ...
[ "def", "update", "(", "self", ",", "prefixes", ")", ":", "if", "self", ".", "ip_prefix", "not", "in", "prefixes", ":", "prefixes", ".", "append", "(", "self", ".", "ip_prefix", ")", "self", ".", "log", ".", "info", "(", "\"announcing %s for %s\"", ",", ...
28.833333
17
def resize(self, dims): """Resize our drawing area to encompass a space defined by the given dimensions. """ width, height = dims[:2] self.gl_resize(width, height)
[ "def", "resize", "(", "self", ",", "dims", ")", ":", "width", ",", "height", "=", "dims", "[", ":", "2", "]", "self", ".", "gl_resize", "(", "width", ",", "height", ")" ]
33
7.166667
def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile ...
[ "def", "stop", "(", "self", ")", ":", "# Get the pid from the pidfile", "try", ":", "pf", "=", "file", "(", "self", ".", "pidfile", ",", "'r'", ")", "pid", "=", "int", "(", "pf", ".", "read", "(", ")", ".", "strip", "(", ")", ")", "pf", ".", "clo...
31.102564
13.923077
def get_cursor(self, project_name, logstore_name, shard_id, start_time): """ Get cursor from log service for batch pull logs Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string ...
[ "def", "get_cursor", "(", "self", ",", "project_name", ",", "logstore_name", ",", "shard_id", ",", "start_time", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "params", "=", "{", "'type'", ":", "'cursor'", ",", "'from'", ":...
47.357143
32.642857
def init_desc_matrix(l): ''' from elist.elist import * from elist.jprint import pobj l = [1,[4],2,[3,[5,6]]] desc_matrix = init_desc_matrix(l) pobj(desc_matrix) ''' leaf = is_leaf(l) root_desc = new_ele_description(leaf=leaf,depth=0,breadth_path=[],path=[],parent_...
[ "def", "init_desc_matrix", "(", "l", ")", ":", "leaf", "=", "is_leaf", "(", "l", ")", "root_desc", "=", "new_ele_description", "(", "leaf", "=", "leaf", ",", "depth", "=", "0", ",", "breadth_path", "=", "[", "]", ",", "path", "=", "[", "]", ",", "p...
26.5
22.055556
def set_hint_style(self, hint_style): """Changes the :ref:`HINT_STYLE` for the font options object. This controls whether to fit font outlines to the pixel grid, and if so, whether to optimize for fidelity or contrast. """ cairo.cairo_font_options_set_hint_style(self._pointer, h...
[ "def", "set_hint_style", "(", "self", ",", "hint_style", ")", ":", "cairo", ".", "cairo_font_options_set_hint_style", "(", "self", ".", "_pointer", ",", "hint_style", ")", "self", ".", "_check_status", "(", ")" ]
44
17.75
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
[ "def", "convert", "(", "self", ",", "vroot", ",", "entry_variables", ")", ":", "self", ".", "graph_info", "=", "GraphInfo", "(", "vroot", ")", "self", ".", "entry_variables", "=", "entry_variables", "with", "nn", ".", "parameter_scope", "(", "self", ".", "...
37.68
14.96
def encode (self): """Encodes this SeqDelay to a binary bytearray.""" delay_s = int( math.floor(self.delay) ) delay_ms = int( (self.delay - delay_s) * 255.0 ) return struct.pack('>H', delay_s) + struct.pack('B', delay_ms)
[ "def", "encode", "(", "self", ")", ":", "delay_s", "=", "int", "(", "math", ".", "floor", "(", "self", ".", "delay", ")", ")", "delay_ms", "=", "int", "(", "(", "self", ".", "delay", "-", "delay_s", ")", "*", "255.0", ")", "return", "struct", "."...
46.8
12.8
def data(self, value): """ Saves a new image to disk """ self.loader.save_image(self.category, self.image, value)
[ "def", "data", "(", "self", ",", "value", ")", ":", "self", ".", "loader", ".", "save_image", "(", "self", ".", "category", ",", "self", ".", "image", ",", "value", ")" ]
28.2
9.8
def write_skycatalog(self,filename): """ Write out the all_radec catalog for this image to a file. """ if self.all_radec is None: return ralist = self.all_radec[0]#.tolist() declist = self.all_radec[1]#.tolist() f = open(filename,'w') f.write("#Sky pos...
[ "def", "write_skycatalog", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "all_radec", "is", "None", ":", "return", "ralist", "=", "self", ".", "all_radec", "[", "0", "]", "#.tolist()", "declist", "=", "self", ".", "all_radec", "[", "1", "]...
37.714286
8.714286
def encode_password(password): """Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password """ log = logging.getLogger(mod_logger + '.password_encoder') log.debug('Encoding password: {p}'.format(p=password)) encoded_password = '' for ...
[ "def", "encode_password", "(", "password", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.password_encoder'", ")", "log", ".", "debug", "(", "'Encoding password: {p}'", ".", "format", "(", "p", "=", "password", ")", ")", "encod...
36.076923
14
def _create_list(value, allow_filename=False): """Create a list from the input value. If the input is a list already, return it. If the input is a comma-separated string, split it. """ if isinstance(value, list): return value elif isinstance(value, string_type): if allow_filena...
[ "def", "_create_list", "(", "value", ",", "allow_filename", "=", "False", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "string_type", ")", ":", "if", "allow_filename", "and",...
35.5625
16.125
def AddVSSProcessingOptions(self, argument_group): """Adds the VSS processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. """ argument_group.add_argument( '--no_vss', '--no-vss', dest='no_vss', action='store_true', defaul...
[ "def", "AddVSSProcessingOptions", "(", "self", ",", "argument_group", ")", ":", "argument_group", ".", "add_argument", "(", "'--no_vss'", ",", "'--no-vss'", ",", "dest", "=", "'no_vss'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "h...
46.555556
23.074074
def _bin_op(instance, opnode, op, other, context, reverse=False): """Get an inference callable for a normal binary operation. If *reverse* is True, then the reflected method will be used instead. """ if reverse: method_name = protocols.REFLECTED_BIN_OP_METHOD[op] else: method_name =...
[ "def", "_bin_op", "(", "instance", ",", "opnode", ",", "op", ",", "other", ",", "context", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "method_name", "=", "protocols", ".", "REFLECTED_BIN_OP_METHOD", "[", "op", "]", "else", ":", "method...
30.222222
18.777778
def _generate(num_particles, D, box, rs): """Generate a list of `Particle` objects.""" X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1 Y0 = rs.rand(num_particles) * (box.y2 - box.y1) + box.y1 Z0 = rs.rand(num_particles) * (box.z2 - box.z1) + box.z1 return [Particle(D=D, ...
[ "def", "_generate", "(", "num_particles", ",", "D", ",", "box", ",", "rs", ")", ":", "X0", "=", "rs", ".", "rand", "(", "num_particles", ")", "*", "(", "box", ".", "x2", "-", "box", ".", "x1", ")", "+", "box", ".", "x1", "Y0", "=", "rs", ".",...
55
13.285714
def solve_T(self, P, V): r'''Method to calculate `T` from a specified `P` and `V` for the VDW EOS. Uses `a`, and `b`, obtained from the class's namespace. .. math:: T = \frac{1}{R V^{2}} \left(P V^{2} \left(V - b\right) + V a - a b\right) Parameters ---...
[ "def", "solve_T", "(", "self", ",", "P", ",", "V", ")", ":", "return", "(", "P", "*", "V", "**", "2", "*", "(", "V", "-", "self", ".", "b", ")", "+", "V", "*", "self", ".", "a", "-", "self", ".", "a", "*", "self", ".", "b", ")", "/", ...
27.190476
24.52381
def send_delivered_receipt(self, peer_jid: str, receipt_message_id: str): """ Sends a receipt indicating that a specific message was received, to another person. :param peer_jid: The other peer's JID to send to receipt to :param receipt_message_id: The message ID for which to generate t...
[ "def", "send_delivered_receipt", "(", "self", ",", "peer_jid", ":", "str", ",", "receipt_message_id", ":", "str", ")", ":", "log", ".", "info", "(", "\"[+] Sending delivered receipt to JID {} for message ID {}\"", ".", "format", "(", "peer_jid", ",", "receipt_message_...
61.444444
36.777778
def read_blocks(self, block_size=4096): """Generates buffers containing PCM data for the audio file. """ while True: out = self.mf.read(block_size) if not out: break yield bytes(out)
[ "def", "read_blocks", "(", "self", ",", "block_size", "=", "4096", ")", ":", "while", "True", ":", "out", "=", "self", ".", "mf", ".", "read", "(", "block_size", ")", "if", "not", "out", ":", "break", "yield", "bytes", "(", "out", ")" ]
31.375
9
def delete_variable(self, name): """Deletes a variable from a DataFrame.""" del self.variables[name] self.signal_variable_changed.emit(self, name, "delete")
[ "def", "delete_variable", "(", "self", ",", "name", ")", ":", "del", "self", ".", "variables", "[", "name", "]", "self", ".", "signal_variable_changed", ".", "emit", "(", "self", ",", "name", ",", "\"delete\"", ")" ]
44.25
9.75
async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]: """ Spawns and initializes an XBoard engine. :param command: Path of the engine executable, or a list including the path and arguments. :par...
[ "async", "def", "popen_xboard", "(", "command", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "*", ",", "setpgrp", ":", "bool", "=", "False", ",", "*", "*", "popen_args", ":", "Any", ")", "->", "Tuple", "[", "asyncio", ".", "S...
43.782609
25.782609
def GetPupil(self): """Retrieve pupil data """ pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType', 'ApertureValue', 'entrancePupilDiameter', 'entrancePupil...
[ "def", "GetPupil", "(", "self", ")", ":", "pupil_data", "=", "_co", ".", "namedtuple", "(", "'pupil_data'", ",", "[", "'ZemaxApertureType'", ",", "'ApertureValue'", ",", "'entrancePupilDiameter'", ",", "'entrancePupilPosition'", ",", "'exitPupilDiameter'", ",", "'ex...
50.923077
19.615385
def setup_exchange(self): """Declare the exchange When completed, the on_exchange_declareok method will be invoked by pika. """ logger.debug('Declaring exchange %s', self._exchange) self._channel.exchange_declare(self.on_exchange_declareok, ...
[ "def", "setup_exchange", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Declaring exchange %s'", ",", "self", ".", "_exchange", ")", "self", ".", "_channel", ".", "exchange_declare", "(", "self", ".", "on_exchange_declareok", ",", "self", ".", "_exchang...
44
18.8
def get_signature_vars(section): '''Get signature variables which are variables that will be saved with step signatures''' # signature vars should contain parameters defined in global section # #1155 signature_vars = set( section.parameters.keys() & accessed_vars(strip_param_defs(se...
[ "def", "get_signature_vars", "(", "section", ")", ":", "# signature vars should contain parameters defined in global section", "# #1155", "signature_vars", "=", "set", "(", "section", ".", "parameters", ".", "keys", "(", ")", "&", "accessed_vars", "(", "strip_param_defs",...
37
21.347826
def p_members(self, p): """members : | members member VALUE_SEPARATOR | members member""" if len(p) == 1: p[0] = list() else: p[1].append(p[2]) p[0] = p[1]
[ "def", "p_members", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "1", ":", "p", "[", "0", "]", "=", "list", "(", ")", "else", ":", "p", "[", "1", "]", ".", "append", "(", "p", "[", "2", "]", ")", "p", "[", "0", "...
27.222222
12.777778
def move(fname, folder, options): """Move file to dir if existing """ if os.path.isfile(fname): shutil.move(fname, folder) else: if options.silent is False: print('{0} missing'.format(fname))
[ "def", "move", "(", "fname", ",", "folder", ",", "options", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "shutil", ".", "move", "(", "fname", ",", "folder", ")", "else", ":", "if", "options", ".", "silent", "is", "Fal...
28.5
8.25
async def parse_update(self, bot): """ Read update from stream and deserialize it. :param bot: bot instance. You an get it from Dispatcher :return: :class:`aiogram.types.Update` """ data = await self.request.json() update = types.Update(**data) return upd...
[ "async", "def", "parse_update", "(", "self", ",", "bot", ")", ":", "data", "=", "await", "self", ".", "request", ".", "json", "(", ")", "update", "=", "types", ".", "Update", "(", "*", "*", "data", ")", "return", "update" ]
31.4
10.8
def make_report(plots, path): ''' Creates a fat html report based on the previously created files plots is a list of Plot objects defined by a path and title statsfile is the file to which the stats have been saved, which is parsed to a table (rather dodgy) ''' logging.info("Writing html rep...
[ "def", "make_report", "(", "plots", ",", "path", ")", ":", "logging", ".", "info", "(", "\"Writing html report.\"", ")", "html_head", "=", "\"\"\"<!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <style>\n table, th, td {\n ...
37.131579
15.184211
def enforce_mask_shape(mask, shape): """Reduce a boolean mask to fit a given shape. Parameters ---------- mask : ndarray with bool dtype The mask which is to be reduced shape : tuple of int Shape which broadcasts to the mask shape. Returns ------- A boolean mask, co...
[ "def", "enforce_mask_shape", "(", "mask", ",", "shape", ")", ":", "red", "=", "tuple", "(", "[", "i", "for", "i", "in", "range", "(", "len", "(", "shape", ")", ")", "if", "shape", "[", "i", "]", "==", "1", "]", ")", "return", "mask", ".", "max"...
30
18.5625
def _draw_footer(self): """ Draw the key binds help bar at the bottom of the screen """ n_rows, n_cols = self.term.stdscr.getmaxyx() window = self.term.stdscr.derwin(1, n_cols, self._row, 0) window.erase() window.bkgd(str(' '), self.term.attr('HelpBar')) ...
[ "def", "_draw_footer", "(", "self", ")", ":", "n_rows", ",", "n_cols", "=", "self", ".", "term", ".", "stdscr", ".", "getmaxyx", "(", ")", "window", "=", "self", ".", "term", ".", "stdscr", ".", "derwin", "(", "1", ",", "n_cols", ",", "self", ".", ...
33.75
15.083333
def genotypesPhenotypesGenerator(self, request): """ Returns a generator over the (phenotypes, nextPageToken) pairs defined by the (JSON string) request """ # TODO make paging work using SPARQL? compoundId = datamodel.PhenotypeAssociationSetCompoundId.parse( r...
[ "def", "genotypesPhenotypesGenerator", "(", "self", ",", "request", ")", ":", "# TODO make paging work using SPARQL?", "compoundId", "=", "datamodel", ".", "PhenotypeAssociationSetCompoundId", ".", "parse", "(", "request", ".", "phenotype_association_set_id", ")", "dataset"...
50.266667
15.066667
def replace(self, text): """Do j/v replacement""" for (pattern, repl) in self.patterns: text = re.subn(pattern, repl, text)[0] return text
[ "def", "replace", "(", "self", ",", "text", ")", ":", "for", "(", "pattern", ",", "repl", ")", "in", "self", ".", "patterns", ":", "text", "=", "re", ".", "subn", "(", "pattern", ",", "repl", ",", "text", ")", "[", "0", "]", "return", "text" ]
34
10.4
def _get_cache_value(self, key, empty, type): """Used internally by the accessor properties.""" if type is bool: return key in self if key in self: value = self[key] if value is None: return empty elif type is not None: ...
[ "def", "_get_cache_value", "(", "self", ",", "key", ",", "empty", ",", "type", ")", ":", "if", "type", "is", "bool", ":", "return", "key", "in", "self", "if", "key", "in", "self", ":", "value", "=", "self", "[", "key", "]", "if", "value", "is", "...
31.428571
10.5
def _plot(self): """Plot all dots for series""" r_max = min( self.view.x(1) - self.view.x(0), (self.view.y(0) or 0) - self.view.y(1) ) / (2 * 1.05) for serie in self.series: self.dot(serie, r_max)
[ "def", "_plot", "(", "self", ")", ":", "r_max", "=", "min", "(", "self", ".", "view", ".", "x", "(", "1", ")", "-", "self", ".", "view", ".", "x", "(", "0", ")", ",", "(", "self", ".", "view", ".", "y", "(", "0", ")", "or", "0", ")", "-...
32.125
11.125
def has_header_value (headers, name, value): """ Look in headers for a specific header name and value. Both name and value are case insensitive. @return: True if header name and value are found @rtype: bool """ name = name.lower() value = value.lower() for hname, hvalue in headers: ...
[ "def", "has_header_value", "(", "headers", ",", "name", ",", "value", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "value", "=", "value", ".", "lower", "(", ")", "for", "hname", ",", "hvalue", "in", "headers", ":", "if", "hname", ".", "lo...
28.928571
14.214286
def analyze_log(fp, configs, url_rules): """Analyze log file""" url_classifier = URLClassifier(url_rules) analyzer = LogAnalyzer(url_classifier=url_classifier, min_msecs=configs.min_msecs) for line in fp: analyzer.analyze_line(line) return analyzer.get_data()
[ "def", "analyze_log", "(", "fp", ",", "configs", ",", "url_rules", ")", ":", "url_classifier", "=", "URLClassifier", "(", "url_rules", ")", "analyzer", "=", "LogAnalyzer", "(", "url_classifier", "=", "url_classifier", ",", "min_msecs", "=", "configs", ".", "mi...
40.142857
12.428571
def _check_type(value, expected_type): """Perform type checking on the provided value This is a helper that will raise ``TypeError`` if the provided value is not an instance of the provided type. This method should be used sparingly but can be good for preventing problems earlier when you want to rest...
[ "def", "_check_type", "(", "value", ",", "expected_type", ")", ":", "if", "not", "isinstance", "(", "value", ",", "expected_type", ")", ":", "raise", "TypeError", "(", "\"Value {value!r} has unexpected type {actual_type!r}, expected {expected_type!r}\"", ".", "format", ...
43.470588
23.176471
def is_contact_binary(self, component): """ especially useful for constraints tells whether any component (star, envelope) is part of a contact_binary by checking its siblings for an envelope """ if component not in self._is_contact_binary.keys(): self._updat...
[ "def", "is_contact_binary", "(", "self", ",", "component", ")", ":", "if", "component", "not", "in", "self", ".", "_is_contact_binary", ".", "keys", "(", ")", ":", "self", ".", "_update_cache", "(", ")", "return", "self", ".", "_is_contact_binary", ".", "g...
34
15.454545
def get_default_config(self): """ Returns the default collector settings """ config = super(PostfixCollector, self).get_default_config() config.update({ 'path': 'postfix', 'host': 'localhost', 'port': 7777, ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "PostfixCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'postfix'", ",", "'host'", ":", "'localhost'", ",...
31.5
10.166667
def make_schema_from(value, env): """Make a Schema object from the given spec. The input and output types of this function are super unclear, and are held together by ponies, wishes, duct tape, and a load of tests. See the comments for horrific entertainment. """ # So this thing may not need to evaluate any...
[ "def", "make_schema_from", "(", "value", ",", "env", ")", ":", "# So this thing may not need to evaluate anything[0]", "if", "isinstance", "(", "value", ",", "framework", ".", "Thunk", ")", ":", "value", "=", "framework", ".", "eval", "(", "value", ",", "env", ...
44.357143
27.678571
def get_common_name(cls, csr): """ Read information from CSR. """ from tempfile import NamedTemporaryFile fhandle = NamedTemporaryFile() fhandle.write(csr.encode('latin1')) fhandle.flush() output = cls.exec_output('openssl req -noout -subject -in %s' % ...
[ "def", "get_common_name", "(", "cls", ",", "csr", ")", ":", "from", "tempfile", "import", "NamedTemporaryFile", "fhandle", "=", "NamedTemporaryFile", "(", ")", "fhandle", ".", "write", "(", "csr", ".", "encode", "(", "'latin1'", ")", ")", "fhandle", ".", "...
34.285714
14.142857
def create(self, article, attachment, inline=False, file_name=None, content_type=None): """ This function creates attachment attached to article. :param article: Numeric article id or :class:`Article` object. :param attachment: File object or os path to file :param inline: If tr...
[ "def", "create", "(", "self", ",", "article", ",", "attachment", ",", "inline", "=", "False", ",", "file_name", "=", "None", ",", "content_type", "=", "None", ")", ":", "return", "HelpdeskAttachmentRequest", "(", "self", ")", ".", "post", "(", "self", "....
61.45
29.35
def _get_conn(self, timeout=None): """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and r...
[ "def", "_get_conn", "(", "self", ",", "timeout", "=", "None", ")", ":", "conn", "=", "None", "try", ":", "conn", "=", "self", ".", "pool", ".", "get", "(", "block", "=", "self", ".", "block", ",", "timeout", "=", "timeout", ")", "except", "Attribut...
39.783784
21.513514
def do_get_page(parser, token): """Retrieve a page and insert into the template's context. Example:: {% get_page "news" as news_page %} :param page: the page object, slug or id :param name: name of the context variable to store the page in """ bits = token.split_contents() if 4 !=...
[ "def", "do_get_page", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "4", "!=", "len", "(", "bits", ")", ":", "raise", "TemplateSyntaxError", "(", "'%r expects 4 arguments'", "%", "bits", "[", "0", "]"...
32.842105
16.684211
def get_templates(self, limit=100, offset=0): """ Get all account templates """ url = self.TEMPLATES_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_templates", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEMPLATES_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self...
27.636364
16.181818
def _get_events(self): """Get the list of events.""" events, changed_container_ids = self.docker_util.get_events() if not self._disable_net_metrics: self._invalidate_network_mapping_cache(events) if changed_container_ids and self._service_discovery: get_sd_backend...
[ "def", "_get_events", "(", "self", ")", ":", "events", ",", "changed_container_ids", "=", "self", ".", "docker_util", ".", "get_events", "(", ")", "if", "not", "self", ".", "_disable_net_metrics", ":", "self", ".", "_invalidate_network_mapping_cache", "(", "even...
48.3
17.4
def url(self): """ The url of this window """ with switch_window(self._browser, self.name): return self._browser.url
[ "def", "url", "(", "self", ")", ":", "with", "switch_window", "(", "self", ".", "_browser", ",", "self", ".", "name", ")", ":", "return", "self", ".", "_browser", ".", "url" ]
35.25
10.75
def murmur2(data): """Pure-python Murmur2 implementation. Based on java client, see org.apache.kafka.common.utils.Utils.murmur2 Args: data (bytes): opaque bytes Returns: MurmurHash2 of data """ # Python2 bytes is really a str, causing the bitwise operations below to fail # so conv...
[ "def", "murmur2", "(", "data", ")", ":", "# Python2 bytes is really a str, causing the bitwise operations below to fail", "# so convert to bytearray.", "if", "six", ".", "PY2", ":", "data", "=", "bytearray", "(", "bytes", "(", "data", ")", ")", "length", "=", "len", ...
25
19.731343
def transformer_librispeech_v1(): """HParams for training ASR model on LibriSpeech V1.""" hparams = transformer_base() hparams.num_heads = 4 hparams.filter_size = 1024 hparams.hidden_size = 256 hparams.num_encoder_layers = 5 hparams.num_decoder_layers = 3 hparams.learning_rate = 0.15 hparams.batch_si...
[ "def", "transformer_librispeech_v1", "(", ")", ":", "hparams", "=", "transformer_base", "(", ")", "hparams", ".", "num_heads", "=", "4", "hparams", ".", "filter_size", "=", "1024", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "num_encoder_layers", ...
27.928571
15.142857
def infos(cls, fqdn): """ Display information about hosted certificates for a fqdn. """ if isinstance(fqdn, (list, tuple)): ids = [] for fqd_ in fqdn: ids.extend(cls.infos(fqd_)) return ids ids = cls.usable_id(fqdn) if not ids: ...
[ "def", "infos", "(", "cls", ",", "fqdn", ")", ":", "if", "isinstance", "(", "fqdn", ",", "(", "list", ",", "tuple", ")", ")", ":", "ids", "=", "[", "]", "for", "fqd_", "in", "fqdn", ":", "ids", ".", "extend", "(", "cls", ".", "infos", "(", "f...
27.375
16.8125
def stillRecording(self, deviceId, dataCount): """ For a device that is recording, updates the last timestamp so we now when we last received data. :param deviceId: the device id. :param dataCount: the no of items of data recorded in this batch. :return: """ statu...
[ "def", "stillRecording", "(", "self", ",", "deviceId", ",", "dataCount", ")", ":", "status", "=", "self", ".", "recordingDevices", "[", "deviceId", "]", "if", "status", "is", "not", "None", ":", "if", "status", "[", "'state'", "]", "==", "MeasurementStatus...
49.25
19.916667
def save(self, mark): """Save a position in this collection. :param mark: The position to save :type mark: Mark :raises: DBError, NoTrackingCollection """ self._check_exists() obj = mark.as_dict() try: # Make a 'filter' to find/update existing...
[ "def", "save", "(", "self", ",", "mark", ")", ":", "self", ".", "_check_exists", "(", ")", "obj", "=", "mark", ".", "as_dict", "(", ")", "try", ":", "# Make a 'filter' to find/update existing record, which uses", "# the field name and operation (but not the position).",...
40.411765
16.705882
def updateIdenityStore(self, userPassword, user, userFullnameAttribute, ldapURLForUsers, userEmailAttribute, usernameAttribute, isP...
[ "def", "updateIdenityStore", "(", "self", ",", "userPassword", ",", "user", ",", "userFullnameAttribute", ",", "ldapURLForUsers", ",", "userEmailAttribute", ",", "usernameAttribute", ",", "isPasswordEncrypted", "=", "False", ",", "caseSensitive", "=", "True", ")", "...
55.042857
21.228571
def setCurrentProfile(self, profile): """ Sets the current profile to the inputed profile. :param profile | <XViewProfile> """ try: index = self._profiles.index(profile) except ValueError: index = -1 self._profileComb...
[ "def", "setCurrentProfile", "(", "self", ",", "profile", ")", ":", "try", ":", "index", "=", "self", ".", "_profiles", ".", "index", "(", "profile", ")", "except", "ValueError", ":", "index", "=", "-", "1", "self", ".", "_profileCombo", ".", "setCurrentI...
27.75
13.75
def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.s...
[ "def", "update_md5", "(", "filenames", ")", ":", "import", "re", "for", "name", "in", "filenames", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "name", ")", "f", "=", "open", "(", "name", ",", "'rb'", ")", "md5_data", "[", "base", "]"...
25.5
21.642857
def get_encodings(): ''' return a list of string encodings to try ''' encodings = [__salt_system_encoding__] try: sys_enc = sys.getdefaultencoding() except ValueError: # system encoding is nonstandard or malformed sys_enc = None if sys_enc and sys_enc not in encodings: ...
[ "def", "get_encodings", "(", ")", ":", "encodings", "=", "[", "__salt_system_encoding__", "]", "try", ":", "sys_enc", "=", "sys", ".", "getdefaultencoding", "(", ")", "except", "ValueError", ":", "# system encoding is nonstandard or malformed", "sys_enc", "=", "None...
25.5
19.055556
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' serv = _get_serv(ret=None) # create legacy request in case an InfluxDB 0.8.x version is used if "influxdb08" in serv.__module__: req = [ { 'name': 'jids', 'colu...
[ "def", "save_load", "(", "jid", ",", "load", ",", "minions", "=", "None", ")", ":", "serv", "=", "_get_serv", "(", "ret", "=", "None", ")", "# create legacy request in case an InfluxDB 0.8.x version is used", "if", "\"influxdb08\"", "in", "serv", ".", "__module__"...
25.8
19.8
def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key...
[ "def", "attach_enctype_error_multidict", "(", "request", ")", ":", "oldcls", "=", "request", ".", "files", ".", "__class__", "class", "newcls", "(", "oldcls", ")", ":", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "try", ":", "return", "oldcls"...
38.352941
9.588235
def load_coco(image_set, dirname, shuffle=False): """ wrapper function for loading ms coco dataset Parameters: ---------- image_set : str train2014, val2014, valminusminival2014, minival2014 dirname: str root dir for coco shuffle: boolean initial shuffle """ ...
[ "def", "load_coco", "(", "image_set", ",", "dirname", ",", "shuffle", "=", "False", ")", ":", "anno_files", "=", "[", "'instances_'", "+", "y", ".", "strip", "(", ")", "+", "'.json'", "for", "y", "in", "image_set", ".", "split", "(", "','", ")", "]",...
29.73913
18.347826
def get_model(name, **kwargs): """Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default ...
[ "def", "get_model", "(", "name", ",", "*", "*", "kwargs", ")", ":", "models", "=", "{", "'resnet18_v1'", ":", "resnet18_v1", ",", "'resnet34_v1'", ":", "resnet34_v1", ",", "'resnet50_v1'", ":", "resnet50_v1", ",", "'resnet101_v1'", ":", "resnet101_v1", ",", ...
34.854839
11.129032
def subscribe(self, varIDs=(tc.VAR_DEPARTED_VEHICLES_IDS,), begin=0, end=2**31 - 1): """subscribe(list(integer), double, double) -> None Subscribe to one or more simulation values for the given interval. """ Domain.subscribe(self, "", varIDs, begin, end)
[ "def", "subscribe", "(", "self", ",", "varIDs", "=", "(", "tc", ".", "VAR_DEPARTED_VEHICLES_IDS", ",", ")", ",", "begin", "=", "0", ",", "end", "=", "2", "**", "31", "-", "1", ")", ":", "Domain", ".", "subscribe", "(", "self", ",", "\"\"", ",", "...
47
22
def indices_for_body(self, name, step=3): '''Get a list of the indices for a specific body. Parameters ---------- name : str The name of the body to look up. step : int, optional The number of numbers for each body. Defaults to 3, should be set ...
[ "def", "indices_for_body", "(", "self", ",", "name", ",", "step", "=", "3", ")", ":", "for", "j", ",", "body", "in", "enumerate", "(", "self", ".", "bodies", ")", ":", "if", "body", ".", "name", "==", "name", ":", "return", "list", "(", "range", ...
33.4
22
def read(self, size=-1): """Read `size` bytes from the reader relative to the parsed output. This is generally acceptable in practice since VCF lines are condensed, but if the output line <<< record, this means the actual memory used will be much greater than `size`. """ ...
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "lines", "=", "[", "]", "parsed_size", "=", "0", "while", "True", ":", "line", "=", "self", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "lines", ".", "append", ...
32.526316
17.578947
def get_elasticache_clusters_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache clusters (with nodes' info) in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would...
[ "def", "get_elasticache_clusters_by_region", "(", "self", ",", "region", ")", ":", "# ElastiCache boto module doesn't provide a get_all_intances method,", "# that's why we need to call describe directly (it would be called by", "# the shorthand method anyway...)", "try", ":", "conn", "="...
46.2
26.028571
def cmdify(self): """Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are ...
[ "def", "cmdify", "(", "self", ")", ":", "return", "\" \"", ".", "join", "(", "itertools", ".", "chain", "(", "[", "_quote_if_contains", "(", "self", ".", "command", ",", "r'[\\s^()]'", ")", "]", ",", "(", "_quote_if_contains", "(", "arg", ",", "r'[\\s^]'...
40.395833
27.020833
async def set_lock(self, resource, lock_identifier): """ Tries to set the lock to all the redis instances :param resource: The resource string name to lock :param lock_identifier: The id of the lock. A unique string :return float: The elapsed time that took to lock the instances...
[ "async", "def", "set_lock", "(", "self", ",", "resource", ",", "lock_identifier", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "lock_timeout", "=", "self", ".", "lock_timeout", "successes", "=", "await", "asyncio", ".", "gather", "(", "*", ...
38.8
22.8
def call(self, inpt): """ Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` i...
[ "def", "call", "(", "self", ",", "inpt", ")", ":", "if", "inpt", "is", "Manager", ".", "NONE_INPUT", ":", "return", "False", "# Call (construct) the argument with the input object", "argument_instance", "=", "self", ".", "argument", "(", "inpt", ")", "if", "not"...
32.933333
22.733333
def from_msm(cls, msm, n_macrostates, objective_function=None): """Create and fit lumped model from pre-existing MSM. Parameters ---------- msm : MarkovStateModel The input microstate msm to use. n_macrostates : int The number of macrostates Retu...
[ "def", "from_msm", "(", "cls", ",", "msm", ",", "n_macrostates", ",", "objective_function", "=", "None", ")", ":", "params", "=", "msm", ".", "get_params", "(", ")", "lumper", "=", "cls", "(", "n_macrostates", "=", "n_macrostates", ",", "objective_function",...
28.571429
16.357143
def explain_feature(featurename): '''print the location of single feature and its version if the feature is located inside a git repository, this will also print the git-rev and modified files ''' import os import featuremonkey import importlib import subprocess def guess_version(...
[ "def", "explain_feature", "(", "featurename", ")", ":", "import", "os", "import", "featuremonkey", "import", "importlib", "import", "subprocess", "def", "guess_version", "(", "feature_module", ")", ":", "if", "hasattr", "(", "feature_module", ",", "'__version__'", ...
33.621212
18.833333
def changed_files(self) -> typing.List[str]: """ :return: changed files :rtype: list of str """ changed_files: typing.List[str] = [x.a_path for x in self.repo.index.diff(None)] LOGGER.debug('changed files: %s', changed_files) return changed_files
[ "def", "changed_files", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "changed_files", ":", "typing", ".", "List", "[", "str", "]", "=", "[", "x", ".", "a_path", "for", "x", "in", "self", ".", "repo", ".", "index", ".", "di...
36.875
12.875
def update_hard_unknown_phase_state(self): """Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important, and they should not raise notif about it :return: None """ self.was_in_hard_unknown_r...
[ "def", "update_hard_unknown_phase_state", "(", "self", ")", ":", "self", ".", "was_in_hard_unknown_reach_phase", "=", "self", ".", "in_hard_unknown_reach_phase", "# We do not care about SOFT state at all", "# and we are sure we are no more in such a phase", "if", "self", ".", "st...
50.305556
24.861111
def read_byte_data(self, addr, cmd): """read_byte_data(addr, cmd) -> result Perform SMBus Read Byte Data transaction. """ self._set_addr(addr) res = SMBUS.i2c_smbus_read_byte_data(self._fd, ffi.cast("__u8", cmd)) if res == -1: raise IOError(ffi.errno) ...
[ "def", "read_byte_data", "(", "self", ",", "addr", ",", "cmd", ")", ":", "self", ".", "_set_addr", "(", "addr", ")", "res", "=", "SMBUS", ".", "i2c_smbus_read_byte_data", "(", "self", ".", "_fd", ",", "ffi", ".", "cast", "(", "\"__u8\"", ",", "cmd", ...
32.2
14.7
def add_excludes(self, excludes): # type: (_BaseSourcePaths, list) -> None """Add a list of excludes :param _BaseSourcePaths self: this :param list excludes: list of excludes """ if not isinstance(excludes, list): if isinstance(excludes, tuple): ...
[ "def", "add_excludes", "(", "self", ",", "excludes", ")", ":", "# type: (_BaseSourcePaths, list) -> None", "if", "not", "isinstance", "(", "excludes", ",", "list", ")", ":", "if", "isinstance", "(", "excludes", ",", "tuple", ")", ":", "excludes", "=", "list", ...
35.172414
9.586207
def add_resources(self, resources): """ Add faked child resources to this resource, from the provided resource definitions. Duplicate resource names in the same scope are not permitted. Although this method is typically used to initially load the faked HMC with resource...
[ "def", "add_resources", "(", "self", ",", "resources", ")", ":", "for", "child_attr", "in", "resources", ":", "child_list", "=", "resources", "[", "child_attr", "]", "self", ".", "_process_child_list", "(", "self", ",", "child_attr", ",", "child_list", ")" ]
42.553398
23.563107
def perform_bandfill_corr(self, eigenvalues, kpoint_weights, potalign, vbm, cbm): """ This calculates the band filling correction based on excess of electrons/holes in CB/VB... Note that the total free holes and electrons may also be used for a "shallow donor/acceptor" correction...
[ "def", "perform_bandfill_corr", "(", "self", ",", "eigenvalues", ",", "kpoint_weights", ",", "potalign", ",", "vbm", ",", "cbm", ")", ":", "bf_corr", "=", "0.", "self", ".", "metadata", "[", "\"potalign\"", "]", "=", "potalign", "self", ".", "metadata", "[...
55.793651
31.380952
def run_experiments(experiments, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=False, ...
[ "def", "run_experiments", "(", "experiments", ",", "search_alg", "=", "None", ",", "scheduler", "=", "None", ",", "with_server", "=", "False", ",", "server_port", "=", "TuneServer", ".", "DEFAULT_PORT", ",", "verbose", "=", "2", ",", "resume", "=", "False", ...
33
14.358491
def count_history(self, request, *args, **kwargs): """ To get a historical data of events amount - run **GET** against */api/events/count/history/*. Endpoint support same filters as events list. More about historical data - read at section *Historical data*. Response example: ...
[ "def", "count_history", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "self", ".", "filter_queryset", "(", "self", ".", "get_queryset", "(", ")", ")", "mapped", "=", "{", "'start'", ":", "request", ...
37.722222
24.611111
def strptime(self, value, format): """ By default, parse datetime with TZ. If TZ is False, convert datetime to local time and disable TZ """ value = force_str(value) if format == ISO_8601: try: parsed = parse_datetime(value) if...
[ "def", "strptime", "(", "self", ",", "value", ",", "format", ")", ":", "value", "=", "force_str", "(", "value", ")", "if", "format", "==", "ISO_8601", ":", "try", ":", "parsed", "=", "parse_datetime", "(", "value", ")", "if", "not", "settings", ".", ...
40.636364
20.090909
def register_serializers(self, serializers): """ Adds extra serializers; generally registered during the handler lifecycle """ for new_serializer in serializers: if not isinstance(new_serializer, serializer.Base): msg = "registered serializer %s.%s does not i...
[ "def", "register_serializers", "(", "self", ",", "serializers", ")", ":", "for", "new_serializer", "in", "serializers", ":", "if", "not", "isinstance", "(", "new_serializer", ",", "serializer", ".", "Base", ")", ":", "msg", "=", "\"registered serializer %s.%s does...
40.785714
20.214286
def getAnyAppWithWindow(cls): """Get a random app that has windows. Raise a ValueError exception if no GUI applications are found. """ # Refresh the runningApplications list apps = cls._getRunningApps() for app in apps: pid = app.processIdentifier() ...
[ "def", "getAnyAppWithWindow", "(", "cls", ")", ":", "# Refresh the runningApplications list", "apps", "=", "cls", ".", "_getRunningApps", "(", ")", "for", "app", "in", "apps", ":", "pid", "=", "app", ".", "processIdentifier", "(", ")", "ref", "=", "cls", "."...
37.538462
12.461538
def config_get(key, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Get the value of a key in the git configuration file key The name of the configuration key to ...
[ "def", "config_get", "(", "key", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Sanitize kwargs and make sure ...
31.364583
23.71875
def process_request(self, request): """ Update last activity time or logout. """ if django.VERSION < (1, 10): is_authenticated = request.user.is_authenticated() else: is_authenticated = request.user.is_authenticated if not is_authenticated: r...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "if", "django", ".", "VERSION", "<", "(", "1", ",", "10", ")", ":", "is_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "(", ")", "else", ":", "is_authenticated", "=",...
36.84
17.56
def exists(self, filename): """Check for the existence of a package or script. Unlike other DistributionPoint types, JDS and CDP types have no documented interface for checking whether the server and its children have a complete copy of a file. The best we can do is check for an...
[ "def", "exists", "(", "self", ",", "filename", ")", ":", "# Technically, the results of the casper.jxml page list the", "# package files on the server. This is an undocumented", "# interface, however.", "result", "=", "False", "if", "is_package", "(", "filename", ")", ":", "p...
41.8
19.828571
def classify_catalog(catalog): """ Look at a list of sources and split them according to their class. Parameters ---------- catalog : iterable A list or iterable object of {SimpleSource, IslandSource, OutputSource} objects, possibly mixed. Any other objects will be silently ignored....
[ "def", "classify_catalog", "(", "catalog", ")", ":", "components", "=", "[", "]", "islands", "=", "[", "]", "simples", "=", "[", "]", "for", "source", "in", "catalog", ":", "if", "isinstance", "(", "source", ",", "OutputSource", ")", ":", "components", ...
27.6875
18.5
def values(self) -> List["Package"]: # type: ignore """ Return an iterable of the available `Package` instances. """ values = [self.build_dependencies.get(name) for name in self.build_dependencies] return values
[ "def", "values", "(", "self", ")", "->", "List", "[", "\"Package\"", "]", ":", "# type: ignore", "values", "=", "[", "self", ".", "build_dependencies", ".", "get", "(", "name", ")", "for", "name", "in", "self", ".", "build_dependencies", "]", "return", "...
41.166667
17.166667
def join_import_from(self, import_spec): """ Joins a relative import like `from .foo import bar` with this module as its parent module. If the module is not a root module or package root, it will be joined with the package root. """ if not self.isroot and not self.ispkg: parent = self.nam...
[ "def", "join_import_from", "(", "self", ",", "import_spec", ")", ":", "if", "not", "self", ".", "isroot", "and", "not", "self", ".", "ispkg", ":", "parent", "=", "self", ".", "name", ".", "rpartition", "(", "'.'", ")", "[", "0", "]", "else", ":", "...
34.416667
14.416667
def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from th...
[ "def", "peering_connection_pending_from_vpc", "(", "conn_id", "=", "None", ",", "conn_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "prof...
34.805556
32.277778
def dag_paused(dag_id, paused): """(Un)pauses a dag""" DagModel = models.DagModel with create_session() as session: orm_dag = ( session.query(DagModel) .filter(DagModel.dag_id == dag_id).first() ) if paused == 'true': orm_dag.is_paused = Tr...
[ "def", "dag_paused", "(", "dag_id", ",", "paused", ")", ":", "DagModel", "=", "models", ".", "DagModel", "with", "create_session", "(", ")", "as", "session", ":", "orm_dag", "=", "(", "session", ".", "query", "(", "DagModel", ")", ".", "filter", "(", "...
26.705882
14.941176
def process_command_line(argv): """ parses the arguments. removes our arguments from the command line """ setup = {} for handler in ACCEPTED_ARG_HANDLERS: setup[handler.arg_name] = handler.default_val setup['file'] = '' setup['qt-support'] = '' i = 0 del argv[0] while i ...
[ "def", "process_command_line", "(", "argv", ")", ":", "setup", "=", "{", "}", "for", "handler", "in", "ACCEPTED_ARG_HANDLERS", ":", "setup", "[", "handler", ".", "arg_name", "]", "=", "handler", ".", "default_val", "setup", "[", "'file'", "]", "=", "''", ...
39.283019
21.849057
def symlink( name, target, force=False, backupname=None, makedirs=False, user=None, group=None, copy_target_user=False, copy_target_group=False, mode=None, win_owner=None, win_perms=None, win_deny_perms=None, ...
[ "def", "symlink", "(", "name", ",", "target", ",", "force", "=", "False", ",", "backupname", "=", "None", ",", "makedirs", "=", "False", ",", "user", "=", "None", ",", "group", "=", "None", ",", "copy_target_user", "=", "False", ",", "copy_target_group",...
38.702997
22.512262
def _set_isis(self, v, load=False): """ Setter method for isis, mapped from YANG variable /routing_system/router/isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_isis is considered as a private method. Backends looking to populate this variable should...
[ "def", "_set_isis", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
80.909091
38.045455
def get_subassistants(self): """Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants """ if not hasattr(self, '_subassista...
[ "def", "get_subassistants", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_subassistants'", ")", ":", "self", ".", "_subassistants", "=", "[", "]", "# we want to know, if type(self) defines 'get_subassistant_classes',", "# we don't want to inherit it ...
42.235294
18.941176
def send_rpc(self, name, rpc_id, payload, timeout=1.0): """Send an RPC to a service and synchronously wait for the response. Args: name (str): The short name of the service to send the RPC to rpc_id (int): The id of the RPC we want to call payload (bytes): Any binary...
[ "def", "send_rpc", "(", "self", ",", "name", ",", "rpc_id", ",", "payload", ",", "timeout", "=", "1.0", ")", ":", "return", "self", ".", "_loop", ".", "run_coroutine", "(", "self", ".", "_client", ".", "send_rpc", "(", "name", ",", "rpc_id", ",", "pa...
47
25.611111
def rename(self, node): """ Renames given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ source = node.path base_name, state = QInputDialog.getText(self, "Re...
[ "def", "rename", "(", "self", ",", "node", ")", ":", "source", "=", "node", ".", "path", "base_name", ",", "state", "=", "QInputDialog", ".", "getText", "(", "self", ",", "\"Rename\"", ",", "\"Enter your new name:\"", ",", "text", "=", "os", ".", "path",...
41.837209
24.953488
def OnInit(self): """Initialise the application""" wx.Image.AddHandler(self.handler) frame = MainFrame( config_parser = load_config()) frame.Show(True) self.SetTopWindow(frame) if sys.argv[1:]: wx.CallAfter( frame.load_memory, sys.argv[1] ) else: ...
[ "def", "OnInit", "(", "self", ")", ":", "wx", ".", "Image", ".", "AddHandler", "(", "self", ".", "handler", ")", "frame", "=", "MainFrame", "(", "config_parser", "=", "load_config", "(", ")", ")", "frame", ".", "Show", "(", "True", ")", "self", ".", ...
34.090909
14.272727
def fetch(cwd, remote=None, force=False, refspecs=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, saltenv='base', output_encoding=None): ''' .. versionchanged:...
[ "def", "fetch", "(", "cwd", ",", "remote", "=", "None", ",", "force", "=", "False", ",", "refspecs", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "N...
32.622857
23.388571
def gmean(x, weights=None): """ Return the weighted geometric mean of x """ w_arr, x_arr = _preprocess_inputs(x, weights) return np.exp((w_arr*np.log(x_arr)).sum(axis=0) / w_arr.sum(axis=0))
[ "def", "gmean", "(", "x", ",", "weights", "=", "None", ")", ":", "w_arr", ",", "x_arr", "=", "_preprocess_inputs", "(", "x", ",", "weights", ")", "return", "np", ".", "exp", "(", "(", "w_arr", "*", "np", ".", "log", "(", "x_arr", ")", ")", ".", ...
34.166667
9.5
def uninstall_all_passbands(local=True): """ Uninstall all passbands, either globally or locally (need to call twice to delete ALL passbands) If local=False, you must have permission to access the installation directory """ pbdir = _pbdir_local if local else _pbdir_global for f in os.listdi...
[ "def", "uninstall_all_passbands", "(", "local", "=", "True", ")", ":", "pbdir", "=", "_pbdir_local", "if", "local", "else", "_pbdir_global", "for", "f", "in", "os", ".", "listdir", "(", "pbdir", ")", ":", "pbpath", "=", "os", ".", "path", ".", "join", ...
36.916667
15.75
def _load(self, filename): """Import all filters from a text file""" filename = pathlib.Path(filename) with filename.open() as fd: data = fd.readlines() # Get the strings that correspond to self.fileid bool_head = [l.strip().startswith("[") for l in data] in...
[ "def", "_load", "(", "self", ",", "filename", ")", ":", "filename", "=", "pathlib", ".", "Path", "(", "filename", ")", "with", "filename", ".", "open", "(", ")", "as", "fd", ":", "data", "=", "fd", ".", "readlines", "(", ")", "# Get the strings that co...
33.098039
15.313725
def create_cfg(self, cfg_file, defaults=None, mode='json'): ''' set mode to json or yaml? probably remove this option..Todo Creates the config file for your app with default values The file will only be created if it doesn't exits also sets up the first_run attribute. ...
[ "def", "create_cfg", "(", "self", ",", "cfg_file", ",", "defaults", "=", "None", ",", "mode", "=", "'json'", ")", ":", "assert", "mode", "in", "(", "'json'", ",", "'yaml'", ")", "self", ".", "cfg_mode", "=", "mode", "self", ".", "cfg_file", "=", "cfg...
33.297297
17.945946
def update_compliance_all(self, information, timeout=-1): """ Returns SAS Logical Interconnects to a consistent state. The current SAS Logical Interconnect state is compared to the associated SAS Logical Interconnect group. Args: information: Can be either the resource ID or...
[ "def", "update_compliance_all", "(", "self", ",", "information", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "self", ".", "URI", "+", "\"/compliance\"", "result", "=", "self", ".", "_helper", ".", "update", "(", "information", ",", "uri", ",", ...
39.222222
28.222222