text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def covariance_matrix(self,x,y,names=None,cov=None): """build a pyemu.Cov instance implied by Vario2d Parameters ---------- x : (iterable of floats) x-coordinate locations y : (iterable of floats) y-coordinate locations names : (iterable of str) ...
[ "def", "covariance_matrix", "(", "self", ",", "x", ",", "y", ",", "names", "=", "None", ",", "cov", "=", "None", ")", ":", "if", "not", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", ...
32.033898
15.508475
def modify_filename_id(filename): """Modify filename to have a unique numerical identifier.""" split_filename = os.path.splitext(filename) id_num_re = re.compile('(\(\d\))') id_num = re.findall(id_num_re, split_filename[-2]) if id_num: new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1...
[ "def", "modify_filename_id", "(", "filename", ")", ":", "split_filename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "id_num_re", "=", "re", ".", "compile", "(", "'(\\(\\d\\))'", ")", "id_num", "=", "re", ".", "findall", "(", "id_num_re...
43.5
20.722222
def property_(getter: Map[Domain, Range]) -> property: """ Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable. """ return property(map_(WeakKeyDictionary())(getter))
[ "def", "property_", "(", "getter", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "->", "property", ":", "return", "property", "(", "map_", "(", "WeakKeyDictionary", "(", ")", ")", "(", "getter", ")", ")" ]
35.125
15.125
def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; it is possible that we may create a new dtype of block return the resulting block(s) Parameters ---------- mask : the condition to respe...
[ "def", "putmask", "(", "self", ",", "mask", ",", "new", ",", "align", "=", "True", ",", "inplace", "=", "False", ",", "axis", "=", "0", ",", "transpose", "=", "False", ")", ":", "new_values", "=", "self", ".", "values", "if", "inplace", "else", "se...
33.468468
19.225225
def reset_all(self, suppress_logging=False): """ iterates thru the list of established connections and resets them by disconnecting and reconnecting """ pool_names = list(self.pools) for name in pool_names: self.reset(name, suppress_logging)
[ "def", "reset_all", "(", "self", ",", "suppress_logging", "=", "False", ")", ":", "pool_names", "=", "list", "(", "self", ".", "pools", ")", "for", "name", "in", "pool_names", ":", "self", ".", "reset", "(", "name", ",", "suppress_logging", ")" ]
54.6
4.4
def _validate_names(names): """ Check if the `names` parameter contains duplicates. If duplicates are found, we issue a warning before returning. Parameters ---------- names : array-like or None An array containing a list of the names used for the output DataFrame. Returns ---...
[ "def", "_validate_names", "(", "names", ")", ":", "if", "names", "is", "not", "None", ":", "if", "len", "(", "names", ")", "!=", "len", "(", "set", "(", "names", ")", ")", ":", "msg", "=", "(", "\"Duplicate names specified. This \"", "\"will raise an error...
26.5
21.166667
def markdown(text, escape=True, **kwargs): """Render markdown formatted text to html. :param text: markdown formatted text content. :param escape: if set to False, all html tags will not be escaped. :param use_xhtml: output with xhtml tags. :param hard_wrap: if set to True, it will use the GFM line...
[ "def", "markdown", "(", "text", ",", "escape", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "Markdown", "(", "escape", "=", "escape", ",", "*", "*", "kwargs", ")", "(", "text", ")" ]
47.181818
16.909091
def bench_factory(): """Benchmark for 1000 objects with 2 fields. """ class TestSchema(BaseSchema): attr_1 = StringNode() attr_2 = IntegerNode() @property def attr_3(self): return 'FooBar' @staticmethod def prepare_attr_1(value): ret...
[ "def", "bench_factory", "(", ")", ":", "class", "TestSchema", "(", "BaseSchema", ")", ":", "attr_1", "=", "StringNode", "(", ")", "attr_2", "=", "IntegerNode", "(", ")", "@", "property", "def", "attr_3", "(", "self", ")", ":", "return", "'FooBar'", "@", ...
23.238095
17.666667
def get_spectrum(self, nr_id=None, abmn=None, plot_filename=None): """Return a spectrum and its reciprocal counter part, if present in the dataset. Optimally, refer to the spectrum by its normal-reciprocal id. Returns ------- spectrum_nor : :py:class:`reda.eis.plots.sip_response...
[ "def", "get_spectrum", "(", "self", ",", "nr_id", "=", "None", ",", "abmn", "=", "None", ",", "plot_filename", "=", "None", ")", ":", "assert", "nr_id", "is", "None", "or", "abmn", "is", "None", "# determine nr_id for given abmn tuple", "if", "abmn", "is", ...
38.412698
15.555556
def from_json_list(cls, api_client, data): """Convert a list of JSON values to a list of models """ return [cls.from_json(api_client, item) for item in data]
[ "def", "from_json_list", "(", "cls", ",", "api_client", ",", "data", ")", ":", "return", "[", "cls", ".", "from_json", "(", "api_client", ",", "item", ")", "for", "item", "in", "data", "]" ]
44.5
6.75
def p_ifdef(p): """ ifdef : if_header NEWLINE program ENDIF """ global ENABLED if ENABLED: p[0] = [p[2]] + p[3] p[0] += ['#line %i "%s"' % (p.lineno(4) + 1, CURRENT_FILE[-1])] else: p[0] = ['#line %i "%s"' % (p.lineno(4) + 1, CURRENT_FILE[-1])] ENABLED = IFDEFS[-1][0] ...
[ "def", "p_ifdef", "(", "p", ")", ":", "global", "ENABLED", "if", "ENABLED", ":", "p", "[", "0", "]", "=", "[", "p", "[", "2", "]", "]", "+", "p", "[", "3", "]", "p", "[", "0", "]", "+=", "[", "'#line %i \"%s\"'", "%", "(", "p", ".", "lineno...
24.846154
22.538462
def setup(self, phase=None, quantity='', conductance='', t_initial=None, t_final=None, t_step=None, t_output=None, t_tolerance=None, t_precision=None, t_scheme='', **kwargs): r""" This method takes several arguments that are essential to running the algorithm and adds...
[ "def", "setup", "(", "self", ",", "phase", "=", "None", ",", "quantity", "=", "''", ",", "conductance", "=", "''", ",", "t_initial", "=", "None", ",", "t_final", "=", "None", ",", "t_step", "=", "None", ",", "t_output", "=", "None", ",", "t_tolerance...
42.153846
23.43956
def get_data_info(self): """ imports er tables and places data into Data_info data structure outlined bellow: Data_info - {er_samples: {er_samples.txt info} er_sites: {er_sites.txt info} er_locations: {er_locations.txt info} ...
[ "def", "get_data_info", "(", "self", ")", ":", "Data_info", "=", "{", "}", "data_er_samples", "=", "{", "}", "data_er_sites", "=", "{", "}", "data_er_locations", "=", "{", "}", "data_er_ages", "=", "{", "}", "if", "self", ".", "data_model", "==", "3.0", ...
46.298507
20.761194
def load_file(self, filename): """Read and return the content of the given file. If the current directory is not defined explicitly, the directory name is constructed with the actual simulation start date. If such an directory does not exist, it is created immediately. """ ...
[ "def", "load_file", "(", "self", ",", "filename", ")", ":", "_defaultdir", "=", "self", ".", "DEFAULTDIR", "try", ":", "if", "not", "filename", ".", "endswith", "(", "'.py'", ")", ":", "filename", "+=", "'.py'", "try", ":", "self", ".", "DEFAULTDIR", "...
38.88
15.52
def _denom(self, R, z): """ NAME: _denom PURPOSE: evaluate R^2 + (a + |z|)^2 which is used in the denominator of most equations INPUT: R - Cylindrical Galactocentric radius z - vertical height OUTPUT: R^2 + (a + |z...
[ "def", "_denom", "(", "self", ",", "R", ",", "z", ")", ":", "return", "(", "R", "**", "2.", "+", "(", "self", ".", "_a", "+", "nu", ".", "fabs", "(", "z", ")", ")", "**", "2.", ")" ]
27.0625
15.6875
def register_model(cls, admin=None): """Register *cls* to be included in the API service :param cls: Class deriving from :class:`sandman2.models.Model` """ cls.__url__ = '/{}'.format(cls.__name__.lower()) service_class = type( cls.__name__ + 'Service', (Service,), { ...
[ "def", "register_model", "(", "cls", ",", "admin", "=", "None", ")", ":", "cls", ".", "__url__", "=", "'/{}'", ".", "format", "(", "cls", ".", "__name__", ".", "lower", "(", ")", ")", "service_class", "=", "type", "(", "cls", ".", "__name__", "+", ...
32.75
16.6875
def authenticated(func): """ Decorator to check if Smappee's access token has expired. If it has, use the refresh token to request a new access token """ @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.refresh_token is not None and \ self.token_expira...
[ "def", "authenticated", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "if", "self", ".", "refresh_token", "is", "not", "None", "an...
33.307692
13.307692
def create_app(config_file=None, config=None): """Flask app factory function.""" app = Flask(__name__) app.config.from_pyfile('config.py') app.jinja_env.add_extension('jinja2.ext.do') if config: app.config.update(config) if config_file: app.config.from_pyfile(config_file) # ...
[ "def", "create_app", "(", "config_file", "=", "None", ",", "config", "=", "None", ")", ":", "app", "=", "Flask", "(", "__name__", ")", "app", ".", "config", ".", "from_pyfile", "(", "'config.py'", ")", "app", ".", "jinja_env", ".", "add_extension", "(", ...
42.166667
22
def get_graphviz(self, engine="automatic", graph_attr=None, node_attr=None, edge_attr=None): """ Generate flow graph in the DOT language. Args: engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage'] graph_attr: Mapping of (at...
[ "def", "get_graphviz", "(", "self", ",", "engine", "=", "\"automatic\"", ",", "graph_attr", "=", "None", ",", "node_attr", "=", "None", ",", "edge_attr", "=", "None", ")", ":", "self", ".", "allocate", "(", ")", "from", "graphviz", "import", "Digraph", "...
44.833333
20.598039
def from_equation(expr, vars, pars, name=None, hessian=False): r""" Create a potential class from an expression for the potential. .. note:: This utility requires having `Sympy <http://www.sympy.org/>`_ installed. .. warning:: These potentials are *not* pickle-able and cannot be writ...
[ "def", "from_equation", "(", "expr", ",", "vars", ",", "pars", ",", "name", "=", "None", ",", "hessian", "=", "False", ")", ":", "try", ":", "import", "sympy", "from", "sympy", ".", "utilities", ".", "lambdify", "import", "lambdify", "except", "ImportErr...
32.462069
21.213793
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
[ "def", "clear", "(", "self", ")", ":", "self", ".", "name", ".", "clear", "(", ")", "self", ".", "path", ".", "clear", "(", ")", "self", ".", "generated", "=", "False" ]
25
11.571429
def _stream(self): """execute subprocess with timeout Usage:: >>> with cmd_proc.run_with_timeout() as cmd_proc: ... stdout, stderr = cmd_proc.communicate() ... >>> assert cmd_proc.proc.return_code == 0, "proc exec failed" """ timer =...
[ "def", "_stream", "(", "self", ")", ":", "timer", "=", "None", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "self", ".", "cmd", ",", "cwd", "=", "self", ".", "cwd", ",", "env", "=", "self", ".", "env", ",", "stdout", "=", "subprocess...
28.333333
18.222222
def fields(self, locale=None): """Get fields for a specific locale :param locale: (optional) Locale to fetch, defaults to default_locale. """ if locale is None: locale = self._locale() return self._fields.get(locale, {})
[ "def", "fields", "(", "self", ",", "locale", "=", "None", ")", ":", "if", "locale", "is", "None", ":", "locale", "=", "self", ".", "_locale", "(", ")", "return", "self", ".", "_fields", ".", "get", "(", "locale", ",", "{", "}", ")" ]
29.555556
16.666667
def get_cbm_vbm(self, tol=0.001, abs_tol=False, spin=None): """ Expects a DOS object and finds the cbm and vbm. Args: tol: tolerance in occupations for determining the gap abs_tol: An absolute tolerance (True) and a relative one (False) spin: Possible values ...
[ "def", "get_cbm_vbm", "(", "self", ",", "tol", "=", "0.001", ",", "abs_tol", "=", "False", ",", "spin", "=", "None", ")", ":", "# determine tolerance", "tdos", "=", "self", ".", "get_densities", "(", "spin", ")", "if", "not", "abs_tol", ":", "tol", "="...
36.571429
20.228571
def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] ad = self.getaddress() while ad: result += ad ad = self.getaddress() return result
[ "def", "getaddrlist", "(", "self", ")", ":", "result", "=", "[", "]", "ad", "=", "self", ".", "getaddress", "(", ")", "while", "ad", ":", "result", "+=", "ad", "ad", "=", "self", ".", "getaddress", "(", ")", "return", "result" ]
24
15.272727
def remove(self, *values): """Remove the defined variables. The variables to be removed can be selected in two ways. But the first example shows that passing nothing or an empty iterable to method |Variable2Auxfile.remove| does not remove any variable: >>> from hydpy import du...
[ "def", "remove", "(", "self", ",", "*", "values", ")", ":", "for", "value", "in", "objecttools", ".", "extract", "(", "values", ",", "(", "str", ",", "variabletools", ".", "Variable", ")", ")", ":", "try", ":", "deleted_something", "=", "False", "for",...
38.648649
18.554054
def get_db_attribute(self, table, record, column, key=None): """ Gets values of 'column' in 'record' in 'table'. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl get TBL REC COL[:KEY] """ if key is not None: column = '%s:%s' ...
[ "def", "get_db_attribute", "(", "self", ",", "table", ",", "record", ",", "column", ",", "key", "=", "None", ")", ":", "if", "key", "is", "not", "None", ":", "column", "=", "'%s:%s'", "%", "(", "column", ",", "key", ")", "command", "=", "ovs_vsctl", ...
32.875
13.625
def _handle_get(self, request): # type: (Get) -> CallbackResponses """Called with the lock taken""" data = self._block for i, endpoint in enumerate(request.path[1:]): try: data = data[endpoint] except KeyError: if hasattr(data, "ty...
[ "def", "_handle_get", "(", "self", ",", "request", ")", ":", "# type: (Get) -> CallbackResponses", "data", "=", "self", ".", "_block", "for", "i", ",", "endpoint", "in", "enumerate", "(", "request", ".", "path", "[", "1", ":", "]", ")", ":", "try", ":", ...
38.2
13.4
def _set_attribute(self, name, value): """Make sure namespace gets updated when setting attributes.""" setattr(self, name, value) self.namespace.update({name: getattr(self, name)})
[ "def", "_set_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "setattr", "(", "self", ",", "name", ",", "value", ")", "self", ".", "namespace", ".", "update", "(", "{", "name", ":", "getattr", "(", "self", ",", "name", ")", "}", ")" ]
50.25
6.5
def revealjs(basedir=None, title=None, subtitle=None, description=None, github_user=None, github_repo=None): '''Set up or update a reveals.js presentation with slides written in markdown. Several reveal.js plugins will be set up, too. More info: Demo: https://theno.github.io/revealjs_te...
[ "def", "revealjs", "(", "basedir", "=", "None", ",", "title", "=", "None", ",", "subtitle", "=", "None", ",", "description", "=", "None", ",", "github_user", "=", "None", ",", "github_repo", "=", "None", ")", ":", "basedir", "=", "basedir", "or", "quer...
42.170732
18.804878
def slugify(text, length_limit=0, delimiter=u'-'): """Generates an ASCII-only slug of a string.""" result = [] for word in _punctuation_regex.split(text.lower()): word = _available_unicode_handlers[0](word) if word: result.append(word) slug = delimiter.join(result) if len...
[ "def", "slugify", "(", "text", ",", "length_limit", "=", "0", ",", "delimiter", "=", "u'-'", ")", ":", "result", "=", "[", "]", "for", "word", "in", "_punctuation_regex", ".", "split", "(", "text", ".", "lower", "(", ")", ")", ":", "word", "=", "_a...
34.181818
13.363636
def retrieve(pdb_id, cache_dir = None, bio_cache = None): '''Creates a FASTA object by using a cached copy of the file if it exists or by retrieving the file from the RCSB.''' pdb_id = pdb_id.upper() if bio_cache: return FASTA(bio_cache.get_fasta_contents(pdb_id)) # Check ...
[ "def", "retrieve", "(", "pdb_id", ",", "cache_dir", "=", "None", ",", "bio_cache", "=", "None", ")", ":", "pdb_id", "=", "pdb_id", ".", "upper", "(", ")", "if", "bio_cache", ":", "return", "FASTA", "(", "bio_cache", ".", "get_fasta_contents", "(", "pdb_i...
35.333333
22.296296
def register (g): """ Registers new generator instance 'g'. """ assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .generators.$(t) in that case, otherwise, it w...
[ "def", "register", "(", "g", ")", ":", "assert", "isinstance", "(", "g", ",", "Generator", ")", "id", "=", "g", ".", "id", "(", ")", "__generators", "[", "id", "]", "=", "g", "# A generator can produce several targets of the", "# same type. We want unique occure...
43.26
23.22
def push(self, metric_type, metric_id, value, timestamp=None): """ Pushes a single metric_id, datapoint combination to the server. This method is an assistant method for the put method by removing the need to create data structures first. :param metric_type: MetricType to be ma...
[ "def", "push", "(", "self", ",", "metric_type", ",", "metric_id", ",", "value", ",", "timestamp", "=", "None", ")", ":", "if", "type", "(", "timestamp", ")", "is", "datetime", ":", "timestamp", "=", "datetime_to_time_millis", "(", "timestamp", ")", "item",...
48.117647
28.235294
def _tp_relfq_name(tp, tp_name=None, assumed_globals=None, update_assumed_globals=None, implicit_globals=None): # _type: (type, Optional[Union[Set[Union[type, types.ModuleType]], Mapping[Union[type, types.ModuleType], str]]], Optional[bool]) -> str """Provides the fully qualified name of a type rela...
[ "def", "_tp_relfq_name", "(", "tp", ",", "tp_name", "=", "None", ",", "assumed_globals", "=", "None", ",", "update_assumed_globals", "=", "None", ",", "implicit_globals", "=", "None", ")", ":", "# _type: (type, Optional[Union[Set[Union[type, types.ModuleType]], Mapping[Un...
42.772152
18.164557
def derivativeY(self,mLvl,pLvl,MedShk): ''' Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array ...
[ "def", "derivativeY", "(", "self", ",", "mLvl", ",", "pLvl", ",", "MedShk", ")", ":", "xLvl", "=", "self", ".", "xFunc", "(", "mLvl", ",", "pLvl", ",", "MedShk", ")", "dxdp", "=", "self", ".", "xFunc", ".", "derivativeY", "(", "mLvl", ",", "pLvl", ...
35.6
20.066667
def process(self, quoted=False): ''' Parse an URL ''' self.p = urlparse(self.raw) self.scheme = self.p.scheme self.netloc = self.p.netloc self.opath = self.p.path if not quoted else quote(self.p.path) self.path = [x for x in self.opath.split('/') if x] self.params...
[ "def", "process", "(", "self", ",", "quoted", "=", "False", ")", ":", "self", ".", "p", "=", "urlparse", "(", "self", ".", "raw", ")", "self", ".", "scheme", "=", "self", ".", "p", ".", "scheme", "self", ".", "netloc", "=", "self", ".", "p", "....
43.5
11.7
def render_import_image(self, use_auth=None): """ Configure the import_image plugin """ # import_image is a multi-phase plugin phases = ('postbuild_plugins', 'exit_plugins') plugin = 'import_image' for phase in phases: if self.spec.imagestream_name.va...
[ "def", "render_import_image", "(", "self", ",", "use_auth", "=", "None", ")", ":", "# import_image is a multi-phase plugin", "phases", "=", "(", "'postbuild_plugins'", ",", "'exit_plugins'", ")", "plugin", "=", "'import_image'", "for", "phase", "in", "phases", ":", ...
50.193548
24.774194
def _valid_folder(self, base, name): """Return whether a folder can be searched.""" valid = True fullpath = os.path.join(base, name) if ( not self.recursive or ( self.folder_exclude_check is not None and not self.compare_directory(...
[ "def", "_valid_folder", "(", "self", ",", "base", ",", "name", ")", ":", "valid", "=", "True", "fullpath", "=", "os", ".", "path", ".", "join", "(", "base", ",", "name", ")", "if", "(", "not", "self", ".", "recursive", "or", "(", "self", ".", "fo...
36.6875
22.4375
def create_instance(self, plugin_type, plugin_name, **instance_kwargs): """Create and return an instance of the given plugin.""" plugin_type = self._get_plugin_type(plugin_type) return plugin_type.create_instance(plugin_name, **instance_kwargs)
[ "def", "create_instance", "(", "self", ",", "plugin_type", ",", "plugin_name", ",", "*", "*", "instance_kwargs", ")", ":", "plugin_type", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin_type", ".", "create_instance", "(", "plugin...
66.25
20.25
def parse(self, valstr): # type: (bytes) -> None ''' Parse an El Torito section header from a string. Parameters: valstr - The string to parse. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('...
[ "def", "parse", "(", "self", ",", "valstr", ")", ":", "# type: (bytes) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'El Torito Section Header already initialized'", ")", "(", "self", ".", "header_ind...
31.058824
25.411765
def oortC(self,R,romberg=False,nsigma=None,phi=0.): """ NAME: oortC PURPOSE: calculate the Oort function C INPUT: R - radius at which to calculate C (can be Quantity) OPTIONAL INPUT: nsigma - number of sigma to integrate the velo...
[ "def", "oortC", "(", "self", ",", "R", ",", "romberg", "=", "False", ",", "nsigma", "=", "None", ",", "phi", "=", "0.", ")", ":", "#2C= -meanvR/R-dmeanvphi/R/dphi+dmeanvR/dR", "meanvr", "=", "self", ".", "meanvR", "(", "R", ",", "romberg", "=", "romberg"...
28.181818
29.272727
def weights_to_cpu(state_dict): """Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU. """ state_dict_cpu = OrderedDict() for key, val in state_dict.items(): state_dict_cpu[key] = val.cpu() ...
[ "def", "weights_to_cpu", "(", "state_dict", ")", ":", "state_dict_cpu", "=", "OrderedDict", "(", ")", "for", "key", ",", "val", "in", "state_dict", ".", "items", "(", ")", ":", "state_dict_cpu", "[", "key", "]", "=", "val", ".", "cpu", "(", ")", "retur...
25.461538
14.461538
def parse_results_header(cls, header): """Extract columns from the line under "Summary of all tests:" :param header: content of the results header line :return: list of string providing columns """ header = IORMetricsExtractor.RE_MULTIPLE_SPACES.sub(' ', header) header =...
[ "def", "parse_results_header", "(", "cls", ",", "header", ")", ":", "header", "=", "IORMetricsExtractor", ".", "RE_MULTIPLE_SPACES", ".", "sub", "(", "' '", ",", "header", ")", "header", "=", "header", ".", "split", "(", "' '", ")", "return", "header" ]
39.111111
13.888889
def get_index_text(self, modname, name_cls): """Return text for index entry based on object type.""" name, cls = name_cls add_modules = self.env.config.add_module_names if self.objtype.endswith('method'): try: clsname, methname = name.rsplit('.', 1) ...
[ "def", "get_index_text", "(", "self", ",", "modname", ",", "name_cls", ")", ":", "name", ",", "cls", "=", "name_cls", "add_modules", "=", "self", ".", "env", ".", "config", ".", "add_module_names", "if", "self", ".", "objtype", ".", "endswith", "(", "'me...
40.40625
15.125
def finalizeTempDfa (tempStates): """finalizeTempDfa (tempStates) Input domain: tempState := [ nfaClosure : Long, [ tempArc ], accept : Boolean ] tempArc := [ label, arrow, nfaClosure ] Output domain: state := [ arcMap, accept : Boolean ] """ states = [] accepts = [] stateMap =...
[ "def", "finalizeTempDfa", "(", "tempStates", ")", ":", "states", "=", "[", "]", "accepts", "=", "[", "]", "stateMap", "=", "{", "}", "tempIndex", "=", "0", "for", "tempIndex", "in", "range", "(", "0", ",", "len", "(", "tempStates", ")", ")", ":", "...
31.185185
13.555556
def reload(self): ''' Clear plugin manager state and reload plugins. This method will make use of :meth:`clear` and :meth:`load_plugin`, so all internal state will be cleared, and all plugins defined in :data:`self.app.config['plugin_modules']` will be loaded. ''' ...
[ "def", "reload", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "for", "plugin", "in", "self", ".", "app", ".", "config", ".", "get", "(", "'plugin_modules'", ",", "(", ")", ")", ":", "self", ".", "load_plugin", "(", "plugin", ")" ]
38.727273
25.090909
def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1): """ Open a GuestFS handle with `disk_path` and try mounting the root filesystem. `disk_root` is a hint where it should be looked and will only be used if GuestFS will not be able to deduce it independently. Note that mounting a liv...
[ "def", "guestfs_conn_mount_ro", "(", "disk_path", ",", "disk_root", ",", "retries", "=", "5", ",", "wait", "=", "1", ")", ":", "for", "attempt", "in", "range", "(", "retries", ")", ":", "with", "guestfs_conn_ro", "(", "disk_path", ")", "as", "conn", ":",...
37.190476
19.984127
def FromFile(cls, path, actions_dict, resources_dict, file_format="yaml", name=None): """Create a RecipeObject from a file. The file should be a specially constructed yaml file that describes the recipe as well as the actions that it performs. Args: path (str): The path to ...
[ "def", "FromFile", "(", "cls", ",", "path", ",", "actions_dict", ",", "resources_dict", ",", "file_format", "=", "\"yaml\"", ",", "name", "=", "None", ")", ":", "format_map", "=", "{", "\"yaml\"", ":", "cls", ".", "_process_yaml", "}", "format_handler", "=...
47.1
28.642857
def chain_update(self, block, receipts): """ Handles both "sawtooth/block-commit" Events and "identity/update" Events. For "sawtooth/block-commit", the last_block_num is updated or a fork is detected. For "identity/update", the corresponding cache entry will be updated. "...
[ "def", "chain_update", "(", "self", ",", "block", ",", "receipts", ")", ":", "block_events", "=", "BlockEventExtractor", "(", "block", ")", ".", "extract", "(", "[", "EventSubscription", "(", "event_type", "=", "\"sawtooth/block-commit\"", ")", "]", ")", "rece...
39.761905
19.857143
def export_hmaps_csv(key, dest, sitemesh, array, comment): """ Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param co...
[ "def", "export_hmaps_csv", "(", "key", ",", "dest", ",", "sitemesh", ",", "array", ",", "comment", ")", ":", "curves", "=", "util", ".", "compose_arrays", "(", "sitemesh", ",", "array", ")", "writers", ".", "write_csv", "(", "dest", ",", "curves", ",", ...
37.923077
13.307692
def prime_gen() -> int: # credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra """ A generator for prime numbers starting from 2. """ D = {} yield 2 for q in itertools.islice(itertools.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q * q] = 2 * q ...
[ "def", "prime_gen", "(", ")", "->", "int", ":", "# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra", "D", "=", "{", "}", "yield", "2", "for", "q", "in", "itertools", ".", "islice", "(", "itertools", ".", "count", "(", "3", ")", ",", "0", ",", "No...
25.176471
17.411765
def btc_witness_script_serialize(_stack): """ Given a deserialized witness script stack (i.e. the input-specific witness, as an array of Nones, ints, and strings), turn it back into a hex-encoded script """ stack = _stack if encoding.json_is_base(_stack, 16): # hex-to-bin all hex strings...
[ "def", "btc_witness_script_serialize", "(", "_stack", ")", ":", "stack", "=", "_stack", "if", "encoding", ".", "json_is_base", "(", "_stack", ",", "16", ")", ":", "# hex-to-bin all hex strings ", "stack", "=", "encoding", ".", "json_changebase", "(", "_stack", "...
50
27.818182
def get_tree_root(self): """ Returns the absolute root node of current tree structure.""" root = self while root.up is not None: root = root.up return root
[ "def", "get_tree_root", "(", "self", ")", ":", "root", "=", "self", "while", "root", ".", "up", "is", "not", "None", ":", "root", "=", "root", ".", "up", "return", "root" ]
32.333333
13
def dsync_files(self, source, target): '''Sync directory to directory.''' src_s3_url = S3URL.is_valid(source) dst_s3_url = S3URL.is_valid(target) source_list = self.relative_dir_walk(source) if len(source_list) == 0 or '.' in source_list: raise Failure('Sync command need to sync directory to ...
[ "def", "dsync_files", "(", "self", ",", "source", ",", "target", ")", ":", "src_s3_url", "=", "S3URL", ".", "is_valid", "(", "source", ")", "dst_s3_url", "=", "S3URL", ".", "is_valid", "(", "target", ")", "source_list", "=", "self", ".", "relative_dir_walk...
32.525
17.325
def post_data(self, job_id, body, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-post-data.html>`_ :arg job_id: The name of the job receiving the data :arg body: The data to process :arg reset_end: Optional parameter to specify the end of t...
[ "def", "post_data", "(", "self", ",", "job_id", ",", "body", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "job_id", ",", "body", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for...
41.3
18.4
def _transform_incoming(self, son, collection, skip=0): """Recursively replace all keys that need transforming.""" skip = 0 if skip < 0 else skip if isinstance(son, dict): for (key, value) in son.items(): if key.startswith('$'): if isinstance(value...
[ "def", "_transform_incoming", "(", "self", ",", "son", ",", "collection", ",", "skip", "=", "0", ")", ":", "skip", "=", "0", "if", "skip", "<", "0", "else", "skip", "if", "isinstance", "(", "son", ",", "dict", ")", ":", "for", "(", "key", ",", "v...
46
14.714286
def download_file(url, destination, **kwargs): """ Download file process: - Open the url - Check if it has been downloaded and it hanged. - Download it to the destination folder. Args: :urls: url to take the file. :destionation: place to store the downloaded file. ...
[ "def", "download_file", "(", "url", ",", "destination", ",", "*", "*", "kwargs", ")", ":", "web_file", "=", "open_remote_url", "(", "url", ",", "*", "*", "kwargs", ")", "file_size", "=", "0", "if", "not", "web_file", ":", "logger", ".", "error", "(", ...
28.285714
19.857143
def update(self, params, args, data): # type: (str, dict, dict) -> Union[List[AppModel], AppModel] """ PUT /resource/model_cls/[params:id] data Update resource/s """ ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_...
[ "def", "update", "(", "self", ",", "params", ",", "args", ",", "data", ")", ":", "# type: (str, dict, dict) -> Union[List[AppModel], AppModel]", "ctx", "=", "self", ".", "_create_context", "(", "params", ",", "args", ",", "data", ")", "row_id", "=", "ctx", "."...
31.5
16.375
def recode (inlist,listmap,cols=None): """ Changes the values in a list to a new set of values (useful when you need to recode data from (e.g.) strings to numbers. cols defaults to None (meaning all columns are recoded). Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list Returns: inlist...
[ "def", "recode", "(", "inlist", ",", "listmap", ",", "cols", "=", "None", ")", ":", "lst", "=", "copy", ".", "deepcopy", "(", "inlist", ")", "if", "cols", "!=", "None", ":", "if", "type", "(", "cols", ")", "not", "in", "[", "ListType", ",", "Tupl...
35.758621
15.413793
def download_source_dists(self, arguments, use_wheels=False): """ Download missing source distributions. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param use_wheels: Whether pip and pip-accel are allowed to use whe...
[ "def", "download_source_dists", "(", "self", ",", "arguments", ",", "use_wheels", "=", "False", ")", ":", "download_timer", "=", "Timer", "(", ")", "logger", ".", "info", "(", "\"Downloading missing distribution(s) ..\"", ")", "requirements", "=", "self", ".", "...
52.5625
23.8125
def checkMgtKeyInUse(self, CorpNum, MgtKeyType, MgtKey): """ 파트너 관리번호 사용중 여부 확인. args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 return 사용중 여부 by True/False raise ...
[ "def", "checkMgtKeyInUse", "(", "self", ",", "CorpNum", ",", "MgtKeyType", ",", "MgtKey", ")", ":", "if", "MgtKeyType", "not", "in", "self", ".", "__MgtKeyTypes", ":", "raise", "PopbillException", "(", "-", "99999999", ",", "\"관리번호 형태가 올바르지 않습니다.\")", "", "if"...
37.565217
16.521739
def get_materialized_data_cache(doc=None): """Return the cache directory where data can be written during a build, usually for a Jupyter notebook that generates many files for each execution""" from metapack.constants import MATERIALIZED_DATA_PREFIX from os.path import join if not doc: fro...
[ "def", "get_materialized_data_cache", "(", "doc", "=", "None", ")", ":", "from", "metapack", ".", "constants", "import", "MATERIALIZED_DATA_PREFIX", "from", "os", ".", "path", "import", "join", "if", "not", "doc", ":", "from", "metapack", "import", "Downloader",...
33.235294
21.294118
def run_mainloop_with(self, target): """Start the OS's main loop to process asyncronous BLE events and then run the specified target function in a background thread. Target function should be a function that takes no parameters and optionally return an integer response code. When the t...
[ "def", "run_mainloop_with", "(", "self", ",", "target", ")", ":", "# Create background thread to run user code.", "self", ".", "_user_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_user_thread_main", ",", "args", "=", "(", "target", ...
52.769231
22.423077
def _expect_method(self, command): """Use the expect module to execute ipmitool commands and set status """ child = pexpect.spawn(self._ipmitool_path, self.args + command) i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10) if i == 0: child....
[ "def", "_expect_method", "(", "self", ",", "command", ")", ":", "child", "=", "pexpect", ".", "spawn", "(", "self", ".", "_ipmitool_path", ",", "self", ".", "args", "+", "command", ")", "i", "=", "child", ".", "expect", "(", "[", "pexpect", ".", "TIM...
32.296296
16.296296
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True): """ Save image by cv2 module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This ar...
[ "def", "imsave", "(", "path", ",", "img", ",", "channel_first", "=", "False", ",", "as_uint16", "=", "False", ",", "auto_scale", "=", "True", ")", ":", "img", "=", "_imsave_before", "(", "img", ",", "channel_first", ",", "auto_scale", ")", "if", "auto_sc...
44.742857
27.142857
def wizard_font(text): """ Check input text length for wizard mode. :param text: input text :type text:str :return: font as str """ text_length = len(text) if text_length <= TEXT_XLARGE_THRESHOLD: font = random.choice(XLARGE_WIZARD_FONT) elif text_length > TEXT_XLARGE_THRESH...
[ "def", "wizard_font", "(", "text", ")", ":", "text_length", "=", "len", "(", "text", ")", "if", "text_length", "<=", "TEXT_XLARGE_THRESHOLD", ":", "font", "=", "random", ".", "choice", "(", "XLARGE_WIZARD_FONT", ")", "elif", "text_length", ">", "TEXT_XLARGE_TH...
33.555556
17
def set(self, key, data): """ Set the given data to the container with the given key. Any existing data for the given key is discarded/overwritten. Args: key (str): A key to store the data for. data (numpy.ndarray): Array-like data. Note: The...
[ "def", "set", "(", "self", ",", "key", ",", "data", ")", ":", "self", ".", "raise_error_if_not_open", "(", ")", "if", "key", "in", "self", ".", "_file", ":", "del", "self", ".", "_file", "[", "key", "]", "self", ".", "_file", ".", "create_dataset", ...
28.166667
19.277778
def _in_version(self, *versions): "Returns true if this frame is in any of the specified versions of ID3." for version in versions: if (self._version == version or (isinstance(self._version, collections.Container) and version in self._version)): ...
[ "def", "_in_version", "(", "self", ",", "*", "versions", ")", ":", "for", "version", "in", "versions", ":", "if", "(", "self", ".", "_version", "==", "version", "or", "(", "isinstance", "(", "self", ".", "_version", ",", "collections", ".", "Container", ...
44
16
def add_child(self, child): """ Adds a branch to the current tree. """ self.children.append(child) child.parent = self self.udepth = max([child.udepth for child in self.children]) + 1
[ "def", "add_child", "(", "self", ",", "child", ")", ":", "self", ".", "children", ".", "append", "(", "child", ")", "child", ".", "parent", "=", "self", "self", ".", "udepth", "=", "max", "(", "[", "child", ".", "udepth", "for", "child", "in", "sel...
32.142857
9.285714
def read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None): """ Read SQL database table into a DataFrame. Given a table name and a SQLAlchemy connectable, returns a DataFrame. This function do...
[ "def", "read_sql_table", "(", "table_name", ",", "con", ",", "schema", "=", "None", ",", "index_col", "=", "None", ",", "coerce_float", "=", "True", ",", "parse_dates", "=", "None", ",", "columns", "=", "None", ",", "chunksize", "=", "None", ")", ":", ...
38.875
22.325
def send(self, diff): """ Return Context Manager for a file-like (stream) object to send a diff. """ if Store.skipDryRun(logger, self.dryrun)("send %s", diff): return None (diffTo, diffFrom) = self.toArg.diff(diff) self._client.send(diffTo, diffFrom) progress = Disp...
[ "def", "send", "(", "self", ",", "diff", ")", ":", "if", "Store", ".", "skipDryRun", "(", "logger", ",", "self", ".", "dryrun", ")", "(", "\"send %s\"", ",", "diff", ")", ":", "return", "None", "(", "diffTo", ",", "diffFrom", ")", "=", "self", ".",...
42.2
20.8
def elementwise_cdf(self, p): r"""Convert a sample to random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the CDF. To facilitate efficient sampling, this function returns a *vector* of CDF values, one value for each variable. Basic...
[ "def", "elementwise_cdf", "(", "self", ",", "p", ")", ":", "p", "=", "scipy", ".", "atleast_1d", "(", "p", ")", "if", "len", "(", "p", ")", "!=", "len", "(", "self", ".", "univariate_priors", ")", ":", "raise", "ValueError", "(", "\"length of p must eq...
48.772727
22
def load(self, filething): """load(filething) Load file information from a filename. Args: filething (filething) Raises: mutagen.MutagenError """ fileobj = filething.fileobj try: self.info = self._Info(fileobj) s...
[ "def", "load", "(", "self", ",", "filething", ")", ":", "fileobj", "=", "filething", ".", "fileobj", "try", ":", "self", ".", "info", "=", "self", ".", "_Info", "(", "fileobj", ")", "self", ".", "tags", "=", "self", ".", "_Tags", "(", "fileobj", ",...
26.761905
16.714286
def set(self, key, value, **kwargs): """Create or update the object. Args: key (str): The key of the object to create/update value (str): The value to set for the object **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuth...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'%s/%s'", "%", "(", "self", ".", "path", ",", "key", ".", "replace", "(", "'/'", ",", "'%2F'", ")", ")", "data", "=", "{", "'value'", ":", "...
36.473684
20.052632
def axis_angle(self): """:obj:`numpy.ndarray` of float: The axis-angle representation for the rotation. """ qw, qx, qy, qz = self.quaternion theta = 2 * np.arccos(qw) omega = np.array([1,0,0]) if theta > 0: rx = qx / np.sqrt(1.0 - qw**2) ry = qy / ...
[ "def", "axis_angle", "(", "self", ")", ":", "qw", ",", "qx", ",", "qy", ",", "qz", "=", "self", ".", "quaternion", "theta", "=", "2", "*", "np", ".", "arccos", "(", "qw", ")", "omega", "=", "np", ".", "array", "(", "[", "1", ",", "0", ",", ...
37
6
def _copy_required(lib_path, copy_filt_func, copied_libs): """ Copy libraries required for files in `lib_path` to `lib_path` Augment `copied_libs` dictionary with any newly copied libraries, modifying `copied_libs` in-place - see Notes. This is one pass of ``copy_recurse`` Parameters --------...
[ "def", "_copy_required", "(", "lib_path", ",", "copy_filt_func", ",", "copied_libs", ")", ":", "# Paths will be prepended with `lib_path`", "lib_dict", "=", "tree_libs", "(", "lib_path", ")", "# Map library paths after copy ('copied') to path before copy ('orig')", "rp_lp", "="...
44.404762
22.714286
def init_yaml_constructor(): """ This dark magic is used to make yaml.safe_load encode all strings as utf-8, where otherwise python unicode strings would be returned for non-ascii chars """ def utf_encoding_string_constructor(loader, node): return loader.construct_scalar(node).encode('utf-8'...
[ "def", "init_yaml_constructor", "(", ")", ":", "def", "utf_encoding_string_constructor", "(", "loader", ",", "node", ")", ":", "return", "loader", ".", "construct_scalar", "(", "node", ")", ".", "encode", "(", "'utf-8'", ")", "yaml", ".", "SafeLoader", ".", ...
51.125
22.375
def terrain_report_send(self, lat, lon, spacing, terrain_height, current_height, pending, loaded, force_mavlink1=False): ''' Response from a TERRAIN_CHECK request lat : Latitude (degrees *10^7) (int32_t) lon : L...
[ "def", "terrain_report_send", "(", "self", ",", "lat", ",", "lon", ",", "spacing", ",", "terrain_height", ",", "current_height", ",", "pending", ",", "loaded", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", ...
75.071429
52.5
def to_offset(freq): """Convert a frequency string to the appropriate subclass of BaseCFTimeOffset.""" if isinstance(freq, BaseCFTimeOffset): return freq else: try: freq_data = re.match(_PATTERN, freq).groupdict() except AttributeError: raise ValueError('I...
[ "def", "to_offset", "(", "freq", ")", ":", "if", "isinstance", "(", "freq", ",", "BaseCFTimeOffset", ")", ":", "return", "freq", "else", ":", "try", ":", "freq_data", "=", "re", ".", "match", "(", "_PATTERN", ",", "freq", ")", ".", "groupdict", "(", ...
28.473684
17.105263
def learn(self, features, labels): """ Fits the classifier If it's state is empty, the classifier is fitted, if not the classifier is partially fitted. See sklearn's SGDClassifier fit and partial_fit methods. Args: features (:obj:`list` of :obj:`list` of :obj:`float...
[ "def", "learn", "(", "self", ",", "features", ",", "labels", ")", ":", "labels", "=", "np", ".", "ravel", "(", "labels", ")", "self", ".", "__learn_labels", "(", "labels", ")", "if", "len", "(", "labels", ")", "==", "0", ":", "return", "labels", "=...
38.125
18.541667
def getUserId(self): """ Ask Skype for the authenticated user's identifier, and store it on the connection object. """ self.userId = self("GET", "{0}/users/self/profile".format(self.API_USER), auth=self.Auth.SkypeToken).json().get("username")
[ "def", "getUserId", "(", "self", ")", ":", "self", ".", "userId", "=", "self", "(", "\"GET\"", ",", "\"{0}/users/self/profile\"", ".", "format", "(", "self", ".", "API_USER", ")", ",", "auth", "=", "self", ".", "Auth", ".", "SkypeToken", ")", ".", "jso...
49.333333
25.666667
def write_transaction(self, transaction, mode): # This method offers backward compatibility with the Web API. """Submit a valid transaction to the mempool.""" response = self.post_transaction(transaction, mode) return self._process_post_response(response.json(), mode)
[ "def", "write_transaction", "(", "self", ",", "transaction", ",", "mode", ")", ":", "# This method offers backward compatibility with the Web API.", "response", "=", "self", ".", "post_transaction", "(", "transaction", ",", "mode", ")", "return", "self", ".", "_proces...
59.2
16
def submit_all(self, coords=None, queue=None, debug=False): """ Submit likelihood analyses on a set of coordinates. If coords is `None`, submit all coordinates in the footprint. Inputs: coords : Array of target locations in Galactic coordinates. queue : Overwrite submi...
[ "def", "submit_all", "(", "self", ",", "coords", "=", "None", ",", "queue", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "coords", "is", "None", ":", "pixels", "=", "np", ".", "arange", "(", "hp", ".", "nside2npix", "(", "self", ".", ...
39.72
17.44
def updatetext(self): """Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER``""" if self.TEXTCONTAINER: s = "" for child in self: if isinstance(child, AbstractElement): child...
[ "def", "updatetext", "(", "self", ")", ":", "if", "self", ".", "TEXTCONTAINER", ":", "s", "=", "\"\"", "for", "child", "in", "self", ":", "if", "isinstance", "(", "child", ",", "AbstractElement", ")", ":", "child", ".", "updatetext", "(", ")", "s", "...
41.636364
9.636364
def learning_schedule() -> Callable: """ Returns a method that can be used in argument parsing to check that the argument is a valid learning rate schedule string. :return: A method that can be used as a type in argparse. """ def parse(schedule_str): try: schedule = Learnin...
[ "def", "learning_schedule", "(", ")", "->", "Callable", ":", "def", "parse", "(", "schedule_str", ")", ":", "try", ":", "schedule", "=", "LearningRateSchedulerFixedStep", ".", "parse_schedule_str", "(", "schedule_str", ")", "except", "ValueError", ":", "raise", ...
34.411765
27.470588
def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs): """ Convert a textual representation of \*MRS from one the src_fmt representation to the tgt_fmt representation. By default, only read and convert a single \*MRS object (e.g. for `mrx` this starts at <mrs> and not <mrs-list>), but changing t...
[ "def", "convert", "(", "txt", ",", "src_fmt", ",", "tgt_fmt", ",", "single", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "importlib", "import", "import_module", "reader", "=", "import_module", "(", "'{}.{}'", ".", "format", "(", "'delphin.mrs'"...
42
20.55814
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a, or --action.' ...
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The destroy action must be called with -d, --destroy, '", "'-a, or --action.'", ")", "opts", "=", "__opts__", "__utils__", ...
29.377358
19.943396
def depth_profile(list_, max_depth=None, compress_homogenous=True, compress_consecutive=False, new_depth=False): r""" Returns a nested list corresponding the shape of the nested structures lists represent depth, tuples represent shape. The values of the items do not matter. only the lengths. Args: ...
[ "def", "depth_profile", "(", "list_", ",", "max_depth", "=", "None", ",", "compress_homogenous", "=", "True", ",", "compress_consecutive", "=", "False", ",", "new_depth", "=", "False", ")", ":", "if", "isinstance", "(", "list_", ",", "dict", ")", ":", "lis...
36.761111
19.888889
def __display_header(self, stat_display): """Display the firsts lines (header) in the Curses interface. system + ip + uptime (cloud) """ # First line self.new_line() self.space_between_column = 0 l_uptime = (self.get_stats_display_width(stat_display["syst...
[ "def", "__display_header", "(", "self", ",", "stat_display", ")", ":", "# First line", "self", ".", "new_line", "(", ")", "self", ".", "space_between_column", "=", "0", "l_uptime", "=", "(", "self", ".", "get_stats_display_width", "(", "stat_display", "[", "\"...
38.730769
15.884615
def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs): """ This is a generator function that enumerates all sensors that match the provided arguments. Parameters: name_pattern: pattern that device name should match. For example, 'sensor*'. Default value: '*'....
[ "def", "list_sensors", "(", "name_pattern", "=", "Sensor", ".", "SYSTEM_DEVICE_NAME_CONVENTION", ",", "*", "*", "kwargs", ")", ":", "class_path", "=", "abspath", "(", "Device", ".", "DEVICE_ROOT_PATH", "+", "'/'", "+", "Sensor", ".", "SYSTEM_CLASS_NAME", ")", ...
50.1875
24.5625
def gen_passwd(self): ''' reseting password ''' post_data = self.get_post_data() userinfo = MUser.get_by_name(post_data['u']) sub_timestamp = int(post_data['t']) cur_timestamp = tools.timestamp() if cur_timestamp - sub_timestamp < 600 and cur_timestamp >...
[ "def", "gen_passwd", "(", "self", ")", ":", "post_data", "=", "self", ".", "get_post_data", "(", ")", "userinfo", "=", "MUser", ".", "get_by_name", "(", "post_data", "[", "'u'", "]", ")", "sub_timestamp", "=", "int", "(", "post_data", "[", "'t'", "]", ...
31.111111
16.444444
def setTags(self, tags): """Set the tags for current photo to list tags. (flickr.photos.settags) """ method = 'flickr.photos.setTags' tags = uniq(tags) _dopost(method, auth=True, photo_id=self.id, tags=tags) self._load_properties()
[ "def", "setTags", "(", "self", ",", "tags", ")", ":", "method", "=", "'flickr.photos.setTags'", "tags", "=", "uniq", "(", "tags", ")", "_dopost", "(", "method", ",", "auth", "=", "True", ",", "photo_id", "=", "self", ".", "id", ",", "tags", "=", "tag...
35
9
def bulk_update(manager, model_objs, fields_to_update): """ Bulk updates a list of model objects that are already saved. :type model_objs: list of :class:`Models<django:django.db.models.Model>` :param model_objs: A list of model objects that have been updated. fields_to_update: A list of fields...
[ "def", "bulk_update", "(", "manager", ",", "model_objs", ",", "fields_to_update", ")", ":", "# Add the pk to the value fields so we can join", "value_fields", "=", "[", "manager", ".", "model", ".", "_meta", ".", "pk", ".", "attname", "]", "+", "fields_to_update", ...
32.113208
22.849057
def api(self): """ Access the Api Twilio Domain :returns: Api Twilio Domain :rtype: twilio.rest.api.Api """ if self._api is None: from twilio.rest.api import Api self._api = Api(self) return self._api
[ "def", "api", "(", "self", ")", ":", "if", "self", ".", "_api", "is", "None", ":", "from", "twilio", ".", "rest", ".", "api", "import", "Api", "self", ".", "_api", "=", "Api", "(", "self", ")", "return", "self", ".", "_api" ]
24.636364
10.636364
def StatEntryFromStat(stat, pathspec, ext_attrs = True): """Build a stat entry object from a given stat object. Args: stat: A `Stat` object. pathspec: A `PathSpec` from which `stat` was obtained. ext_attrs: Whether to include extended file attributes in the r...
[ "def", "StatEntryFromStat", "(", "stat", ",", "pathspec", ",", "ext_attrs", "=", "True", ")", ":", "result", "=", "rdf_client_fs", ".", "StatEntry", "(", "pathspec", "=", "pathspec", ")", "for", "attr", "in", "_STAT_ATTRS", ":", "value", "=", "getattr", "(...
28.5
20.861111
def order(self, value): """Set the fields used to sort query results. Sort fields will be applied in the order specified. :type value: str or sequence of strings :param value: Each value is a string giving the name of the property on which to sort, optionally prec...
[ "def", "order", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "value", "]", "self", ".", "_order", "[", ":", "]", "=", "value" ]
39.357143
18.5
def _pull(self): ''' Helper function to pull from remote ''' pull = self.m( 'pulling remote changes', cmdd=dict(cmd='git pull --tags', cwd=self.local), critical=False ) if 'CONFLICT' in pull.get('out'): self.m( ...
[ "def", "_pull", "(", "self", ")", ":", "pull", "=", "self", ".", "m", "(", "'pulling remote changes'", ",", "cmdd", "=", "dict", "(", "cmd", "=", "'git pull --tags'", ",", "cwd", "=", "self", ".", "local", ")", ",", "critical", "=", "False", ")", "if...
27
20.529412
def add_permissions(self, user_id, permissions): """Enables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to enable :returns: True on success, Exception otherwise Example:: add_permissions(123, [...
[ "def", "add_permissions", "(", "self", ",", "user_id", ",", "permissions", ")", ":", "pretty_permissions", "=", "self", ".", "format_permission_object", "(", "permissions", ")", "LOGGER", ".", "warning", "(", "\"Adding the following permissions to %s: %s\"", ",", "use...
46.076923
23.769231
def _get_a(self, _type): """ Gets an instance implementing type <_type> """ tmp = self._get_all(_type) ret = pick(tmp) if len(tmp) != 1: self.l.warn(("get_a: %s all implement %s; " + "picking %s") % (tmp, _type, ret)) return ret
[ "def", "_get_a", "(", "self", ",", "_type", ")", ":", "tmp", "=", "self", ".", "_get_all", "(", "_type", ")", "ret", "=", "pick", "(", "tmp", ")", "if", "len", "(", "tmp", ")", "!=", "1", ":", "self", ".", "l", ".", "warn", "(", "(", "\"get_a...
37.25
14