text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def DEFINE_constant_string(self, name, default, help): """A helper for defining constant strings.""" self.AddOption( type_info.String(name=name, default=default or "", description=help), constant=True)
[ "def", "DEFINE_constant_string", "(", "self", ",", "name", ",", "default", ",", "help", ")", ":", "self", ".", "AddOption", "(", "type_info", ".", "String", "(", "name", "=", "name", ",", "default", "=", "default", "or", "\"\"", ",", "description", "=", ...
44.2
18
def parse(self, character_page): """Parses the DOM and returns character attributes in the main-content area. :type character_page: :class:`bs4.BeautifulSoup` :param character_page: MAL character page's DOM :rtype: dict :return: Character attributes. """ character_info = self.parse_sideba...
[ "def", "parse", "(", "self", ",", "character_page", ")", ":", "character_info", "=", "self", ".", "parse_sidebar", "(", "character_page", ")", "second_col", "=", "character_page", ".", "find", "(", "u'div'", ",", "{", "'id'", ":", "'content'", "}", ")", "....
34.153846
21.461538
def local_method(f): '''Decorator to be used in conjunction with :class:`LocalMixin` methods. ''' name = f.__name__ def _(self, *args): local = self.local if name not in local: setattr(local, name, f(self, *args)) return getattr(local, name) return _
[ "def", "local_method", "(", "f", ")", ":", "name", "=", "f", ".", "__name__", "def", "_", "(", "self", ",", "*", "args", ")", ":", "local", "=", "self", ".", "local", "if", "name", "not", "in", "local", ":", "setattr", "(", "local", ",", "name", ...
27
21
def _ReadStreamDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a stream data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, o...
[ "def", "_ReadStreamDataTypeDefinition", "(", "self", ",", "definitions_registry", ",", "definition_values", ",", "definition_name", ",", "is_member", "=", "False", ")", ":", "if", "is_member", ":", "supported_definition_values", "=", "(", "self", ".", "_SUPPORTED_DEFI...
36.866667
22.333333
def _logger(self): """Create a logger to be used between processes. :returns: Logging instance. """ logger = logging.getLogger(self.NAME) logger.setLevel(self.LOG_LEVEL) shandler = logging.StreamHandler(sys.stdout) fmt = '\033[1;32m%(levelname)-5s %(module)s:%(fu...
[ "def", "_logger", "(", "self", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "self", ".", "NAME", ")", "logger", ".", "setLevel", "(", "self", ".", "LOG_LEVEL", ")", "shandler", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdou...
37.846154
13
def store(self, moments): """ Store object X with weight w """ if len(self.storage) == self.nsave: # merge if we must # print 'must merge' self.storage[-1].combine(moments, mean_free=self.remove_mean) else: # append otherwise # print 'append' ...
[ "def", "store", "(", "self", ",", "moments", ")", ":", "if", "len", "(", "self", ".", "storage", ")", "==", "self", ".", "nsave", ":", "# merge if we must", "# print 'must merge'", "self", ".", "storage", "[", "-", "1", "]", ".", "combine", "(", "momen...
39.8
10.266667
def parse(self, data): # type: (bytes) -> None ''' Parse the passed in data into a UDF Long AD. Parameters: data - The data to parse. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF Long A...
[ "def", "parse", "(", "self", ",", "data", ")", ":", "# type: (bytes) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'UDF Long Allocation descriptor already initialized'", ")", "(", "self", ".", "extent...
32.0625
24.3125
def process_config(self): """ Intended to put any code that should be run after any config reload event """ if 'byte_unit' in self.config: if isinstance(self.config['byte_unit'], basestring): self.config['byte_unit'] = self.config['byte_unit'].split() ...
[ "def", "process_config", "(", "self", ")", ":", "if", "'byte_unit'", "in", "self", ".", "config", ":", "if", "isinstance", "(", "self", ".", "config", "[", "'byte_unit'", "]", ",", "basestring", ")", ":", "self", ".", "config", "[", "'byte_unit'", "]", ...
43.344828
20.034483
def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, si...
[ "def", "random_hash", "(", "size", "=", "9999999999", ",", "hash_type", "=", "None", ")", ":", "if", "not", "hash_type", ":", "hash_type", "=", "'md5'", "hasher", "=", "getattr", "(", "hashlib", ",", "hash_type", ")", "return", "hasher", "(", "salt", "."...
41.375
26.375
def save(self, *args, **kwargs): """sets the `slug` values as the name :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `super.save()` """ if self.slug is None or self.slug == "": self.slug = slugify(self.name) ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "slug", "is", "None", "or", "self", ".", "slug", "==", "\"\"", ":", "self", ".", "slug", "=", "slugify", "(", "self", ".", "name", ")", "feature...
30.363636
17.545455
def prox_yline(y, step): """Projection onto line in y""" if not np.isscalar(y): y= y[0] if y > -0.75: return np.array([-0.75]) else: return np.array([y])
[ "def", "prox_yline", "(", "y", ",", "step", ")", ":", "if", "not", "np", ".", "isscalar", "(", "y", ")", ":", "y", "=", "y", "[", "0", "]", "if", "y", ">", "-", "0.75", ":", "return", "np", ".", "array", "(", "[", "-", "0.75", "]", ")", "...
23.25
16.125
def send(self, send_string, newline=None): """Saves and sends the send string provided.""" self.current_send_string = send_string newline = newline if newline is not None else self.newline self.channel.send(send_string + newline)
[ "def", "send", "(", "self", ",", "send_string", ",", "newline", "=", "None", ")", ":", "self", ".", "current_send_string", "=", "send_string", "newline", "=", "newline", "if", "newline", "is", "not", "None", "else", "self", ".", "newline", "self", ".", "...
42.833333
13.666667
def chord(annotation, sr=22050, length=None, **kwargs): '''Sonify chords This uses mir_eval.sonify.chords. ''' intervals, chords = annotation.to_interval_values() return filter_kwargs(mir_eval.sonify.chords, chords, intervals, fs=sr, length=length...
[ "def", "chord", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "*", "*", "kwargs", ")", ":", "intervals", ",", "chords", "=", "annotation", ".", "to_interval_values", "(", ")", "return", "filter_kwargs", "(", "mir_eval", "."...
28.75
19.083333
def _set_req_to_reinstall(self, req): # type: (InstallRequirement) -> None """ Set a requirement to be installed. """ # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. if not self.use_user_site or dist_in_usersite(req...
[ "def", "_set_req_to_reinstall", "(", "self", ",", "req", ")", ":", "# type: (InstallRequirement) -> None", "# Don't uninstall the conflict if doing a user install and the", "# conflict is not a user install.", "if", "not", "self", ".", "use_user_site", "or", "dist_in_usersite", "...
40.8
9
def mixin(target, resource, name=None): """Do the correct mixin depending on the type of input resource. - Method or Function: mixin_function_or_method. - class: mixin_class. - other: set_mixin. And returns the result of the choosen method (one or a list of mixins). """...
[ "def", "mixin", "(", "target", ",", "resource", ",", "name", "=", "None", ")", ":", "result", "=", "None", "if", "ismethod", "(", "resource", ")", "or", "isfunction", "(", "resource", ")", ":", "result", "=", "Mixin", ".", "mixin_function_or_method", "("...
28.677419
23.354839
def imag(self, newimag): """Setter for the imaginary part. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element. """ try: iter(newim...
[ "def", "imag", "(", "self", ",", "newimag", ")", ":", "try", ":", "iter", "(", "newimag", ")", "except", "TypeError", ":", "# `newimag` is not iterable, assume it can be assigned to", "# all indexed parts", "for", "part", "in", "self", ".", "parts", ":", "part", ...
34.513514
15.648649
def create_hook(self, name, config, events=['push'], active=True): """Create a hook on this repository. :param str name: (required), name of the hook :param dict config: (required), key-value pairs which act as settings for this hook :param list events: (optional), events th...
[ "def", "create_hook", "(", "self", ",", "name", ",", "config", ",", "events", "=", "[", "'push'", "]", ",", "active", "=", "True", ")", ":", "json", "=", "None", "if", "name", "and", "config", "and", "isinstance", "(", "config", ",", "dict", ")", "...
46.789474
19.894737
def filter(self, func): """ Filter array along an axis. Applies a function which should evaluate to boolean, along a single axis or multiple axes. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. Param...
[ "def", "filter", "(", "self", ",", "func", ")", ":", "if", "self", ".", "mode", "==", "'local'", ":", "reshaped", "=", "self", ".", "_align", "(", "self", ".", "baseaxes", ")", "filtered", "=", "asarray", "(", "list", "(", "filter", "(", "func", ",...
34.974359
22.512821
def write(self, msg): """ Write to this and the redirected stream """ if self.redirect is not None: self.redirect.write(msg) if six.PY2: from xdoctest.utils.util_str import ensure_unicode msg = ensure_unicode(msg) super(TeeStringIO, sel...
[ "def", "write", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "redirect", "is", "not", "None", ":", "self", ".", "redirect", ".", "write", "(", "msg", ")", "if", "six", ".", "PY2", ":", "from", "xdoctest", ".", "utils", ".", "util_str", "...
32.4
8.2
def create_random_connections(self, n=5): '''Create random connections for all agents in the environment. :param int n: the number of connections for each agent Existing agent connections that would be created by chance are not doubled in the agent's :attr:`connections`, but count towa...
[ "def", "create_random_connections", "(", "self", ",", "n", "=", "5", ")", ":", "if", "type", "(", "n", ")", "!=", "int", ":", "raise", "TypeError", "(", "\"Argument 'n' must be of type int.\"", ")", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", ...
40.263158
19.631579
def writeText (self, filename=None): """Writes a text representation of this sequence to the given filename (defaults to self.txtpath). """ if filename is None: filename = self.txtpath with open(filename, 'wt') as output: self.printText(output)
[ "def", "writeText", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "txtpath", "with", "open", "(", "filename", ",", "'wt'", ")", "as", "output", ":", "self", ".", "printText", "...
29.888889
10.222222
def get_item_ids_by_bank(self, bank_id): """Gets the list of ``Item`` ``Ids`` associated with a ``Bank``. arg: bank_id (osid.id.Id): ``Id`` of the ``Bank`` return: (osid.id.IdList) - list of related item ``Ids`` raise: NotFound - ``bank_id`` is not found raise: NullArgumen...
[ "def", "get_item_ids_by_bank", "(", "self", ",", "bank_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_resource_ids_by_bin", "id_list", "=", "[", "]", "for", "item", "in", "self", ".", "get_items_by_bank", "(", "bank_id", ")", "...
44
16.111111
def _insert_error(self, path, node): """ Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. """ field = path[0] ...
[ "def", "_insert_error", "(", "self", ",", "path", ",", "node", ")", ":", "field", "=", "path", "[", "0", "]", "if", "len", "(", "path", ")", "==", "1", ":", "if", "field", "in", "self", ".", "tree", ":", "subtree", "=", "self", ".", "tree", "["...
34.115385
10.615385
def remove_ip(self, ip_id): """ Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json method had success else False """ ip_id = ' "IpAddressResourceId": %s' % ip_id json_scheme = self.gen_...
[ "def", "remove_ip", "(", "self", ",", "ip_id", ")", ":", "ip_id", "=", "' \"IpAddressResourceId\": %s'", "%", "ip_id", "json_scheme", "=", "self", ".", "gen_def_json_scheme", "(", "'SetRemoveIpAddress'", ",", "ip_id", ")", "json_obj", "=", "self", ".", "call_...
48.727273
19.272727
def authenticate(self, email=None, password=None): """ Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns -...
[ "def", "authenticate", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "if", "self", ".", "session", ".", "authenticate", "(", "email", ",", "password", ")", ":", "return", "True" ]
26.2
17.56
def get_enum_labels(enum_cls): """ Return list of enumeration labels from Enum class. The list is useful when creating an attribute, for the `enum_labels` parameter. The enumeration values are checked to ensure they are unique, start at zero, and increment by one. :param enum_cls: the Enum cl...
[ "def", "get_enum_labels", "(", "enum_cls", ")", ":", "if", "not", "issubclass", "(", "enum_cls", ",", "enum", ".", "Enum", ")", ":", "raise", "EnumTypeError", "(", "\"Input class '%s' must be derived from enum.Enum\"", "%", "enum_cls", ")", "# Check there are no dupli...
36.073171
19.146341
def error_message(self): """Returns an error message if the operation failed for any reason. Failure as defined here means ended for any reason other than 'success'. This means that a successful cancelation will also return an error message. Returns: string, string will be empty if job did not e...
[ "def", "error_message", "(", "self", ")", ":", "error", "=", "google_v2_operations", ".", "get_error", "(", "self", ".", "_op", ")", "if", "error", ":", "job_id", "=", "self", ".", "get_field", "(", "'job-id'", ")", "task_id", "=", "self", ".", "get_fiel...
35.85
23.25
def p_ConstValue_boolean(p): """ConstValue : BooleanLiteral""" p[0] = model.Value(type=model.Value.BOOLEAN, value=p[1])
[ "def", "p_ConstValue_boolean", "(", "p", ")", ":", "p", "[", "0", "]", "=", "model", ".", "Value", "(", "type", "=", "model", ".", "Value", ".", "BOOLEAN", ",", "value", "=", "p", "[", "1", "]", ")" ]
40.333333
10
def _callable_from_gvcf(data, vrn_file, out_dir): """Retrieve callable regions based on ref call regions in gVCF. Uses https://github.com/lijiayong/gvcf_regions """ methods = {"freebayes": "freebayes", "platypus": "platypus", "gatk-haplotype": "gatk"} gvcf_type = methods.get(dd.get_v...
[ "def", "_callable_from_gvcf", "(", "data", ",", "vrn_file", ",", "out_dir", ")", ":", "methods", "=", "{", "\"freebayes\"", ":", "\"freebayes\"", ",", "\"platypus\"", ":", "\"platypus\"", ",", "\"gatk-haplotype\"", ":", "\"gatk\"", "}", "gvcf_type", "=", "method...
51.058824
20.823529
def submit_link(self, sr, title, url, follow=True): """Login required. POSTs a link submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink after...
[ "def", "submit_link", "(", "self", ",", "sr", ",", "title", ",", "url", ",", "follow", "=", "True", ")", ":", "return", "self", ".", "_submit", "(", "sr", ",", "title", ",", "'link'", ",", "url", "=", "url", ",", "follow", "=", "follow", ")" ]
64.25
35.9375
def make_sub_call(id_, lineno, params): """ This will return an AST node for a sub/procedure call. """ return symbols.CALL.make_node(id_, params, lineno)
[ "def", "make_sub_call", "(", "id_", ",", "lineno", ",", "params", ")", ":", "return", "symbols", ".", "CALL", ".", "make_node", "(", "id_", ",", "params", ",", "lineno", ")" ]
40.5
3.75
def k_nearest(self, vec, k): """Get the k nearest neighbors of a vector (in terms of highest inner products). :param (np.array) vec: query vector :param (int) k: number of top neighbors to return :return (list[tuple[str, float]]): a list of (word, score) pairs, in descending order ...
[ "def", "k_nearest", "(", "self", ",", "vec", ",", "k", ")", ":", "nbr_score_pairs", "=", "self", ".", "inner_products", "(", "vec", ")", "return", "sorted", "(", "nbr_score_pairs", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "["...
45.4
21.9
def create_visual_input(camera_parameters, name): """ Creates image input op. :param camera_parameters: Parameters for visual observation from BrainInfo. :param name: Desired name of input op. :return: input op. """ o_size_h = camera_parameters['height'] o...
[ "def", "create_visual_input", "(", "camera_parameters", ",", "name", ")", ":", "o_size_h", "=", "camera_parameters", "[", "'height'", "]", "o_size_w", "=", "camera_parameters", "[", "'width'", "]", "bw", "=", "camera_parameters", "[", "'blackAndWhite'", "]", "if",...
33.736842
17.842105
def _pooling_output_shape(input_shape, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: compute the output shape for the pooling layer.""" dims = (1,) + pool_size + (1,) # NHWC spatial_strides = strides or (1,) * len(pool_size) strides = (1,) + spatial_strides + (1,) pad...
[ "def", "_pooling_output_shape", "(", "input_shape", ",", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "None", ",", "padding", "=", "'VALID'", ")", ":", "dims", "=", "(", "1", ",", ")", "+", "pool_size", "+", "(", "1", ",", ")", ...
51.9
14.2
def vars_class(cls): """Return a dict of vars for the given class, including all ancestors. This differs from the usual behaviour of `vars` which returns attributes belonging to the given class and not its ancestors. """ return dict(chain.from_iterable( vars(cls).items() for cls in reversed...
[ "def", "vars_class", "(", "cls", ")", ":", "return", "dict", "(", "chain", ".", "from_iterable", "(", "vars", "(", "cls", ")", ".", "items", "(", ")", "for", "cls", "in", "reversed", "(", "cls", ".", "__mro__", ")", ")", ")" ]
41
16.875
def logger(self, iteration, ret): """Print out relevant information at each epoch""" print("Learning rate: {:f}".format(self.lr_scheduler.get_lr()[0])) entropies = getEntropies(self.model) print("Entropy and max entropy: ", float(entropies[0]), entropies[1]) print("Training time for epoch=", self.ep...
[ "def", "logger", "(", "self", ",", "iteration", ",", "ret", ")", ":", "print", "(", "\"Learning rate: {:f}\"", ".", "format", "(", "self", ".", "lr_scheduler", ".", "get_lr", "(", ")", "[", "0", "]", ")", ")", "entropies", "=", "getEntropies", "(", "se...
53.461538
16.230769
def from_conll(this_class, text): """Construct a Token from a line in CoNLL-X format.""" fields = text.split('\t') fields[0] = int(fields[0]) # index fields[6] = int(fields[6]) # head index if fields[5] != '_': # feats fields[5] = tuple(fields[5].split('|')) f...
[ "def", "from_conll", "(", "this_class", ",", "text", ")", ":", "fields", "=", "text", ".", "split", "(", "'\\t'", ")", "fields", "[", "0", "]", "=", "int", "(", "fields", "[", "0", "]", ")", "# index", "fields", "[", "6", "]", "=", "int", "(", ...
47.7
9.3
def read(self, where=None, columns=None, **kwargs): """we have n indexable columns, with an arbitrary number of data axes """ if not self.read_axes(where=where, **kwargs): return None raise NotImplementedError("Panel is removed in pandas 0.25.0")
[ "def", "read", "(", "self", ",", "where", "=", "None", ",", "columns", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "read_axes", "(", "where", "=", "where", ",", "*", "*", "kwargs", ")", ":", "return", "None", "raise"...
32.444444
19.888889
def get_api(i): """ Input: { (path) - path to module, if comes from access function or (module_uoa) - if comes from CMD (func) - func for API (out) - output } Output: { return - return co...
[ "def", "get_api", "(", "i", ")", ":", "p", "=", "i", ".", "get", "(", "'path'", ",", "''", ")", "f", "=", "i", ".", "get", "(", "'func'", ",", "''", ")", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "muoa", "=", "i", ".", "g...
28.267176
19.267176
def validate_auth_type(self): """ Validate the detected authorization type against the list of handlers. This will return the full module path to the detected handler. """ for handler in HANDLERS: handler_type = handler.split(".")[-2] if han...
[ "def", "validate_auth_type", "(", "self", ")", ":", "for", "handler", "in", "HANDLERS", ":", "handler_type", "=", "handler", ".", "split", "(", "\".\"", ")", "[", "-", "2", "]", "if", "handler_type", "==", "self", ".", "auth_type", ":", "self", ".", "h...
30.666667
17.066667
def loop_qt4(kernel): """Start a kernel with PyQt4 event loop integration.""" from IPython.external.qt_for_kernel import QtCore from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 kernel.app = get_app_qt4([" "]) kernel.app.setQuitOnLastWindowClosed(False) kernel.timer = QtCore...
[ "def", "loop_qt4", "(", "kernel", ")", ":", "from", "IPython", ".", "external", ".", "qt_for_kernel", "import", "QtCore", "from", "IPython", ".", "lib", ".", "guisupport", "import", "get_app_qt4", ",", "start_event_loop_qt4", "kernel", ".", "app", "=", "get_ap...
39.153846
15.230769
def upload(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs): """ This method uploads a local file to the SAS servers file system. localfile - path to the local file to upload remotefile - path to remote file to create or overwrite overwrite ...
[ "def", "upload", "(", "self", ",", "localfile", ":", "str", ",", "remotefile", ":", "str", ",", "overwrite", ":", "bool", "=", "True", ",", "permission", ":", "str", "=", "''", ",", "*", "*", "kwargs", ")", ":", "valid", "=", "self", ".", "_sb", ...
34.494737
18.578947
def visit_oper(self, node, _): """Return an operator as a string. Currently only "=" and ":" (both synonyms) Arguments --------- node : parsimonious.nodes.Node. _ (children) : list, unused Result ------ str The operator as a string. ...
[ "def", "visit_oper", "(", "self", ",", "node", ",", "_", ")", ":", "oper", "=", "node", ".", "text", "if", "oper", "==", "':'", ":", "oper", "=", "'='", "return", "oper" ]
20.592593
21.925926
def set_config(config): """Set bigchaindb.config equal to the default config dict, then update that with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default co...
[ "def", "set_config", "(", "config", ")", ":", "# Deep copy the default config into bigchaindb.config", "bigchaindb", ".", "config", "=", "copy", ".", "deepcopy", "(", "bigchaindb", ".", "_config", ")", "# Update the default config with whatever is in the passed config", "upda...
41.176471
20.529412
def is_not_none(self, a, message=None): "Check if a value is not None" if a is None: self.log_error("{} is None".format(str(a)), message) return False return True
[ "def", "is_not_none", "(", "self", ",", "a", ",", "message", "=", "None", ")", ":", "if", "a", "is", "None", ":", "self", ".", "log_error", "(", "\"{} is None\"", ".", "format", "(", "str", "(", "a", ")", ")", ",", "message", ")", "return", "False"...
34.166667
13.833333
def ex_varassign(name, expr): """Assign an expression into a single variable. The expression may either be an `ast.expr` object or a value to be used as a literal. """ if not isinstance(expr, ast.expr): expr = ex_literal(expr) return ast.Assign([ex_lvalue(name)], expr)
[ "def", "ex_varassign", "(", "name", ",", "expr", ")", ":", "if", "not", "isinstance", "(", "expr", ",", "ast", ".", "expr", ")", ":", "expr", "=", "ex_literal", "(", "expr", ")", "return", "ast", ".", "Assign", "(", "[", "ex_lvalue", "(", "name", "...
41.571429
8.285714
def request_spot_instances(self, price, image_id, count=1, type='one-time', valid_from=None, valid_until=None, launch_group=None, availability_zone_group=None, key_name=None, security_groups=None, ...
[ "def", "request_spot_instances", "(", "self", ",", "price", ",", "image_id", ",", "count", "=", "1", ",", "type", "=", "'one-time'", ",", "valid_from", "=", "None", ",", "valid_until", "=", "None", ",", "launch_group", "=", "None", ",", "availability_zone_gr...
41.073529
20.470588
def ipshuffle(l, random=None): r"""Shuffle list `l` inplace and return it.""" import random as _random _random.shuffle(l, random) return l
[ "def", "ipshuffle", "(", "l", ",", "random", "=", "None", ")", ":", "import", "random", "as", "_random", "_random", ".", "shuffle", "(", "l", ",", "random", ")", "return", "l" ]
30
12
def i2c_config(self, read_delay_time=0, pin_type=None, clk_pin=0, data_pin=0): """ NOTE: THIS METHOD MUST BE CALLED BEFORE ANY I2C REQUEST IS MADE This method initializes Firmata for I2c operations. It allows setting of a read time delay amount, and to optionally track the pins a...
[ "def", "i2c_config", "(", "self", ",", "read_delay_time", "=", "0", ",", "pin_type", "=", "None", ",", "clk_pin", "=", "0", ",", "data_pin", "=", "0", ")", ":", "data", "=", "[", "read_delay_time", "&", "0x7f", ",", "(", "read_delay_time", ">>", "7", ...
50.882353
32.058824
def item_gemeente_adapter(obj, request): """ Adapter for rendering an object of :class: `crabpy.gateway.capakey.Gemeente` to json. """ return { 'id': obj.id, 'naam': obj.naam, 'centroid': obj.centroid, 'bounding_box': obj.bounding_box }
[ "def", "item_gemeente_adapter", "(", "obj", ",", "request", ")", ":", "return", "{", "'id'", ":", "obj", ".", "id", ",", "'naam'", ":", "obj", ".", "naam", ",", "'centroid'", ":", "obj", ".", "centroid", ",", "'bounding_box'", ":", "obj", ".", "boundin...
25.636364
10.909091
def build_update_script(file_name, slot_assignments=None, os_info=None, sensor_graph=None, app_info=None, use_safeupdate=False): """Build a trub script that loads given firmware into the given slots. slot_assignments should be a list of tuples in the following form: ("slot X" or "co...
[ "def", "build_update_script", "(", "file_name", ",", "slot_assignments", "=", "None", ",", "os_info", "=", "None", ",", "sensor_graph", "=", "None", ",", "app_info", "=", "None", ",", "use_safeupdate", "=", "False", ")", ":", "resolver", "=", "ProductResolver"...
44.06383
24.765957
def delete_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Deletes an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto...
[ "def", "delete_api_integration_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resou...
46.695652
35.73913
async def updateTrigger(self, iden, query): ''' Change an existing trigger's query ''' trig = self.cell.triggers.get(iden) self._trig_auth_check(trig.get('useriden')) self.cell.triggers.mod(iden, query)
[ "async", "def", "updateTrigger", "(", "self", ",", "iden", ",", "query", ")", ":", "trig", "=", "self", ".", "cell", ".", "triggers", ".", "get", "(", "iden", ")", "self", ".", "_trig_auth_check", "(", "trig", ".", "get", "(", "'useriden'", ")", ")",...
34.857143
11.428571
def start(self): '''Get ready for a profiling run''' self._configs = self._client.config_get('slow-*') self._client.config_set('slowlog-max-len', 100000) self._client.config_set('slowlog-log-slower-than', 0) self._client.execute_command('slowlog', 'reset')
[ "def", "start", "(", "self", ")", ":", "self", ".", "_configs", "=", "self", ".", "_client", ".", "config_get", "(", "'slow-*'", ")", "self", ".", "_client", ".", "config_set", "(", "'slowlog-max-len'", ",", "100000", ")", "self", ".", "_client", ".", ...
48.5
16.5
def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id): """Build an approval symlink URN.""" return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add( approval_type).Add(subject_id).Add(approval_id)
[ "def", "ApprovalSymlinkUrnBuilder", "(", "approval_type", ",", "subject_id", ",", "user", ",", "approval_id", ")", ":", "return", "aff4", ".", "ROOT_URN", ".", "Add", "(", "\"users\"", ")", ".", "Add", "(", "user", ")", ".", "Add", "(", "\"approvals\"", ")...
60
20
def create_customer(self, customer_deets): """Creates a new customer.""" request = self._post('customers', customer_deets) return self.responder(request)
[ "def", "create_customer", "(", "self", ",", "customer_deets", ")", ":", "request", "=", "self", ".", "_post", "(", "'customers'", ",", "customer_deets", ")", "return", "self", ".", "responder", "(", "request", ")" ]
43.5
5.25
def make_cluster_name_vector(cluster_vect, src_names): """ Converts the cluster membership dictionary to an array Parameters ---------- cluster_vect : `numpy.ndarray' An array filled with the index of the seed of a cluster if a source belongs to a cluster, and with -1 if it does not. ...
[ "def", "make_cluster_name_vector", "(", "cluster_vect", ",", "src_names", ")", ":", "out_array", "=", "np", ".", "where", "(", "cluster_vect", ">=", "0", ",", "src_names", "[", "cluster_vect", "]", ",", "\"\"", ")", "return", "out_array" ]
33
23.05
def hitalic(*content, sep=' '): """ Make italic text (HTML) :param content: :param sep: :return: """ return _md(quote_html(_join(*content, sep=sep)), symbols=MD_SYMBOLS[5])
[ "def", "hitalic", "(", "*", "content", ",", "sep", "=", "' '", ")", ":", "return", "_md", "(", "quote_html", "(", "_join", "(", "*", "content", ",", "sep", "=", "sep", ")", ")", ",", "symbols", "=", "MD_SYMBOLS", "[", "5", "]", ")" ]
21.444444
19
def parse_networks_output(out): """ Parses the output of the Docker CLI 'docker network ls' and returns it in the format similar to the Docker API. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict] """ if not out: return [] line_iter...
[ "def", "parse_networks_output", "(", "out", ")", ":", "if", "not", "out", ":", "return", "[", "]", "line_iter", "=", "islice", "(", "out", ".", "splitlines", "(", ")", ",", "1", ",", "None", ")", "# Skip header", "return", "list", "(", "map", "(", "_...
31.230769
19.846154
def createbot(name, directory, verbosity): """ Creates a Bot's directory structure for the given bot NAME in the current directory or optionally in the given DIRECTORY. """ handle_template('bot', name, target=directory, verbosity=verbosity) click.echo(f"Success: '{name}' bot was successfully cre...
[ "def", "createbot", "(", "name", ",", "directory", ",", "verbosity", ")", ":", "handle_template", "(", "'bot'", ",", "name", ",", "target", "=", "directory", ",", "verbosity", "=", "verbosity", ")", "click", ".", "echo", "(", "f\"Success: '{name}' bot was succ...
48.142857
17.571429
def append_records(self, records): '''Add observations from row-major storage. This is primarily useful for deserializing sparsely packed data. Parameters ---------- records : iterable of dicts or Observations Each element of `records` corresponds to one observation...
[ "def", "append_records", "(", "self", ",", "records", ")", ":", "for", "obs", "in", "records", ":", "if", "isinstance", "(", "obs", ",", "Observation", ")", ":", "self", ".", "append", "(", "*", "*", "obs", ".", "_asdict", "(", ")", ")", "else", ":...
32.666667
19.466667
def reset_rf_samples(): """ Undoes the changes produced by set_rf_samples. """ forest._generate_sample_indices = (lambda rs, n_samples: forest.check_random_state(rs).randint(0, n_samples, n_samples))
[ "def", "reset_rf_samples", "(", ")", ":", "forest", ".", "_generate_sample_indices", "=", "(", "lambda", "rs", ",", "n_samples", ":", "forest", ".", "check_random_state", "(", "rs", ")", ".", "randint", "(", "0", ",", "n_samples", ",", "n_samples", ")", ")...
43
13.6
def _read_translations(self): """Read from the old translations.txt. """ print('Reading original translations') self.translations_map = {} n_translations = 0 with open(os.path.join(self.src_dir, 'translations.txt'), 'rb') as csvfile: reader =...
[ "def", "_read_translations", "(", "self", ")", ":", "print", "(", "'Reading original translations'", ")", "self", ".", "translations_map", "=", "{", "}", "n_translations", "=", "0", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "sr...
42.214286
11.142857
def intersection(self, other): """ Return the intersection between this time interval and the given time interval, or ``None`` if the two intervals do not overlap. :rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType`` """ relative_position = self.rela...
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "relative_position", "=", "self", ".", "relative_position_of", "(", "other", ")", "if", "relative_position", "in", "[", "self", ".", "RELATIVE_POSITION_PP_C", ",", "self", ".", "RELATIVE_POSITION_PI_LC", ...
37.952381
9.809524
def merge_tiers(self, tiers, tiernew=None, gapt=0, sep='_', safe=False): """Merge tiers into a new tier and when the gap is lower then the threshhold glue the annotations together. :param list tiers: List of tier names. :param str tiernew: Name for the new tier, if ``None`` the name wil...
[ "def", "merge_tiers", "(", "self", ",", "tiers", ",", "tiernew", "=", "None", ",", "gapt", "=", "0", ",", "sep", "=", "'_'", ",", "safe", "=", "False", ")", ":", "if", "tiernew", "is", "None", ":", "tiernew", "=", "u'{}_merged'", ".", "format", "("...
43.485714
15.6
def check_login(func): """检查用户登录状态 :param func: 需要被检查的函数 """ @wraps(func) def wrapper(*args, **kwargs): ret = func(*args, **kwargs) if type(ret) == requests.Response: # 检测结果是否为JSON if ret.content[0]!=b'{' and ret.content[0]!=b'[': return ret ...
[ "def", "check_login", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "type", "(", "ret", ...
32.576923
15.961538
def archive(class_obj: type) -> type: """ Decorator to annotate the Archive class. Registers the decorated class as the Archive known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _archive_resource_type _archive_resource_type = class_obj return class_obj
[ "def", "archive", "(", "class_obj", ":", "type", ")", "->", "type", ":", "assert", "isinstance", "(", "class_obj", ",", "type", ")", ",", "\"class_obj is not a Class\"", "global", "_archive_resource_type", "_archive_resource_type", "=", "class_obj", "return", "class...
34.666667
11.333333
def check_crystal_equivalence(crystal_a, crystal_b): """Function that identifies whether two crystals are equivalent""" # getting symmetry datasets for both crystals cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0) cryst_b = spglib.get_...
[ "def", "check_crystal_equivalence", "(", "crystal_a", ",", "crystal_b", ")", ":", "# getting symmetry datasets for both crystals", "cryst_a", "=", "spglib", ".", "get_symmetry_dataset", "(", "ase_to_spgcell", "(", "crystal_a", ")", ",", "symprec", "=", "1e-5", ",", "a...
52.380952
30.333333
def precompute_sharp_round(nxk, nyk, xc, yc): """ Pre-computes mask arrays to be used by the 'sharp_round' function for roundness computations based on two- and four-fold symmetries. """ # Create arrays for the two- and four-fold symmetry computations: s4m = np.ones((nyk,nxk),dtype=np.int16) ...
[ "def", "precompute_sharp_round", "(", "nxk", ",", "nyk", ",", "xc", ",", "yc", ")", ":", "# Create arrays for the two- and four-fold symmetry computations:", "s4m", "=", "np", ".", "ones", "(", "(", "nyk", ",", "nxk", ")", ",", "dtype", "=", "np", ".", "int1...
29.5
18.75
def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a PUT request to url with optional authentication """ res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) return ...
[ "def", "rest_put", "(", "self", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "auth", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ")", ":", "res", "=", "requests", ".", "put", "(", "url", ",", ...
48.428571
17.571429
def plot(self,minval=None,maxval=None,fig=None,log=False, npts=500,**kwargs): """ Plots distribution. Parameters ---------- minval : float,optional minimum value to plot. Required if minval of Distribution is `-np.inf`. maxval : fl...
[ "def", "plot", "(", "self", ",", "minval", "=", "None", ",", "maxval", "=", "None", ",", "fig", "=", "None", ",", "log", "=", "False", ",", "npts", "=", "500", ",", "*", "*", "kwargs", ")", ":", "if", "minval", "is", "None", ":", "minval", "=",...
31.470588
22.137255
def get_error(self): """ Get an error string from the device """ err_str = hidapi.hid_error(self._device) if err_str == ffi.NULL: return None else: return ffi.string(err_str)
[ "def", "get_error", "(", "self", ")", ":", "err_str", "=", "hidapi", ".", "hid_error", "(", "self", ".", "_device", ")", "if", "err_str", "==", "ffi", ".", "NULL", ":", "return", "None", "else", ":", "return", "ffi", ".", "string", "(", "err_str", ")...
26.444444
9.555556
def vdotg(v1, v2, ndim): """ Compute the dot product of two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdotg_c.html :param v1: First vector in the dot product. :type v1: list[ndim] :param v2: Second vector in the dot product. ...
[ "def", "vdotg", "(", "v1", ",", "v2", ",", "ndim", ")", ":", "v1", "=", "stypes", ".", "toDoubleVector", "(", "v1", ")", "v2", "=", "stypes", ".", "toDoubleVector", "(", "v2", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "return", ...
29.7
14.3
def _add_video_timing(self, pic): """Add a `p:video` element under `p:sld/p:timing`. The element will refer to the specified *pic* element by its shape id, and cause the video play controls to appear for that video. """ sld = self._spTree.xpath('/p:sld')[0] childTnLst = ...
[ "def", "_add_video_timing", "(", "self", ",", "pic", ")", ":", "sld", "=", "self", ".", "_spTree", ".", "xpath", "(", "'/p:sld'", ")", "[", "0", "]", "childTnLst", "=", "sld", ".", "get_or_add_childTnLst", "(", ")", "childTnLst", ".", "add_video", "(", ...
42.444444
14.111111
def check_disk_usage(filehandle, meta): """Checks the upload directory to see if the uploaded file would exceed the total disk allotment. Meant as a quick and dirty example. """ # limit it at twenty kilobytes if no default is provided MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 10...
[ "def", "check_disk_usage", "(", "filehandle", ",", "meta", ")", ":", "# limit it at twenty kilobytes if no default is provided", "MAX_DISK_USAGE", "=", "current_app", ".", "config", ".", "get", "(", "'MAX_DISK_USAGE'", ",", "20", "*", "1024", ")", "CURRENT_USAGE", "="...
43
16.714286
def serial_get(self): """ Create the serial connection from the framework settings and return it, setting the framework instance in the process. """ frmwk_c1218_settings = { 'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'], 'pktsize': self.advanced_options['C1218_PACKET_SIZE'] } frmwk_serial_s...
[ "def", "serial_get", "(", "self", ")", ":", "frmwk_c1218_settings", "=", "{", "'nbrpkts'", ":", "self", ".", "advanced_options", "[", "'C1218_MAX_PACKETS'", "]", ",", "'pktsize'", ":", "self", ".", "advanced_options", "[", "'C1218_PACKET_SIZE'", "]", "}", "frmwk...
47.318182
31.5
def debug_print(lst, lvl=0): """ Print scope tree args: lst (list): parse result lvl (int): current nesting level """ pad = ''.join(['\t.'] * lvl) t = type(lst) if t is list: for p in lst: debug_print(p, lvl) elif hasattr(lst, 'tokens'): print(pad,...
[ "def", "debug_print", "(", "lst", ",", "lvl", "=", "0", ")", ":", "pad", "=", "''", ".", "join", "(", "[", "'\\t.'", "]", "*", "lvl", ")", "t", "=", "type", "(", "lst", ")", "if", "t", "is", "list", ":", "for", "p", "in", "lst", ":", "debug...
26.142857
12.5
def get_all_devs(auth, url, network_address=None, category=None, label=None): """Takes string input of IP address to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.aut...
[ "def", "get_all_devs", "(", "auth", ",", "url", ",", "network_address", "=", "None", ",", "category", "=", "None", ",", "label", "=", "None", ")", ":", "base_url", "=", "\"/imcrs/plat/res/device?resPrivilegeFilter=false\"", "end_url", "=", "\"&start=0&size=1000&orde...
37.826923
22.923077
def update(self): """Update the position of the mark in the collection. :return: this object, for chaining :rtype: Mark """ rec = self._c.find_one({}, {self._fld: 1}, sort=[(self._fld, -1)], limit=1) if rec is None: self._pos = self._empty_pos() elif ...
[ "def", "update", "(", "self", ")", ":", "rec", "=", "self", ".", "_c", ".", "find_one", "(", "{", "}", ",", "{", "self", ".", "_fld", ":", "1", "}", ",", "sort", "=", "[", "(", "self", ".", "_fld", ",", "-", "1", ")", "]", ",", "limit", "...
37.470588
16.058824
def instr(str, substr): """ Locate the position of the first occurrence of substr column in the given string. Returns null if either of the arguments are null. .. note:: The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. >>> df = spark.createD...
[ "def", "instr", "(", "str", ",", "substr", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "return", "Column", "(", "sc", ".", "_jvm", ".", "functions", ".", "instr", "(", "_to_java_column", "(", "str", ")", ",", "substr", ")", ")" ]
38.071429
21.214286
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_ms...
[ "def", "raise_for_status", "(", "self", ")", ":", "http_error_msg", "=", "''", "if", "400", "<=", "self", ".", "status_code", "<", "500", ":", "http_error_msg", "=", "'%s Client Error: %s'", "%", "(", "self", ".", "status_code", ",", "self", ".", "reason", ...
34.923077
23.846154
def _temp_filename(contents): """ Make a temporary file with `contents`. The file will be cleaned up on exit. """ fp = tempfile.NamedTemporaryFile( prefix='codequalitytmp', delete=False) name = fp.name fp.write(contents) fp.close() _files_to_cleanup.append(name) return n...
[ "def", "_temp_filename", "(", "contents", ")", ":", "fp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "'codequalitytmp'", ",", "delete", "=", "False", ")", "name", "=", "fp", ".", "name", "fp", ".", "write", "(", "contents", ")", "fp"...
23.923077
12.230769
def base26int(s, _start=1 - ord('A')): """Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799 """ return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
[ "def", "base26int", "(", "s", ",", "_start", "=", "1", "-", "ord", "(", "'A'", ")", ")", ":", "return", "sum", "(", "(", "_start", "+", "ord", "(", "c", ")", ")", "*", "26", "**", "i", "for", "i", ",", "c", "in", "enumerate", "(", "reversed",...
31.857143
17.571429
def print_system_users(): r""" prints users on the system On unix looks for /bin/bash users in /etc/passwd CommandLine: python -m utool.util_cplat --test-print_system_users Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_cplat import * # NOQA ...
[ "def", "print_system_users", "(", ")", ":", "import", "utool", "as", "ut", "text", "=", "ut", ".", "read_from", "(", "'/etc/passwd'", ")", "userinfo_text_list", "=", "text", ".", "splitlines", "(", ")", "userinfo_list", "=", "[", "uitext", ".", "split", "(...
29.333333
17.375
def format_spec_to_regex(field_name, format_spec): """Make an attempt at converting a format spec to a regular expression.""" # NOTE: remove escaped backslashes so regex matches regex_match = fmt_spec_regex.match(format_spec.replace('\\', '')) if regex_match is None: raise Va...
[ "def", "format_spec_to_regex", "(", "field_name", ",", "format_spec", ")", ":", "# NOTE: remove escaped backslashes so regex matches", "regex_match", "=", "fmt_spec_regex", ".", "match", "(", "format_spec", ".", "replace", "(", "'\\\\'", ",", "''", ")", ")", "if", "...
45.783784
16.594595
def renameAfterCreation(obj): """Rename the content after it was created/added """ # Check if the _bika_id was already set bika_id = getattr(obj, "_bika_id", None) if bika_id is not None: return bika_id # Can't rename without a subtransaction commit when using portal_factory transact...
[ "def", "renameAfterCreation", "(", "obj", ")", ":", "# Check if the _bika_id was already set", "bika_id", "=", "getattr", "(", "obj", ",", "\"_bika_id\"", ",", "None", ")", "if", "bika_id", "is", "not", "None", ":", "return", "bika_id", "# Can't rename without a sub...
42.942857
18.342857
def headerData(self, section, orientation, role): """ Returns the header for a section (row or column depending on orientation). Reimplemented from QAbstractTableModel to make the headers start at 0. """ if role == Qt.DisplayRole: if self._separateFieldOrientation == orie...
[ "def", "headerData", "(", "self", ",", "section", ",", "orientation", ",", "role", ")", ":", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "if", "self", ".", "_separateFieldOrientation", "==", "orientation", ":", "nFields", "=", "len", "(", "self", ...
41.117647
15.294118
def _bind(l, bind=None): '''Bind helper.''' if bind is None: return method = bind.get('method', 'simple') if method is None: return elif method == 'simple': l.simple_bind_s(bind.get('dn', ''), bind.get('password', '')) elif method == 'sasl': sasl_class = getattr(l...
[ "def", "_bind", "(", "l", ",", "bind", "=", "None", ")", ":", "if", "bind", "is", "None", ":", "return", "method", "=", "bind", ".", "get", "(", "'method'", ",", "'simple'", ")", "if", "method", "is", "None", ":", "return", "elif", "method", "==", ...
37.75
19.25
def add_context(request): """ Add variables to all dictionaries passed to templates. """ # Whether the user has president privileges try: PRESIDENT = Manager.objects.filter( incumbent__user=request.user, president=True, ).count() > 0 except TypeError: PRES...
[ "def", "add_context", "(", "request", ")", ":", "# Whether the user has president privileges", "try", ":", "PRESIDENT", "=", "Manager", ".", "objects", ".", "filter", "(", "incumbent__user", "=", "request", ".", "user", ",", "president", "=", "True", ",", ")", ...
36.913043
16.73913
def check_valid_cpc_status(method, uri, cpc): """ Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError wit...
[ "def", "check_valid_cpc_status", "(", "method", ",", "uri", ",", "cpc", ")", ":", "status", "=", "cpc", ".", "properties", ".", "get", "(", "'status'", ",", "None", ")", "if", "status", "is", "None", ":", "# Do nothing if no status is set on the faked CPC", "r...
46.722222
22.777778
def _get_calculated_size(self, size, data): """ Get's the final size of the field and runs the lambda functions recursively until a final size is derived. If size is None then it will just return the length of the data as it is assumed it is the final field (None should only be s...
[ "def", "_get_calculated_size", "(", "self", ",", "size", ",", "data", ")", ":", "# if the size is derived from a lambda function, run it now; otherwise", "# return the value we passed in or the length of the data if the size", "# is None (last field value)", "if", "size", "is", "None...
45
19.666667
def listMigrationRequests(self, migration_request_id="", block_name="", dataset="", user="", oldest=False): """ get the status of the migration migratee : can be dataset or block_name """ conn = self.dbi.connection() migratee = "" tr...
[ "def", "listMigrationRequests", "(", "self", ",", "migration_request_id", "=", "\"\"", ",", "block_name", "=", "\"\"", ",", "dataset", "=", "\"\"", ",", "user", "=", "\"\"", ",", "oldest", "=", "False", ")", ":", "conn", "=", "self", ".", "dbi", ".", "...
33.904762
17.238095
def rotatePoint(x, y, rotationDegrees, pivotx=0, pivoty=0): """ Rotates the point at `x` and `y` by `rotationDegrees`. The point is rotated around the origin by default, but can be rotated around another pivot point by specifying `pivotx` and `pivoty`. The points are rotated counterclockwise. ...
[ "def", "rotatePoint", "(", "x", ",", "y", ",", "rotationDegrees", ",", "pivotx", "=", "0", ",", "pivoty", "=", "0", ")", ":", "# Reuse the code in rotatePoints()", "return", "list", "(", "rotatePoints", "(", "[", "(", "x", ",", "y", ")", "]", ",", "rot...
30.043478
21.608696
def get_output_margin(self, status=None): """Get the output margin (number of rows for the prompt, footer and timing message.""" margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1 if special.is_timing_enabled(): margin += 1 if status: ...
[ "def", "get_output_margin", "(", "self", ",", "status", "=", "None", ")", ":", "margin", "=", "self", ".", "get_reserved_space", "(", ")", "+", "self", ".", "get_prompt", "(", "self", ".", "prompt", ")", ".", "count", "(", "'\\n'", ")", "+", "1", "if...
37.6
15.3
def loadStructuredGrid(filename): # not tested """Load a ``vtkStructuredGrid`` object from file and return a ``Actor(vtkActor)`` object.""" reader = vtk.vtkStructuredGridReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtkStructuredGridGeometryFilter() gf.SetInputConnection(reader...
[ "def", "loadStructuredGrid", "(", "filename", ")", ":", "# not tested", "reader", "=", "vtk", ".", "vtkStructuredGridReader", "(", ")", "reader", ".", "SetFileName", "(", "filename", ")", "reader", ".", "Update", "(", ")", "gf", "=", "vtk", ".", "vtkStructur...
42
9.555556
def split(X, Y, question): """Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ true_X, false_X = [], [] true_Y, false_Y = [], [] for x, y in zip(X, Y): if question.match(x): ...
[ "def", "split", "(", "X", ",", "Y", ",", "question", ")", ":", "true_X", ",", "false_X", "=", "[", "]", ",", "[", "]", "true_Y", ",", "false_Y", "=", "[", "]", ",", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "X", ",", "Y", ")", ":"...
25.190476
19.333333
def enabled_service_owners(): ''' Return which packages own each of the services that are currently enabled. CLI Example: salt myminion introspect.enabled_service_owners ''' error = {} if 'pkg.owner' not in __salt__: error['Unsupported Package Manager'] = ( 'The mod...
[ "def", "enabled_service_owners", "(", ")", ":", "error", "=", "{", "}", "if", "'pkg.owner'", "not", "in", "__salt__", ":", "error", "[", "'Unsupported Package Manager'", "]", "=", "(", "'The module for the package manager on this system does not '", "'support looking up w...
29.138889
22.638889
def aggregate(self, mongo_collection, aggregate_query, mongo_db=None, **kwargs): """ Runs an aggregation pipeline and returns the results https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.aggregate https://api.mongodb.com/python/current/exam...
[ "def", "aggregate", "(", "self", ",", "mongo_collection", ",", "aggregate_query", ",", "mongo_db", "=", "None", ",", "*", "*", "kwargs", ")", ":", "collection", "=", "self", ".", "get_collection", "(", "mongo_collection", ",", "mongo_db", "=", "mongo_db", ")...
54.111111
29.444444
def valid_name(name): "Validate a cookie name string" if isinstance(name, bytes): name = name.decode('ascii') if not Definitions.COOKIE_NAME_RE.match(name): return False # This module doesn't support $identifiers, which are part of an obsolete # and highly complex standard which is n...
[ "def", "valid_name", "(", "name", ")", ":", "if", "isinstance", "(", "name", ",", "bytes", ")", ":", "name", "=", "name", ".", "decode", "(", "'ascii'", ")", "if", "not", "Definitions", ".", "COOKIE_NAME_RE", ".", "match", "(", "name", ")", ":", "ret...
34.545455
16.545455
def __handle_scale_rot(self): """Handle scaling and rotation of the surface""" if self.__is_rot_pending: self.__execute_rot(self.untransformed_image) self.__is_rot_pending = False # Scale the image using the recently rotated surface to keep the orientation correct ...
[ "def", "__handle_scale_rot", "(", "self", ")", ":", "if", "self", ".", "__is_rot_pending", ":", "self", ".", "__execute_rot", "(", "self", ".", "untransformed_image", ")", "self", ".", "__is_rot_pending", "=", "False", "# Scale the image using the recently rotated sur...
49.071429
22.642857