text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update_tenant(self, tenant, name=None, description=None, enabled=True): """ ADMIN ONLY. Updates an existing tenant. """ tenant_id = utils.get_id(tenant) data = {"tenant": { "enabled": enabled, }} if name: data["tenant"]["nam...
[ "def", "update_tenant", "(", "self", ",", "tenant", ",", "name", "=", "None", ",", "description", "=", "None", ",", "enabled", "=", "True", ")", ":", "tenant_id", "=", "utils", ".", "get_id", "(", "tenant", ")", "data", "=", "{", "\"tenant\"", ":", "...
36.785714
12.785714
def program_global_reg(self): """ Send the global register to the chip. Loads the values of self['GLOBAL_REG'] onto the chip. Includes enabling the clock, and loading the Control (CTR) and DAC shadow registers. """ self._clear_strobes() gr_size = len(s...
[ "def", "program_global_reg", "(", "self", ")", ":", "self", ".", "_clear_strobes", "(", ")", "gr_size", "=", "len", "(", "self", "[", "'GLOBAL_REG'", "]", "[", ":", "]", ")", "# get the size", "self", "[", "'SEQ'", "]", "[", "'SHIFT_IN'", "]", "[", "0"...
41.619048
26.761905
def build_url_request(self): """ Build the url to use for making a call to the Bbox API :return: url string """ # Check if the ip is LAN or WAN if net.IPAddress(self.ip).is_private(): url = "http://{}".format(self.ip) self.authentication_type = Bbo...
[ "def", "build_url_request", "(", "self", ")", ":", "# Check if the ip is LAN or WAN", "if", "net", ".", "IPAddress", "(", "self", ".", "ip", ")", ".", "is_private", "(", ")", ":", "url", "=", "\"http://{}\"", ".", "format", "(", "self", ".", "ip", ")", "...
37.73913
18.695652
def setup(self, interval): """Prepares the tests for execution, interval in ms""" self.trace_counter = 0 self._halt = False self.interval = interval
[ "def", "setup", "(", "self", ",", "interval", ")", ":", "self", ".", "trace_counter", "=", "0", "self", ".", "_halt", "=", "False", "self", ".", "interval", "=", "interval" ]
29.333333
14.333333
def threshold(np, acc, stream_raster, threshold=100., workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Run threshold for stream raster""" fname = TauDEM.func_name('threshold') return TauDEM.run(FileClass.get_executable_fullpath(...
[ "def", "threshold", "(", "np", ",", "acc", ",", "stream_raster", ",", "threshold", "=", "100.", ",", "workingdir", "=", "None", ",", "mpiexedir", "=", "None", ",", "exedir", "=", "None", ",", "log_file", "=", "None", ",", "runtime_file", "=", "None", "...
63.9
23.4
def _check_groups(s, groups): """Ensures that all particles are included in exactly 1 group""" ans = [] for g in groups: ans.extend(g) if np.unique(ans).size != np.size(ans): return False elif np.unique(ans).size != s.obj_get_positions().shape[0]: return False else: ...
[ "def", "_check_groups", "(", "s", ",", "groups", ")", ":", "ans", "=", "[", "]", "for", "g", "in", "groups", ":", "ans", ".", "extend", "(", "g", ")", "if", "np", ".", "unique", "(", "ans", ")", ".", "size", "!=", "np", ".", "size", "(", "ans...
34.272727
18.818182
def check_basic_battery_status(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0 MIB Excerpt The status of the UPS batteries. A batteryLow(3) value indicates the UPS will be unable to sustain the current load, and its services will be lost if power is not ...
[ "def", "check_basic_battery_status", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "apc_battery_states", "=", "{", "'1'", ":", "'unknown'", ",", "'2'", ":", "'batteryNormal'", ",", "'3'", ":", "'batteryLow'", ",", "'4'", ":", "'batteryI...
31.294118
18.470588
def gauge(self, name, value, rate=1): # type: (str, float, float) -> None """Send a Gauge metric with the specified value""" if self._should_send_metric(name, rate): if not is_numeric(value): value = float(value) self._request( Gauge( ...
[ "def", "gauge", "(", "self", ",", "name", ",", "value", ",", "rate", "=", "1", ")", ":", "# type: (str, float, float) -> None", "if", "self", ".", "_should_send_metric", "(", "name", ",", "rate", ")", ":", "if", "not", "is_numeric", "(", "value", ")", ":...
33.071429
13.071429
def readinto(self, b): """Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. If *b* is non-empty, a 0 return value indicates that the connection was shutdown at th...
[ "def", "readinto", "(", "self", ",", "b", ")", ":", "self", ".", "_checkClosed", "(", ")", "self", ".", "_checkReadable", "(", ")", "if", "self", ".", "_timeout_occurred", ":", "raise", "IOError", "(", "\"cannot read from timed out object\"", ")", "while", "...
35.75
13.958333
def refresh(self): """Obtain a new access token from the refresh_token.""" if self.refresh_token is None: raise InvalidInvocation("refresh token not provided") self._request_token( grant_type="refresh_token", refresh_token=self.refresh_token )
[ "def", "refresh", "(", "self", ")", ":", "if", "self", ".", "refresh_token", "is", "None", ":", "raise", "InvalidInvocation", "(", "\"refresh token not provided\"", ")", "self", ".", "_request_token", "(", "grant_type", "=", "\"refresh_token\"", ",", "refresh_toke...
41.857143
17.714286
def create_network(kwargs=None, call=None): ''' ... versionchanged:: 2017.7.0 Create a GCE network. Must specify name and cidr. CLI Example: .. code-block:: bash salt-cloud -f create_network gce name=mynet cidr=10.10.10.0/24 mode=legacy description=optional salt-cloud -f create_ne...
[ "def", "create_network", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_network function must be called with -f or --function.'", ")", "if", "not", "kwargs", "o...
26.584615
20.861538
def less(args): """ %prog less filename position | less Enhance the unix `less` command by seeking to a file location first. This is useful to browse big files. Position is relative 0.00 - 1.00, or bytenumber. $ %prog less myfile 0.1 # Go to 10% of the current file and streaming $ %prog l...
[ "def", "less", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "must_open", "p", "=", "OptionParser", "(", "less", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "...
28.675
22.475
def start_trace(self, full=False, frame=None, below=0, under=None): """Start tracing from here""" if self.tracing: return self.reset() log.info('Starting trace') frame = frame or sys._getframe().f_back # Setting trace without pausing self.set_trace(fra...
[ "def", "start_trace", "(", "self", ",", "full", "=", "False", ",", "frame", "=", "None", ",", "below", "=", "0", ",", "under", "=", "None", ")", ":", "if", "self", ".", "tracing", ":", "return", "self", ".", "reset", "(", ")", "log", ".", "info",...
33.230769
12.230769
def copy_attr(self, other): """ Copies all other attributes (not methods) from the other object to this instance. """ if not isinstance(other, Symbol): return # Nothing done if not a Symbol object tmp = re.compile('__.*__') for attr in (x for x in dir(other)...
[ "def", "copy_attr", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Symbol", ")", ":", "return", "# Nothing done if not a Symbol object", "tmp", "=", "re", ".", "compile", "(", "'__.*__'", ")", "for", "attr", "in", "(", ...
36.315789
18.947368
def random_soup(face_count=100): """ Return random triangles as a Trimesh Parameters ----------- face_count : int Number of faces desired in mesh Returns ----------- soup : trimesh.Trimesh Geometry with face_count random faces """ vertices = np.random.random((face_c...
[ "def", "random_soup", "(", "face_count", "=", "100", ")", ":", "vertices", "=", "np", ".", "random", ".", "random", "(", "(", "face_count", "*", "3", ",", "3", ")", ")", "-", "0.5", "faces", "=", "np", ".", "arange", "(", "face_count", "*", "3", ...
24.666667
16.666667
def crypto_box_seal_open(ciphertext, pk, sk): """ Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's public key ``pk`` and the sender...
[ "def", "crypto_box_seal_open", "(", "ciphertext", ",", "pk", ",", "sk", ")", ":", "ensure", "(", "isinstance", "(", "ciphertext", ",", "bytes", ")", ",", "\"input ciphertext must be bytes\"", ",", "raising", "=", "TypeError", ")", "ensure", "(", "isinstance", ...
31.163265
18.918367
def MakeTokenRegex(meta_left, meta_right): """Return a (compiled) regular expression for tokenization. Args: meta_left, meta_right: e.g. '{' and '}' - The regular expressions are memoized. - This function is public so the syntax highlighter can use it. """ key = meta_left, meta_right if key no...
[ "def", "MakeTokenRegex", "(", "meta_left", ",", "meta_right", ")", ":", "key", "=", "meta_left", ",", "meta_right", "if", "key", "not", "in", "_token_re_cache", ":", "# - Need () grouping for re.split", "# - The first character must be a non-space. This allows us to ignore",...
35.090909
14.818182
def validate_inferred_freq(freq, inferred_freq, freq_infer): """ If the user passes a freq and another freq is inferred from passed data, require that they match. Parameters ---------- freq : DateOffset or None inferred_freq : DateOffset or None freq_infer : bool Returns ------...
[ "def", "validate_inferred_freq", "(", "freq", ",", "inferred_freq", ",", "freq_infer", ")", ":", "if", "inferred_freq", "is", "not", "None", ":", "if", "freq", "is", "not", "None", "and", "freq", "!=", "inferred_freq", ":", "raise", "ValueError", "(", "'Infe...
30.515152
20.575758
def exclude_paths(root, patterns, dockerfile=None): """ Given a root directory path and a list of .dockerignore patterns, return an iterator of all paths (both regular files and directories) in the root directory that do *not* match any of the patterns. All paths returned are relative to the root. ...
[ "def", "exclude_paths", "(", "root", ",", "patterns", ",", "dockerfile", "=", "None", ")", ":", "if", "dockerfile", "is", "None", ":", "dockerfile", "=", "'Dockerfile'", "patterns", ".", "append", "(", "'!'", "+", "dockerfile", ")", "pm", "=", "PatternMatc...
31.866667
17.866667
def is_selected(self, request): """ Helper method that returns ``True`` if the menu item is active. A menu item is considered as active if it's URL or one of its descendants URL is equals to the current URL. """ current_url = request.get_full_path() return self.ur...
[ "def", "is_selected", "(", "self", ",", "request", ")", ":", "current_url", "=", "request", ".", "get_full_path", "(", ")", "return", "self", ".", "url", "==", "current_url", "or", "len", "(", "[", "c", "for", "c", "in", "self", ".", "children", "if", ...
45.222222
13.666667
def _read(self, length): """ Reads C{length} bytes from the stream. If an attempt to read past the end of the buffer is made, L{IOError} is raised. """ bytes = self.read(length) if len(bytes) != length: self.seek(0 - len(bytes), 1) raise IOError(...
[ "def", "_read", "(", "self", ",", "length", ")", ":", "bytes", "=", "self", ".", "read", "(", "length", ")", "if", "len", "(", "bytes", ")", "!=", "length", ":", "self", ".", "seek", "(", "0", "-", "len", "(", "bytes", ")", ",", "1", ")", "ra...
29.384615
20.153846
def _desy_bookkeeping(self, key, value): """Populate the ``_desy_bookkeeping`` key.""" return { 'date': normalize_date(value.get('d')), 'expert': force_single_element(value.get('a')), 'status': value.get('s'), }
[ "def", "_desy_bookkeeping", "(", "self", ",", "key", ",", "value", ")", ":", "return", "{", "'date'", ":", "normalize_date", "(", "value", ".", "get", "(", "'d'", ")", ")", ",", "'expert'", ":", "force_single_element", "(", "value", ".", "get", "(", "'...
34.428571
13.142857
def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'): """ Return a logger. Args: name (str): name to pass to the logging module. level (int): level of logging. fmt (str): format string. Returns: logging.Logger: logger from ``l...
[ "def", "get_logger", "(", "name", ",", "level", "=", "None", ",", "fmt", "=", "':%(lineno)d: %(message)s'", ")", ":", "if", "name", "not", "in", "Logger", ".", "loggers", ":", "if", "Logger", ".", "level", "is", "None", "and", "level", "is", "None", ":...
36.5
12.730769
def add_item_metadata(self, handle, key, value): """Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value """ ...
[ "def", "add_item_metadata", "(", "self", ",", "handle", ",", "key", ",", "value", ")", ":", "_mkdir_if_missing", "(", "self", ".", "_metadata_fragments_abspath", ")", "prefix", "=", "self", ".", "_handle_to_fragment_absprefixpath", "(", "handle", ")", "fpath", "...
36.142857
17.357143
def get_column_metadata(conn, table: str, schema='public'): """Returns column data following db.Column parameter specification.""" query = """\ SELECT attname as name, format_type(atttypid, atttypmod) AS data_type, NOT attnotnull AS nullable FROM pg_catalog.pg_attribute WHERE attrelid=%s::regclass AND a...
[ "def", "get_column_metadata", "(", "conn", ",", "table", ":", "str", ",", "schema", "=", "'public'", ")", ":", "query", "=", "\"\"\"\\\nSELECT\n attname as name,\n format_type(atttypid, atttypmod) AS data_type,\n NOT attnotnull AS nullable\nFROM pg_catalog.pg_attribute\nWHERE attr...
32.125
17.3125
def formationz(c, z, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): """ Rearrange eqn 18 from Correa et al (2015c) to return formation redshift for a concentration at a given redshift Parameters ---------- c : float / numpy array Concentration of halo z : float / numpy array ...
[ "def", "formationz", "(", "c", ",", "z", ",", "Ascaling", "=", "900", ",", "omega_M_0", "=", "0.25", ",", "omega_lambda_0", "=", "0.75", ")", ":", "Y1", "=", "np", ".", "log", "(", "2", ")", "-", "0.5", "Yc", "=", "np", ".", "log", "(", "1", ...
31.1875
21.34375
def message_length(message): ''' message_length returns visual length of message. Ascii chars are counted as 1, non-asciis are 2. :param str message: random unicode mixed text :rtype: int ''' length = 0 for char in map(east_asian_width, message): if char == 'W': leng...
[ "def", "message_length", "(", "message", ")", ":", "length", "=", "0", "for", "char", "in", "map", "(", "east_asian_width", ",", "message", ")", ":", "if", "char", "==", "'W'", ":", "length", "+=", "2", "elif", "char", "==", "'Na'", ":", "length", "+...
23.875
21
def get_polygon(self, reverse=False): """ Returns a tuple of coordinates of 5 points describing a polygon. Points are listed in clockwise order, first point is the same as the last. :param reverse: `True` if x and y coordinates should be switched and `False` otherwise :type reverse: boo...
[ "def", "get_polygon", "(", "self", ",", "reverse", "=", "False", ")", ":", "bbox", "=", "self", ".", "reverse", "(", ")", "if", "reverse", "else", "self", "polygon", "=", "(", "(", "bbox", ".", "min_x", ",", "bbox", ".", "min_y", ")", ",", "(", "...
43.9375
10.875
def path(self, tax_ids): """Get the node at the end of the path described by tax_ids.""" assert tax_ids[0] == self.tax_id if len(tax_ids) == 1: return self n = tax_ids[1] try: child = next(i for i in self.children if i.tax_id == n) except StopIter...
[ "def", "path", "(", "self", ",", "tax_ids", ")", ":", "assert", "tax_ids", "[", "0", "]", "==", "self", ".", "tax_id", "if", "len", "(", "tax_ids", ")", "==", "1", ":", "return", "self", "n", "=", "tax_ids", "[", "1", "]", "try", ":", "child", ...
29.692308
16.846154
def l(*members, meta=None) -> List: """Creates a new list from members.""" return List( # pylint: disable=abstract-class-instantiated plist(iterable=members), meta=meta )
[ "def", "l", "(", "*", "members", ",", "meta", "=", "None", ")", "->", "List", ":", "return", "List", "(", "# pylint: disable=abstract-class-instantiated", "plist", "(", "iterable", "=", "members", ")", ",", "meta", "=", "meta", ")" ]
37.4
13
def basic_query(returns): """decorator factory for NS queries""" return compose( reusable, map_send(parse_request), map_yield(prepare_params, snug.prefix_adder(API_PREFIX)), map_return(loads(returns)), oneyield, )
[ "def", "basic_query", "(", "returns", ")", ":", "return", "compose", "(", "reusable", ",", "map_send", "(", "parse_request", ")", ",", "map_yield", "(", "prepare_params", ",", "snug", ".", "prefix_adder", "(", "API_PREFIX", ")", ")", ",", "map_return", "(", ...
28.555556
17.222222
def disambiguate(self, words): """Disambiguate previously analyzed words. Parameters ---------- words: list of dict A sentence of words. Returns ------- list of dict Sentence of disambiguated words. """ words = vm.Sentence...
[ "def", "disambiguate", "(", "self", ",", "words", ")", ":", "words", "=", "vm", ".", "SentenceAnalysis", "(", "[", "as_wordanalysis", "(", "w", ")", "for", "w", "in", "words", "]", ")", "disambiguated", "=", "self", ".", "_morf", ".", "disambiguate", "...
30.125
19.4375
def list_(): ''' Returns the machine's bridges list CLI Example: .. code-block:: bash salt '*' bridge.list ''' brs = _os_dispatch('brshow') if not brs: return None brlist = [] for br in brs: brlist.append(br) return brlist
[ "def", "list_", "(", ")", ":", "brs", "=", "_os_dispatch", "(", "'brshow'", ")", "if", "not", "brs", ":", "return", "None", "brlist", "=", "[", "]", "for", "br", "in", "brs", ":", "brlist", ".", "append", "(", "br", ")", "return", "brlist" ]
15.166667
24.833333
def values(self): """ Iterate values. """ for key, value in self.__data__.items(): if key not in (META, KEY): yield DictTree(__data__=value)
[ "def", "values", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "__data__", ".", "items", "(", ")", ":", "if", "key", "not", "in", "(", "META", ",", "KEY", ")", ":", "yield", "DictTree", "(", "__data__", "=", "value", ")" ]
27.714286
8
def splitalleles(consensus): """ takes diploid consensus alleles with phase data stored as a mixture of upper and lower case characters and splits it into 2 alleles """ ## store two alleles, allele1 will start with bigbase allele1 = list(consensus) allele2 = list(consensus) hidx = [i for (i, j)...
[ "def", "splitalleles", "(", "consensus", ")", ":", "## store two alleles, allele1 will start with bigbase", "allele1", "=", "list", "(", "consensus", ")", "allele2", "=", "list", "(", "consensus", ")", "hidx", "=", "[", "i", "for", "(", "i", ",", "j", ")", "...
32.208333
16.208333
def upload_function_zip(self, location, zip_path, project_id=None): """ Uploads zip file with sources. :param location: The location where the function is created. :type location: str :param zip_path: The path of the valid .zip file to upload. :type zip_path: str ...
[ "def", "upload_function_zip", "(", "self", ",", "location", ",", "zip_path", ",", "project_id", "=", "None", ")", ":", "response", "=", "self", ".", "get_conn", "(", ")", ".", "projects", "(", ")", ".", "locations", "(", ")", ".", "functions", "(", ")"...
46.333333
22.6
def get_metadata(model): """Get metadata for a given model. Parameters ---------- model : `~astropy.modeling.Model` Model. Returns ------- metadata : dict Metadata for the model. Raises ------ synphot.exceptions.SynphotError Invalid model. """ ...
[ "def", "get_metadata", "(", "model", ")", ":", "if", "not", "isinstance", "(", "model", ",", "Model", ")", ":", "raise", "SynphotError", "(", "'{0} is not a model.'", ".", "format", "(", "model", ")", ")", "if", "isinstance", "(", "model", ",", "_CompoundM...
20.571429
22.178571
def mark(self, digits: int = None) -> float: """ Return time in seconds since last mark, reset, or construction. :param digits: number of fractional decimal digits to retain (default as constructed) """ self._mark[:] = [self._mark[1], time()] rv = self._mark[1] - self._...
[ "def", "mark", "(", "self", ",", "digits", ":", "int", "=", "None", ")", "->", "float", ":", "self", ".", "_mark", "[", ":", "]", "=", "[", "self", ".", "_mark", "[", "1", "]", ",", "time", "(", ")", "]", "rv", "=", "self", ".", "_mark", "[...
32.444444
18.444444
def find_autosummary_in_docstring(name, module=None, filename=None): """Find out what items are documented in the given object's docstring. See `find_autosummary_in_lines`. """ try: real_name, obj, parent = import_by_name(name) lines = pydoc.getdoc(obj).splitlines() return find_...
[ "def", "find_autosummary_in_docstring", "(", "name", ",", "module", "=", "None", ",", "filename", "=", "None", ")", ":", "try", ":", "real_name", ",", "obj", ",", "parent", "=", "import_by_name", "(", "name", ")", "lines", "=", "pydoc", ".", "getdoc", "(...
35.785714
18.428571
def users_for_perms(cls, perm_names, db_session=None): """ return users hat have one of given permissions :param perm_names: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query....
[ "def", "users_for_perms", "(", "cls", ",", "perm_names", ",", "db_session", "=", "None", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "query", "=", "db_session", ".", "query", "(", "cls", ".", "model", ")", "query", "=", "query", ...
34.964286
19.607143
def instance(self, counter=None): """Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. ...
[ "def", "instance", "(", "self", ",", "counter", "=", "None", ")", ":", "if", "not", "counter", ":", "history", "=", "self", ".", "history", "(", ")", "if", "not", "history", ":", "return", "history", "else", ":", "return", "Response", ".", "_from_json"...
33.909091
23.318182
def printUnusedImports(self): """Produce a report of unused imports.""" for module in self.listModules(): names = [(unused.lineno, unused.name) for unused in module.unused_names] names.sort() for lineno, name in names: if not self....
[ "def", "printUnusedImports", "(", "self", ")", ":", "for", "module", "in", "self", ".", "listModules", "(", ")", ":", "names", "=", "[", "(", "unused", ".", "lineno", ",", "unused", ".", "name", ")", "for", "unused", "in", "module", ".", "unused_names"...
47.384615
13.307692
def parse_pr_numbers(git_log_lines): """ Parse PR numbers from commit messages. At GitHub those have the format: `here is the message (#1234)` being `1234` the PR number. """ prs = [] for line in git_log_lines: pr_number = parse_pr_number(line) if pr_number: ...
[ "def", "parse_pr_numbers", "(", "git_log_lines", ")", ":", "prs", "=", "[", "]", "for", "line", "in", "git_log_lines", ":", "pr_number", "=", "parse_pr_number", "(", "line", ")", "if", "pr_number", ":", "prs", ".", "append", "(", "pr_number", ")", "return"...
24.571429
15.857143
def get_total_ram(): """The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine. """ with open('/proc/meminfo', 'r') as f: for line in f.readlines(): if line: ...
[ "def", "get_total_ram", "(", ")", ":", "with", "open", "(", "'/proc/meminfo'", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "if", "line", ":", "key", ",", "value", ",", "unit", "=", "line", ".", "spl...
38.5
13.642857
def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to ...
[ "def", "register_archive_format", "(", "name", ",", "function", ",", "extra_args", "=", "None", ",", "description", "=", "''", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "[", "]", "if", "not", "isinstance", "(", "function", ",", ...
48.5
22.5
def Compare(fromMo, toMo, diff): """ Internal method to support CompareManagedObject functionality. """ from UcsBase import UcsUtils if (fromMo.classId != toMo.classId): return CompareStatus.TypesDifferent for prop in UcsUtils.GetUcsPropertyMetaAttributeList(str(fromMo.classId)): propMeta = UcsUtils.IsPropert...
[ "def", "Compare", "(", "fromMo", ",", "toMo", ",", "diff", ")", ":", "from", "UcsBase", "import", "UcsUtils", "if", "(", "fromMo", ".", "classId", "!=", "toMo", ".", "classId", ")", ":", "return", "CompareStatus", ".", "TypesDifferent", "for", "prop", "i...
36.05
23.3
def p_jr(p): """ asm : JR jr_flags COMMA expr | JR jr_flags COMMA pexpr """ p[4] = Expr.makenode(Container('-', p.lineno(3)), p[4], Expr.makenode(Container(MEMORY.org + 2, p.lineno(1)))) p[0] = Asm(p.lineno(1), 'JR %s,N' % p[2], p[4])
[ "def", "p_jr", "(", "p", ")", ":", "p", "[", "4", "]", "=", "Expr", ".", "makenode", "(", "Container", "(", "'-'", ",", "p", ".", "lineno", "(", "3", ")", ")", ",", "p", "[", "4", "]", ",", "Expr", ".", "makenode", "(", "Container", "(", "M...
42.833333
19.333333
def iflat_tasks_wti(self, status=None, op="==", nids=None): """ Generator to iterate over all the tasks of the `Flow`. Yields: (task, work_index, task_index) If status is not None, only the tasks whose status satisfies the condition (task.status op status) are selec...
[ "def", "iflat_tasks_wti", "(", "self", ",", "status", "=", "None", ",", "op", "=", "\"==\"", ",", "nids", "=", "None", ")", ":", "return", "self", ".", "_iflat_tasks_wti", "(", "status", "=", "status", ",", "op", "=", "op", ",", "nids", "=", "nids", ...
43.857143
23
def convert_anything_to_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Convert arbitrary files to text, using ``strings`` or ``strings2``. (``strings`` is a standard Unix command to get text from any old rubbish.) """ ...
[ "def", "convert_anything_to_text", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ",", "config", ":", "TextProcessingConfig", "=", "_DEFAULT_CONFIG", ")", "->", "str", ":", "strings", "=", "tools", "[", "'strings'", "]", ...
37.6875
19.0625
def composite_qc(df_orig, size=(16, 12)): """ Plot composite QC figures """ df = df_orig.rename(columns={"hli_calc_age_sample_taken": "Age", "hli_calc_gender": "Gender", "eth7_max": "Ethnicity", "MeanCoverage": "Mean coverage", ...
[ "def", "composite_qc", "(", "df_orig", ",", "size", "=", "(", "16", ",", "12", ")", ")", ":", "df", "=", "df_orig", ".", "rename", "(", "columns", "=", "{", "\"hli_calc_age_sample_taken\"", ":", "\"Age\"", ",", "\"hli_calc_gender\"", ":", "\"Gender\"", ","...
36.283333
16.616667
def set_data(self, vertices=None, tris=None, data=None): """Set the data Parameters ---------- vertices : ndarray, shape (Nv, 3) | None Vertex coordinates. tris : ndarray, shape (Nf, 3) | None Indices into the vertex array. data : ndarray, shape (...
[ "def", "set_data", "(", "self", ",", "vertices", "=", "None", ",", "tris", "=", "None", ",", "data", "=", "None", ")", ":", "# modifier pour tenier compte des None self._recompute = True", "if", "data", "is", "not", "None", ":", "self", ".", "_data", "=", "d...
32.73913
10.565217
def _http_post(self, url, data, **kwargs): """ Performs the HTTP POST request. """ if not kwargs.get('file_upload', False): data = json.dumps(data) kwargs.update({'data': data}) return self._http_request('post', url, kwargs)
[ "def", "_http_post", "(", "self", ",", "url", ",", "data", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "get", "(", "'file_upload'", ",", "False", ")", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "kwargs", ".", "up...
25.181818
13.909091
def run(self, *args, **kwargs): """Update the cache of all DNS entries and perform checks Args: *args: Optional list of arguments **kwargs: Optional list of keyword arguments Returns: None """ try: zones = list(DNSZone.get_all().v...
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "zones", "=", "list", "(", "DNSZone", ".", "get_all", "(", ")", ".", "values", "(", ")", ")", "buckets", "=", "{", "k", ".", "lower", "(", ")", ":", ...
38.180952
20.733333
def edit_block(object): """ Handles edit blocks undo states. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def edit_block_wrapper(*args, **kwargs): """ Handles edit blocks undo states. :...
[ "def", "edit_block", "(", "object", ")", ":", "@", "functools", ".", "wraps", "(", "object", ")", "def", "edit_block_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Handles edit blocks undo states.\n\n :param \\*args: Arguments.\...
23.171429
15.914286
def vtas2cas(tas, h): """ tas2cas conversion both m/s """ p, rho, T = vatmos(h) qdyn = p*((1.+rho*tas*tas/(7.*p))**3.5-1.) cas = np.sqrt(7.*p0/rho0*((qdyn/p0+1.)**(2./7.)-1.)) # cope with negative speed cas = np.where(tas<0, -1*cas, cas) return cas
[ "def", "vtas2cas", "(", "tas", ",", "h", ")", ":", "p", ",", "rho", ",", "T", "=", "vatmos", "(", "h", ")", "qdyn", "=", "p", "*", "(", "(", "1.", "+", "rho", "*", "tas", "*", "tas", "/", "(", "7.", "*", "p", ")", ")", "**", "3.5", "-",...
29.888889
14.888889
def list_(env=None, user=None): """ List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... } """ cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user) ret = _execcmd(cmd, user=user) if ret['retcode'] == ...
[ "def", "list_", "(", "env", "=", "None", ",", "user", "=", "None", ")", ":", "cmd", "=", "_create_conda_cmd", "(", "'list'", ",", "args", "=", "[", "'--json'", "]", ",", "env", "=", "env", ",", "user", "=", "user", ")", "ret", "=", "_execcmd", "(...
32.15
18.45
def getBinding(self): """Return the Binding object that is referenced by this port.""" wsdl = self.getService().getWSDL() return wsdl.bindings[self.binding]
[ "def", "getBinding", "(", "self", ")", ":", "wsdl", "=", "self", ".", "getService", "(", ")", ".", "getWSDL", "(", ")", "return", "wsdl", ".", "bindings", "[", "self", ".", "binding", "]" ]
44.25
5.75
def _space_in_headerblock(relative_path, contents, linter_options): """Check for space between the filename in a header block and description. like such: # /path/to/filename # # Description """ del relative_path del linter_options check_index = 1 if len(contents) > 0: ...
[ "def", "_space_in_headerblock", "(", "relative_path", ",", "contents", ",", "linter_options", ")", ":", "del", "relative_path", "del", "linter_options", "check_index", "=", "1", "if", "len", "(", "contents", ")", ">", "0", ":", "if", "_line_is_shebang", "(", "...
31.448276
18.62069
def year(self, value=None): """ We do *NOT* know for what year we are converting so lets assume the year has 365 days. """ if value is None: return self.day() / 365 else: self.millisecond(self.day(value * 365))
[ "def", "year", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "self", ".", "day", "(", ")", "/", "365", "else", ":", "self", ".", "millisecond", "(", "self", ".", "day", "(", "value", "*", "365", "...
30.444444
13.333333
def _build_config(self): ''' Build the config of the napalm syslog parser. ''' if not self.config_dict: if not self.config_path: # No custom config path requested # Read the native config files self.config_path = os.path.join( ...
[ "def", "_build_config", "(", "self", ")", ":", "if", "not", "self", ".", "config_dict", ":", "if", "not", "self", ".", "config_path", ":", "# No custom config path requested", "# Read the native config files", "self", ".", "config_path", "=", "os", ".", "path", ...
50.695652
21.391304
def get_formset(self, request, obj=None, **kwargs): """ Return a form, if the obj has a staffmember object, otherwise return an empty form """ if obj is not None and self.model.objects.filter(user=obj).count(): return super(StaffMemberAdmin, self).get_formset( ...
[ "def", "get_formset", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "obj", "is", "not", "None", "and", "self", ".", "model", ".", "objects", ".", "filter", "(", "user", "=", "obj", ")", ".", "count...
31.722222
20.055556
def is_distributed(partition_column, lower_bound, upper_bound): """ Check if is possible distribute a query given that args Args: partition_column: column used to share the data between the workers lower_bound: the minimum value to be requested from the partition_column upper_bound: the...
[ "def", "is_distributed", "(", "partition_column", ",", "lower_bound", ",", "upper_bound", ")", ":", "if", "(", "(", "partition_column", "is", "not", "None", ")", "and", "(", "lower_bound", "is", "not", "None", ")", "and", "(", "upper_bound", "is", "not", "...
38.925926
25.296296
async def get_protocol_version(self): """ This method returns the major and minor values for the protocol version, i.e. 2.4 :returns: Firmata protocol version """ if self.query_reply_data.get(PrivateConstants.REPORT_VERSION) == '': await self._send_command([P...
[ "async", "def", "get_protocol_version", "(", "self", ")", ":", "if", "self", ".", "query_reply_data", ".", "get", "(", "PrivateConstants", ".", "REPORT_VERSION", ")", "==", "''", ":", "await", "self", ".", "_send_command", "(", "[", "PrivateConstants", ".", ...
44
17.384615
def prepend_multi(self, keys, format=None, persist_to=0, replicate_to=0): """Prepend to multiple keys. Multi variant of :meth:`prepend` .. seealso:: :meth:`prepend`, :meth:`upsert_multi`, :meth:`upsert` """ return _Base.prepend_multi(self, keys, format=format, ...
[ "def", "prepend_multi", "(", "self", ",", "keys", ",", "format", "=", "None", ",", "persist_to", "=", "0", ",", "replicate_to", "=", "0", ")", ":", "return", "_Base", ".", "prepend_multi", "(", "self", ",", "keys", ",", "format", "=", "format", ",", ...
50.75
20.75
def is_empty(self): """ A group of modules is considered empty if it has no children or if all its children are empty. >>> from admin_tools.dashboard.modules import DashboardModule, LinkList >>> mod = Group() >>> mod.is_empty() True >>> mod.children.appen...
[ "def", "is_empty", "(", "self", ")", ":", "if", "super", "(", "Group", ",", "self", ")", ".", "is_empty", "(", ")", ":", "return", "True", "for", "child", "in", "self", ".", "children", ":", "if", "not", "child", ".", "is_empty", "(", ")", ":", "...
32.32
17.84
def create_file_from_path(self, share_name, directory_name, file_name, local_file_path, content_settings=None, metadata=None, validate_content=False, progress_callback=None, max_connections=2, timeout=None): ''' Cr...
[ "def", "create_file_from_path", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "local_file_path", ",", "content_settings", "=", "None", ",", "metadata", "=", "None", ",", "validate_content", "=", "False", ",", "progress_callback", "=...
52.54
22.58
def next(self): """ Handles the next debug event. @see: L{cont}, L{dispatch}, L{wait}, L{stop} @raise WindowsError: Raises an exception on error. If the wait operation causes an error, debugging is stopped (meaning all debugees are either killed or detached fro...
[ "def", "next", "(", "self", ")", ":", "try", ":", "event", "=", "self", ".", "wait", "(", ")", "except", "Exception", ":", "self", ".", "stop", "(", ")", "raise", "try", ":", "self", ".", "dispatch", "(", ")", "finally", ":", "self", ".", "cont",...
30
22.583333
def _build_menu(self, context_menu: QMenu): """Build the context menu.""" logger.debug("Show tray icon enabled in settings: {}".format(cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON])) # Items selected for display are shown on top self._fill_context_menu_with_model_item_actions(context_menu...
[ "def", "_build_menu", "(", "self", ",", "context_menu", ":", "QMenu", ")", ":", "logger", ".", "debug", "(", "\"Show tray icon enabled in settings: {}\"", ".", "format", "(", "cm", ".", "ConfigManager", ".", "SETTINGS", "[", "cm", ".", "SHOW_TRAY_ICON", "]", "...
59.454545
19.727273
def copy_files(src_dir, dst_dir, filespec='*', recursive=False): """ Copies any files matching filespec from src_dir into dst_dir. If `recursive` is `True`, also copies any matching directories. """ import os from .modules import copyfiles if src_dir == dst_dir: raise RuntimeError(...
[ "def", "copy_files", "(", "src_dir", ",", "dst_dir", ",", "filespec", "=", "'*'", ",", "recursive", "=", "False", ")", ":", "import", "os", "from", ".", "modules", "import", "copyfiles", "if", "src_dir", "==", "dst_dir", ":", "raise", "RuntimeError", "(", ...
30.08
22.16
def _set_element_text(self, prop_name, value): """Set string value of *name* property to *value*.""" if not is_string(value): value = str(value) if len(value) > 255: tmpl = ( "exceeded 255 char limit for property, got:\n\n'%s'" ) r...
[ "def", "_set_element_text", "(", "self", ",", "prop_name", ",", "value", ")", ":", "if", "not", "is_string", "(", "value", ")", ":", "value", "=", "str", "(", "value", ")", "if", "len", "(", "value", ")", ">", "255", ":", "tmpl", "=", "(", "\"excee...
34.416667
14.166667
def map_from_config(cls, config, context_names, section_key="scoring_contexts"): """ Loads a whole set of ScoringContext's from a configuration file while maintaining a cache of model names. This aids in better memory management and allows model aliases to be imp...
[ "def", "map_from_config", "(", "cls", ",", "config", ",", "context_names", ",", "section_key", "=", "\"scoring_contexts\"", ")", ":", "model_key_map", "=", "{", "}", "context_map", "=", "{", "}", "for", "context_name", "in", "context_names", ":", "section", "=...
40.290323
19.709677
def set_errors(self, errors): """Set parameter error estimate """ if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
[ "def", "set_errors", "(", "self", ",", "errors", ")", ":", "if", "errors", "is", "None", ":", "self", ".", "__errors__", "=", "None", "return", "self", ".", "__errors__", "=", "[", "asscalar", "(", "e", ")", "for", "e", "in", "errors", "]" ]
34.166667
11.333333
def time_report(self, source=None, **kwargs): """ This will generate a time table for the source api_calls :param source: obj this can be an int(index), str(key), slice, list of api_calls or an api_call :return: ReprListList """ if source is None: api_...
[ "def", "time_report", "(", "self", ",", "source", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source", "is", "None", ":", "api_calls", "=", "[", "self", "[", "-", "1", "]", "]", "elif", "isinstance", "(", "source", ",", "list", ")", ":...
37.857143
9.952381
def _call_method_from_namespace(obj, method_name, namespace): """Call the method, retrieved from obj, with the correct arguments via the namespace Args: obj: any kind of object method_name: method to be called namespace: an argparse.Namespace object containing parsed command ...
[ "def", "_call_method_from_namespace", "(", "obj", ",", "method_name", ",", "namespace", ")", ":", "method", "=", "getattr", "(", "obj", ",", "method_name", ")", "method_parser", "=", "method", ".", "parser", "arg_names", "=", "_get_args_name_from_parser", "(", "...
36.75
13.8125
def regexNamer(regex, usePageUrl=False): """Get name from regular expression.""" @classmethod def _namer(cls, imageUrl, pageUrl): """Get first regular expression group.""" url = pageUrl if usePageUrl else imageUrl mo = regex.search(url) if mo: return mo.group(1) ...
[ "def", "regexNamer", "(", "regex", ",", "usePageUrl", "=", "False", ")", ":", "@", "classmethod", "def", "_namer", "(", "cls", ",", "imageUrl", ",", "pageUrl", ")", ":", "\"\"\"Get first regular expression group.\"\"\"", "url", "=", "pageUrl", "if", "usePageUrl"...
32.7
10.3
def get_manifest(self, repo_name, digest=None, version="v1"): ''' get_manifest should return an image manifest for a particular repo and tag. The image details are extracted when the client is generated. Parameters ========== repo_name: reference to the <username>/<reposi...
[ "def", "get_manifest", "(", "self", ",", "repo_name", ",", "digest", "=", "None", ",", "version", "=", "\"v1\"", ")", ":", "accepts", "=", "{", "'config'", ":", "\"application/vnd.docker.container.image.v1+json\"", ",", "'v1'", ":", "\"application/vnd.docker.distrib...
32.733333
26
def update_gradients_full(self, dL_dK, X, X2=None): #def dK_dtheta(self, dL_dK, X, X2, target): """derivative of the covariance matrix with respect to the parameters.""" X,slices = X[:,:-1],index_to_slices(X[:,-1]) if X2 is None: X2,slices2 = X,slices K = np.zeros((X....
[ "def", "update_gradients_full", "(", "self", ",", "dL_dK", ",", "X", ",", "X2", "=", "None", ")", ":", "#def dK_dtheta(self, dL_dK, X, X2, target):", "X", ",", "slices", "=", "X", "[", ":", ",", ":", "-", "1", "]", ",", "index_to_slices", "(", "X", "[", ...
57.314516
35.983871
def main(): """ Default entry point """ importer = ExchangeRatesImporter() print("####################################") latest_rates_json = importer.get_latest_rates() # translate into an array of PriceModels # TODO mapper = currencyrates.FixerioModelMapper() mapper = None rat...
[ "def", "main", "(", ")", ":", "importer", "=", "ExchangeRatesImporter", "(", ")", "print", "(", "\"####################################\"", ")", "latest_rates_json", "=", "importer", ".", "get_latest_rates", "(", ")", "# translate into an array of PriceModels", "# TODO ma...
30.521739
14.347826
def get_query_info(sql, con, partition_column): """ Return a columns name list and the query string Args: sql: SQL query or table name con: database connection or url string partition_column: column used to share the data between the workers Returns: Columns name list and q...
[ "def", "get_query_info", "(", "sql", ",", "con", ",", "partition_column", ")", ":", "engine", "=", "create_engine", "(", "con", ")", "if", "is_table", "(", "engine", ",", "sql", ")", ":", "table_metadata", "=", "get_table_metadata", "(", "engine", ",", "sq...
35.541667
15.625
def quick_ratio(self): """Return an upper bound on ratio() relatively quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute. """ # viewing a and b as multisets, set matches to the cardinality # of their intersection; this cou...
[ "def", "quick_ratio", "(", "self", ")", ":", "# viewing a and b as multisets, set matches to the cardinality", "# of their intersection; this counts the number of matches", "# without regard to order, so is clearly an upper bound", "if", "self", ".", "fullbcount", "is", "None", ":", ...
39.785714
16.5
def process_default(self, event): """ Writes event string representation to file object provided to my_init(). @param event: Event to be processed. Can be of any type of events but IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW). @type event: Event ...
[ "def", "process_default", "(", "self", ",", "event", ")", ":", "self", ".", "_out", ".", "write", "(", "str", "(", "event", ")", ")", "self", ".", "_out", ".", "write", "(", "'\\n'", ")", "self", ".", "_out", ".", "flush", "(", ")" ]
35.083333
17.416667
def apply_mask(img, mask): """Return the image with the given `mask` applied.""" from .mask import apply_mask vol, _ = apply_mask(img, mask) return vector_to_volume(vol, read_img(mask).get_data().astype(bool))
[ "def", "apply_mask", "(", "img", ",", "mask", ")", ":", "from", ".", "mask", "import", "apply_mask", "vol", ",", "_", "=", "apply_mask", "(", "img", ",", "mask", ")", "return", "vector_to_volume", "(", "vol", ",", "read_img", "(", "mask", ")", ".", "...
36.833333
16.666667
def separation_from(self, another_icrf): """Return the angle between this position and another. >>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0]))) 45deg 00' 00.0" You can also compute separations across an array of positions. >>> directions = ICRF([[1,0,-1,0], [0,1,0,-1],...
[ "def", "separation_from", "(", "self", ",", "another_icrf", ")", ":", "p1", "=", "self", ".", "position", ".", "au", "p2", "=", "another_icrf", ".", "position", ".", "au", "u1", "=", "p1", "/", "length_of", "(", "p1", ")", "u2", "=", "p2", "/", "le...
32.375
17
def get_namespace( self, namespace_id, include_history=True ): """ Given a namespace ID, get the ready namespace op for it. Return the dict with the parameters on success. Return None if the namespace has not yet been revealed. """ cur = self.db.cursor() return ...
[ "def", "get_namespace", "(", "self", ",", "namespace_id", ",", "include_history", "=", "True", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_namespace_ready", "(", "cur", ",", "namespace_id", ",", "include_history", ...
39.1
22.9
def _create_stable_task_type(superclass, options_scope): """Creates a singleton (via `memoized`) subclass instance for the given superclass and scope. Currently we need to support registering the same task type multiple times in different scopes. However we still want to have each task class know the options sco...
[ "def", "_create_stable_task_type", "(", "superclass", ",", "options_scope", ")", ":", "subclass_name", "=", "'{0}_{1}'", ".", "format", "(", "superclass", ".", "__name__", ",", "options_scope", ".", "replace", "(", "'.'", ",", "'_'", ")", ".", "replace", "(", ...
48
24
def delete_record(self, record): """ Permanently removes record from table. """ try: self.session.delete(record) self.session.commit() except Exception as e: self.session.rollback() raise ProgrammingError(e) finally: ...
[ "def", "delete_record", "(", "self", ",", "record", ")", ":", "try", ":", "self", ".", "session", ".", "delete", "(", "record", ")", "self", ".", "session", ".", "commit", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "session", ".", ...
27.833333
8.333333
def get_folders(cls, session, mailbox_or_id): """List the folders for the mailbox. Args: mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Fold...
[ "def", "get_folders", "(", "cls", ",", "session", ",", "mailbox_or_id", ")", ":", "if", "isinstance", "(", "mailbox_or_id", ",", "Mailbox", ")", ":", "mailbox_or_id", "=", "mailbox_or_id", ".", "id", "return", "cls", "(", "'/mailboxes/%d/folders.json'", "%", "...
32.833333
18.888889
def convert(self, imtls, idx=0): """ Convert a probability curve into a record of dtype `imtls.dt`. :param imtls: DictArray instance :param idx: extract the data corresponding to the given inner index """ curve = numpy.zeros(1, imtls.dt) for imt in imtls: ...
[ "def", "convert", "(", "self", ",", "imtls", ",", "idx", "=", "0", ")", ":", "curve", "=", "numpy", ".", "zeros", "(", "1", ",", "imtls", ".", "dt", ")", "for", "imt", "in", "imtls", ":", "curve", "[", "imt", "]", "=", "self", ".", "array", "...
34.454545
14.272727
def prop_samples(self,prop,return_values=True,conf=0.683): """Returns samples of given property, based on MCMC sampling :param prop: Name of desired property. Must be column of ``self.samples``. :param return_values: (optional) If ``True`` (default), then also return (...
[ "def", "prop_samples", "(", "self", ",", "prop", ",", "return_values", "=", "True", ",", "conf", "=", "0.683", ")", ":", "samples", "=", "self", ".", "samples", "[", "prop", "]", ".", "values", "if", "return_values", ":", "sorted", "=", "np", ".", "s...
33.911765
18.764706
def terms(self): """Iterator over the terms of the sum Yield from the (possibly) infinite list of terms of the indexed sum, if the sum was written out explicitly. Each yielded term in an instance of :class:`.Expression` """ from qnet.algebra.core.scalar_algebra import Sc...
[ "def", "terms", "(", "self", ")", ":", "from", "qnet", ".", "algebra", ".", "core", ".", "scalar_algebra", "import", "ScalarValue", "for", "mapping", "in", "yield_from_ranges", "(", "self", ".", "ranges", ")", ":", "term", "=", "self", ".", "term", ".", ...
42.571429
17.714286
def search(self, remote_path, keyword, recurrent='0', **kwargs): """按文件名搜索文件(不支持查找目录). :param remote_path: 需要检索的目录路径,路径必须以 /apps/ 开头。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:``\\\\ ? | " > < : *``; ...
[ "def", "search", "(", "self", ",", "remote_path", ",", "keyword", ",", "recurrent", "=", "'0'", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'path'", ":", "remote_path", ",", "'wd'", ":", "keyword", ",", "'re'", ":", "recurrent", ",", "}",...
32.607143
17.321429
def list_time_ranges(self, filter=market_filter(), granularity='DAYS', session=None, lightweight=None): """ Returns a list of time ranges in the granularity specified in the request (i.e. 3PM to 4PM, Aug 14th to Aug 15th) associated with the markets selected by the MarketFilter. ...
[ "def", "list_time_ranges", "(", "self", ",", "filter", "=", "market_filter", "(", ")", ",", "granularity", "=", "'DAYS'", ",", "session", "=", "None", ",", "lightweight", "=", "None", ")", ":", "params", "=", "clean_locals", "(", "locals", "(", ")", ")",...
53.166667
25.388889
def printrdf(wflow, ctx, style): # type: (Process, ContextType, Text) -> Text """Serialize the CWL document into a string, ready for printing.""" rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8') if not rdf: return u"" return rdf.decode('utf-8')
[ "def", "printrdf", "(", "wflow", ",", "ctx", ",", "style", ")", ":", "# type: (Process, ContextType, Text) -> Text", "rdf", "=", "gather", "(", "wflow", ",", "ctx", ")", ".", "serialize", "(", "format", "=", "style", ",", "encoding", "=", "'utf-8'", ")", "...
47
20.833333
def get_default_is_active(): """ Stormpath user is active by default if e-mail verification is disabled. """ directory = APPLICATION.default_account_store_mapping.account_store verif_email = directory.account_creation_policy.verification_email_status return verif_email == AccountCreationPoli...
[ "def", "get_default_is_active", "(", ")", ":", "directory", "=", "APPLICATION", ".", "default_account_store_mapping", ".", "account_store", "verif_email", "=", "directory", ".", "account_creation_policy", ".", "verification_email_status", "return", "verif_email", "==", "A...
42.125
20.125
def add_callback(instance, prop, callback, echo_old=False, priority=0): """ Attach a callback function to a property in an instance Parameters ---------- instance The instance to add the callback to prop : str Name of callback property in `instance` callback : func T...
[ "def", "add_callback", "(", "instance", ",", "prop", ",", "callback", ",", "echo_old", "=", "False", ",", "priority", "=", "0", ")", ":", "p", "=", "getattr", "(", "type", "(", "instance", ")", ",", "prop", ")", "if", "not", "isinstance", "(", "p", ...
29.307692
22.333333
def Pitzer(T, Tc, omega): r'''Calculates enthalpy of vaporization at arbitrary temperatures using a fit by [2]_ to the work of Pitzer [1]_; requires a chemical's critical temperature and acentric factor. The enthalpy of vaporization is given by: .. math:: \frac{\Delta_{vap} H}{RT_c}=7.08(1...
[ "def", "Pitzer", "(", "T", ",", "Tc", ",", "omega", ")", ":", "Tr", "=", "T", "/", "Tc", "return", "R", "*", "Tc", "*", "(", "7.08", "*", "(", "1.", "-", "Tr", ")", "**", "0.354", "+", "10.95", "*", "omega", "*", "(", "1.", "-", "Tr", ")"...
31.767857
26.482143
def _describe_fields(cls): """ Return a dictionary for the class fields description. Fields should NOT be wrapped by _precomputed_field, if necessary """ dispatch_table = { 'ShortestPathModel': 'sssp', 'GraphColoringModel': 'graph_coloring', 'P...
[ "def", "_describe_fields", "(", "cls", ")", ":", "dispatch_table", "=", "{", "'ShortestPathModel'", ":", "'sssp'", ",", "'GraphColoringModel'", ":", "'graph_coloring'", ",", "'PagerankModel'", ":", "'pagerank'", ",", "'ConnectedComponentsModel'", ":", "'connected_compon...
42.904762
16.904762
def case(context, case_id, case_name, institute, collaborator, vcf, vcf_sv, vcf_cancer, vcf_research, vcf_sv_research, vcf_cancer_research, peddy_ped, reupload_sv, rankscore_treshold, rankmodel_version): """ Update a case in the database """ adapter = context.obj['adapter'] if not ...
[ "def", "case", "(", "context", ",", "case_id", ",", "case_name", ",", "institute", ",", "collaborator", ",", "vcf", ",", "vcf_sv", ",", "vcf_cancer", ",", "vcf_research", ",", "vcf_sv_research", ",", "vcf_cancer_research", ",", "peddy_ped", ",", "reupload_sv", ...
41.847059
20.223529
def tagdict(self): """return a dict converted from this string interpreted as a tag-string .. code-block:: py >>> from pprint import pprint >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict >>> pprint({str(k): str(v) for k, v in dict_.items()}) ...
[ "def", "tagdict", "(", "self", ")", ":", "tagdict", "=", "getattr", "(", "self", ",", "'_tagdict'", ",", "None", ")", "if", "tagdict", "is", "None", ":", "try", ":", "self", ".", "_tagdict", "=", "tags", ".", "decode", "(", "self", ")", "except", "...
36.294118
17
def get_suppliers_per_page(self, per_page=1000, page=1, params=None): """ Get suppliers per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list """ ...
[ "def", "get_suppliers_per_page", "(", "self", ",", "per_page", "=", "1000", ",", "page", "=", "1", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "SUPPLIERS", ",", "per_page", "=", "per_page", "...
41
20.6