text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def do(self): 'Do or redo the action' self._runner = self._generator(*self.args, **self.kwargs) rets = next(self._runner) if isinstance(rets, tuple): self._text = rets[0] return rets[1:] elif rets is None: self._text = '' r...
[ "def", "do", "(", "self", ")", ":", "self", ".", "_runner", "=", "self", ".", "_generator", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "rets", "=", "next", "(", "self", ".", "_runner", ")", "if", "isinstance", "(", ...
29.923077
14.076923
async def debug(self, client_id, conn_string, command, args): """Send a debug command to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will...
[ "async", "def", "debug", "(", "self", ",", "client_id", ",", "conn_string", ",", "command", ",", "args", ")", ":", "conn_id", "=", "self", ".", "_client_info", "(", "client_id", ",", "'connections'", ")", "[", "conn_string", "]", "return", "await", "self",...
39.5
23.958333
def _generate_vdev(self, base, offset): """Generate virtual device number based on base vdev :param base: base virtual device number, string of 4 bit hex. :param offset: offset to base, integer. """ vdev = hex(int(base, 16) + offset)[2:] return vdev.rjust(4, '0')
[ "def", "_generate_vdev", "(", "self", ",", "base", ",", "offset", ")", ":", "vdev", "=", "hex", "(", "int", "(", "base", ",", "16", ")", "+", "offset", ")", "[", "2", ":", "]", "return", "vdev", ".", "rjust", "(", "4", ",", "'0'", ")" ]
43.571429
7.142857
def cli_char(name, tibiadata, json): """Displays information about a Tibia character.""" name = " ".join(name) char = _fetch_and_parse(Character.get_url, Character.from_content, Character.get_url_tibiadata, Character.from_tibiadata, tibiadata, name) ...
[ "def", "cli_char", "(", "name", ",", "tibiadata", ",", "json", ")", ":", "name", "=", "\" \"", ".", "join", "(", "name", ")", "char", "=", "_fetch_and_parse", "(", "Character", ".", "get_url", ",", "Character", ".", "from_content", ",", "Character", ".",...
42.1
14.6
def CheckFont(page, fontname): """Return an entry in the page's font list if reference name matches. """ for f in page.getFontList(): if f[4] == fontname: return f if f[3].lower() == fontname.lower(): return f return None
[ "def", "CheckFont", "(", "page", ",", "fontname", ")", ":", "for", "f", "in", "page", ".", "getFontList", "(", ")", ":", "if", "f", "[", "4", "]", "==", "fontname", ":", "return", "f", "if", "f", "[", "3", "]", ".", "lower", "(", ")", "==", "...
29.888889
11
def set_permissions_in_context(self, context={}): """ Provides permissions for mongoadmin for use in the context""" context['has_view_permission'] = self.mongoadmin.has_view_permission(self.request) context['has_edit_permission'] = self.mongoadmin.has_edit_permission(self.request) conte...
[ "def", "set_permissions_in_context", "(", "self", ",", "context", "=", "{", "}", ")", ":", "context", "[", "'has_view_permission'", "]", "=", "self", ".", "mongoadmin", ".", "has_view_permission", "(", "self", ".", "request", ")", "context", "[", "'has_edit_pe...
63.25
33.625
def get_assembly_size(assembly_file): """Returns the number of nucleotides and the size per contig for the provided assembly file path Parameters ---------- assembly_file : str Path to assembly file. Returns ------- assembly_size : int Size of the assembly in nucleotide...
[ "def", "get_assembly_size", "(", "assembly_file", ")", ":", "assembly_size", "=", "0", "contig_size", "=", "{", "}", "header", "=", "\"\"", "with", "open", "(", "assembly_file", ")", "as", "fh", ":", "for", "line", "in", "fh", ":", "# Skip empty lines", "i...
23.384615
18.948718
def _handle_message(self, data): """ Parses keypad messages from the panel. :param data: keypad data to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` """ try: data = data.decode('utf-8') except: ra...
[ "def", "_handle_message", "(", "self", ",", "data", ")", ":", "try", ":", "data", "=", "data", ".", "decode", "(", "'utf-8'", ")", "except", ":", "raise", "InvalidMessageError", "(", "'Decode failed for message: {0}'", ".", "format", "(", "data", ")", ")", ...
24.769231
18.5
def checkout(branch, quiet=False, as_path=False): """Check out that branch Defaults to a quiet checkout, giving no stdout if stdout it wanted, call with quiet = False Defaults to checking out branches If as_path is true, then treat "branch" like a file, i.e. $ git checkout -- branc...
[ "def", "checkout", "(", "branch", ",", "quiet", "=", "False", ",", "as_path", "=", "False", ")", ":", "try", ":", "if", "as_path", ":", "branch", "=", "'-- %s'", "%", "branch", "run", "(", "'checkout %s %s'", "%", "(", "quiet", "and", "'-q'", "or", "...
35.846154
18.038462
def insert(self, parts, leaf_value, update=False): """Add a list of nodes into the tree. The list will be converted into a TreeMap (chain) and then merged with the current TreeMap. For example, this method would insert `['a','b','c']` as `{'a':{'b':{'c':{}}}}`. Argumen...
[ "def", "insert", "(", "self", ",", "parts", ",", "leaf_value", ",", "update", "=", "False", ")", ":", "tree", "=", "self", "if", "not", "parts", ":", "return", "tree", "cur", "=", "tree", "last", "=", "len", "(", "parts", ")", "-", "1", "for", "i...
29.527778
19.527778
def model_fn(features, labels, mode, params, config): """Builds the model function for use in an Estimator. Arguments: features: The input features for the Estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionar...
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ",", "config", ")", ":", "del", "labels", ",", "config", "# Set up the model's learnable parameters.", "logit_concentration", "=", "tf", ".", "compat", ".", "v1", ".", "get_variable",...
37.715447
19.520325
def iterator(self): """Iterate over models and chains for each variable.""" if self.combined: grouped_data = [[(0, datum)] for datum in self.data] skip_dims = {"chain"} else: grouped_data = [datum.groupby("chain") for datum in self.data] skip_dims ...
[ "def", "iterator", "(", "self", ")", ":", "if", "self", ".", "combined", ":", "grouped_data", "=", "[", "[", "(", "0", ",", "datum", ")", "]", "for", "datum", "in", "self", ".", "data", "]", "skip_dims", "=", "{", "\"chain\"", "}", "else", ":", "...
42.710526
15.736842
def clean(self): """Verifies that beginning date is before ending date.""" cleaned_data = super(DatasetUploadForm, self).clean() date_begin = self.cleaned_data.get('date_begin') date_end = self.cleaned_data.get('date_end') if date_end < date_begin: msg = u'End date sh...
[ "def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "DatasetUploadForm", ",", "self", ")", ".", "clean", "(", ")", "date_begin", "=", "self", ".", "cleaned_data", ".", "get", "(", "'date_begin'", ")", "date_end", "=", "self", ".", ...
45.5
11.8
def find_config_file(self, project=None, extension='.conf'): """Return the config file. :param project: "zvmsdk" :param extension: the type of the config file """ cfg_dirs = self._get_config_dirs() config_files = self._search_dirs(cfg_dirs, project, extension) ...
[ "def", "find_config_file", "(", "self", ",", "project", "=", "None", ",", "extension", "=", "'.conf'", ")", ":", "cfg_dirs", "=", "self", ".", "_get_config_dirs", "(", ")", "config_files", "=", "self", ".", "_search_dirs", "(", "cfg_dirs", ",", "project", ...
30.818182
18.727273
def ReadFile(self, definitions_registry, path): """Reads data type definitions from a file into the registry. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. path (str): path of the file to read from. """ with open(path, 'r') as file_objec...
[ "def", "ReadFile", "(", "self", ",", "definitions_registry", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "file_object", ":", "self", ".", "ReadFileObject", "(", "definitions_registry", ",", "file_object", ")" ]
37.4
16.6
def content_from_path(path, encoding='utf-8'): """Return the content of the specified file as a string. This function also supports loading resources from packages. """ if not os.path.isabs(path) and ':' in path: package, path = path.split(':', 1) content = resource_string(package, path...
[ "def", "content_from_path", "(", "path", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", "and", "':'", "in", "path", ":", "package", ",", "path", "=", "path", ".", "split", "(", "':'", ",",...
33.142857
12.642857
def add_arguments(self, parser): """ Entry point for subclassed commands to add custom arguments. """ subparsers = parser.add_subparsers(help='sub-command help', dest='command') add_parser = partial(_add_subparser, subparsers, parser) ...
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "subparsers", "=", "parser", ".", "add_subparsers", "(", "help", "=", "'sub-command help'", ",", "dest", "=", "'command'", ")", "add_parser", "=", "partial", "(", "_add_subparser", ",", "subparsers"...
40.166667
16.583333
def report_many(self, event_list, metadata=None, block=None): """ Reports all the given events to Alooma by formatting them properly and placing them in the buffer to be sent by the Sender instance :param event_list: A list of dicts / strings representing events :param metadata: ...
[ "def", "report_many", "(", "self", ",", "event_list", ",", "metadata", "=", "None", ",", "block", "=", "None", ")", ":", "failed_list", "=", "[", "]", "for", "index", ",", "event", "in", "enumerate", "(", "event_list", ")", ":", "queued_successfully", "=...
56.571429
22.857143
def rotate(name, **kwargs): ''' Add a log to the logadm configuration name : string alias for entryname kwargs : boolean|string|int optional additional flags and parameters ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} ...
[ "def", "rotate", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "# cleanup kwargs", "kwargs", "=", "salt", "."...
35.238806
20.671642
def init(self, dir_or_plan=None, backend_config=None, reconfigure=IsFlagged, backend=True, **kwargs): """ refer to https://www.terraform.io/docs/commands/init.html By default, this assumes you want to use backend config, and tries to init fresh. The flags -reconfigure and -...
[ "def", "init", "(", "self", ",", "dir_or_plan", "=", "None", ",", "backend_config", "=", "None", ",", "reconfigure", "=", "IsFlagged", ",", "backend", "=", "True", ",", "*", "*", "kwargs", ")", ":", "options", "=", "kwargs", "options", "[", "'backend_con...
47.88
19.72
def on_sigchld(self, _signum, _unused_frame): """Invoked when a child sends up an SIGCHLD signal. :param int _signum: The signal that was invoked :param frame _unused_frame: The frame that was interrupted """ LOGGER.info('SIGCHLD received from child') if not self.active...
[ "def", "on_sigchld", "(", "self", ",", "_signum", ",", "_unused_frame", ")", ":", "LOGGER", ".", "info", "(", "'SIGCHLD received from child'", ")", "if", "not", "self", ".", "active_processes", "(", "False", ")", ":", "LOGGER", ".", "info", "(", "'Stopping w...
42.166667
16.333333
def get_all_handleable_roots(self): """ Get list of all handleable devices, return only those that represent root nodes within the filtered device tree. """ nodes = self.get_device_tree() return [node.device for node in sorted(nodes.values(), key=DevNode._...
[ "def", "get_all_handleable_roots", "(", "self", ")", ":", "nodes", "=", "self", ".", "get_device_tree", "(", ")", "return", "[", "node", ".", "device", "for", "node", "in", "sorted", "(", "nodes", ".", "values", "(", ")", ",", "key", "=", "DevNode", "....
44
13.8
def read_metrics_file(path: str) -> List[Dict[str, Any]]: """ Reads lines metrics file and returns list of mappings of key and values. :param path: File to read metric values from. :return: Dictionary of metric names (e.g. perplexity-train) mapping to a list of values. """ with open(path) as fi...
[ "def", "read_metrics_file", "(", "path", ":", "str", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "with", "open", "(", "path", ")", "as", "fin", ":", "metrics", "=", "[", "parse_metrics_line", "(", "i", ",", "line", ".", ...
42.1
23.7
async def get(self, uid: int, cached_msg: CachedMessage = None, requirement: FetchRequirement = FetchRequirement.METADATA) \ -> Optional[MessageT]: """Return the message with the given UID. Args: uid: The message UID. cached_msg: The last known cach...
[ "async", "def", "get", "(", "self", ",", "uid", ":", "int", ",", "cached_msg", ":", "CachedMessage", "=", "None", ",", "requirement", ":", "FetchRequirement", "=", "FetchRequirement", ".", "METADATA", ")", "->", "Optional", "[", "MessageT", "]", ":", "..."...
32.133333
22
def hybrid_meco_velocity(m1, m2, chi1, chi2, qm1=None, qm2=None): """Return the velocity of the hybrid MECO Parameters ---------- m1 : float Mass of the primary object in solar masses. m2 : float Mass of the secondary object in solar masses. chi1: float Dimensionless spi...
[ "def", "hybrid_meco_velocity", "(", "m1", ",", "m2", ",", "chi1", ",", "chi2", ",", "qm1", "=", "None", ",", "qm2", "=", "None", ")", ":", "if", "qm1", "is", "None", ":", "qm1", "=", "1", "if", "qm2", "is", "None", ":", "qm2", "=", "1", "# Set ...
30.837838
21.216216
def rem_or(self, start, end, instr, target=None, include_beyond_target=False): """ Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be spe...
[ "def", "rem_or", "(", "self", ",", "start", ",", "end", ",", "instr", ",", "target", "=", "None", ",", "include_beyond_target", "=", "False", ")", ":", "assert", "(", "start", ">=", "0", "and", "end", "<=", "len", "(", "self", ".", "code", ")", "an...
35.815789
16.131579
def add_agent(self, overall_index=None, team_index=None): """ Creates the agent using self.agent_class and adds it to the index manager. :param overall_index: The index of the bot in the config file if it already exists. :param team_index: The index of the team to place the agent in ...
[ "def", "add_agent", "(", "self", ",", "overall_index", "=", "None", ",", "team_index", "=", "None", ")", ":", "if", "overall_index", "is", "None", ":", "if", "not", "self", ".", "index_manager", ".", "has_free_slots", "(", ")", ":", "return", "overall_inde...
49.85
25.45
def add_info_widget(self, widget): ''' add right panel widget ''' if not self.screen: self.log.debug("No screen instance to add widget") else: self.screen.add_info_widget(widget)
[ "def", "add_info_widget", "(", "self", ",", "widget", ")", ":", "if", "not", "self", ".", "screen", ":", "self", ".", "log", ".", "debug", "(", "\"No screen instance to add widget\"", ")", "else", ":", "self", ".", "screen", ".", "add_info_widget", "(", "w...
36.833333
12.833333
def _validate_auths(self, path, obj, app): """ make sure that apiKey and basicAuth are empty list in Operation object. """ errs = [] for k, v in six.iteritems(obj.authorizations or {}): if k not in app.raw.authorizations: errs.append('auth {0} not fou...
[ "def", "_validate_auths", "(", "self", ",", "path", ",", "obj", ",", "app", ")", ":", "errs", "=", "[", "]", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ".", "authorizations", "or", "{", "}", ")", ":", "if", "k", "not", "in...
39.285714
21.928571
def immediateAssignmentExtended(StartingTime_presence=0): """IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19""" a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x39) # 00111001 d = PageModeAndSpareHalfOctets() f = ChannelDescription() g = RequestReference() h = TimingAdvance(...
[ "def", "immediateAssignmentExtended", "(", "StartingTime_presence", "=", "0", ")", ":", "a", "=", "L2PseudoLength", "(", ")", "b", "=", "TpPd", "(", "pd", "=", "0x6", ")", "c", "=", "MessageType", "(", "mesType", "=", "0x39", ")", "# 00111001", "d", "=",...
32.941176
12.470588
def vcmp_host(opt_vcmp_host, opt_username, opt_password, opt_port): '''vcmp fixture''' m = ManagementRoot( opt_vcmp_host, opt_username, opt_password, port=opt_port) return m
[ "def", "vcmp_host", "(", "opt_vcmp_host", ",", "opt_username", ",", "opt_password", ",", "opt_port", ")", ":", "m", "=", "ManagementRoot", "(", "opt_vcmp_host", ",", "opt_username", ",", "opt_password", ",", "port", "=", "opt_port", ")", "return", "m" ]
37.8
23
def update(self, scope, at=0): """Update scope. Add another scope to this one. Args: scope (Scope): Scope object Kwargs: at (int): Level to update """ if hasattr(scope, '_mixins') and not at: self._mixins.update(scope._mixins) self[at][...
[ "def", "update", "(", "self", ",", "scope", ",", "at", "=", "0", ")", ":", "if", "hasattr", "(", "scope", ",", "'_mixins'", ")", "and", "not", "at", ":", "self", ".", "_mixins", ".", "update", "(", "scope", ".", "_mixins", ")", "self", "[", "at",...
40.333333
12.5
def makeairplantloop(data, commdct): """make the edges for the airloop and the plantloop""" anode = "epnode" endnode = "EndNode" # in plantloop get: # demand inlet, outlet, branchlist # supply inlet, outlet, branchlist plantloops = loops.plantloopfields(data, commdct) # splitter...
[ "def", "makeairplantloop", "(", "data", ",", "commdct", ")", ":", "anode", "=", "\"epnode\"", "endnode", "=", "\"EndNode\"", "# in plantloop get:", "# demand inlet, outlet, branchlist", "# supply inlet, outlet, branchlist", "plantloops", "=", "loops", ".", "plantloo...
38.705882
15.854671
def ensure_table(self, cls): """Ensure table's existence - as per the gludb spec.""" cur = self._conn().cursor() table_name = cls.get_table_name() index_names = cls.index_names() or [] cols = ['id text primary key', 'value text'] for name in index_names: col...
[ "def", "ensure_table", "(", "self", ",", "cls", ")", ":", "cur", "=", "self", ".", "_conn", "(", ")", ".", "cursor", "(", ")", "table_name", "=", "cls", ".", "get_table_name", "(", ")", "index_names", "=", "cls", ".", "index_names", "(", ")", "or", ...
28.52
18.48
def with_name(self, name): """Sets the name scope for future operations.""" with self.g.as_default(), scopes.var_and_name_scope((name, None)) as ( name_scope, var_scope): return Layer(copy=self, name=self._name, scope=(name_scope, var_scope))
[ "def", "with_name", "(", "self", ",", "name", ")", ":", "with", "self", ".", "g", ".", "as_default", "(", ")", ",", "scopes", ".", "var_and_name_scope", "(", "(", "name", ",", "None", ")", ")", "as", "(", "name_scope", ",", "var_scope", ")", ":", "...
52
18.8
def element_to_extension_element(element): """ Convert an element into a extension element :param element: The element instance :return: An extension element instance """ exel = ExtensionElement(element.c_tag, element.c_namespace, text=element.text) exel.attrib...
[ "def", "element_to_extension_element", "(", "element", ")", ":", "exel", "=", "ExtensionElement", "(", "element", ".", "c_tag", ",", "element", ".", "c_namespace", ",", "text", "=", "element", ".", "text", ")", "exel", ".", "attributes", ".", "update", "(", ...
32.666667
17.833333
def match_file(self, file, separators=None): """ Matches the file to this path-spec. *file* (:class:`str`) is the file path to be matched against :attr:`self.patterns <PathSpec.patterns>`. *separators* (:class:`~collections.abc.Collection` of :class:`str`) optionally contains the path separators to normal...
[ "def", "match_file", "(", "self", ",", "file", ",", "separators", "=", "None", ")", ":", "norm_file", "=", "util", ".", "normalize_file", "(", "file", ",", "separators", "=", "separators", ")", "return", "util", ".", "match_file", "(", "self", ".", "patt...
37.666667
18.733333
def __get_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return channel
[ "def", "__get_channel", "(", "self", ")", ":", "if", "self", ".", "__config", ".", "get", "(", "WebDriverManager", ".", "ENABLE_THREADING_SUPPORT", ",", "False", ")", ":", "channel", "=", "current_thread", "(", ")", ".", "ident", "else", ":", "channel", "=...
32
21.5
def addFailure(self, test, err): """ registers a test as failure :param test: test to register :param err: error the test gave """ super().addFailure(test, err) self.test_info(test) self._call_test_results('addFailure', test, err)
[ "def", "addFailure", "(", "self", ",", "test", ",", "err", ")", ":", "super", "(", ")", ".", "addFailure", "(", "test", ",", "err", ")", "self", ".", "test_info", "(", "test", ")", "self", ".", "_call_test_results", "(", "'addFailure'", ",", "test", ...
28.6
8.8
def _describe(node, parent): """Generate lines describing the given `node` tuple. This is the recursive back-end that powers ``describe()``. With its extra ``parent`` parameter, this routine remembers the nearest non-placeholder ancestor so that it can compare it against the actual value of the ``...
[ "def", "_describe", "(", "node", ",", "parent", ")", ":", "name", ",", "logger", ",", "children", "=", "node", "is_placeholder", "=", "isinstance", "(", "logger", ",", "logging", ".", "PlaceHolder", ")", "if", "is_placeholder", ":", "yield", "'<--[%s]'", "...
35.9375
16.171875
def create_resource(output_model, rtype, unique, links, existing_ids=None, id_helper=None): ''' General-purpose routine to create a new resource in the output model, based on data provided output_model - Versa connection to model to be updated rtype - Type IRI for the new resource, set wit...
[ "def", "create_resource", "(", "output_model", ",", "rtype", ",", "unique", ",", "links", ",", "existing_ids", "=", "None", ",", "id_helper", "=", "None", ")", ":", "if", "isinstance", "(", "id_helper", ",", "str", ")", ":", "idg", "=", "idgen", "(", "...
50.266667
29.466667
def get_app_state(app_id): """ get app state """ try: conn = get_conn() c = conn.cursor() c.execute("SELECT state FROM app WHERE id='{0}' ".format(app_id)) result = c.fetchone() conn.close() if result: state = result[0] return stat...
[ "def", "get_app_state", "(", "app_id", ")", ":", "try", ":", "conn", "=", "get_conn", "(", ")", "c", "=", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "\"SELECT state FROM app WHERE id='{0}' \"", ".", "format", "(", "app_id", ")", ")", "res...
22.368421
19.526316
def get(self, key, raw=False, fallback=None): """ Get a string value from the componnet. Arguments: key - the key to retrieve raw - Control whether the value is interpolated or returned raw. By default, values are interpolated. fallback - The return value ...
[ "def", "get", "(", "self", ",", "key", ",", "raw", "=", "False", ",", "fallback", "=", "None", ")", ":", "return", "self", ".", "_component", ".", "get", "(", "key", ",", "raw", "=", "raw", ",", "fallback", "=", "fallback", ")" ]
38.181818
16
def TypeFactory(v): """Ensure `v` is a valid Type. This function is used to convert user-specified types into internal types for the verification engine. It allows Type subclasses, Type subclass instances, Python type, and user-defined classes to be passed. Returns an instance of the type of `v`....
[ "def", "TypeFactory", "(", "v", ")", ":", "if", "v", "is", "None", ":", "return", "Nothing", "(", ")", "elif", "issubclass", "(", "type", "(", "v", ")", ",", "Type", ")", ":", "return", "v", "elif", "issubclass", "(", "v", ",", "Type", ")", ":", ...
30.238095
20
def filter_tagged_lines(tagged_lines, include_tags=None, exclude_tags=None): r""" Return iterable of tagged lines where the tags all start with one of the include_tags prefixes >>> filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')]) <generator object filter_ta...
[ "def", "filter_tagged_lines", "(", "tagged_lines", ",", "include_tags", "=", "None", ",", "exclude_tags", "=", "None", ")", ":", "include_tags", "=", "(", "include_tags", ",", ")", "if", "isinstance", "(", "include_tags", ",", "str", ")", "else", "include_tags...
58.272727
31.181818
def byName(cls, name, recurse=True, default=None): """ Returns the addon whose name matches the inputted name. If the optional recurse flag is set to True, then all the base classes will be searched for the given addon as well. If no addon is found, the default is returned. ...
[ "def", "byName", "(", "cls", ",", "name", ",", "recurse", "=", "True", ",", "default", "=", "None", ")", ":", "cls", ".", "initAddons", "(", ")", "prop", "=", "'_{0}__addons'", ".", "format", "(", "cls", ".", "__name__", ")", "try", ":", "return", ...
37.809524
14.380952
def _set_show_bare_metal_state(self, v, load=False): """ Setter method for show_bare_metal_state, mapped from YANG variable /brocade_preprovision_rpc/show_bare_metal_state (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_bare_metal_state is considered as a priv...
[ "def", "_set_show_bare_metal_state", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
83.727273
39.863636
def remove_elements_with_source(source, field): """Remove all elements matching ``source`` in ``field``.""" return freeze( [element for element in field if element.get('source', '').lower() != source] )
[ "def", "remove_elements_with_source", "(", "source", ",", "field", ")", ":", "return", "freeze", "(", "[", "element", "for", "element", "in", "field", "if", "element", ".", "get", "(", "'source'", ",", "''", ")", ".", "lower", "(", ")", "!=", "source", ...
43.6
21.8
def _write_scalar(self, name:str, scalar_value, iteration:int)->None: "Writes single scalar value to Tensorboard." tag = self.metrics_root + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
[ "def", "_write_scalar", "(", "self", ",", "name", ":", "str", ",", "scalar_value", ",", "iteration", ":", "int", ")", "->", "None", ":", "tag", "=", "self", ".", "metrics_root", "+", "name", "self", ".", "tbwriter", ".", "add_scalar", "(", "tag", "=", ...
62.5
23.5
def update_checks(self, check_configs): """ Maintains the values in the `checks` attribute's dictionary. Each key in the dictionary is a port, and each value is a nested dictionary mapping each check's name to the Check instance. This method makes sure the attribute reflects al...
[ "def", "update_checks", "(", "self", ",", "check_configs", ")", ":", "for", "check_name", ",", "check_config", "in", "six", ".", "iteritems", "(", "check_configs", ")", ":", "if", "check_name", "==", "\"interval\"", ":", "continue", "for", "port", "in", "sel...
42.538462
17.384615
def _drop_hstore_required(self, table_name, field, key): """Drops a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_drop.format( table=self.quote_name(table_name), ...
[ "def", "_drop_hstore_required", "(", "self", ",", "table_name", ",", "field", ",", "key", ")", ":", "name", "=", "self", ".", "_required_constraint_name", "(", "table_name", ",", "field", ",", "key", ")", "sql", "=", "self", ".", "sql_hstore_required_drop", ...
34.272727
15.636364
def pipe_xpathfetchpage(context=None, _INPUT=None, conf=None, **kwargs): """A source that fetches the content of a given website as DOM nodes or a string. Loopable. context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : dict URL -- url object cont...
[ "def", "pipe_xpathfetchpage", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conf", "=", "DotDict", "(", "conf", ")", "urls", "=", "utils", ".", "listize", "(", "conf", "[", "'...
34.484848
19.393939
async def init(self, *args, dialect=None, **kwargs): """ :param args: args for pool :param dialect: sqlalchemy postgres dialect :param kwargs: kwargs for pool :return: None """ self.__pool = await create_pool(*args, dialect=dialect, **kwargs)
[ "async", "def", "init", "(", "self", ",", "*", "args", ",", "dialect", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__pool", "=", "await", "create_pool", "(", "*", "args", ",", "dialect", "=", "dialect", ",", "*", "*", "kwargs", ...
36.375
10.375
def utctimetuple(self): "Return UTC time tuple compatible with time.gmtime()." offset = self.utcoffset() if offset: self -= offset y, m, d = self.year, self.month, self.day hh, mm, ss = self.hour, self.minute, self.second return _build_struct_time(y, m, d, hh,...
[ "def", "utctimetuple", "(", "self", ")", ":", "offset", "=", "self", ".", "utcoffset", "(", ")", "if", "offset", ":", "self", "-=", "offset", "y", ",", "m", ",", "d", "=", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day", ...
40.5
15.5
def vertex_normals(vertices, faces): """Calculates the normals of a triangular mesh""" def normalize_v3(arr): ''' Normalize a numpy array of 3 component vectors shape=(n,3) ''' lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2) arr /= lens[:, np.newaxis] tris = vertices[fac...
[ "def", "vertex_normals", "(", "vertices", ",", "faces", ")", ":", "def", "normalize_v3", "(", "arr", ")", ":", "''' Normalize a numpy array of 3 component vectors shape=(n,3) '''", "lens", "=", "np", ".", "sqrt", "(", "arr", "[", ":", ",", "0", "]", "**", "2",...
34.222222
19.277778
def make_handle_URL(self, handle, indices=None, overwrite=None, other_url=None): ''' Create the URL for a HTTP request (URL + query string) to request a specific handle from the Handle Server. :param handle: The handle to access. :param indices: Optional. A list of integers or s...
[ "def", "make_handle_URL", "(", "self", ",", "handle", ",", "indices", "=", "None", ",", "overwrite", "=", "None", ",", "other_url", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "'make_handle_URL...'", ")", "separator", "=", "'?'", "if", "other_url",...
41
22.348837
def find_directories(root,fullpath=True): ''' Return directories at one level specified by user (not recursive) ''' directories = [] for item in os.listdir(root): # Don't include hidden directories if not re.match("^[.]",item): if os.path.isdir(os.path.join(root, item...
[ "def", "find_directories", "(", "root", ",", "fullpath", "=", "True", ")", ":", "directories", "=", "[", "]", "for", "item", "in", "os", ".", "listdir", "(", "root", ")", ":", "# Don't include hidden directories", "if", "not", "re", ".", "match", "(", "\...
34
16.133333
def description(self): """ Get a string describing the HID descriptor. """ return \ """HIDDevice: {} | {:x}:{:x} | {} | {} | {} release_number: {} usage_page: {} usage: {} interface_number: {}\ """.format(self.path, self.vendor_id, self.product_i...
[ "def", "description", "(", "self", ")", ":", "return", "\"\"\"HIDDevice:\n {} | {:x}:{:x} | {} | {} | {}\n release_number: {}\n usage_page: {}\n usage: {}\n interface_number: {}\\\n\"\"\"", ".", "format", "(", "self", ".", "path", ",", "self", ".", "vendor_id", ","...
23.954545
12.318182
def to_list(self): """ Set the current encoder output to :class:`giraffez.Row` objects and returns the cursor. This is the default value so it is not necessary to select this unless the encoder settings have been changed already. """ self.conn.set_encoding(ROW_EN...
[ "def", "to_list", "(", "self", ")", ":", "self", ".", "conn", ".", "set_encoding", "(", "ROW_ENCODING_LIST", ")", "self", ".", "processor", "=", "lambda", "x", ",", "y", ":", "Row", "(", "x", ",", "y", ")", "return", "self" ]
39.1
16.7
def _get_data(self) -> BaseFrameManager: """Perform the map step Returns: A BaseFrameManager object. """ def iloc(partition, row_internal_indices, col_internal_indices): return partition.iloc[row_internal_indices, col_internal_indices] masked_data = sel...
[ "def", "_get_data", "(", "self", ")", "->", "BaseFrameManager", ":", "def", "iloc", "(", "partition", ",", "row_internal_indices", ",", "col_internal_indices", ")", ":", "return", "partition", ".", "iloc", "[", "row_internal_indices", ",", "col_internal_indices", ...
31.277778
19.277778
def make_supercell(system, matrix, supercell=[1, 1, 1]): """ Return a supercell. This functions takes the input unitcell and creates a supercell of it that is returned as a new :class:`pywindow.molecular.MolecularSystem`. Parameters ---------- system : :attr:`pywindow.molecular.MolecularSy...
[ "def", "make_supercell", "(", "system", ",", "matrix", ",", "supercell", "=", "[", "1", ",", "1", ",", "1", "]", ")", ":", "user_supercell", "=", "[", "[", "1", ",", "supercell", "[", "0", "]", "]", ",", "[", "1", ",", "supercell", "[", "1", "]...
34.071429
23.357143
def option(self, key, value): """Adds an input option for the underlying data source. You can set the following option(s) for reading files: * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps in the JSON/CSV datasources or partition valu...
[ "def", "option", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "_jreader", "=", "self", ".", "_jreader", ".", "option", "(", "key", ",", "to_str", "(", "value", ")", ")", "return", "self" ]
49.5
24.5
def parse(cls, buff, offset): """ Given a buffer and offset, returns the parsed value and new offset. Parses the ``size_primitive`` first to determine how many more bytes to consume to extract the value. """ size, offset = cls.size_primitive.parse(buff, offset) i...
[ "def", "parse", "(", "cls", ",", "buff", ",", "offset", ")", ":", "size", ",", "offset", "=", "cls", ".", "size_primitive", ".", "parse", "(", "buff", ",", "offset", ")", "if", "size", "==", "-", "1", ":", "return", "None", ",", "offset", "var_stru...
31.055556
18.944444
def prepare_env(org): """ Example shows how to configure environment from scratch """ # Add services key_service = org.service(type='builtin:cobalt_secure_store', name='Keystore') wf_service = org.service(type='builtin:workflow_service', name='Workflow', parameters='{}') # Add services to environm...
[ "def", "prepare_env", "(", "org", ")", ":", "# Add services", "key_service", "=", "org", ".", "service", "(", "type", "=", "'builtin:cobalt_secure_store'", ",", "name", "=", "'Keystore'", ")", "wf_service", "=", "org", ".", "service", "(", "type", "=", "'bui...
31.225806
16.612903
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs): """ Try and return page content in the requested format using selenium """ try: # **TODO**: Find what exception this will throw and catch it and call # self.driver.execute_script("w...
[ "def", "_get_site", "(", "self", ",", "url", ",", "headers", ",", "cookies", ",", "timeout", ",", "driver_args", ",", "driver_kwargs", ")", ":", "try", ":", "# **TODO**: Find what exception this will throw and catch it and call", "# self.driver.execute_script(\"window.sto...
41.025641
21.282051
def make_tmp_dir(prefix): """ Create a temporary directory :param prefix(str): Name prefix for the new directory :return: a string with the resulting name of new directory """ # Time in ISO8601 format now = datetime.now().isoformat() # A random UUID is appended to the output directory...
[ "def", "make_tmp_dir", "(", "prefix", ")", ":", "# Time in ISO8601 format", "now", "=", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "# A random UUID is appended to the output directory in order to", "# avoid name collisions", "f_uuid", "=", "uuid", "."...
30.538462
21.923077
def get_chron_var(temp_sheet, start_row): """ Capture all the vars in the chron sheet (for json-ld output) :param obj temp_sheet: :param int start_row: :return: (list of dict) column data """ col_dict = OrderedDict() out_list = [] column = 1 while (temp_sheet.cell_value(start_ro...
[ "def", "get_chron_var", "(", "temp_sheet", ",", "start_row", ")", ":", "col_dict", "=", "OrderedDict", "(", ")", "out_list", "=", "[", "]", "column", "=", "1", "while", "(", "temp_sheet", ".", "cell_value", "(", "start_row", ",", "0", ")", "!=", "''", ...
31.923077
15.846154
def _rfind(expr, sub, start=0, end=None): """ Return highest indexes in each strings in the sequence or scalar where the substring is fully contained between [start:end]. Return -1 on failure. Equivalent to standard str.rfind(). :param expr: :param sub: :param start: :param end: :re...
[ "def", "_rfind", "(", "expr", ",", "sub", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "return", "_string_op", "(", "expr", ",", "RFind", ",", "output_type", "=", "types", ".", "int64", ",", "_sub", "=", "sub", ",", "_start", "=", "...
30.333333
19.666667
def match_tokens(expected_tokens): """Generate a grammar function that will match 'expected_tokens' only.""" if isinstance(expected_tokens, Token): # Match a single token. def _grammar_func(tokens): try: next_token = next(iter(tokens)) except StopIteration...
[ "def", "match_tokens", "(", "expected_tokens", ")", ":", "if", "isinstance", "(", "expected_tokens", ",", "Token", ")", ":", "# Match a single token.", "def", "_grammar_func", "(", "tokens", ")", ":", "try", ":", "next_token", "=", "next", "(", "iter", "(", ...
36.307692
15.423077
def current_state_str(self): """Return string representation of the current state of the sensor.""" if self.sample_ok: msg = '' temperature = self._get_value_opc_attr('temperature') if temperature is not None: msg += 'Temp: %s ºC, ' % temperature ...
[ "def", "current_state_str", "(", "self", ")", ":", "if", "self", ".", "sample_ok", ":", "msg", "=", "''", "temperature", "=", "self", ".", "_get_value_opc_attr", "(", "'temperature'", ")", "if", "temperature", "is", "not", "None", ":", "msg", "+=", "'Temp:...
43.526316
12.578947
def convert_clip(params, w_name, scope_name, inputs, layers, weights, names): """ Convert clip operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary wi...
[ "def", "convert_clip", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting clip ...'", ")", "if", "params", "[", "'min'", "]", "==", "0", ":", "print", "(", "...
33.84
15.2
def parse_ma_file(seq_obj, in_file): """ read seqs.ma file and create dict with sequence object """ name = "" index = 1 total = defaultdict(int) with open(in_file) as handle_in: line = handle_in.readline().strip() cols = line.split("\t") samples = cols[2:] ...
[ "def", "parse_ma_file", "(", "seq_obj", ",", "in_file", ")", ":", "name", "=", "\"\"", "index", "=", "1", "total", "=", "defaultdict", "(", "int", ")", "with", "open", "(", "in_file", ")", "as", "handle_in", ":", "line", "=", "handle_in", ".", "readlin...
32.172414
9.206897
def tick(self): """ Advances time in the game. Use this once all "choices" have been submitted for the current game state using the other methods. """ if self.state == AuctionState.NOMINATE: # if no nominee submitted, exception if self.nominee is None: ...
[ "def", "tick", "(", "self", ")", ":", "if", "self", ".", "state", "==", "AuctionState", ".", "NOMINATE", ":", "# if no nominee submitted, exception", "if", "self", ".", "nominee", "is", "None", ":", "raise", "InvalidActionError", "(", "\"Tick was invoked during no...
52.55102
18.632653
def service_delete(service_id=None, name=None, profile=None, **connection_args): ''' Delete a service from Keystone service catalog CLI Examples: .. code-block:: bash salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.service_delete name=nova ''' ...
[ "def", "service_delete", "(", "service_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "name", ":",...
34.764706
24.764706
def event_transition(self, event_cls, event_type, ion_type, value): """Returns an ion event event_transition that yields to another co-routine.""" annotations = self.annotations or () depth = self.depth whence = self.whence if ion_type is IonType.SYMBOL: if not annot...
[ "def", "event_transition", "(", "self", ",", "event_cls", ",", "event_type", ",", "ion_type", ",", "value", ")", ":", "annotations", "=", "self", ".", "annotations", "or", "(", ")", "depth", "=", "self", ".", "depth", "whence", "=", "self", ".", "whence"...
42.666667
20.333333
def get_renderer_context(self): """ Returns a dict that is passed through to Renderer.render(), as the `renderer_context` keyword argument. """ # Note: Additionally 'response' will also be added to the context, # by the Response object. return { ...
[ "def", "get_renderer_context", "(", "self", ")", ":", "# Note: Additionally 'response' will also be added to the context,", "# by the Response object.", "return", "{", "'view'", ":", "self", ",", "'args'", ":", "getattr", "(", "self", ",", "'args'", ",", "(", ")",...
39.714286
15.285714
def format_time(time): """ Formats the given time into HH:MM:SS """ h, r = divmod(time / 1000, 3600) m, s = divmod(r, 60) return "%02d:%02d:%02d" % (h, m, s)
[ "def", "format_time", "(", "time", ")", ":", "h", ",", "r", "=", "divmod", "(", "time", "/", "1000", ",", "3600", ")", "m", ",", "s", "=", "divmod", "(", "r", ",", "60", ")", "return", "\"%02d:%02d:%02d\"", "%", "(", "h", ",", "m", ",", "s", ...
28.166667
13.166667
def from_csv(self, label_column='labels'): ''' Read dataset from csv. ''' df = pd.read_csv(self.path, header=0) X = df.loc[:, df.columns != label_column].to_dict('records') X = map_dict_list(X, if_func=lambda k, v: v and math.isfinite(v)) y = list(df[label_column]...
[ "def", "from_csv", "(", "self", ",", "label_column", "=", "'labels'", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "self", ".", "path", ",", "header", "=", "0", ")", "X", "=", "df", ".", "loc", "[", ":", ",", "df", ".", "columns", "!=", "la...
37.777778
17.555556
def add_member(self, address, **kwargs): """ Add a member to a group. All Fiesta membership options can be passed in as keyword arguments. Some valid options include: - `group_name`: Since each member can access a group using their own name, you can override the `grou...
[ "def", "add_member", "(", "self", ",", "address", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'membership/%s'", "%", "self", ".", "id", "kwargs", "[", "\"address\"", "]", "=", "address", "if", "\"group_name\"", "not", "in", "kwargs", "and", "self", ...
40.147059
22.323529
def evaluate_report(report): """Iterate over validation errors.""" if report["valid"]: return for warn in report["warnings"]: LOGGER.warning(warn) # We only ever test one table at a time. for err in report["tables"][0]["errors"]: LOGGER.error(e...
[ "def", "evaluate_report", "(", "report", ")", ":", "if", "report", "[", "\"valid\"", "]", ":", "return", "for", "warn", "in", "report", "[", "\"warnings\"", "]", ":", "LOGGER", ".", "warning", "(", "warn", ")", "# We only ever test one table at a time.", "for"...
39.7
10.4
def get_notify_observers_kwargs(self): """ Return the mapping between the metrics call and the iterated variables. Return ---------- notify_observers_kwargs: dict, the mapping between the iterated variables. """ return {'x_new': self._linear.adj_op(sel...
[ "def", "get_notify_observers_kwargs", "(", "self", ")", ":", "return", "{", "'x_new'", ":", "self", ".", "_linear", ".", "adj_op", "(", "self", ".", "_x_new", ")", ",", "'z_new'", ":", "self", ".", "_z", ",", "'idx'", ":", "self", ".", "idx", "}" ]
33.727273
14.181818
def sync(self, hooks=True, async_hooks=True): """Synchronize user repositories. :param bool hooks: True for syncing hooks. :param bool async_hooks: True for sending of an asynchronous task to sync hooks. .. note:: Syncing happens from GitHu...
[ "def", "sync", "(", "self", ",", "hooks", "=", "True", ",", "async_hooks", "=", "True", ")", ":", "active_repos", "=", "{", "}", "github_repos", "=", "{", "repo", ".", "id", ":", "repo", "for", "repo", "in", "self", ".", "api", ".", "repositories", ...
37.886792
18.075472
def set_file_notice(self, doc, text): """Raises OrderError if no package or file defined. Raises SPDXValueError if not free form text. Raises CardinalityError if more than one. """ if self.has_package(doc) and self.has_file(doc): if not self.file_notice_set: ...
[ "def", "set_file_notice", "(", "self", ",", "doc", ",", "text", ")", ":", "if", "self", ".", "has_package", "(", "doc", ")", "and", "self", ".", "has_file", "(", "doc", ")", ":", "if", "not", "self", ".", "file_notice_set", ":", "self", ".", "file_no...
42.0625
11.6875
def CanSetRoleTo(self, Role): """Checks if the new role can be applied to the member. :Parameters: Role : `enums`.chatMemberRole* New chat member role. :return: True if the new role can be applied, False otherwise. :rtype: bool """ t = self._Owner....
[ "def", "CanSetRoleTo", "(", "self", ",", "Role", ")", ":", "t", "=", "self", ".", "_Owner", ".", "_Alter", "(", "'CHATMEMBER'", ",", "self", ".", "Id", ",", "'CANSETROLETO'", ",", "Role", ",", "'ALTER CHATMEMBER CANSETROLETO'", ")", "return", "(", "chop", ...
35.769231
17.461538
def _update_pandas_kwargs(self, dtype=False, parse_dates=True, kwargs= {}): """ Construct args suitable for pandas read_csv :param dtype: If true, create a dtype type map. Otherwise, pass argument value to read_csv :param parse_dates: If true, create a list of date/time columns for the parse_da...
[ "def", "_update_pandas_kwargs", "(", "self", ",", "dtype", "=", "False", ",", "parse_dates", "=", "True", ",", "kwargs", "=", "{", "}", ")", ":", "from", "datetime", "import", "datetime", ",", "time", ",", "date", "type_map", "=", "{", "None", ":", "No...
33.055556
25.166667
def createContactItem(self, person, address): """ Create a new L{PostalAddress} associated with the given person based on the given postal address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type addres...
[ "def", "createContactItem", "(", "self", ",", "person", ",", "address", ")", ":", "if", "address", ":", "return", "PostalAddress", "(", "store", "=", "person", ".", "store", ",", "person", "=", "person", ",", "address", "=", "address", ")" ]
35.736842
19.842105
def GET_subdomain_ops(self, path_info, txid): """ Get all subdomain operations processed in a given transaction. Returns the list of subdomains on success (can be empty) Returns 502 on failure to get subdomains """ blockstackd_url = get_blockstackd_url() subdomain...
[ "def", "GET_subdomain_ops", "(", "self", ",", "path_info", ",", "txid", ")", ":", "blockstackd_url", "=", "get_blockstackd_url", "(", ")", "subdomain_ops", "=", "None", "try", ":", "subdomain_ops", "=", "blockstackd_client", ".", "get_subdomain_ops_at_txid", "(", ...
50
28.111111
def canvases_with(drawable): """ Return a list of all canvases where `drawable` has been painted. Note: This function is inefficient because it inspects all objects on all canvases, recursively. Avoid calling it if you have a large number of canvases and primitives. """ return [...
[ "def", "canvases_with", "(", "drawable", ")", ":", "return", "[", "c", "for", "c", "in", "ROOT", ".", "gROOT", ".", "GetListOfCanvases", "(", ")", "if", "drawable", "in", "find_all_primitives", "(", "c", ")", "]" ]
40.3
18.5
def datetime(self, to_timezone=None, naive=False): """Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo...
[ "def", "datetime", "(", "self", ",", "to_timezone", "=", "None", ",", "naive", "=", "False", ")", ":", "if", "to_timezone", ":", "dt", "=", "self", ".", "datetime", "(", ")", ".", "astimezone", "(", "pytz", ".", "timezone", "(", "to_timezone", ")", "...
35.727273
17
def write(self, path=None, *args, **kwargs): """ Perform formatting and write the formatted string to a file or stdout. Optional arguments can be used to format the editor's contents. If no file path is given, prints to standard output. Args: path (str): Full file p...
[ "def", "write", "(", "self", ",", "path", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "path", "is", "None", ":", "print", "(", "self", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "else", ":"...
39.941176
21
def returner(ret): ''' Return data to a remote carbon server using the text metric protocol Each metric will look like:: [module].[function].[minion_id].[metric path [...]].[metric name] ''' opts = _get_options(ret) metric_base = ret['fun'] # Strip the hostname from the carbon bas...
[ "def", "returner", "(", "ret", ")", ":", "opts", "=", "_get_options", "(", "ret", ")", "metric_base", "=", "ret", "[", "'fun'", "]", "# Strip the hostname from the carbon base if we are returning from virt", "# module since then we will get stable metric bases even if the VM is...
32.052632
23.947368
async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout): """Send an RPC on behalf of a client. See :meth:`AbstractDeviceAdapter.send_rpc`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will ...
[ "async", "def", "send_rpc", "(", "self", ",", "client_id", ",", "conn_string", ",", "address", ",", "rpc_id", ",", "payload", ",", "timeout", ")", ":", "conn_id", "=", "self", ".", "_client_connection", "(", "client_id", ",", "conn_string", ")", "return", ...
46.852941
24.970588
def handle_read(self): """ Handle the 'channel readable' state. E.g. read from a socket. """ with self.lock: logger.debug("handle_read()") if self._eof or self._socket is None: return if self._state == "tls-handshake": w...
[ "def", "handle_read", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "logger", ".", "debug", "(", "\"handle_read()\"", ")", "if", "self", ".", "_eof", "or", "self", ".", "_socket", "is", "None", ":", "return", "if", "self", ".", "_state", "...
43.185185
12.555556
def get_settings(editor_override=None): """Utility function to retrieve settings.py values with defaults""" flavor = getattr(settings, "DJANGO_WYSIWYG_FLAVOR", "yui") if editor_override is not None: flavor = editor_override return { "DJANGO_WYSIWYG_MEDIA_URL": getattr(settings, "DJANGO...
[ "def", "get_settings", "(", "editor_override", "=", "None", ")", ":", "flavor", "=", "getattr", "(", "settings", ",", "\"DJANGO_WYSIWYG_FLAVOR\"", ",", "\"yui\"", ")", "if", "editor_override", "is", "not", "None", ":", "flavor", "=", "editor_override", "return",...
38.636364
24.363636
def _label_desc(self, label, desc, label_color=''): ''' Generic styler for a line consisting of a label and description. ''' return self.BRIGHT + label_color + label + self.RESET + desc
[ "def", "_label_desc", "(", "self", ",", "label", ",", "desc", ",", "label_color", "=", "''", ")", ":", "return", "self", ".", "BRIGHT", "+", "label_color", "+", "label", "+", "self", ".", "RESET", "+", "desc" ]
66.666667
26.666667
def find(self, **kwargs): """ Finds row matching specific field value Args: **kwargs: (**only one argument accepted**) fielname=value, e.g., formula="OH" Returns: list element or None """ if len(kwargs) != 1: raise ValueError("One and...
[ "def", "find", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"One and only one keyword argument accepted\"", ")", "key", "=", "list", "(", "kwargs", ".", "keys", "(", ")", ...
27.571429
18.714286
def add_user_role(self, user, role_name): """Associate a role name with a user.""" # For SQL: user.roles is list of pointers to Role objects if isinstance(self.db_adapter, SQLDbAdapter): # user.roles is a list of Role IDs # Get or add role role = self.db_adap...
[ "def", "add_user_role", "(", "self", ",", "user", ",", "role_name", ")", ":", "# For SQL: user.roles is list of pointers to Role objects", "if", "isinstance", "(", "self", ".", "db_adapter", ",", "SQLDbAdapter", ")", ":", "# user.roles is a list of Role IDs", "# Get or ad...
40.176471
16.058824
def get_string(self, ionicstep_start=1, ionicstep_end=None, significant_figures=8): """ Write Xdatcar class into a file Args: filename (str): Filename of output XDATCAR file. ionicstep_start (int): Starting number of ionic step. ...
[ "def", "get_string", "(", "self", ",", "ionicstep_start", "=", "1", ",", "ionicstep_end", "=", "None", ",", "significant_figures", "=", "8", ")", ":", "from", "pymatgen", ".", "io", ".", "vasp", "import", "Poscar", "if", "(", "ionicstep_start", "<", "1", ...
47.282609
13.586957
def vlans(self): """list[dict]: A list of dictionary items describing the details of vlan interfaces. This method fetches the VLAN interfaces Examples: >>> import pynos.device >>> switch = '10.24.39.202' >>> auth = ('admin', 'password') >>>...
[ "def", "vlans", "(", "self", ")", ":", "urn", "=", "\"{urn:brocade.com:mgmt:brocade-interface-ext}\"", "result", "=", "[", "]", "has_more", "=", "''", "last_vlan_id", "=", "''", "while", "(", "has_more", "==", "''", ")", "or", "(", "has_more", "==", "'true'"...
48.678571
16.892857
def sim_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False): """Return the Monge-Elkan similarity of two strings. This is a wrapper for :py:meth:`MongeElkan.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison ...
[ "def", "sim_monge_elkan", "(", "src", ",", "tar", ",", "sim_func", "=", "sim_levenshtein", ",", "symmetric", "=", "False", ")", ":", "return", "MongeElkan", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "sim_func", ",", "symmetric", ")" ]
24.352941
21.264706