text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def UsersUpdate (self, user_id, parameters): """ Update the current user. @param user_id (int) - id of the user to be updated @param parameters (dictionary) - user object to update the user with @return (bool) - Boolean indicating ...
[ "def", "UsersUpdate", "(", "self", ",", "user_id", ",", "parameters", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/users/{0}.json'", ".", "format", "(", "user_id", ")", ",", "'PUT'", ",", "parameters", ")", ":", "return", "True", "else", ":", ...
40.214286
20.642857
def exists(self, client=None): """Test whether this notification exists. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.st...
[ "def", "exists", "(", "self", ",", "client", "=", "None", ")", ":", "if", "self", ".", "notification_id", "is", "None", ":", "raise", "ValueError", "(", "\"Notification not intialized by server\"", ")", "client", "=", "self", ".", "_require_client", "(", "clie...
33.828571
23.314286
def generate_epochs_info(epoch_list): """ use epoch_list to generate epoch_info defined below Parameters ---------- epoch_list: list of 3D (binary) array in shape [condition, nEpochs, nTRs] Contains specification of epochs and conditions, assuming 1. all subjects have the same number of...
[ "def", "generate_epochs_info", "(", "epoch_list", ")", ":", "time1", "=", "time", ".", "time", "(", ")", "epoch_info", "=", "[", "]", "for", "sid", ",", "epoch", "in", "enumerate", "(", "epoch_list", ")", ":", "for", "cond", "in", "range", "(", "epoch"...
39.486486
18.351351
def select(self, value=None, field=None, **kwargs): """ If the ``field`` argument is present, ``select`` finds a select box on the page and selects a particular option from it. Otherwise it finds an option inside the current scope and selects it. If the select box is a multiple select, `...
[ "def", "select", "(", "self", ",", "value", "=", "None", ",", "field", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "field", ":", "self", ".", "find", "(", "\"select\"", ",", "field", ",", "*", "*", "kwargs", ")", ".", "find", "(", "\"...
48.65
31.25
def _call_member(obj, name, failfast=True, *args, **kwargs): """ Calls the specified method, property or attribute of the given object Parameters ---------- obj : object The object that will be used name : str Name of method, property or attribute failfast : bool If True...
[ "def", "_call_member", "(", "obj", ",", "name", ",", "failfast", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "attr", "=", "getattr", "(", "obj", ",", "name", ")", "except", "AttributeError", "as", "e", ":", "if", ...
29.777778
19.888889
def produce(self, obj, val, ctx=None): """ factory function to create primitives :param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives :param val: value to construct primitives :return: the created primitive """ val = obj.default if val == None els...
[ "def", "produce", "(", "self", ",", "obj", ",", "val", ",", "ctx", "=", "None", ")", ":", "val", "=", "obj", ".", "default", "if", "val", "==", "None", "else", "val", "if", "val", "==", "None", ":", "return", "None", "obj", "=", "deref", "(", "...
33.483871
15.526882
def writeline(self, addition): """writeline() Functions like a file.writeline() call; however, it stores into the object's cached memory rather than a file's IO. """ addition = addition.strip() self.held = self.held + addition + "\n"
[ "def", "writeline", "(", "self", ",", "addition", ")", ":", "addition", "=", "addition", ".", "strip", "(", ")", "self", ".", "held", "=", "self", ".", "held", "+", "addition", "+", "\"\\n\"" ]
32.375
12.5
def zipline_magic(line, cell=None): """The zipline IPython cell magic. """ load_extensions( default=True, extensions=[], strict=True, environ=os.environ, ) try: return run.main( # put our overrides at the start of the parameter list so that ...
[ "def", "zipline_magic", "(", "line", ",", "cell", "=", "None", ")", ":", "load_extensions", "(", "default", "=", "True", ",", "extensions", "=", "[", "]", ",", "strict", "=", "True", ",", "environ", "=", "os", ".", "environ", ",", ")", "try", ":", ...
38.129032
19.580645
def runtime_deps(self): # install_requires """Returns list of runtime dependencies of the package specified in setup.py. Dependencies are in RPM SPECFILE format - see dependency_to_rpm() for details, but names are already transformed according to current distro. Return...
[ "def", "runtime_deps", "(", "self", ")", ":", "# install_requires", "install_requires", "=", "self", ".", "metadata", "[", "'install_requires'", "]", "if", "self", ".", "metadata", "[", "'entry_points'", "]", "and", "'setuptools'", "not", "in", "install_requires",...
39.888889
21.666667
def _exception_message(excp): """Return the message from an exception as either a str or unicode object. Supports both Python 2 and Python 3. >>> msg = "Exception message" >>> excp = Exception(msg) >>> msg == _exception_message(excp) True >>> msg = u"unicöde" >>> excp = Exception(msg)...
[ "def", "_exception_message", "(", "excp", ")", ":", "if", "isinstance", "(", "excp", ",", "Py4JJavaError", ")", ":", "# 'Py4JJavaError' doesn't contain the stack trace available on the Java side in 'message'", "# attribute in Python 2. We should call 'str' function on this exception in...
37.695652
20.217391
def creator(entry, config): """Preparing and creating script.""" script = render(config.script, model=config.model, env=config.env, item=config.item) temp = tempfile.NamedTemporaryFile(prefix="script-", suffix=".py", mode='w+t', delete=False) temp.writelines(script) temp.close()...
[ "def", "creator", "(", "entry", ",", "config", ")", ":", "script", "=", "render", "(", "config", ".", "script", ",", "model", "=", "config", ".", "model", ",", "env", "=", "config", ".", "env", ",", "item", "=", "config", ".", "item", ")", "temp", ...
41
27.875
def calledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is called with partial SinonMatcher(args/kwargs) Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.calledWithMatch(*args, **kwargs)): raise cls...
[ "def", "calledWithMatch", "(", "cls", ",", "spy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=invalid-name", "cls", ".", "__is_spy", "(", "spy", ")", "if", "not", "(", "spy", ".", "calledWithMatch", "(", "*", "args", ",", "*"...
42.5
14.75
def to_match(self): """Return a unicode object with the MATCH representation of this expression.""" self.validate() mark_name, field_name = self.fold_scope_location.get_location_name() validate_safe_string(mark_name) template = u'$%(mark_name)s.%(field_name)s' template_...
[ "def", "to_match", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "mark_name", ",", "field_name", "=", "self", ".", "fold_scope_location", ".", "get_location_name", "(", ")", "validate_safe_string", "(", "mark_name", ")", "template", "=", "u'$%(mark...
44.035714
25.071429
def hierarch_cluster(M): """Cluster matrix using hierarchical clustering. Parameters ---------- M : np.ndarray Matrix, for example, distance matrix. Returns ------- Mclus : np.ndarray Clustered matrix. indices : np.ndarray Indices used to cluster the matrix. ...
[ "def", "hierarch_cluster", "(", "M", ")", ":", "import", "scipy", "as", "sp", "import", "scipy", ".", "cluster", "link", "=", "sp", ".", "cluster", ".", "hierarchy", ".", "linkage", "(", "M", ")", "indices", "=", "sp", ".", "cluster", ".", "hierarchy",...
23.92
17
def load_environment(global_conf, app_conf): """Configure the application environment.""" conf.update(strings.deep_decode(global_conf)) conf.update(strings.deep_decode(app_conf)) conf.update(conv.check(conv.struct( { 'app_conf': conv.set_value(app_conf), 'app_dir': conv.s...
[ "def", "load_environment", "(", "global_conf", ",", "app_conf", ")", ":", "conf", ".", "update", "(", "strings", ".", "deep_decode", "(", "global_conf", ")", ")", "conf", ".", "update", "(", "strings", ".", "deep_decode", "(", "app_conf", ")", ")", "conf",...
44.894366
23.852113
def from_dictionary(cls, dictionary): """Parse a dictionary representing all command line parameters.""" if not isinstance(dictionary, dict): raise TypeError('dictionary has to be a dict type, got: {}'.format(type(dictionary))) return cls(dictionary)
[ "def", "from_dictionary", "(", "cls", ",", "dictionary", ")", ":", "if", "not", "isinstance", "(", "dictionary", ",", "dict", ")", ":", "raise", "TypeError", "(", "'dictionary has to be a dict type, got: {}'", ".", "format", "(", "type", "(", "dictionary", ")", ...
47
19
def raise_if(self, exception, message, *args, **kwargs): """ If current exception has smaller priority than minimum, subclass of this class only warns user, otherwise normal exception will be raised. """ if issubclass(exception, self.minimum_defect): raise exception(*...
[ "def", "raise_if", "(", "self", ",", "exception", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "issubclass", "(", "exception", ",", "self", ".", "minimum_defect", ")", ":", "raise", "exception", "(", "*", "args", ",", "*...
47.75
15
def _multiplyThroughputs(self): ''' Overrides base class in order to deal with opaque components. ''' index = 0 for component in self.components: if component.throughput != None: break index += 1 return BaseObservationMode._multiplyThrough...
[ "def", "_multiplyThroughputs", "(", "self", ")", ":", "index", "=", "0", "for", "component", "in", "self", ".", "components", ":", "if", "component", ".", "throughput", "!=", "None", ":", "break", "index", "+=", "1", "return", "BaseObservationMode", ".", "...
32.8
20.4
def Handle_Search(self, msg): """ Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str """ search_term = msg['object']['searchTerm'] results = self.db.searchForItem(search_term) ...
[ "def", "Handle_Search", "(", "self", ",", "msg", ")", ":", "search_term", "=", "msg", "[", "'object'", "]", "[", "'searchTerm'", "]", "results", "=", "self", ".", "db", ".", "searchForItem", "(", "search_term", ")", "reply", "=", "{", "\"status\"", ":", ...
26.857143
16.47619
def ldSet(self, what, key, value): """List/dictionary-aware set.""" if isListKey(key): # Make sure we keep the indexes consistent, insert missing_values # as necessary. We do remember the lists, so that we can remove # missing values after inserting all values from all selectors. self.li...
[ "def", "ldSet", "(", "self", ",", "what", ",", "key", ",", "value", ")", ":", "if", "isListKey", "(", "key", ")", ":", "# Make sure we keep the indexes consistent, insert missing_values", "# as necessary. We do remember the lists, so that we can remove", "# missing values aft...
35.285714
17.142857
def rpy2(): '''Lazily import the rpy2 module''' if LazyImport.rpy2_module is None: try: rpy2 = __import__('rpy2.robjects') except ImportError: raise ImportError('The rpy2 module is required') LazyImport.rpy2_module = rpy2 tr...
[ "def", "rpy2", "(", ")", ":", "if", "LazyImport", ".", "rpy2_module", "is", "None", ":", "try", ":", "rpy2", "=", "__import__", "(", "'rpy2.robjects'", ")", "except", "ImportError", ":", "raise", "ImportError", "(", "'The rpy2 module is required'", ")", "LazyI...
41.125
14.875
def find_file(path, filename, max_depth=5): """Returns full filepath if the file is in path or a subdirectory.""" for root, dirs, files in os.walk(path): if filename in files: return os.path.join(root, filename) # Don't search past max_depth depth = root[len(path) + 1:].count(os.sep) if depth...
[ "def", "find_file", "(", "path", ",", "filename", ",", "max_depth", "=", "5", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "if", "filename", "in", "files", ":", "return", "os", ".", "path", "...
33.545455
11.272727
def add_nic(self, uuid, type, id=None, hwaddr=None): """ Add a nic to a machine :param uuid: uuid of the kvm container (same as the used in create) :param type: nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs) param id: id # depends on the ...
[ "def", "add_nic", "(", "self", ",", "uuid", ",", "type", ",", "id", "=", "None", ",", "hwaddr", "=", "None", ")", ":", "args", "=", "{", "'uuid'", ":", "uuid", ",", "'type'", ":", "type", ",", "'id'", ":", "id", ",", "'hwaddr'", ":", "hwaddr", ...
39.666667
23.888889
def p_pragma_assign(self, p): 'pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN' p[0] = Pragma(PragmaEntry(p[3], p[5], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_pragma_assign", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Pragma", "(", "PragmaEntry", "(", "p", "[", "3", "]", ",", "p", "[", "5", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", ",", "lineno", "...
47.4
13.4
def send_empty(self, message): """ Eventually remove from the observer list in case of a RST message. :type message: Message :param message: the message :return: the message unmodified """ host, port = message.destination key_token = hash(str(host) + str(...
[ "def", "send_empty", "(", "self", ",", "message", ")", ":", "host", ",", "port", "=", "message", ".", "destination", "key_token", "=", "hash", "(", "str", "(", "host", ")", "+", "str", "(", "port", ")", "+", "str", "(", "message", ".", "token", ")"...
37.153846
14.538462
def inserir(self, id_script_type, script, model, description): """Inserts a new Script and returns its identifier. :param id_script_type: Identifier of the Script Type. Integer value and greater than zero. :param script: Script name. String with a minimum 3 and maximum of 40 characters ...
[ "def", "inserir", "(", "self", ",", "id_script_type", ",", "script", ",", "model", ",", "description", ")", ":", "script_map", "=", "dict", "(", ")", "script_map", "[", "'id_script_type'", "]", "=", "id_script_type", "script_map", "[", "'script'", "]", "=", ...
44.571429
28.642857
def get_structure_with_nodes(self): """ Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X. """ new_s = Structure.from_sites(self.structure) for v in self.vnodes: new_s.append("X", v.frac_coords) return ne...
[ "def", "get_structure_with_nodes", "(", "self", ")", ":", "new_s", "=", "Structure", ".", "from_sites", "(", "self", ".", "structure", ")", "for", "v", "in", "self", ".", "vnodes", ":", "new_s", ".", "append", "(", "\"X\"", ",", "v", ".", "frac_coords", ...
35
9.444444
def replace(self, text=None): """ Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrenc...
[ "def", "replace", "(", "self", ",", "text", "=", "None", ")", ":", "if", "text", "is", "None", "or", "isinstance", "(", "text", ",", "bool", ")", ":", "text", "=", "self", ".", "lineEditReplace", ".", "text", "(", ")", "current_occurences", "=", "sel...
40.244444
13.933333
def iter_keys(self, number=-1, etag=None): """Iterate over the public keys of this user. .. versionadded:: 0.5 :param int number: (optional), number of keys to return. Default: -1 returns all available keys :param str etag: (optional), ETag from a previous request to the sa...
[ "def", "iter_keys", "(", "self", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'keys'", ",", "base_url", "=", "self", ".", "_api", ")", "return", "self", ".", "_iter", "(", "int", "...
39.538462
18.153846
def procces_filters(all_needs, current_needlist): """ Filters all needs with given configuration :param current_needlist: needlist object, which stores all filters :param all_needs: List of all needs inside document :return: list of needs, which passed the filters """ if current_needlist[...
[ "def", "procces_filters", "(", "all_needs", ",", "current_needlist", ")", ":", "if", "current_needlist", "[", "\"sort_by\"", "]", "is", "not", "None", ":", "if", "current_needlist", "[", "\"sort_by\"", "]", "==", "\"id\"", ":", "all_needs", "=", "sorted", "(",...
39.54
24.14
def add_whitelist_entry(self, address, netmask, note=None): """ Adds a new entry to this user's IP whitelist, if enabled """ result = self._client.post("{}/whitelist".format(Profile.api_endpoint), data={ "address": address, "netmask...
[ "def", "add_whitelist_entry", "(", "self", ",", "address", ",", "netmask", ",", "note", "=", "None", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "\"{}/whitelist\"", ".", "format", "(", "Profile", ".", "api_endpoint", ")", ",", "dat...
37.133333
20.6
def list_buckets(self, instance): """ List the buckets for an instance. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Bucket] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity...
[ "def", "list_buckets", "(", "self", ",", "instance", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "response", "=", "self", ".", "_client", ".", "get_proto", "(", "path", "=", "'...
42.2
14.866667
def ssa(n,h,K,f,T): """ssa -- multi-stage (serial) safety stock allocation model Parameters: - n: number of stages - h[i]: inventory cost on stage i - K: number of linear segments - f: (non-linear) cost function - T[i]: production lead time on stage i Returns the mode...
[ "def", "ssa", "(", "n", ",", "h", ",", "K", ",", "f", ",", "T", ")", ":", "model", "=", "Model", "(", "\"safety stock allocation\"", ")", "# calculate endpoints for linear segments", "a", ",", "b", "=", "{", "}", ",", "{", "}", "for", "i", "in", "ran...
32.65
17.825
def get_covers(work, args): """ Get missing covers. """ with contextlib.ExitStack() as cm: if args.filename == EMBEDDED_ALBUM_ART_SYMBOL: tmp_prefix = "%s_" % (os.path.splitext(os.path.basename(inspect.getfile(inspect.currentframe())))[0]) tmp_dir = cm.enter_context(tempfile.TemporaryDirectory(pref...
[ "def", "get_covers", "(", "work", ",", "args", ")", ":", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "cm", ":", "if", "args", ".", "filename", "==", "EMBEDDED_ALBUM_ART_SYMBOL", ":", "tmp_prefix", "=", "\"%s_\"", "%", "(", "os", ".", "path", ...
51.284091
27.340909
def int(self, *args): """ Return the integer stored in the specified node. Any type of integer will be decoded: byte, short, long, long long """ data = self.bytes(*args) if data is not None: if len(data) == 1: return struct.unpack("...
[ "def", "int", "(", "self", ",", "*", "args", ")", ":", "data", "=", "self", ".", "bytes", "(", "*", "args", ")", "if", "data", "is", "not", "None", ":", "if", "len", "(", "data", ")", "==", "1", ":", "return", "struct", ".", "unpack", "(", "\...
35.055556
14.833333
def _fill_pixels(one, other): # type: (_Raster, _Raster) -> _Raster """Merges two single band rasters with the same band by filling the pixels according to depth. """ assert len(one.band_names) == len(other.band_names) == 1, "Rasters are not single band" # We raise an error in the intersection is ...
[ "def", "_fill_pixels", "(", "one", ",", "other", ")", ":", "# type: (_Raster, _Raster) -> _Raster", "assert", "len", "(", "one", ".", "band_names", ")", "==", "len", "(", "other", ".", "band_names", ")", "==", "1", ",", "\"Rasters are not single band\"", "# We r...
49.5
24.840909
def scan(self): """Scan this node's dependents for implicit dependencies.""" # Don't bother scanning non-derived files, because we don't # care what their dependencies are. # Don't scan again, if we already have scanned. if self.implicit is not None: return se...
[ "def", "scan", "(", "self", ")", ":", "# Don't bother scanning non-derived files, because we don't", "# care what their dependencies are.", "# Don't scan again, if we already have scanned.", "if", "self", ".", "implicit", "is", "not", "None", ":", "return", "self", ".", "impl...
41.9375
17.729167
def put(self, request, id=None, **kwargs): """ Handles put requests. """ if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_update_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to pe...
[ "def", "put", "(", "self", ",", "request", ",", "id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "id", ":", "obj", "=", "get_object_or_404", "(", "self", ".", "queryset", "(", "request", ")", ",", "id", "=", "id", ")", "if", "not", "...
38.615385
16.461538
def process_paths(options, candidates=None, error=True): """Process files and log errors.""" errors = check_path(options, rootdir=CURDIR, candidates=candidates) if options.format in ['pycodestyle', 'pep8']: pattern = "%(filename)s:%(lnum)s:%(col)s: %(text)s" elif options.format == 'pylint': ...
[ "def", "process_paths", "(", "options", ",", "candidates", "=", "None", ",", "error", "=", "True", ")", ":", "errors", "=", "check_path", "(", "options", ",", "rootdir", "=", "CURDIR", ",", "candidates", "=", "candidates", ")", "if", "options", ".", "for...
33.85
20.7
def temp_output_file(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False): """ A context manager for convenience in creating a temporary file, which is deleted when exiting the context. Usage: with temp_output_file() as (fd, path): ... """ return _temp_output(False, prefix=p...
[ "def", "temp_output_file", "(", "prefix", "=", "\"tmp\"", ",", "suffix", "=", "\"\"", ",", "dir", "=", "None", ",", "make_parents", "=", "False", ",", "always_clean", "=", "False", ")", ":", "return", "_temp_output", "(", "False", ",", "prefix", "=", "pr...
37.818182
22.909091
def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FA...
[ "def", "fatal", "(", "msg", ",", "exitcode", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# NOTE: Can't use normal arg named `pause` since function has same name.", "pause_before_exit", "=", "kwargs", ".", "pop", "(", "\"pause\"", ")", "if", "\"pause\"", "in", "k...
44.444444
15.888889
def config_args(self): ''' Returns an iterator of 2-tuples (config_name, value), one for each configuration option in this config. This is more-or-less an internal method, but see, e.g., launch_tor()'s implementation if you think you need to use this for something. See :...
[ "def", "config_args", "(", "self", ")", ":", "everything", "=", "dict", "(", ")", "everything", ".", "update", "(", "self", ".", "config", ")", "everything", ".", "update", "(", "self", ".", "unsaved", ")", "for", "(", "k", ",", "v", ")", "in", "li...
36.133333
19.8
def register(cls, associations, backend, style_aliases={}): """ Register the supplied dictionary of associations between elements and plotting classes to the specified backend. """ if backend not in cls.registry: cls.registry[backend] = {} cls.registry[backend...
[ "def", "register", "(", "cls", ",", "associations", ",", "backend", ",", "style_aliases", "=", "{", "}", ")", ":", "if", "backend", "not", "in", "cls", ".", "registry", ":", "cls", ".", "registry", "[", "backend", "]", "=", "{", "}", "cls", ".", "r...
47.972973
22.891892
def convert_to_vcard(name, value, allowed_object_type): """converts user input into vcard compatible data structures :param name: object name, only required for error messages :type name: str :param value: user input :type value: str or list(str) :param allowed_object_type: set the accepted retu...
[ "def", "convert_to_vcard", "(", "name", ",", "value", ",", "allowed_object_type", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "if", "allowed_object_type", "==", "ObjectType", ".", "list_with_strings", ":", "raise", "ValueError", "(", "\"E...
43.025641
17.564103
def write_fundamental(self, keyTimeValueDict): ''' write fundamental ''' if self.first: Base.metadata.create_all(self.__getEngine(), checkfirst=True) self.first=False sqls=self._fundamentalToSqls(keyTimeValueDict) session=self.Session() try: ...
[ "def", "write_fundamental", "(", "self", ",", "keyTimeValueDict", ")", ":", "if", "self", ".", "first", ":", "Base", ".", "metadata", ".", "create_all", "(", "self", ".", "__getEngine", "(", ")", ",", "checkfirst", "=", "True", ")", "self", ".", "first",...
32.583333
16.75
def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts): """ One mode not only means all-in-one, it runs every thing in one process over tornado.ioloop, for debug purpose """ ctx.obj['debug'] = False g = ctx.obj g['testing_mode'] = True if scripts: from pyspider....
[ "def", "one", "(", "ctx", ",", "interactive", ",", "enable_phantomjs", ",", "enable_puppeteer", ",", "scripts", ")", ":", "ctx", ".", "obj", "[", "'debug'", "]", "=", "False", "g", "=", "ctx", ".", "obj", "g", "[", "'testing_mode'", "]", "=", "True", ...
36.352113
19.957746
def linkToChannelInputFile(self, session, channelInputFile, force=False): """ Create database relationships between the link node dataset and the channel input file. The link node dataset only stores references to the links and nodes--not the geometry. The link and node geometries are s...
[ "def", "linkToChannelInputFile", "(", "self", ",", "session", ",", "channelInputFile", ",", "force", "=", "False", ")", ":", "# Only perform operation if the channel input file has not been assigned or the force parameter is true", "if", "self", ".", "channelInputFile", "is", ...
45.589286
28.767857
def rewrite_elife_authors_json(json_content, doi): """ this does the work of rewriting elife authors json """ # Convert doi from testing doi if applicable article_doi = elifetools.utils.convert_testing_doi(doi) # Edge case fix an affiliation name if article_doi == "10.7554/eLife.06956": fo...
[ "def", "rewrite_elife_authors_json", "(", "json_content", ",", "doi", ")", ":", "# Convert doi from testing doi if applicable", "article_doi", "=", "elifetools", ".", "utils", ".", "convert_testing_doi", "(", "doi", ")", "# Edge case fix an affiliation name", "if", "article...
89.135593
55.389831
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
[ "def", "isNumber", "(", "self", ",", "value", ")", ":", "try", ":", "str", "(", "value", ")", "float", "(", "value", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
20.909091
15.818182
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
[ "def", "parse", "(", "self", ",", "inputstring", ",", "document", ")", ":", "link", "=", "json", ".", "loads", "(", "inputstring", ")", "env", "=", "document", ".", "settings", ".", "env", "source_dir", "=", "os", ".", "path", ".", "dirname", "(", "e...
41.346939
21.510204
def scan_to_module(python_modules, module, ignore=tuple()): """ Scans `python_modules` with :py:func:`scan` and adds found providers to `module`'s :py:attr:`wiring.configuration.Module.providers`. `ignore` argument is passed through to :py:func:`scan`. """ def callback(specification, provider):...
[ "def", "scan_to_module", "(", "python_modules", ",", "module", ",", "ignore", "=", "tuple", "(", ")", ")", ":", "def", "callback", "(", "specification", ",", "provider", ")", ":", "module", ".", "providers", "[", "specification", "]", "=", "provider", "sca...
41.2
15.8
def com_google_fonts_check_fsselection(ttFont, style): """Checking OS/2 fsSelection value.""" from fontbakery.utils import check_bit_entry from fontbakery.constants import (STATIC_STYLE_NAMES, RIBBI_STYLE_NAMES, FsSelection) # Checking fsS...
[ "def", "com_google_fonts_check_fsselection", "(", "ttFont", ",", "style", ")", ":", "from", "fontbakery", ".", "utils", "import", "check_bit_entry", "from", "fontbakery", ".", "constants", "import", "(", "STATIC_STYLE_NAMES", ",", "RIBBI_STYLE_NAMES", ",", "FsSelectio...
39.266667
10.8
def police_priority_map_conform_map_pri7_conform(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map...
[ "def", "police_priority_map_conform_map_pri7_conform", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "police_priority_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"police-priority-map\"", ...
49.846154
20.846154
def _close_thread(self, thread, thread_name): """Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread """ if thread is not None and thread.isAlive(): self.logger.debug("Waiting for {} thread to close".format...
[ "def", "_close_thread", "(", "self", ",", "thread", ",", "thread_name", ")", ":", "if", "thread", "is", "not", "None", "and", "thread", ".", "isAlive", "(", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Waiting for {} thread to close\"", ".", "for...
48.25
19.333333
def _selectTransition(self, allocentricLocation, objectDict, visitCounts): """ Choose the transition that lands us in the location we've touched the least often. Break ties randomly, i.e. choose the first candidate in a shuffled list. """ candidates = list(transition for t...
[ "def", "_selectTransition", "(", "self", ",", "allocentricLocation", ",", "objectDict", ",", "visitCounts", ")", ":", "candidates", "=", "list", "(", "transition", "for", "transition", "in", "self", ".", "transitions", ".", "keys", "(", ")", "if", "(", "allo...
39.178571
21.678571
def ar1_gen(rho, mu, sigma, size=1): """Create an autoregressive series of order one AR(1) generator. .. math:: X_t = \mu_t + \rho (X_{t-1}-\mu_{t-1} + \epsilon_t If mu is a sequence and size > len(mu), the algorithm loops through mu. :Stochastics: rho : scalar in [0,1] mu...
[ "def", "ar1_gen", "(", "rho", ",", "mu", ",", "sigma", ",", "size", "=", "1", ")", ":", "mu", "=", "np", ".", "asarray", "(", "mu", ",", "float", ")", "mu", "=", "np", ".", "resize", "(", "mu", ",", "size", ")", "r", "=", "mu", ".", "copy",...
25.814815
19.481481
def decode_field(self, field, value): """Decode the given JSON value. Args: field: a messages.Field for the field we're decoding. value: a python value we'd like to decode. Returns: A value suitable for assignment to field. """ for decoder in _GetF...
[ "def", "decode_field", "(", "self", ",", "field", ",", "value", ")", ":", "for", "decoder", "in", "_GetFieldCodecs", "(", "field", ",", "'decoder'", ")", ":", "result", "=", "decoder", "(", "field", ",", "value", ")", "value", "=", "result", ".", "valu...
37.3125
14.5625
def decode_transaction_input(self, transaction_hash: bytes) -> Dict: """Return inputs of a method call""" transaction = self.contract.web3.eth.getTransaction( transaction_hash, ) return self.contract.decode_function_input( transaction['input'], )
[ "def", "decode_transaction_input", "(", "self", ",", "transaction_hash", ":", "bytes", ")", "->", "Dict", ":", "transaction", "=", "self", ".", "contract", ".", "web3", ".", "eth", ".", "getTransaction", "(", "transaction_hash", ",", ")", "return", "self", "...
33.666667
19.888889
def set_nonblock(fd): # type: (int) -> None """Set the given file descriptor to non-blocking mode.""" fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
[ "def", "set_nonblock", "(", "fd", ")", ":", "# type: (int) -> None", "fcntl", ".", "fcntl", "(", "fd", ",", "fcntl", ".", "F_SETFL", ",", "fcntl", ".", "fcntl", "(", "fd", ",", "fcntl", ".", "F_GETFL", ")", "|", "os", ".", "O_NONBLOCK", ")" ]
36.5
14.666667
def write(self, arg): """ Write a string or bytes object to the buffer """ if isinstance(arg, str): arg = arg.encode(self.encoding) return self._buffer.write(arg)
[ "def", "write", "(", "self", ",", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "arg", "=", "arg", ".", "encode", "(", "self", ".", "encoding", ")", "return", "self", ".", "_buffer", ".", "write", "(", "arg", ")" ]
38.8
6.4
def set_outgoing(self, value): """ Setter for 'outgoing' field. :param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows. """ if not isinstance(value, list): raise TypeError("OutgoingList new value must be a list") ...
[ "def", "set_outgoing", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "TypeError", "(", "\"OutgoingList new value must be a list\"", ")", "for", "element", "in", "value", ":", "if", "not", "isins...
46
16.727273
def read_openke_translation(filename, delimiter='\t', entity_first=True): """Returns map with entity or relations from plain text.""" result = {} with open(filename, "r") as f: _ = next(f) # pass the total entry number for line in f: line_slice = line.rstrip().split(delimiter) ...
[ "def", "read_openke_translation", "(", "filename", ",", "delimiter", "=", "'\\t'", ",", "entity_first", "=", "True", ")", ":", "result", "=", "{", "}", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "_", "=", "next", "(", "f", ")...
38.666667
16.75
def _on_mode_change(self, mode): """Mode change broadcast from Abode SocketIO server.""" if isinstance(mode, (tuple, list)): mode = mode[0] if mode is None: _LOGGER.warning("Mode change event with no mode.") return if not mode or mode.lower() not in ...
[ "def", "_on_mode_change", "(", "self", ",", "mode", ")", ":", "if", "isinstance", "(", "mode", ",", "(", "tuple", ",", "list", ")", ")", ":", "mode", "=", "mode", "[", "0", "]", "if", "mode", "is", "None", ":", "_LOGGER", ".", "warning", "(", "\"...
39.846154
24.423077
def setup(self, np=np, numpy_version=numpy_version, StrictVersion=StrictVersion, new_pandas=new_pandas): """Lives in zipline.__init__ for doctests.""" if numpy_version >= StrictVersion('1.14'): self.old_opts = np.get_printoptions() np.set_printoptions(leg...
[ "def", "setup", "(", "self", ",", "np", "=", "np", ",", "numpy_version", "=", "numpy_version", ",", "StrictVersion", "=", "StrictVersion", ",", "new_pandas", "=", "new_pandas", ")", ":", "if", "numpy_version", ">=", "StrictVersion", "(", "'1.14'", ")", ":", ...
27.894737
15.210526
def diffsp(self, col: str, serie: "iterable", name: str="Diff"): """ Add a diff column in percentage from a serie. The serie is an iterable of the same length than the dataframe :param col: column to diff :type col: str :param serie: serie to diff from :type ser...
[ "def", "diffsp", "(", "self", ",", "col", ":", "str", ",", "serie", ":", "\"iterable\"", ",", "name", ":", "str", "=", "\"Diff\"", ")", ":", "try", ":", "d", "=", "[", "]", "for", "i", ",", "row", "in", "self", ".", "df", ".", "iterrows", "(", ...
34.909091
16.181818
def delete(self): """ Removes current SyncItem """ url = SyncList.key.format(clientId=self.clientIdentifier) url += '/' + str(self.id) self._server.query(url, self._server._session.delete)
[ "def", "delete", "(", "self", ")", ":", "url", "=", "SyncList", ".", "key", ".", "format", "(", "clientId", "=", "self", ".", "clientIdentifier", ")", "url", "+=", "'/'", "+", "str", "(", "self", ".", "id", ")", "self", ".", "_server", ".", "query"...
43.2
15.2
def client_ident(self): """ Return the client identifier as included in many command replies. """ return irc.client.NickMask.from_params( self.nick, self.user, self.server.servername)
[ "def", "client_ident", "(", "self", ")", ":", "return", "irc", ".", "client", ".", "NickMask", ".", "from_params", "(", "self", ".", "nick", ",", "self", ".", "user", ",", "self", ".", "server", ".", "servername", ")" ]
33.285714
9.857143
def findPkt(pkt): """ Search through a string of binary for a valid xl320 package. in: buffer to search through out: a list of valid data packet """ # print('findpkt', pkt) # print('-----------------------') ret = [] while len(pkt)-10 >= 0: if pkt[0:4] != [0xFF, 0xFF, 0xFD, 0x00]: pkt.pop(0) # get rid o...
[ "def", "findPkt", "(", "pkt", ")", ":", "# print('findpkt', pkt)", "# print('-----------------------')", "ret", "=", "[", "]", "while", "len", "(", "pkt", ")", "-", "10", ">=", "0", ":", "if", "pkt", "[", "0", ":", "4", "]", "!=", "[", "0xFF", ",", "...
25.717949
14.179487
def delete(self, container, del_objects=False): """ Deletes the specified container. If the container contains objects, the command will fail unless 'del_objects' is passed as True. In that case, each object will be deleted first, and then the container. """ if del_object...
[ "def", "delete", "(", "self", ",", "container", ",", "del_objects", "=", "False", ")", ":", "if", "del_objects", ":", "nms", "=", "self", ".", "list_object_names", "(", "container", ",", "full_listing", "=", "True", ")", "self", ".", "api", ".", "bulk_de...
49.818182
18.181818
def from_dict(cls, obj_dict): """ Load the object from a dictionary (produced with :py:func:`Concise.to_dict`) Returns: Concise: Loaded Concise object. """ # convert the output into a proper form obj_dict['output'] = helper.rec_dict_to_numpy_dict(obj_dict["o...
[ "def", "from_dict", "(", "cls", ",", "obj_dict", ")", ":", "# convert the output into a proper form", "obj_dict", "[", "'output'", "]", "=", "helper", ".", "rec_dict_to_numpy_dict", "(", "obj_dict", "[", "\"output\"", "]", ")", "helper", ".", "dict_to_numpy_dict", ...
36.378378
21.405405
def update(self, **kwargs): """Call this to change the configuration of the service on the device. This method uses HTTP PUT alter the service state on the device. The attributes of the instance will be packaged as a dictionary. That dictionary will be updated with kwargs. It is then...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "checked", "=", "self", ".", "_check_node_parameters", "(", "*", "*", "kwargs", ")", "return", "self", ".", "_update", "(", "*", "*", "checked", ")" ]
42.888889
26.277778
def do_notify(context, event_type, payload): """Generic Notifier. Parameters: - `context`: session context - `event_type`: the event type to report, i.e. ip.usage - `payload`: dict containing the payload to send """ LOG.debug('IP_BILL: notifying {}'.format(payload)) notifie...
[ "def", "do_notify", "(", "context", ",", "event_type", ",", "payload", ")", ":", "LOG", ".", "debug", "(", "'IP_BILL: notifying {}'", ".", "format", "(", "payload", ")", ")", "notifier", "=", "n_rpc", ".", "get_notifier", "(", "'network'", ")", "notifier", ...
32.5
14.75
def binary_dilation(x, radius=3): """Return fast binary morphological dilation of an image. see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__. Parameters ----------- x : 2D array A binary image. r...
[ "def", "binary_dilation", "(", "x", ",", "radius", "=", "3", ")", ":", "mask", "=", "disk", "(", "radius", ")", "x", "=", "_binary_dilation", "(", "x", ",", "selem", "=", "mask", ")", "return", "x" ]
24.047619
25.380952
def flag_inner_classes(obj): """ Mutates any attributes on ``obj`` which are classes, with link to ``obj``. Adds a convenience accessor which instantiates ``obj`` and then calls its ``setup`` method. Recurses on those objects as well. """ for tup in class_members(obj): tup[1]._pare...
[ "def", "flag_inner_classes", "(", "obj", ")", ":", "for", "tup", "in", "class_members", "(", "obj", ")", ":", "tup", "[", "1", "]", ".", "_parent", "=", "obj", "tup", "[", "1", "]", ".", "_parent_inst", "=", "None", "tup", "[", "1", "]", ".", "__...
30.357143
15.642857
def getvalue(self) -> str: """Get the internal contents as a str""" return self.buffer.byte_buf.decode(encoding=self.encoding, errors=self.errors)
[ "def", "getvalue", "(", "self", ")", "->", "str", ":", "return", "self", ".", "buffer", ".", "byte_buf", ".", "decode", "(", "encoding", "=", "self", ".", "encoding", ",", "errors", "=", "self", ".", "errors", ")" ]
53.333333
20
def chrome_tracing_dump(self, filename=None): """Return a list of profiling events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome w...
[ "def", "chrome_tracing_dump", "(", "self", ",", "filename", "=", "None", ")", ":", "# TODO(rkn): Support including the task specification data in the", "# timeline.", "# TODO(rkn): This should support viewing just a window of time or a", "# limited number of events.", "profile_table", ...
44.942029
21.985507
def _harvest_lost_resources(self): """Return lost resources to pool.""" with self._lock: for i in self._unavailable_range(): rtracker = self._reference_queue[i] if rtracker is not None and rtracker.available(): self.put_resource(rtracker.re...
[ "def", "_harvest_lost_resources", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "for", "i", "in", "self", ".", "_unavailable_range", "(", ")", ":", "rtracker", "=", "self", ".", "_reference_queue", "[", "i", "]", "if", "rtracker", "is", "not"...
45.857143
11.571429
def get_features(self, did, wid, eid): ''' Gets the feature list for specified document / workspace / part studio. Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response: Onshape resp...
[ "def", "get_features", "(", "self", ",", "did", ",", "wid", ",", "eid", ")", ":", "return", "self", ".", "_api", ".", "request", "(", "'get'", ",", "'/api/partstudios/d/'", "+", "did", "+", "'/w/'", "+", "wid", "+", "'/e/'", "+", "eid", "+", "'/featu...
31.428571
26.142857
def gather_verify_arguments(self): """ Need to add some information before running verify() :return: dictionary with arguments to the verify call """ kwargs = {'client_id': self.service_context.client_id, 'iss': self.service_context.issuer, '...
[ "def", "gather_verify_arguments", "(", "self", ")", ":", "kwargs", "=", "{", "'client_id'", ":", "self", ".", "service_context", ".", "client_id", ",", "'iss'", ":", "self", ".", "service_context", ".", "issuer", ",", "'keyjar'", ":", "self", ".", "service_c...
33.5
17
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
[ "def", "commonprefix", "(", "m", ")", ":", "if", "not", "m", ":", "return", "''", "s1", "=", "min", "(", "m", ")", "s2", "=", "max", "(", "m", ")", "for", "i", ",", "c", "in", "enumerate", "(", "s1", ")", ":", "if", "c", "!=", "s2", "[", ...
26.666667
21.555556
def serve(): """main entry point""" logging.getLogger().setLevel(logging.DEBUG) logging.info('Python Tornado Crossdock Server Running ...') server = Server(DefaultServerPortTChannel) endtoend_handler = EndToEndHandler() app = make_app(server, endtoend_handler) app.listen(DefaultClientPortHTT...
[ "def", "serve", "(", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logging", ".", "info", "(", "'Python Tornado Crossdock Server Running ...'", ")", "server", "=", "Server", "(", "DefaultServerPortTChannel"...
38.454545
8.090909
def _convert_string_name(self, k): """converts things like FOO_BAR to Foo-Bar which is the normal form""" k = String(k, "iso-8859-1") klower = k.lower().replace('_', '-') bits = klower.split('-') return "-".join((bit.title() for bit in bits))
[ "def", "_convert_string_name", "(", "self", ",", "k", ")", ":", "k", "=", "String", "(", "k", ",", "\"iso-8859-1\"", ")", "klower", "=", "k", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'-'", ")", "bits", "=", "klower", ".", "split", ...
46.166667
6.166667
def _create_solver(self): r""" This method creates the petsc sparse linear solver. """ # http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/KSP/KSPType.html#KSPType iterative_solvers = ['richardson', 'chebyshev', 'cg', 'groppcg', 'pipecg', 'p...
[ "def", "_create_solver", "(", "self", ")", ":", "# http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/KSP/KSPType.html#KSPType", "iterative_solvers", "=", "[", "'richardson'", ",", "'chebyshev'", ",", "'cg'", ",", "'groppcg'", ",", "'pipecg'", ",", "'pipecgrr'", ",...
47.926471
22.294118
def _search(self, addr): """ Checks which segment that the address `addr` should belong to, and, returns the offset of that segment. Note that the address may not actually belong to the block. :param addr: The address to search :return: The offset of the segment. """ ...
[ "def", "_search", "(", "self", ",", "addr", ")", ":", "start", "=", "0", "end", "=", "len", "(", "self", ".", "_list", ")", "while", "start", "!=", "end", ":", "mid", "=", "(", "start", "+", "end", ")", "//", "2", "segment", "=", "self", ".", ...
26.923077
18.769231
def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :par...
[ "def", "create_xml_path", "(", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "fp_", ":", "return", "create_xml_str", "(", "salt", ".", "utils", "...
29.793103
25.586207
def setdefault(self, k, d=None): """Override dict.setdefault() to title-case keys.""" return super(HeaderDict, self).setdefault(k.title(), d)
[ "def", "setdefault", "(", "self", ",", "k", ",", "d", "=", "None", ")", ":", "return", "super", "(", "HeaderDict", ",", "self", ")", ".", "setdefault", "(", "k", ".", "title", "(", ")", ",", "d", ")" ]
38.75
17.75
def is_well_grounded_concept(c: Concept, cutoff: float = 0.7) -> bool: """Check if a concept has a high grounding score. """ return is_grounded(c) and (top_grounding_score(c) >= cutoff)
[ "def", "is_well_grounded_concept", "(", "c", ":", "Concept", ",", "cutoff", ":", "float", "=", "0.7", ")", "->", "bool", ":", "return", "is_grounded", "(", "c", ")", "and", "(", "top_grounding_score", "(", "c", ")", ">=", "cutoff", ")" ]
47.75
23.5
def _string_width(self, s): """Get width of a string in the current font""" s = str(s) w = 0 for i in s: w += self.character_widths[i] return w * self.font_size / 1000.0
[ "def", "_string_width", "(", "self", ",", "s", ")", ":", "s", "=", "str", "(", "s", ")", "w", "=", "0", "for", "i", "in", "s", ":", "w", "+=", "self", ".", "character_widths", "[", "i", "]", "return", "w", "*", "self", ".", "font_size", "/", ...
31.571429
11.857143
def ticket_skips(self, ticket_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_skips#list-skips-for-the-current-account" api_path = "/api/v2/tickets/{ticket_id}/skips.json" api_path = api_path.format(ticket_id=ticket_id) return self.call(api_path, **kwargs)
[ "def", "ticket_skips", "(", "self", ",", "ticket_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/tickets/{ticket_id}/skips.json\"", "api_path", "=", "api_path", ".", "format", "(", "ticket_id", "=", "ticket_id", ")", "return", "self", ".", ...
61.6
21.6
def handle_new_selection(self, models): """Handles the selection for generic widgets This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list of newly selected (or clicked on) models. The method looks at the previous selection, the pa...
[ "def", "handle_new_selection", "(", "self", ",", "models", ")", ":", "models", "=", "self", ".", "_check_model_types", "(", "models", ")", "if", "extend_selection", "(", ")", ":", "already_selected_elements", "=", "models", "&", "self", ".", "_selected", "newl...
49.12
31.16
def connect(self, callback, ref=False, position='first', before=None, after=None): """ Connect the callback to the event group. The callback will receive events from *all* of the emitters in the group. See :func:`EventEmitter.connect() <vispy.event.EventEmitter.connect>` ...
[ "def", "connect", "(", "self", ",", "callback", ",", "ref", "=", "False", ",", "position", "=", "'first'", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "self", ".", "_connect_emitters", "(", "True", ")", "return", "EventEmitter", "....
44.727273
15.181818
def invitations(): """List and manage received invitations. """ with Session() as session: try: result = session.VFolder.invitations() invitations = result.get('invitations', []) if len(invitations) < 1: print('No invitations.') ret...
[ "def", "invitations", "(", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "result", "=", "session", ".", "VFolder", ".", "invitations", "(", ")", "invitations", "=", "result", ".", "get", "(", "'invitations'", ",", "[", "]", ...
42.702128
15.234043
def write(self, path, wrap_ttl=None, **kwargs): """Wrap the hvac write call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, se...
[ "def", "write", "(", "self", ",", "path", ",", "wrap_ttl", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "sanitize_mount", "(", "path", ")", "val", "=", "None", "if", "path", ".", "startswith", "(", "'cubbyhole'", ")", ":", "self", "...
39
15.615385
def check_usufy(self, query, **kwargs): """ Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to ...
[ "def", "check_usufy", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "launchQueryForMode", "(", "query", "=", "query", ",", "mode", "=", "\"usufy\"", ")", "if", "self", ".", "_somethingFound", "(", "data", ",", ...
32.3
21.5
def get_subnets(): """ :return: all knows subnets """ LOGGER.debug("SubnetService.get_subnets") args = {'http_operation': 'GET', 'operation_path': ''} response = SubnetService.requester.call(args) ret = None if response.rc == 0: ret = [] ...
[ "def", "get_subnets", "(", ")", ":", "LOGGER", ".", "debug", "(", "\"SubnetService.get_subnets\"", ")", "args", "=", "{", "'http_operation'", ":", "'GET'", ",", "'operation_path'", ":", "''", "}", "response", "=", "SubnetService", ".", "requester", ".", "call"...
41.722222
17.944444
def setData(self, column, role, value): """ if value is valid sets the data to value Args: column: column of item role: role of item (see Qt doc) value: value to be set """ assert isinstance(column, int) assert isinstance(role, int) ...
[ "def", "setData", "(", "self", ",", "column", ",", "role", ",", "value", ")", ":", "assert", "isinstance", "(", "column", ",", "int", ")", "assert", "isinstance", "(", "role", ",", "int", ")", "# make sure that the right row is selected, this is not always the cas...
36.625
22.75
def from_response_data(cls, response_data): """ Response factory :param response_data: requests.models.Response :return: pybomb.clients.Response """ response_json = response_data.json() return cls( response_data.url, response_json["numbe...
[ "def", "from_response_data", "(", "cls", ",", "response_data", ")", ":", "response_json", "=", "response_data", ".", "json", "(", ")", "return", "cls", "(", "response_data", ".", "url", ",", "response_json", "[", "\"number_of_page_results\"", "]", ",", "response...
26.6875
15.4375
def param(name, value_info, is_required=True, label=None, desc=None): """ Annotate a parameter of the action being defined. @param name: name of the parameter defined. @type name: unicode or str @param value_info: the parameter value information. @type value_info: value.IValueInfo @param is_...
[ "def", "param", "(", "name", ",", "value_info", ",", "is_required", "=", "True", ",", "label", "=", "None", ",", "desc", "=", "None", ")", ":", "_annotate", "(", "\"param\"", ",", "name", ",", "value_info", ",", "is_required", "=", "is_required", ",", ...
42.125
10.125
def set_qubit(self, qubit, element): """ Sets the qubit to the element Args: qubit (qbit): Element of self.qregs. element (DrawElement): Element to set in the qubit """ self.qubit_layer[self.qregs.index(qubit)] = element
[ "def", "set_qubit", "(", "self", ",", "qubit", ",", "element", ")", ":", "self", ".", "qubit_layer", "[", "self", ".", "qregs", ".", "index", "(", "qubit", ")", "]", "=", "element" ]
34.625
10.375
def camel_case_to_snake_case(name): """ HelloWorld -> hello_world """ s1 = _FIRST_CAP_RE.sub(r'\1_\2', name) return _ALL_CAP_RE.sub(r'\1_\2', s1).lower()
[ "def", "camel_case_to_snake_case", "(", "name", ")", ":", "s1", "=", "_FIRST_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "name", ")", "return", "_ALL_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
28
4.333333