code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def user_default_loader(self, pk): try: obj = User.objects.get(pk=pk) except User.DoesNotExist: return None else: self.user_default_add_related_pks(obj) return obj
Load a User from the database.
def columns(self): fields = [f.label for f in self.form_fields if self.cleaned_data["field_%s_export" % f.id]] if self.cleaned_data["field_0_export"]: fields.append(self.entry_time_name) return fields
Returns the list of selected column names.
def readPlistFromString(data): try: plistData = buffer(data) except TypeError, err: raise NSPropertyListSerializationException(err) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( ...
Read a plist data from a string. Return the root object.
def new_bundle(name, scriptmap, filemap=None): if name in BUNDLEMAP: logger.warn('overwriting bundle %s' % name) BUNDLEMAP[name] = Bundle(scriptmap, filemap)
Create a bundle and add to available bundles
def as_txt(self): s = "IIIF Image Server Error\n\n" s += self.text if (self.text) else 'UNKNOWN_ERROR' s += "\n\n" if (self.parameter): s += "parameter=%s\n" % self.parameter if (self.code): s += "code=%d\n\n" % self.code for header in sorted(self....
Text rendering of error response. Designed for use with Image API version 1.1 and above where the error response is suggested to be text or html but not otherwise specified. Intended to provide useful information for debugging.
def heating_values(self): heating_dict = { 'level': self.heating_level, 'target': self.target_heating_level, 'active': self.now_heating, 'remaining': self.heating_remaining, 'last_seen': self.last_seen, } return heating_dict
Return a dict of all the current heating values.
def _update_redundancy_router_interfaces(self, context, router, port, modified_port_data, redundancy_router_ids=None, ha_settings_db=None): router_id = router['id'] if h...
To be called when the router interfaces are updated, like in the case of change in port admin_state_up status
def _get_page_elements(self): page_elements = [] for attribute, value in list(self.__dict__.items()) + list(self.__class__.__dict__.items()): if attribute != 'parent' and isinstance(value, CommonObject): page_elements.append(value) return page_elements
Return page elements and page objects of this page object :returns: list of page elements and page objects
def remove(self, expr): self._assert_supports_contents() index = self._contents.index(expr) self._contents.remove(expr) return index
Remove a provided expression from its list of contents. :param Union[TexExpr,str] expr: Content to add :return: index of the expression removed :rtype: int >>> expr = TexExpr('textbf', ('hello',)) >>> expr.remove('hello') 0 >>> expr TexExpr('textbf', [])
def handle_symbol_search(self, call_id, payload): self.log.debug('handle_symbol_search: in %s', Pretty(payload)) syms = payload["syms"] qfList = [] for sym in syms: p = sym.get("pos") if p: item = self.editor.to_quickfix_item(str(p["file"]), ...
Handler for symbol search results
def _compute_valid(self): r if self._dimension != 2: raise NotImplementedError("Validity check only implemented in R^2") poly_sign = None if self._degree == 1: first_deriv = self._nodes[:, 1:] - self._nodes[:, :-1] poly_sign = _SIGN(np.linalg.det(first...
r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is...
def convert_cmus_output(self, cmus_output): cmus_output = cmus_output.split('\n') cmus_output = [x.replace('tag ', '') for x in cmus_output if not x in ''] cmus_output = [x.replace('set ', '') for x in cmus_output] status = {} partitioned = (item.partition(' ') for item in cmus_o...
Change the newline separated string of output data into a dictionary which can then be used to replace the strings in the config format. cmus_output: A string with information about cmus that is newline seperated. Running cmus-remote -Q in a terminal will show you what you're de...
def metadata(self): resp = self.r_session.get(self.database_url) resp.raise_for_status() return response_to_json_dict(resp)
Retrieves the remote database metadata dictionary. :returns: Dictionary containing database metadata details
def obfn_fvarf(self): return self.Xf if self.opt['fEvalX'] else \ sl.rfftn(self.Y, None, self.cri.axisN)
Variable to be evaluated in computing data fidelity term, depending on 'fEvalX' option value.
def rhochange(self): self.lu, self.piv = sl.lu_factor(self.Z, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
Re-factorise matrix when rho changes
def connect_service(service, credentials, region_name = None, config = None, silent = False): api_client = None try: client_params = {} client_params['service_name'] = service.lower() session_params = {} session_params['aws_access_key_id'] = credentials['AccessKeyId'] ses...
Instantiates an AWS API client :param service: :param credentials: :param region_name: :param config: :param silent: :return:
def seed(vault_client, opt): if opt.thaw_from: opt.secrets = tempfile.mkdtemp('aomi-thaw') auto_thaw(vault_client, opt) Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) \ .sync(vault_client, opt) if opt.thaw_from: rmtree(opt.secrets)
Will provision vault based on the definition within a Secretfile
def find_anomalies(errors, index, z_range=(0, 10)): threshold = find_threshold(errors, z_range) sequences = find_sequences(errors, threshold) anomalies = list() denominator = errors.mean() + errors.std() for start, stop in sequences: max_error = errors[start:stop + 1].max() score = (...
Find sequences of values that are anomalous. We first find the ideal threshold for the set of errors that we have, and then find the sequences of values that are above this threshold. Lastly, we compute a score proportional to the maximum error in the sequence, and finally return the index pairs that ...
def contains_bad_glyph(glyph_data, data): def check_glyph(char): for cmap in glyph_data["cmap"].tables: if cmap.isUnicode(): if char in cmap.cmap: return True return False for part in data: text = part.get("full_text", "") try: ...
Pillow only looks for glyphs in the font used so we need to make sure our font has the glygh. Although we could substitute a glyph from another font eg symbola but this adds more complexity and is of limited value.
def set_cols_valign(self, array): self._check_row_size(array) self._valign = array return self
Set the desired columns vertical alignment - the elements of the array should be either "t", "m" or "b": * "t": column aligned on the top of the cell * "m": column aligned on the middle of the cell * "b": column aligned on the bottom of the cell
def stringize( self, rnf_profile=RnfProfile(), ): sorted_segments = sorted(self.segments, key=lambda x: ( x.genome_id * (10 ** 23) + x.chr_id * (10 ** 21) + (x.left + (int(x.left == 0) * x.right - 1)) * (10 ** 11) + x.right * (10 ** 1) + ...
Create RNF representation of this read. Args: read_tuple_id_width (int): Maximal expected string length of read tuple ID. genome_id_width (int): Maximal expected string length of genome ID. chr_id_width (int): Maximal expected string length of chromosome ID. coor_width (int): Maximal expected string leng...
def server_receives_binary_from(self, name=None, timeout=None, connection=None, label=None): server, name = self._servers.get_with_name(name) msg, ip, port = server.receive_from(timeout=timeout, alias=connection) self._register_receive(server, label, name, connection=connection) return m...
Receive raw binary message. Returns message, ip, and port. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | ${binary} | ${ip} | ${port} = | Server receives binary from | | ${binary} | ${ip} | ${port} = | Server receiv...
def pull(self, arm_id, success, failure): self.__beta_dist_dict[arm_id].observe(success, failure)
Pull arms. Args: arm_id: Arms master id. success: The number of success. failure: The number of failure.
def _new_page(self): self._current_page = Drawing(*self._pagesize) if self._bgimage: self._current_page.add(self._bgimage) self._pages.append(self._current_page) self.page_count += 1 self._position = [1, 0]
Helper function to start a new page. Not intended for external use.
def pull_release(self, name, version, destfolder=".", force=False): unique_id = name.replace('/', '_') depdict = { 'name': name, 'unique_id': unique_id, 'required_version': version, 'required_version_string': str(version) } destdir = os.pat...
Download and unpack a released iotile component by name and version range If the folder that would be created already exists, this command fails unless you pass force=True Args: name (string): The name of the component to download version (SemanticVersionRange): The val...
def getVersion(data): data = data.splitlines() return next(( v for v, u in zip(data, data[1:]) if len(v) == len(u) and allSame(u) and hasDigit(v) and "." in v ))
Parse version from changelog written in RST format.
def consume_socket_output(frames, demux=False): if demux is False: return six.binary_type().join(frames) out = [None, None] for frame in frames: assert frame != (None, None) if frame[0] is not None: if out[0] is None: out[0] = frame[0] else: ...
Iterate through frames read from the socket and return the result. Args: demux (bool): If False, stdout and stderr are multiplexed, and the result is the concatenation of all the frames. If True, the streams are demultiplexed, and the result is a 2-tuple where each item...
def _req(self, method="get", verb=None, headers={}, params={}, data={}): url = self.BASE_URL.format(verb=verb) request_headers = {"content-type": "application/json"} request_params = {"api_key": self.API_KEY} request_headers.update(headers) request_params.update(params) r...
Method to wrap all request building :return: a Response object based on the specified method and request values.
def is_org_admin(self, organisation_id): return (self._has_role(organisation_id, self.roles.administrator) or self.is_admin())
Is the user authorized to administrate the organisation
def decipher_all(decipher, objid, genno, x): if isinstance(x, str): return decipher(objid, genno, x) if isinstance(x, list): x = [decipher_all(decipher, objid, genno, v) for v in x] elif isinstance(x, dict): for (k, v) in x.iteritems(): x[k] = decipher_all(decipher, objid...
Recursively deciphers the given object.
def clear_jobs(self, recursive=True): if recursive: for link in self._links.values(): link.clear_jobs(recursive) self.jobs.clear()
Clear a dictionary with all the jobs If recursive is True this will include jobs from all internal `Link`
def _match_serializers_by_query_arg(self, serializers): arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME') if arg_name: arg_value = request.args.get(arg_name, None) if arg_value is None: return None try: return serializer...
Match serializer by query arg.
def copy_user_agent_from_driver(self): selenium_user_agent = self.driver.execute_script("return navigator.userAgent;") self.headers.update({"user-agent": selenium_user_agent})
Updates requests' session user-agent with the driver's user agent This method will start the browser process if its not already running.
def install(source, venv=None, requirement_files=None, upgrade=False, ignore_platform=False, install_args=''): requirement_files = requirement_files or [] logger.info('Installing %s', source) processed_source = get_source(source) metadata = _ge...
Install a Wagon archive. This can install in a provided `venv` or in the current virtualenv in case one is currently active. `upgrade` is merely pip's upgrade. `ignore_platform` will allow to ignore the platform check, meaning that if an archive was created for a specific platform (e.g. win32), ...
def station(self, station_id, *, num_songs=25, recently_played=None): station_info = { 'station_id': station_id, 'num_entries': num_songs, 'library_content_only': False } if recently_played is not None: station_info['recently_played'] = recently_played response = self._call( mc_calls.RadioStation...
Get information about a station. Parameters: station_id (str): A station ID. Use 'IFL' for I'm Feeling Lucky. num_songs (int, Optional): The maximum number of songs to return from the station. Default: ``25`` recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'} where `...
def trace(self, urls=None, **overrides): if urls is not None: overrides['urls'] = urls return self.where(accept='TRACE', **overrides)
Sets the acceptable HTTP method to TRACE
def rng_annotation(self, stmt, p_elem): ext = stmt.i_extension prf, extkw = stmt.raw_keyword (modname,rev)=stmt.i_module.i_prefixes[prf] prefix = self.add_namespace( statements.modulename_to_module(self.module,modname,rev)) eel = SchemaNode(prefix + ":" + extkw, p_ele...
Append YIN representation of extension statement `stmt`.
def FilterRange(self, start_time=None, stop_time=None): start_time = self._NormalizeTime(start_time) stop_time = self._NormalizeTime(stop_time) self.data = [ p for p in self.data if (start_time is None or p[1] >= start_time) and (stop_time is None or p[1] < stop_time) ]
Filter the series to lie between start_time and stop_time. Removes all values of the series which are outside of some time range. Args: start_time: If set, timestamps before start_time will be dropped. stop_time: If set, timestamps at or past stop_time will be dropped.
def quic_graph_lasso(X, num_folds, metric): print("QuicGraphicalLasso + GridSearchCV with:") print(" metric: {}".format(metric)) search_grid = { "lam": np.logspace(np.log10(0.01), np.log10(1.0), num=100, endpoint=True), "init_method": ["cov"], "score_metric": [metric], } mo...
Run QuicGraphicalLasso with mode='default' and use standard scikit GridSearchCV to find the best lambda. Primarily demonstrates compatibility with existing scikit tooling.
def load_calibration(labware: Labware): calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] labware_offset_path = calibration_path/'{}.json'.format(labware._id) if labware_offset_path.exists(): calibration_data = _read_file(str(labware_offset_path)) offset_array = calibration_dat...
Look up a calibration if it exists and apply it to the given labware.
def _detect_categorical_columns(self,data): numeric_cols = set(data._get_numeric_data().columns.values) date_cols = set(data.select_dtypes(include=[np.datetime64]).columns) likely_cat = set(data.columns) - numeric_cols likely_cat = list(likely_cat - date_cols) for var in data._ge...
Detect categorical columns if they are not specified. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- likely_cat : list List of variables that appear to be categorical.
def delete_genelist(list_id, case_id=None): if case_id: case_obj = app.db.case(case_id) app.db.remove_genelist(list_id, case_obj=case_obj) return redirect(request.referrer) else: app.db.remove_genelist(list_id) return redirect(url_for('.index'))
Delete a whole gene list with links to cases or a link.
def parse_string(self, xmlstr, initialize=True): try: domtree = minidom.parseString(xmlstr) except xml.parsers.expat.ExpatError, e: raise ManifestXMLParseError(e) self.load_dom(domtree, initialize)
Load manifest from XML string
def get_items_by_id(self, jid, node, ids): iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node) ) iq.payload.payload.items = [ pubsub_xso.Item(id_) for id_ in ids ] if ...
Request specific items by their IDs from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param ids: The item IDs to return. :type ids: :class:`~collections.abc.Ite...
def parse_key_curve(value=None): if isinstance(value, ec.EllipticCurve): return value if value is None: return ca_settings.CA_DEFAULT_ECC_CURVE curve = getattr(ec, value.strip(), type) if not issubclass(curve, ec.EllipticCurve): raise ValueError('%s: Not a known Eliptic Curve' % ...
Parse an elliptic curve value. This function uses a value identifying an elliptic curve to return an :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a class name of one of the classes named under "Elliptic Curves" in :any:`cg:hazmat/primitives/as...
def _get_snapshot(name, suffix, array): snapshot = name + '.' + suffix try: for snap in array.get_volume(name, snap=True): if snap['name'] == snapshot: return snapshot except purestorage.PureError: return None
Private function to check snapshot
def corr_dw_v1(self): con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess old = self.sequences.states.fastaccess_old new = self.sequences.states.fastaccess_new idx = der.toy[self.idx_sim] if (con.maxdw[idx] > 0.) and ((old....
Adjust the water stage drop to the highest value allowed and correct the associated fluxes. Note that method |corr_dw_v1| calls the method `interp_v` of the respective application model. Hence the requirements of the actual `interp_v` need to be considered additionally. Required control parameter...
def get_initial_centroids(self): if self.seed is not None: np.random.seed(self.seed) n = self.data.shape[0] rand_indices = np.random.randint(0, n, self.k) centroids = self.data[rand_indices,:].toarray() self.centroids=centroids return centroids
Randomly choose k data points as initial centroids
def bind(self, func: Callable[[Any], 'Writer']) -> 'Writer': a, w = self.run() b, w_ = func(a).run() if isinstance(w_, Monoid): w__ = cast(Monoid, w).append(w_) else: w__ = w + w_ return Writer(b, w__)
Flat is better than nested. Haskell: (Writer (x, v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `append` v')
def _reset (self): self.entries = [] self.default_entry = None self.disallow_all = False self.allow_all = False self.last_checked = 0 self.sitemap_urls = []
Reset internal flags and entry lists.
def cosine_similarity(evaluated_model, reference_model): if not (isinstance(evaluated_model, TfModel) and isinstance(reference_model, TfModel)): raise ValueError( "Arguments has to be instances of 'sumy.models.TfDocumentModel'") terms = frozenset(evaluated_model.terms) | frozenset(reference_...
Computes cosine similarity of two text documents. Each document has to be represented as TF model of non-empty document. :returns float: 0 <= cos <= 1, where 0 means independence and 1 means exactly the same.
def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0, random_state=None): generator = check_random_state(random_state) X = generator.randn(n_samples, n_features) y = func(*X.T) + bias if noise > 0.0: y += generator.normal(scale=noise, size=y.shape) r...
Make dataset for a regression problem. Examples -------- >>> f = lambda x: 0.5*x + np.sin(2*x) >>> X, y = make_regression(f, bias=.5, noise=1., random_state=1) >>> X.shape (100, 1) >>> y.shape (100,) >>> X[:5].round(2) array([[ 1.62], [-0.61], [-0.53], ...
def download(url, target_file, chunk_size=4096): r = requests.get(url, stream=True) with open(target_file, 'w+') as out: with click.progressbar(r.iter_content(chunk_size=chunk_size), int(r.headers['Content-Length'])/chunk_size, label='Downloa...
Simple requests downloader
def numlistbetween(num1, num2, option='list', listoption='string'): if option == 'list': if listoption == 'string': output = '' output += str(num1) for currentnum in range(num1 + 1, num2 + 1): output += ',' output += str(currentnum) ...
List Or Count The Numbers Between Two Numbers
def diffusion_mds(means, weights, d, diffusion_rounds=10): for i in range(diffusion_rounds): weights = weights*weights weights = weights/weights.sum(0) X = dim_reduce(means, weights, d) if X.shape[0]==2: return X.dot(weights) else: return X.T.dot(weights)
Dimensionality reduction using MDS, while running diffusion on W. Args: means (array): genes x clusters weights (array): clusters x cells d (int): desired dimensionality Returns: W_reduced (array): array of shape (d, cells)
def pkdecrypt(self, conn): for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']: keyring.sendline(conn, msg) line = keyring.recvline(conn) assert keyring.recvline(conn) == b'END' remote_pubkey = parse_ecdh(line) identity = self.get_identity(keygrip=self.keygri...
Handle decryption using ECDH.
def _get_go2nt(self, goids): go2nt_all = self.grprobj.go2nt return {go:go2nt_all[go] for go in goids}
Get go2nt for given goids.
def import_obj(clsname, default_module=None): if default_module is not None: if not clsname.startswith(default_module + '.'): clsname = '{0}.{1}'.format(default_module, clsname) mod, clsname = clsname.rsplit('.', 1) mod = importlib.import_module(mod) try: obj = getattr(mod, c...
Import the object given by clsname. If default_module is specified, import from this module.
def schema_from_table(table, schema=None): schema = schema if schema is not None else {} pairs = [] for name, column in table.columns.items(): if name in schema: dtype = dt.dtype(schema[name]) else: dtype = dt.dtype( getattr(table.bind, 'dialect', SQLA...
Retrieve an ibis schema from a SQLAlchemy ``Table``. Parameters ---------- table : sa.Table Returns ------- schema : ibis.expr.datatypes.Schema An ibis schema corresponding to the types of the columns in `table`.
def _record(self): return struct.pack(self.FMT, 1, self.platform_id, 0, self.id_string, self.checksum, 0x55, 0xaa)
An internal method to generate a string representing this El Torito Validation Entry. Parameters: None. Returns: String representing this El Torito Validation Entry.
def _get_retrier(self, receiver: Address) -> _RetryQueue: if receiver not in self._address_to_retrier: retrier = _RetryQueue(transport=self, receiver=receiver) self._address_to_retrier[receiver] = retrier retrier.start() return self._address_to_retrier[receiver]
Construct and return a _RetryQueue for receiver
def _limited_iterator(self): i = 0 while True: for crash_id in self._basic_iterator(): if self._filter_disallowed_values(crash_id): continue if crash_id is None: yield crash_id continue ...
this is the iterator for the case when "number_of_submissions" is set to an integer. It goes through the innermost iterator exactly the number of times specified by "number_of_submissions" To do that, it might run the innermost iterator to exhaustion. If that happens, that innermost i...
def get_hash(self): depencency_hashes = [dep.get_hash() for dep in self.dep()] sl = inspect.getsourcelines hash_sources = [sl(self.__class__), self.args, self.kwargs, *depencency_hashes] hash_input = pickle.dumps(hash_sources) return hashlib.md5(hash_input...
Retruns a hash based on the the current table code and kwargs. Also changes based on dependent tables.
def _serialize_items(self, serializer, kind, items): if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False): serializer = serializer(items, many=True, read_only=True) serializer.bind(kind, self) return serializer.data else: ret...
Return serialized items or list of ids, depending on `hydrate_XXX` query param.
def render_configuration(self, configuration=None): if configuration is None: configuration = self.environment if isinstance(configuration, dict): return {k: self.render_configuration(v) for k, v in configuration.items()} elif isinstance(configuration, list): ...
Render variables in configuration object but don't instantiate anything
def packages(self, login=None, platform=None, package_type=None, type_=None, access=None): logger.debug('') method = self._anaconda_client_api.user_packages return self._create_worker(method, login=login, platform=platform, package_type=package...
Return all the available packages for a given user. Parameters ---------- type_: Optional[str] Only find packages that have this conda `type`, (i.e. 'app'). access : Optional[str] Only find packages that have this access level (e.g. 'private', 'authen...
def check_errors(self, response, data): if "error_id" in data: error_id = data["error_id"] if error_id in self.error_ids: raise self.error_ids[error_id](response) if "error_code" in data: error_code = data["error_code"] if error_code in sel...
Check for errors and raise an appropriate error if needed
def update(self): from .link import Link diff = self.diff() status = { 'added': 'active', 'removed': 'disconnected', 'changed': 'active' } for section in ['added', 'removed', 'changed']: if not diff[section]: continu...
Updates topology Links are not deleted straightaway but set as "disconnected"
def auto_detect(self, args): suffixes = [ ".tgz", ".txz", ".tbz", ".tlz" ] if (not args[0].startswith("-") and args[0] not in self.commands and args[0].endswith(tuple(suffixes))): packages, not_found = [], [] ...
Check for already Slackware binary packages exist
def find_spec(self, fullname, path, target=None): if fullname.startswith(self.package_prefix): for path in self._get_paths(fullname): if os.path.exists(path): return ModuleSpec( name=fullname, loader=self.loader_clas...
Claims modules that are under ipynb.fs
def parse_numtuple(s,intype,length=2,scale=1): if intype == int: numrx = intrx_s; elif intype == float: numrx = fltrx_s; else: raise NotImplementedError("Not implemented for type: {}".format( intype)); if parse_utuple(s, numrx, length=length) is None: raise Va...
parse a string into a list of numbers of a type
def get_choices(self): if 'choiceInfo' not in self.dto[self.name]: raise GPException('not a choice parameter') if self.get_choice_status()[1] == "NOT_INITIALIZED": print(self.get_choice_status()) print("choice status not initialized") request = urllib.requ...
Returns a list of dictionary objects, one dictionary object per choice. Each object has two keys defined: 'value', 'label'. The 'label' entry is what should be displayed on the UI, the 'value' entry is what is written into GPJobSpec.
def run_parallel(self): try: self.start_parallel() result = self.empty_result(*self.context) while self.num_processes > 0: r = self.result_queue.get() self.maybe_put_task() if r is POISON_PILL: self.num_proce...
Perform the computation in parallel, reading results from the output queue and passing them to ``process_result``.
def parent(self): family = self.repository.get_parent_package_family(self.resource) return PackageFamily(family) if family else None
Get the parent package family. Returns: `PackageFamily`.
def _get_application(self, subdomain): with self.lock: app = self.instances.get(subdomain) if app is None: app = self.create_application(subdomain=subdomain) self.instances[subdomain] = app return app
Return a WSGI application for subdomain. The subdomain is passed to the create_application constructor as a keyword argument. :param subdomain: Subdomain to get or create an application with
def add_ui(self, klass, *args, **kwargs): ui = klass(self.widget, *args, **kwargs) self.widget.uis.append(ui) return ui
Add an UI element for the current scene. The approach is the same as renderers. .. warning:: The UI api is not yet finalized
def i2c_monitor_read(self): data = array.array('H', (0,) * self.BUFFER_SIZE) ret = api.py_aa_i2c_monitor_read(self.handle, self.BUFFER_SIZE, data) _raise_error_if_negative(ret) del data[ret:] return data.tolist()
Retrieved any data fetched by the monitor. This function has an integrated timeout mechanism. You should use :func:`poll` to determine if there is any data available. Returns a list of data bytes and special symbols. There are three special symbols: `I2C_MONITOR_NACK`, I2C_MONITOR_STAR...
def command_exists(command, noop_invocation, exc_msg): try: found = bool(shutil.which(command)) except AttributeError: try: p = subprocess.Popen(noop_invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: found = False else: ...
Verify that the provided command exists. Raise CommandDoesNotExistException in case of an error or if the command does not exist. :param command: str, command to check (python 3 only) :param noop_invocation: list of str, command to check (python 2 only) :param exc_msg: str, message of exception when co...
def createLinkToSelf(self, new_zone, callback=None, errback=None, **kwargs): zone = Zone(self.config, new_zone) kwargs['link'] = self.data['zone'] return zone.create(callback=callback, errback=errback, **kwargs)
Create a new linked zone, linking to ourselves. All records in this zone will then be available as "linked records" in the new zone. :param str new_zone: the new zone name to link to this one :return: new Zone
def _process_underscores(self, tokens): "Strip underscores to make sure the number is correct after join" groups = [[str(''.join(el))] if b else list(el) for (b,el) in itertools.groupby(tokens, lambda k: k=='_')] flattened = [el for group in groups for el in group] proc...
Strip underscores to make sure the number is correct after join
def linkify(self, timeperiods): new_exclude = [] if hasattr(self, 'exclude') and self.exclude != []: logger.debug("[timeentry::%s] have excluded %s", self.get_name(), self.exclude) excluded_tps = self.exclude for tp_name in excluded_tps: timepriod = ti...
Will make timeperiod in exclude with id of the timeperiods :param timeperiods: Timeperiods object :type timeperiods: :return: None
def is_read_only(cls, db: DATABASE_SUPPORTER_FWD_REF, logger: logging.Logger = None) -> bool: def convert_enums(row_): return [True if x == 'Y' else (False if x == 'N' else None) for x in row_] try: sql = r...
Do we have read-only access?
def get_disk_quota(username, machine_name=None): try: ua = Account.objects.get( username=username, date_deleted__isnull=True) except Account.DoesNotExist: return 'Account not found' result = ua.get_disk_quota() if result is None: return False return re...
Returns disk quota for username in KB
def get_file_name(url): return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'
Returns file name of file at given url.
def ls(self): if self.isfile(): raise NotDirectoryError('Cannot ls() on non-directory node: {path}'.format(path=self._pyerarchy_path)) return os.listdir(self._pyerarchy_path)
List the children entities of the directory. Raises exception if the object is a file. :return:
def set_all_attribute_values(self, value): for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue if isinstance(type_instance, bool): self.__dict__[attribute_name] = va...
sets all the attribute values to the value and propagate to any children
def query_unbound_ong(self, base58_address: str) -> int: contract_address = self.get_asset_address('ont') unbound_ong = self.__sdk.rpc.get_allowance("ong", Address(contract_address).b58encode(), base58_address) return int(unbound_ong)
This interface is used to query the amount of account's unbound ong. :param base58_address: a base58 encode address which indicate which account's unbound ong we want to query. :return: the amount of unbound ong in the form of int.
def parse_networking_file(): pairs = dict() allocated_subnets = [] try: with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f: version = f.readline() for line in f.read().splitlines(): try: _, key, value = line.split(' ', 3) ...
Parse the VMware networking file.
def pprint_tree_differences(self, missing_pys, missing_docs): if missing_pys: print('The following Python files appear to be missing:') for pyfile in missing_pys: print(pyfile) print('\n') if missing_docs: print('The following documentation...
Pprint the missing files of each given set. :param set missing_pys: The set of missing Python files. :param set missing_docs: The set of missing documentation files. :rtype: None
def circular_gaussian_kernel(sd,radius): i,j = np.mgrid[-radius:radius+1,-radius:radius+1].astype(float) / radius mask = i**2 + j**2 <= 1 i = i * radius / sd j = j * radius / sd kernel = np.zeros((2*radius+1,2*radius+1)) kernel[mask] = np.e ** (-(i[mask]**2+j[mask]**2) / ...
Create a 2-d Gaussian convolution kernel sd - standard deviation of the gaussian in pixels radius - build a circular kernel that convolves all points in the circle bounded by this radius
def get_edge_schema_element_or_raise(self, edge_classname): schema_element = self.get_element_by_class_name_or_raise(edge_classname) if not schema_element.is_edge: raise InvalidClassError(u'Non-edge class provided: {}'.format(edge_classname)) return schema_element
Return the schema element with the given name, asserting that it's of edge type.
def _write(self, text): spaces = ' ' * (self.indent * self.indentlevel) t = spaces + text.strip() + '\n' if hasattr(t, 'encode'): t = t.encode(self.encoding, 'xmlcharrefreplace') self.stream.write(t)
Write text by respecting the current indentlevel
def source_lines(self, filename): with self.filesystem.open(filename) as f: return f.readlines()
Return a list for source lines of file `filename`.
def label_const(self, const:Any=0, label_cls:Callable=None, **kwargs)->'LabelList': "Label every item with `const`." return self.label_from_func(func=lambda o: const, label_cls=label_cls, **kwargs)
Label every item with `const`.
def calc_avr_uvr_v1(self): con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess for i in range(2): if flu.h <= (con.hm+der.hv[i]): flu.avr[i] = 0. flu.uvr[i] = 0. else: flu.avr[i] = (f...
Calculate the flown through area and the wetted perimeter of both outer embankments. Note that each outer embankment lies beyond its foreland and that all water flowing exactly above the a embankment is added to |AVR|. The theoretical surface seperating water above the foreland from water above its...
def is_user_valid(self, userID): cur = self.conn.cursor() cur.execute('SELECT * FROM users WHERE id=? LIMIT 1', [userID]) results = cur.fetchall() cur.close() return len(results) > 0
Check if this User ID is valid.
def pre_validate(self, form): for preprocessor in self._preprocessors: preprocessor(form, self) super(FieldHelper, self).pre_validate(form)
Calls preprocessors before pre_validation
def identify(file_elements): if not file_elements: return _validate_file_elements(file_elements) iterator = PeekableIterator((element_i, element) for (element_i, element) in enumerate(file_elements) if element.type != elements.TYPE_METADATA) try: _, first_...
Outputs an ordered sequence of instances of TopLevel types. Elements start with an optional TableElement, followed by zero or more pairs of (TableHeaderElement, TableElement).
def _OpenPathSpec(self, path_specification, ascii_codepage='cp1252'): if not path_specification: return None file_entry = self._file_system.GetFileEntryByPathSpec(path_specification) if file_entry is None: return None file_object = file_entry.GetFileObject() if file_object is None: ...
Opens the Windows Registry file specified by the path specification. Args: path_specification (dfvfs.PathSpec): path specification. ascii_codepage (Optional[str]): ASCII string codepage. Returns: WinRegistryFile: Windows Registry file or None.
def get_help_msg(self, dotspace_ending=False, **kwargs): context = self.get_context_for_help_msgs(kwargs) if self.help_msg is not None and len(self.help_msg) > 0: context = copy(context) try: help_msg = self.help_msg ...
The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the instance level or at the class level. The help message is formatted according to help_msg.format(**kwargs), and may be terminated with a dot and a ...