code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def _zp_decode(self, msg): zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]] return {: zone_partitions}
ZP: Zone partitions.
def hide(self): thr_is_alive = self._spin_thread and self._spin_thread.is_alive() if thr_is_alive and not self._hide_spin.is_set(): self._hide_spin.set() sys.stdout.write("\r") self._clear_line() sys.stdou...
Hide the spinner to allow for custom writing to the terminal.
def example_alter_configs(a, args): resources = [] for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]): resource = ConfigResource(restype, resname) resources.append(resource) for k, v in [conf.split() for conf in configs.split()]: resource.set_confi...
Alter configs atomically, replacing non-specified configuration properties with their default values.
def renew_service(request, pk): default_provider.load_services() service = get_object_or_404(ServicesActivated, pk=pk) service_name = str(service.name) service_object = default_provider.get_service(service_name) lets_auth = getattr(service_object, ) getattr(service_object, )(pk=pk) retu...
renew an existing service :param request object :param pk: the primary key of the service to renew :type pk: int
def export_flow_di_data(params, plane): output_flow = eTree.SubElement(plane, BpmnDiagramGraphExport.bpmndi_namespace + consts.Consts.bpmn_edge) output_flow.set(consts.Consts.id, params[consts.Consts.id] + "_gui") output_flow.set(consts.Consts.bpmn_element, params[consts.Consts.id]) ...
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element. :param params: dictionary with edge parameters, :param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data).
def rank_for_in(self, leaderboard_name, member): if self.order == self.ASC: try: return self.redis_connection.zrank( leaderboard_name, member) + 1 except: return None else: try: return self.r...
Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard.
def geom_symm_match(g, atwts, ax, theta, do_refl): import numpy as np from scipy import linalg as spla g = make_nd_vec(g, nd=None, t=np.float64, norm=False) atwts = make_nd_vec(atwts, nd=None, t=np.float64, norm=False) if not g.shape[0] == 3 * atwts.shape[0]: raise Val...
[Revised match factor calculation] .. todo:: Complete geom_symm_match docstring
def items(self): if ver == (2, 7): return self.viewitems() elif ver == (2, 6): return self.iteritems() elif ver >= (3, 0): return self.items()
On Python 2.7+: D.items() -> a set-like object providing a view on D's items On Python 2.6: D.items() -> an iterator over D's items
def create_screenshot(self, app_id, filename, position=1): with open(filename, ) as s_file: s_content = s_file.read() s_encoded = b64encode(s_content) url = self.url() % app_id mtype, encoding = mimetypes.guess_type(filename) if mtype is None: ...
Add a screenshot to the web app identified by by ``app_id``. Screenshots are ordered by ``position``. :returns: HttpResponse: * status_code (int) 201 is successful * content (dict) containing screenshot data
def subtract_column_median(df, prefix=): df = df.copy() df.replace([np.inf, -np.inf], np.nan, inplace=True) mask = [l.startswith(prefix) for l in df.columns.values] df.iloc[:, mask] = df.iloc[:, mask] - df.iloc[:, mask].median(axis=0) return df
Apply column-wise normalisation to expression columns. Default is median transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return:
def read_request_from_str(data, **params): method, uri = None, None headers = {} host = try: split_list = data.split() headers_text = split_list[0] body = .join(split_list[1:]) except: headers_text = data body = body = force_bytes(body) for k,...
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param data: :param params: :return:
def create_assembly_instance(self, assembly_uri, part_uri, configuration): payload = { "documentId": part_uri["did"], "elementId": part_uri["eid"], "versionId": part_uri["wvm"], "isAssembly": False, ...
Insert a configurable part into an assembly. Args: - assembly (dict): eid, wid, and did of the assembly into which will be inserted - part (dict): eid and did of the configurable part - configuration (dict): the configuration Returns: - requests.Response...
def md5_string(s): m = hashlib.md5() m.update(s) return str(m.hexdigest())
Shortcut to create md5 hash :param s: :return:
def _process_response(self, resp, out_folder=None): CHUNK = 4056 maintype = self._mainType(resp) contentDisposition = resp.headers.get() contentEncoding = resp.headers.get() contentType = resp.headers.get() contentLength = resp.headers.get() if maintype.l...
processes the response object
def sign(self, secret=None): keypair = self.keypair if not secret else Keypair.from_seed(secret) self.gen_te() self.te.sign(keypair)
Sign the generated :class:`TransactionEnvelope <stellar_base.transaction_envelope.TransactionEnvelope>` from the list of this builder's operations. :param str secret: The secret seed to use if a key pair or secret was not provided when this class was originaly instantiated, or if ...
def api_representation(self): return dict(EmailAddress=dict(Name=self.name, Address=self.email))
Returns the JSON formatting required by Outlook's API for contacts
def draw_mini_map(self, surf): if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("minimap")): surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.observation.render_data.minimap)) else: hm...
Draw the minimap.
def warp(self, srid=None, format=None, geom=None): clone = self._clone() for obj in clone: obj.convert(format, geom) if srid: fp = tempfile.NamedTemporaryFile(suffix= % format or ) with obj.raster() as r, r.warp(srid, fp.name) as w: ...
Returns a new RasterQuerySet with possibly warped/converted rasters. Keyword args: format -- raster file extension format as str geom -- geometry for masking or spatial subsetting srid -- spatial reference identifier as int for warping to
def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e...
Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser
def add_arguments(self, parser): parser.add_argument(, default=self.length, type=int, help=_( % self.length)) parser.add_argument(, default=self.allowed_chars, type=str, help=_( % self.allowed_chars))
Define optional arguments with default values
def first_available(self, *quantities): for i, q in enumerate(quantities): if self.has_quantity(q): if i: warnings.warn(.format(quantities[0], q)) return q
Return the first available quantity in the input arguments. Return `None` if none of them is available.
def set_driver_simulated(self): self._device_dict["servermain.MULTIPLE_TYPES_DEVICE_DRIVER"] = "Simulator" if self._is_sixteen_bit: self._device_dict["servermain.DEVICE_MODEL"] = 0 else: self._device_dict["servermain.DEVICE_MODEL"] = 1 self._device_dict["...
Sets the device driver type to simulated
def select_groups(adata, groups=, key=): strings_to_categoricals(adata) if isinstance(groups, list) and isinstance(groups[0], int): groups = [str(n) for n in groups] categories = adata.obs[key].cat.categories groups_masks = np.array([categories[i] == adata.obs[key].values for i, name in enumerate(c...
Get subset of groups in adata.obs[key].
def get_user_info(self, request): if not current_user.is_authenticated: return {} user_info = { : current_user.get_id(), } if in current_app.config: for attr in current_app.config[]: if hasattr(current_user, attr): ...
Implement custom getter.
def read_length_block(fp, fmt=, padding=1): length = read_fmt(fmt, fp)[0] data = fp.read(length) assert len(data) == length, (len(data), length) read_padding(fp, length, padding) return data
Read a block of data with a length marker at the beginning. :param fp: file-like :param fmt: format of the length marker :return: bytes object
def scanStoVars(self, strline): for wd in strline.split(): if wd in self.stodict: strline = strline.replace(wd, str(self.stodict[wd])) return strline
scan input string line, replace sto parameters with calculated results.
def Write(self, grr_message): grr_message = grr_message.SerializeToString() try: with io.open(self.logfile, "wb") as fd: fd.write(grr_message) except (IOError, OSError): self.logfile)
Write the message into the transaction log.
def parse_reqtype(self): if self.job_args[] == : return dict() else: setup = { : self.job_args.get() } prefixes = self.job_args.get() if self.job_args.get() is not None: auth...
Return the authentication body.
def set_value(self, index, col, value, takeable=False): warnings.warn("set_value is deprecated and will be removed " "in a future release. Please use " ".at[] or .iat[] accessors instead", FutureWarning, stacklevel=2) return self...
Put single value at passed column and index. .. deprecated:: 0.21.0 Use .at[] or .iat[] accessors instead. Parameters ---------- index : row label col : column label value : scalar takeable : interpret the index/col as indexers, default False ...
def env(config, endpoint): access_token = config[][endpoint][][] click.echo(.format(, endpoint)) click.echo(.format(, access_token)) click.echo() click.echo()
Print RENKU environment variables. Run this command to configure your Renku client: $ eval "$(renku env)"
def _init_hdrgos(self, hdrgos_dflt, hdrgos_usr=None, add_dflt=True): if (hdrgos_usr is None or hdrgos_usr is False) and not self.sections: return set(hdrgos_dflt) hdrgos_init = set() if hdrgos_usr: chk_goids(hdrgos_usr, "User-provided GO group h...
Initialize GO high
def write_xmlbif(self, filename): with open(filename, ) as fout: fout.write(self.__str__())
Write the xml data into the file. Parameters ---------- filename: Name of the file. Examples ------- >>> writer = XMLBIFWriter(model) >>> writer.write_xmlbif(test_file)
def getSolution(self, domains, constraints, vconstraints): msg = "%s is an abstract class" % self.__class__.__name__ raise NotImplementedError(msg)
Return one solution for the given problem @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of ...
def _extract_value_from_storage(self, string): parts = string.split(self.separator) pk = parts.pop() return self.separator.join(parts), pk
Taking a string that was a member of the zset, extract the value and pk Parameters ---------- string: str The member extracted from the sorted set Returns ------- tuple Tuple with the value and the pk, extracted from the string
def clean_key_name(key): result = _illegal_in_column_name.sub("_", key.strip()) if result[0].isdigit(): result = % result if result.upper() in sql_reserved_words: result = % key return result.lower()
Makes ``key`` a valid and appropriate SQL column name: 1. Replaces illegal characters in column names with ``_`` 2. Prevents name from beginning with a digit (prepends ``_``) 3. Lowercases name. If you want case-sensitive table or column names, you are a bad person and you should feel bad.
def c_struct(self): member = .join(self.c_member_funcs(True)) if self.opts.windll: return .format( self._c_dll_base(), member, self.name ) return .format( self._c_dll_base(), member, *self._c_struct_names() )
Get the struct of the module.
def add_tip_labels_to_axes(self): if self.style.orient in ("up", "down"): ypos = np.zeros(self.ntips) xpos = np.arange(self.ntips) if self.style.orient in ("right", "left"): xpos = np.zeros(self.ntips) ypos = np.arange(self.ntips) ...
Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting.
def get_progress(self): count_remaining = len(self.items_queued) + len(self.items_in_progress) percentage_remaining = 100 / self.count_total * count_remaining return 100 - percentage_remaining
Get the progress of the queue in percentage (float). Returns: float: The 'finished' progress in percentage.
def NormalizePath(path, sep="/"): if not path: return sep path = SmartUnicode(path) path_list = path.split(sep) if path_list[0] in [".", "..", ""]: path_list.pop(0) i = 0 while True: list_len = len(path_list) for i in range(i, len(path_list)): if path_lis...
A sane implementation of os.path.normpath. The standard implementation treats leading / and // as different leading to incorrect normal forms. NOTE: Its ok to use a relative path here (without leading /) but any /../ will still be removed anchoring the path at the top level (e.g. foo/../../../../bar => bar)...
def cycles(self): def walk_node(node, seen): if node in seen: yield (node,) return seen.add(node) for edge in self.edges[node]: for cycle in walk_node(edge, set(seen)): yield (node,) + ...
Fairly expensive cycle detection algorithm. This method will return the shortest unique cycles that were detected. Debug usage may look something like: print("The following cycles were found:") for cycle in network.cycles(): print(" ", " -> ".join(cycle))
def download_task(url, headers, destination, download_type=): bot.verbose("Downloading %s from %s" % (download_type, url)) file_name = "%s.%s" % (destination, next(tempfile._get_candidate_names())) tar_download = download(url, file_name, headers=headers) try:...
download an image layer (.tar.gz) to a specified download folder. This task is done by using local versions of the same download functions that are used for the client. core stream/download functions of the parent client. Parameters ========== image_id: the shasum id of the la...
def mute_modmail_author(self, _unmute=False): path = if _unmute else return self.reddit_session.request_json( self.reddit_session.config[path], data={: self.fullname})
Mute the sender of this modmail message. :param _unmute: Unmute the user instead. Please use :meth:`unmute_modmail_author` instead of setting this directly.
def get_bug_stats(self, startday, endday): threshold = 1 if self.weekly_mode else 15 bug_ids = (BugJobMap.failures.by_date(startday, endday) .values() .annotate(total=Count()) ...
Get all intermittent failures per specified date range and repository, returning a dict of bug_id's with total, repository and platform totals if totals are greater than or equal to the threshold. eg: { "1206327": { "total": 5, "per_repos...
def exampleRand(S, A): db = "MDP-%sx%s.db" % (S, A) if os.path.exists(db): os.remove(db) conn = sqlite3.connect(db) with conn: c = conn.cursor() cmd = statesactions % (S, A) c.executescript(cmd) for a in range(1, A+1): cmd = % (a, a) ...
WARNING: This will delete a database with the same name as 'db'.
def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4): selem = sim.ball(bw) if ants_segs is None: ants_segs = np.zeros_like(aseg, dtype=np.uint8) aseg[aseg == 42] = 3 gm = anat.copy() gm[aseg != 3] = 0 refined = refine_aseg(aseg) newrefmask = sim.binary_dilation(r...
Grow mask including pixels that have a high likelihood. GM tissue parameters are sampled in image patches of ``ww`` size. This is inspired on mindboggle's solution to the problem: https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660
def check_if_release_is_current(log): if __version__ == : return client = xmlrpclib.ServerProxy() latest_pypi_version = client.package_releases() latest_version_nums = [int(i) for i in latest_pypi_version[0].split()] this_version_nums = [int(i) for i in __version__.split()] for i i...
Warns the user if their release is behind the latest PyPi __version__.
def install(*pkgs, **kwargs): ** attributes = kwargs.get(, False) if not pkgs: return "Plese specify a package or packages to upgrade" cmd = _quietnix() cmd.append() if kwargs.get(, False): cmd.extend(_zip_flatten(, pkgs)) else: cmd.extend(pkgs) out = _run(cm...
Installs a single or multiple packages via nix :type pkgs: list(str) :param pkgs: packages to update :param bool attributes: Pass the list of packages or single package as attribues, not package names. default: False :return: Installed packages. Example element: ``gcc-3.3.2`` ...
def random_unitary_matrix(dim, seed=None): warnings.warn( , DeprecationWarning) return random.random_unitary(dim, seed).data
Deprecated in 0.8+
def load_csv_data(resource_name): data_bytes = pkgutil.get_data(, .format(resource_name)) if data_bytes is None: raise ValueError("No data resource found with name {}".format(resource_name)) else: data = data_bytes.decode() reader = csv.reader(data.splitlines()) nex...
Loads first column of specified CSV file from package data.
def _convert(self, value): if isinstance(value, PasswordHash): return value elif isinstance(value, str): value = value.encode() return PasswordHash.new(value, self.rounds) elif value is not None: raise TypeError( .format(ty...
Returns a PasswordHash from the given string. PasswordHash instances or None values will return unchanged. Strings will be hashed and the resulting PasswordHash returned. Any other input will result in a TypeError.
def generate_sample_json(): check = EpubCheck(samples.EPUB3_VALID) with open(samples.RESULT_VALID, ) as jsonfile: jsonfile.write(check._stdout) check = EpubCheck(samples.EPUB3_INVALID) with open(samples.RESULT_INVALID, ) as jsonfile: jsonfile.write(check._stdout)
Generate sample json data for testing
def generate_patches(self): start_pos = self.start_position or Position(None, None) end_pos = self.end_position or Position(None, None) path_list = Query._walk_directory(self.root_directory) path_list = Query._sublist(path_list, start_pos.path, end_pos.path) path_list =...
Generates a list of patches for each file underneath self.root_directory that satisfy the given conditions given query conditions, where patches for each file are suggested by self.suggestor.
def exists(self, index, id, doc_type=, params=None): try: self.transport.perform_request( , _make_path(index, doc_type, id), params=params) except exceptions.NotFoundError: return gen.Return(False) raise gen.Return(True)
Returns a boolean indicating whether or not given document exists in Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_ :arg index: The name of the index :arg id: The document ID :arg doc_type: The type of the document (uses `_all` by default to fetch the ...
def compute_header_hmac_hash(context): return hmac.new( hashlib.sha512( b * 8 + hashlib.sha512( context._.header.value.dynamic_header.master_seed.data + context.transformed_key + b ).digest() ).digest(), ...
Compute HMAC-SHA256 hash of header. Used to prevent header tampering.
def clear(self): with self._hlock: self.handlers.clear() with self._mlock: self.memoize.clear()
Discards all registered handlers and cached results
def generateCertificate(self, alias, commonName, organizationalUnit, city, state, country, keyalg="RSA", keysize=1024, sigalg="SHA256withRSA", validity=90 ...
Use this operation to create a self-signed certificate or as a starting point for getting a production-ready CA-signed certificate. The portal will generate a certificate for you and store it in its keystore.
def uniq(args): p = OptionParser(uniq.__doc__) p.add_option("--seq", default=False, action="store_true", help="Uniqify the sequences [default: %default]") p.add_option("-t", "--trimname", dest="trimname", action="store_true", default=False, help="turn on the defline ...
%prog uniq fasta uniq.fasta remove fasta records that are the same
def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs): return Signature(self.tcex, name, file_name, file_type, file_content, owner=owner, **kwargs)
Create the Signature TI object. Args: owner: file_content: file_name: file_type: name: **kwargs: Return:
def fix_missing(df, col, name, na_dict): if is_numeric_dtype(col): if pd.isnull(col).sum() or (name in na_dict): df[name+] = pd.isnull(col) filler = na_dict[name] if name in na_dict else col.median() df[name] = col.fillna(filler) na_dict[name] = filler ...
Fill missing data in a column of df with the median, and add a {name}_na column which specifies if the data was missing. Parameters: ----------- df: The data frame that will be changed. col: The column of data to fix by filling in missing data. name: The name of the new filled column in df. ...
def get_email_forwarding(netid): subscriptions = get_netid_subscriptions(netid, Subscription.SUBS_CODE_U_FORWARDING) for subscription in subscriptions: if subscription.subscription_code == Subscription.SUBS_CODE_U_FORWARDING: return_obj = UwEmailForwarding() if subscription....
Return a restclients.models.uwnetid.UwEmailForwarding object on the given uwnetid
def _copy_mbox(self, mbox): tmp_path = tempfile.mktemp(prefix=) with mbox.container as f_in: with open(tmp_path, mode=) as f_out: for l in f_in: f_out.write(l) return tmp_path
Copy the contents of a mbox to a temporary file
def invalid_example_number(region_code): if not _is_valid_region_code(region_code): return None metadata = PhoneMetadata.metadata_for_region(region_code.upper()) desc = _number_desc_by_type(metadata, PhoneNumberType.FIXED_LINE) if desc is None or desc.example_number...
Gets an invalid number for the specified region. This is useful for unit-testing purposes, where you want to test what will happen with an invalid number. Note that the number that is returned will always be able to be parsed and will have the correct country code. It may also be a valid *short* number...
def get_device_by_name(self, device_name): found_device = None for device in self.get_devices(): if device.name == device_name: found_device = device break if found_device is None: logger.debug(.format(device_...
Search the list of connected devices by name. device_name param is the string name of the device
def jsonarrtrim(self, name, path, start, stop): return self.execute_command(, name, str_path(path), start, stop)
Trim the array JSON value under ``path`` at key ``name`` to the inclusive range given by ``start`` and ``stop``
def kpl_set_on_mask(self, address, group, mask): addr = Address(address) device = self.plm.devices[addr.id] device.states[group].set_on_mask(mask)
Get the status of a KPL button.
def _init_glyph(self, plot, mapping, properties): plot_method = properties.pop(, None) properties = mpl_to_bokeh(properties) data = dict(properties, **mapping) if self._has_holes: plot_method = elif plot_method is None: plot_method = self._plot_m...
Returns a Bokeh glyph object.
def parse(cls, buff, offset): size, offset = cls.size_primitive.parse(buff, offset) if size == -1: return None, offset var_struct = struct.Struct("!%ds" % size) value = var_struct.unpack_from(buff, offset)[0] value = cls.parse_value(value) offset +=...
Given a buffer and offset, returns the parsed value and new offset. Parses the ``size_primitive`` first to determine how many more bytes to consume to extract the value.
def isPe32(self): if self.ntHeaders.optionalHeader.magic.value == consts.PE32: return True return False
Determines if the current L{PE} instance is a PE32 file. @rtype: bool @return: C{True} if the current L{PE} instance is a PE32 file. Otherwise, returns C{False}.
def fts_match(self, fts_mask, segment): fts_mask = set(fts_mask) fts_seg = self.fts(segment) if fts_seg: return fts_seg <= fts_mask else: return None
Evaluates whether a set of features 'match' a segment (are a subset of that segment's features) Args: fts_mask (list): list of (value, feature) tuples segment (unicode): IPA string corresponding to segment (consonant or vowel) Returns: ...
def sort_targets(targets): roots, inverted_deps = invert_dependencies(targets) ordered = [] visited = set() def topological_sort(target): if target not in visited: visited.add(target) if target in inverted_deps: for dep in inverted_deps[target]: topological_sort(dep) ...
:API: public :return: the targets that `targets` depend on sorted from most dependent to least.
def run_primlist(self, primlist, skip_remaining=False): runlist = self.open_primlist(primlist) for index, run in enumerate(runlist): logging.info(, index + 1, len(runlist)) join = self.run_run(run, use_thread=True) status = join() if skip_remainin...
Runs runs from a primlist. Parameters ---------- primlist : string Filename of primlist. skip_remaining : bool If True, skip remaining runs, if a run does not exit with status FINISHED. Note ---- Primlist is a text file of the following f...
def check(self, pointer, expected, raise_onerror=False): obj = self.document for token in Pointer(pointer): try: obj = token.extract(obj, bypass_ref=True) except ExtractError as error: if raise_onerror: raise Error(*err...
Check if value exists into object. :param pointer: the path to search in :param expected: the expected value :param raise_onerror: should raise on error? :return: boolean
def lastId(self): if self._last is False: self._last = self.childIds[-1] return self._last
Children passage :rtype: str :returns: First children of the graph. Shortcut to self.graph.children[0]
def call_on_commit(self, callback): if not self.in_transaction(): callback() else: self._on_commit_queue.append(callback)
Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were registered. If the transaction fails, the callb...
def signal_to_exception(sig: signal.Signals) -> SignalException: signal.signal(sig, _sig_exc_handler) return SignalException(sig)
Convert a ``signal.Signals`` to a ``SignalException``. This allows for natural, pythonic signal handing with the use of try-except blocks. .. code-block:: python import signal import zproc zproc.signal_to_exception(signals.SIGTERM) try: ... except zproc.Si...
def _query(self, method, path, data=None, page=False, retry=0): if(data): data = dict( (k.replace(, ), v) for k, v in data.items()) data = dict( (k.replace(, ), v) for k, v in data.items()) data = dict( (k.replace(, ),...
Fetch an object from the Graph API and parse the output, returning a tuple where the first item is the object yielded by the Graph API and the second is the URL for the next page of results, or ``None`` if results have been exhausted. :param method: A string describing the HTTP method. ...
def to_vars_dict(self): return { : self._access_key, : self._secret_key, : self._region_name, : (self._vpc or ), : (self._vpc_id or ), }
Return local state which is relevant for the cluster setup process.
def _sign(translator, expr): op = expr.op() arg, = op.args arg_ = translator.translate(arg) return .format(arg_)
Workaround for missing sign function
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): return self.user
Return default user object.
def process_response(self, response): if response.status_code != 200: raise TwilioException(, response) return json.loads(response.text)
Load a JSON response. :param Response response: The HTTP response. :return dict: The JSON-loaded content.
def get_dashboard_panels_visibility_by_section(section_name): registry_info = get_dashboard_registry_record() if section_name not in registry_info: if len(pairs) == 0 or len(pairs) % 2 != 0: setup_dashboard_panels_visibility_registry(section_name) return get_dashboard_...
Return a list of pairs as values that represents the role-permission view relation for the panel section passed in. :param section_name: the panels section id. :return: a list of tuples.
def _to_legacy_path(dict_path): elements = [] for part in dict_path: element_kwargs = {"type": part["kind"]} if "id" in part: element_kwargs["id"] = part["id"] elif "name" in part: element_kwargs["name"] = part["name"] element = _app_engine_key_pb2.Pa...
Convert a tuple of ints and strings in a legacy "Path". .. note: This assumes, but does not verify, that each entry in ``dict_path`` is valid (i.e. doesn't have more than one key out of "name" / "id"). :type dict_path: lsit :param dict_path: The "structured" path for a key, i.e. i...
def trigger(self, source, actions, event_args): type = BlockType.TRIGGER return self.action_block(source, actions, type, event_args=event_args)
Perform actions as a result of an event listener (TRIGGER)
async def create_scene(self, scene_name, room_id) -> Scene: _raw = await self._scenes_entry_point.create_scene(room_id, scene_name) result = Scene(_raw, self.request) self.scenes.append(result) return result
Create a scene and returns the scene object. :raises PvApiError when something is wrong with the hub.
def _join_info_fields(self): if self.info_dict: info_fields = [] if len(self.info_dict) > 1: self.info_dict.pop(".", None) for field, value in self.info_dict.items(): if field == value: info_fields.append(value) ...
Updates info attribute from info dict.
def create_token(self, request, refresh_token=False, **kwargs): if "save_token" in kwargs: warnings.warn("`save_token` has been deprecated, it was not called internally." "If you do, call `request_validator.save_token()` instead.", Depreca...
Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token:
def symlink_bundles(self, app, bundle_dir): for bundle_counter, bundle in enumerate(app.bundles): count = 0 for path, relpath in bundle.filemap.items(): bundle_path = os.path.join(bundle_dir, relpath) count += 1 if os.path.exists(bundle_path): continue if ...
For each bundle in the given app, symlinks relevant matched paths. Validates that at least one path was matched by a bundle.
def highlightBlock(self, text): if self._allow_highlight: start = self.previousBlockState() + 1 end = start + len(text) for i, (fmt, letter) in enumerate(self._charlist[start:end]): self.setFormat(i, 1, fmt) self.s...
Actually highlight the block
def point_distance(point1, point2): lon1 = point1[][0] lat1 = point1[][1] lon2 = point2[][0] lat2 = point2[][1] deg_lat = number2radius(lat2 - lat1) deg_lon = number2radius(lon2 - lon1) a = math.pow(math.sin(deg_lat / 2), 2) + math.cos(number2radius(lat1)) * \ math.cos(number2ra...
calculate the distance between two points on the sphere like google map reference http://www.movable-type.co.uk/scripts/latlong.html Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object return distance
def get_dependencies(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.get_dependencies_with_http_info(id, **kwargs) else: (data) = self.get_dependencies_with_http_info(id, **kwargs) return data
Get the direct dependencies of the specified configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >...
def searchForUsers(self, name, limit=10): params = {"search": name, "limit": limit} j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_USER, params=params)) return [User._from_graphql(node) for node in j[name]["users"]["nodes"]]
Find and get user by his/her name :param name: Name of the user :param limit: The max. amount of users to fetch :return: :class:`models.User` objects, ordered by relevance :rtype: list :raises: FBchatException if request failed
def _load_activity(self, activity): fpths = [] full_path = errors = [] paths = settings.ACTIVITY_MODULES_IMPORT_PATHS number_of_paths = len(paths) for index_no in range(number_of_paths): full_path = "%s.%s" % (paths[index_no], activity) f...
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path.
def get_job(self, id_job, hub=None, group=None, project=None, access_token=None, user_id=None): if access_token: self.req.credential.set_token(access_token) if user_id: self.req.credential.set_user_id(user_id) if not self.check_credentials(): ...
Get the information about a job, by its id
def close_db(self, exception): if self.is_connected: if exception is None and not transaction.isDoomed(): transaction.commit() else: transaction.abort() self.connection.close()
Added as a `~flask.Flask.teardown_request` to applications to commit the transaction and disconnect ZODB if it was used during the request.
def load(self, infile): model = pickle.load(infile) self.__dict__.update(model.__dict__)
Deserialize a model from a stored file. By default, unpickle an entire object. If `dump` is overridden to use a different storage format, `load` should be as well. :param file outfile: A file-like object from which to retrieve the serialized model.
def date_to_number(self, date): if isinstance(date, datetime.datetime): delta = date - self._null_date elif isinstance(date, datetime.date): delta = date - self._null_date.date() else: raise TypeError(date) return delta.days + delta.seconds / ...
Converts a date or datetime instance to a corresponding float value.
def get_text_position_and_inner_alignment(ax, pos, scale=default_text_relative_padding, with_transAxes_kwargs=True): xy = get_text_position_in_ax_coord(ax,pos,scale=scale) alignment_fontdict = get_text_alignment(pos) if with_transAxes_kwargs: alignment_fontdict = {**alignment_fontdict, **{:ax.transAxes...
Return text position and its alignment in its bounding box. The returned position is given in Axes coordinate, as defined in matplotlib documentation on transformation. The returned alignment is given in dictionary, which can be put as a fontdict to text-relavent method.
def update_properties(self, new_properties): [self._update_property_from_dict(section, option, new_properties) for section in self.sections() for option in self.options(section)]
Update config properties values Property name must be equal to 'Section_option' of config property :param new_properties: dict with new properties values
def _process_transfer(self, ud, ase, offsets, data): self._put_data(ud, ase, offsets, data) with self._transfer_lock: if ud.local_path.use_stdin: self._upload_bytes_total += offsets.num_bytes elif offsets.chunk...
Process transfer instructions :param Uploader self: this :param blobxfer.models.upload.Descriptor ud: upload descriptor :param blobxfer.models.azure.StorageEntity ase: Storage entity :param blobxfer.models.upload.Offsets offsets: offsets :param bytes data: data to upload
def attach_arguments(cls, parser, prefix=, skip_formats=False, format_excludes=None, format_title=None, format_desc=None, skip_render=False, render_excludes=None, render_title=None, render_desc=None, skip_filters=False, ...
Attach argparse arguments to an argparse parser/group with table options. These are renderer options and filtering options with the ability to turn off headers and footers. The return value is function that parses an argparse.Namespace object into keyword arguments for a layout.Table c...