code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_referenced_services(specs): """ Returns all services that are referenced in specs.apps.depends.services, or in specs.bundles.services """ active_services = set() for app_spec in specs['apps'].values(): for service in app_spec['depends']['services']: active_services.a...
Returns all services that are referenced in specs.apps.depends.services, or in specs.bundles.services
def wrap(self, cause): """ Wraps another exception into an application exception object. If original exception is of ApplicationException type it is returned without changes. Otherwise a new ApplicationException is created and original error is set as its cause. :param cause: a...
Wraps another exception into an application exception object. If original exception is of ApplicationException type it is returned without changes. Otherwise a new ApplicationException is created and original error is set as its cause. :param cause: an original error object :return: a...
def _sample_oat(problem, N, num_levels=4): """Generate trajectories without groups Arguments --------- problem : dict The problem definition N : int The number of samples to generate num_levels : int, default=4 The number of grid levels """ group_membership = np....
Generate trajectories without groups Arguments --------- problem : dict The problem definition N : int The number of samples to generate num_levels : int, default=4 The number of grid levels
def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False): """Summarize the I-TASSER run in a dictionary containing modeling results and top predictions from COACH Args: only_attributes (str, list): Attributes that should be returned. If not provided, all are return...
Summarize the I-TASSER run in a dictionary containing modeling results and top predictions from COACH Args: only_attributes (str, list): Attributes that should be returned. If not provided, all are returned. exclude_attributes (str, list): Attributes that should be excluded. ...
def provide_session(func): """ Function decorator that provides a session if it isn't provided. If you want to reuse a session or run the function as part of a database transaction, you pass it to the function, if not this wrapper will create one and close it for you. """ @wraps(func) de...
Function decorator that provides a session if it isn't provided. If you want to reuse a session or run the function as part of a database transaction, you pass it to the function, if not this wrapper will create one and close it for you.
def write_monitor_keyring(keyring, monitor_keyring, uid=-1, gid=-1): """create the monitor keyring file""" write_file(keyring, monitor_keyring, 0o600, None, uid, gid)
create the monitor keyring file
def open(self): '''Open and return a stream for the dataset contents.''' return self.workspace._rest.open_intermediate_dataset_contents( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
Open and return a stream for the dataset contents.
def state_fidelity(state0: State, state1: State) -> bk.BKTensor: """Return the quantum fidelity between pure states.""" assert state0.qubits == state1.qubits # FIXME tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2) return tensor
Return the quantum fidelity between pure states.
def render(self): "Re-render Jupyter cell for batch of images." clear_output() self.write_csv() if self.empty() and self._skipped>0: return display(f'No images to show :). {self._skipped} pairs were ' f'skipped since at least one of the images was deleted ...
Re-render Jupyter cell for batch of images.
def var_explained(y_true, y_pred): """Fraction of variance explained. """ var_resid = K.var(y_true - y_pred) var_y_true = K.var(y_true) return 1 - var_resid / var_y_true
Fraction of variance explained.
def _allocate_address_nova(self, instance, network_ids): """ Allocates a floating/public ip address to the given instance, using the OpenStack Compute ('Nova') API. :param instance: instance to assign address to :param list network_id: List of IDs (as strings) of networks ...
Allocates a floating/public ip address to the given instance, using the OpenStack Compute ('Nova') API. :param instance: instance to assign address to :param list network_id: List of IDs (as strings) of networks where to request allocation the floating IP. **Ignored** (onl...
def RR_calc(classes, TOP): """ Calculate RR (Global performance index). :param classes: classes :type classes : list :param TOP: test outcome positive :type TOP : dict :return: RR as float """ try: class_number = len(classes) result = sum(list(TOP.values())) ...
Calculate RR (Global performance index). :param classes: classes :type classes : list :param TOP: test outcome positive :type TOP : dict :return: RR as float
def latex(self, force=False): """ Build PDF documentation. """ if sys.platform == 'win32': sys.stderr.write('latex build has not been tested on windows\n') else: ret_code = self._sphinx_build('latex') os.chdir(os.path.join(BUILD_PATH, 'latex'))...
Build PDF documentation.
def avl_join(t1, t2, node): """ Joins two trees `t1` and `t1` with an intermediate key-value pair CommandLine: python -m utool.experimental.euler_tour_tree_avl avl_join Example: >>> # DISABLE_DOCTEST >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> s...
Joins two trees `t1` and `t1` with an intermediate key-value pair CommandLine: python -m utool.experimental.euler_tour_tree_avl avl_join Example: >>> # DISABLE_DOCTEST >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> self = EulerTourTree(['a', 'b', 'c', 'b',...
def filter_query(self, query, field, value): """Filter a query.""" return query.where(field ** "%{}%".format(value.lower()))
Filter a query.
def get_column_keys_and_names(table): """ Return a generator of tuples k, c such that k is the name of the python attribute for the column and c is the name of the column in the sql table. """ ins = inspect(table) return ((k, c.name) for k, c in ins.mapper.c.items())
Return a generator of tuples k, c such that k is the name of the python attribute for the column and c is the name of the column in the sql table.
def md5(filename:str)->str: """ Given a filename produce an md5 hash of the contents. >>> import tempfile, os >>> f = tempfile.NamedTemporaryFile(delete=False) >>> f.write(b'Hello Wirld!') 12 >>> f.close() >>> md5(f.name) '997c62b6afe9712cad3baffb49cb8c8a' >>> os.unlink(f.name) ...
Given a filename produce an md5 hash of the contents. >>> import tempfile, os >>> f = tempfile.NamedTemporaryFile(delete=False) >>> f.write(b'Hello Wirld!') 12 >>> f.close() >>> md5(f.name) '997c62b6afe9712cad3baffb49cb8c8a' >>> os.unlink(f.name)
def load_lang_conf(): """ Load language setting from language config file if it exists, otherwise try to use the local settings if Spyder provides a translation, or return the default if no translation provided. """ if osp.isfile(LANG_FILE): with open(LANG_FILE, 'r') as f: ...
Load language setting from language config file if it exists, otherwise try to use the local settings if Spyder provides a translation, or return the default if no translation provided.
def hmget(self, key, *fields): """ Returns the values associated with the specified `fields` in a hash. For every ``field`` that does not exist in the hash, :data:`None` is returned. Because a non-existing keys are treated as empty hashes, calling :meth:`hmget` against a non-ex...
Returns the values associated with the specified `fields` in a hash. For every ``field`` that does not exist in the hash, :data:`None` is returned. Because a non-existing keys are treated as empty hashes, calling :meth:`hmget` against a non-existing key will return a list of :data:`Non...
def GetEntries(self, parser_mediator, match=None, **unused_kwargs): """Extract device information from the iPod plist. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. match (Optional[dict[str: object]]): keys e...
Extract device information from the iPod plist. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
def add_fields(self, log_record, record, message_dict): """ Override this method to implement custom logic for adding fields. """ for field in self._required_fields: log_record[field] = record.__dict__.get(field) log_record.update(message_dict) merge_record_ex...
Override this method to implement custom logic for adding fields.
def rgb(self, **kwargs): ''' Convert the image to a 3 band RGB for plotting This method shares the same arguments as plot(). It will perform visual adjustment on the image and prepare the data for plotting in MatplotLib. Values are converted to an appropriate precision and the a...
Convert the image to a 3 band RGB for plotting This method shares the same arguments as plot(). It will perform visual adjustment on the image and prepare the data for plotting in MatplotLib. Values are converted to an appropriate precision and the axis order is changed to put the band ...
def ttl(self, key): """ Emulate ttl Even though the official redis commands documentation at http://redis.io/commands/ttl states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1 when key does not have a timeout." the redis-py lib returns None for bo...
Emulate ttl Even though the official redis commands documentation at http://redis.io/commands/ttl states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1 when key does not have a timeout." the redis-py lib returns None for both these cases. The lib behavior...
def api_key(value=None): """Set or get the API key. Also set via environment variable GRAPHISTRY_API_KEY.""" if value is None: return PyGraphistry._config['api_key'] # setter if value is not PyGraphistry._config['api_key']: PyGraphistry._config['api_key'...
Set or get the API key. Also set via environment variable GRAPHISTRY_API_KEY.
def add_uppercase(table): """ Extend the table with uppercase options >>> print("а" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["а"] == "a") True >>> print("А" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["А"] == "A") True ...
Extend the table with uppercase options >>> print("а" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["а"] == "a") True >>> print("А" in add_uppercase({"а": "a"})) True >>> print(add_uppercase({"а": "a"})["А"] == "A") True >>> print(len(add_uppercase({"а": "a"...
def _get_controllers(self): """Iterate through the installed controller entry points and import the module and assign the handle to the CLI._controllers dict. :return: dict """ controllers = dict() for pkg in pkg_resources.iter_entry_points(group=self.CONTROLLERS): ...
Iterate through the installed controller entry points and import the module and assign the handle to the CLI._controllers dict. :return: dict
def object2code(key, code): """Returns code for widget from dict object""" if key in ["xscale", "yscale"]: if code == "log": code = True else: code = False else: code = unicode(code) return code
Returns code for widget from dict object
def _init_go_sets(self, go_fins): """Get lists of GO IDs.""" go_sets = [] assert go_fins, "EXPECTED FILES CONTAINING GO IDs" assert len(go_fins) >= 2, "EXPECTED 2+ GO LISTS. FOUND: {L}".format( L=' '.join(go_fins)) obj = GetGOs(self.godag) for fin in go_fins: ...
Get lists of GO IDs.
def atom_fractions(atoms): r'''Calculates the atomic fractions of each element in a compound, given a dictionary of its atoms and their counts, in the format {symbol: count}. .. math:: a_i = \frac{n_i}{\sum_i n_i} Parameters ---------- atoms : dict dictionary of counts of ...
r'''Calculates the atomic fractions of each element in a compound, given a dictionary of its atoms and their counts, in the format {symbol: count}. .. math:: a_i = \frac{n_i}{\sum_i n_i} Parameters ---------- atoms : dict dictionary of counts of individual atoms, indexed by sy...
def V_vertical_conical_concave(D, a, h): r'''Calculates volume of a vertical tank with a concave conical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2}{12} \left(3h + a - \frac{(a+h)^3}{a^2}\right) ,\;\; 0 \le h < |a| .. math:...
r'''Calculates volume of a vertical tank with a concave conical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2}{12} \left(3h + a - \frac{(a+h)^3}{a^2}\right) ,\;\; 0 \le h < |a| .. math:: V = \frac{\pi D^2}{12} (3h + a ),\;...
def get_lang_array(self): """gets supported langs as an array""" r = self.yandex_translate_request("getLangs", "") self.handle_errors(r) return r.json()["dirs"]
gets supported langs as an array
def format_timedelta(td_object): """Format a timedelta object for display to users Returns ------- str """ def get_total_seconds(td): # timedelta.total_seconds not in py2.6 return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6 seconds = i...
Format a timedelta object for display to users Returns ------- str
def get_context_json(self, context): ''' Return a base answer for a json answer ''' # Initialize answer answer = {} # Metadata builder answer['meta'] = self.__jcontext_metadata(context) # Filter builder answer['filter'] = self.__jcontext_filter(c...
Return a base answer for a json answer
def action_logging(f): """ Decorator to log user actions """ @functools.wraps(f) def wrapper(*args, **kwargs): with create_session() as session: if g.user.is_anonymous: user = 'anonymous' else: user = g.user.username log =...
Decorator to log user actions
def _edge_mapping(G): """Assigns a variable for each edge in G. (u, v) and (v, u) map to the same variable. """ edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)} edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()}) return edge_mapping
Assigns a variable for each edge in G. (u, v) and (v, u) map to the same variable.
def ParseRow(header, row): """Parses a single row of osquery output. Args: header: A parsed header describing the row format. row: A row in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryRow` instance. """ precondition.AssertDictType(row, Text, Text) result...
Parses a single row of osquery output. Args: header: A parsed header describing the row format. row: A row in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryRow` instance.
def repo_data(PACKAGES_TXT, repo, flag): """Grap data packages """ (name, location, size, unsize, rname, rlocation, rsize, runsize) = ([] for i in range(8)) for line in PACKAGES_TXT.splitlines(): if _meta_.rsl_deps in ["on", "ON"] and "--resolve-off" not in flag: status(0.000005...
Grap data packages
def lal(self): """ Returns a LAL Object that contains this data """ lal_data = None if self._data.dtype == float32: lal_data = _lal.CreateREAL4Vector(len(self)) elif self._data.dtype == float64: lal_data = _lal.CreateREAL8Vector(len(self)) elif self._data...
Returns a LAL Object that contains this data
def correct_rates(rates, opt_qes, combs): """Applies optimal qes to rates. Should be closer to fitted_rates afterwards. Parameters ---------- rates: numpy array of rates of all PMT combinations opt_qes: numpy array of optimal qe values for all PMTs combs: pmt combinations used to correct ...
Applies optimal qes to rates. Should be closer to fitted_rates afterwards. Parameters ---------- rates: numpy array of rates of all PMT combinations opt_qes: numpy array of optimal qe values for all PMTs combs: pmt combinations used to correct Returns ------- corrected_rates: nump...
def create(args): """ cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories). ""...
cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories).
def extract_package_name(line): """Return package name in import statement.""" assert '\\' not in line assert '(' not in line assert ')' not in line assert ';' not in line if line.lstrip().startswith(('import', 'from')): word = line.split()[1] else: # Ignore doctests. ...
Return package name in import statement.
def getSimilarTermsForTerm(self, term, contextId=None, posType=None, getFingerprint=None, startIndex=0, maxResults=10): """Get the similar terms of a given term Args: term, str: A term in the retina (required) contextId, int: The identifier of a context (optional) pos...
Get the similar terms of a given term Args: term, str: A term in the retina (required) contextId, int: The identifier of a context (optional) posType, str: Part of speech (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of t...
def decrypt_from(self, f, mac_bytes=10): """ Decrypts a message from f. """ ctx = DecryptionContext(self.curve, f, self, mac_bytes) yield ctx ctx.read()
Decrypts a message from f.
def create_aside(self, block_type, keys): """ The aside version of construct_xblock: take a type and key. Return an instance """ aside_cls = XBlockAside.load_class(block_type) return aside_cls(runtime=self, scope_ids=keys)
The aside version of construct_xblock: take a type and key. Return an instance
def _make_string_formatter(f, offset=None): """ A closure-izer for string arguments that include a format and possibly an offset. """ format = f delta = offset return lambda v: time.strftime(format, (_date(v, delta)).timetuple())
A closure-izer for string arguments that include a format and possibly an offset.
def com_google_fonts_check_ttx_roundtrip(font): """Checking with fontTools.ttx""" from fontTools import ttx import sys ttFont = ttx.TTFont(font) failed = False class TTXLogger: msgs = [] def __init__(self): self.original_stderr = sys.stderr self.original_stdout = sys.stdout sys.s...
Checking with fontTools.ttx
def flattenTrees(root, nodeSelector: Callable[[LNode], bool]): """ Walk all nodes and discover trees of nodes (usually operators) and reduce them to single node with multiple outputs :attention: selected nodes has to have single output and has to be connected to nets with single driver ...
Walk all nodes and discover trees of nodes (usually operators) and reduce them to single node with multiple outputs :attention: selected nodes has to have single output and has to be connected to nets with single driver
def woodbury_inv(self): """ The inverse of the woodbury matrix, in the gaussian likelihood case it is defined as $$ (K_{xx} + \Sigma_{xx})^{-1} \Sigma_{xx} := \texttt{Likelihood.variance / Approximate likelihood covariance} $$ """ if self._woodbury_inv is ...
The inverse of the woodbury matrix, in the gaussian likelihood case it is defined as $$ (K_{xx} + \Sigma_{xx})^{-1} \Sigma_{xx} := \texttt{Likelihood.variance / Approximate likelihood covariance} $$
def shape(self): """ Returns (rowCount, valueCount) """ bf = self.copy() content = requests.get(bf.dataset_url).json() rowCount = content['status']['rowCount'] valueCount = content['status']['valueCount'] return (rowCount, valueCount)
Returns (rowCount, valueCount)
def start_stack(awsclient, stack_name, use_suspend=False): """Start an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code """ exit_code = 0 # check for DisableStop #disable_stop = ...
Start an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code
def _derive_charge(self, config): """Use a temperature window to identify the roast charge. The charge will manifest as a sudden downward trend on the temperature. Once found, we save it and avoid overwriting. The charge is needed in order to derive the turning point. :param co...
Use a temperature window to identify the roast charge. The charge will manifest as a sudden downward trend on the temperature. Once found, we save it and avoid overwriting. The charge is needed in order to derive the turning point. :param config: Current snapshot of the configuration ...
def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( opts=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) )
Return the first configured instance.
def addresses(self): """ Return a new raw REST interface to address resources :rtype: :py:class:`ns1.rest.ipam.Adresses` """ import ns1.rest.ipam return ns1.rest.ipam.Addresses(self.config)
Return a new raw REST interface to address resources :rtype: :py:class:`ns1.rest.ipam.Adresses`
def read_status(self, num_bytes=2): """Read up to 24 bits (num_bytes) of SPI flash status register contents via RDSR, RDSR2, RDSR3 commands Not all SPI flash supports all three commands. The upper 1 or 2 bytes may be 0xFF. """ SPIFLASH_RDSR = 0x05 SPIFLASH_RDSR2...
Read up to 24 bits (num_bytes) of SPI flash status register contents via RDSR, RDSR2, RDSR3 commands Not all SPI flash supports all three commands. The upper 1 or 2 bytes may be 0xFF.
def match_url(self, request): """ Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str`` """ parsed_url = urlparse(request.path_url) ...
Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str``
def precondition_u_kn(u_kn, N_k, f_k): """Subtract a sample-dependent constant from u_kn to improve precision Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_s...
Subtract a sample-dependent constant from u_kn to improve precision Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of samp...
def mouseDoubleClickEvent(self, event): """Reimplement Qt method""" index_clicked = self.indexAt(event.pos()) if self.model.breakpoints: filename = self.model.breakpoints[index_clicked.row()][0] line_number_str = self.model.breakpoints[index_clicked.row()][1] ...
Reimplement Qt method
def _transform_legacy_stats(self, stats): """Convert legacy stats to new stats with pools key.""" # Fill pools for legacy driver reports if stats and 'pools' not in stats: pool = stats.copy() pool['pool_name'] = self.id for key in ('driver_version', 'shared_ta...
Convert legacy stats to new stats with pools key.
def visible_fields(self): """ Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when configuring this fields...
Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when configuring this fieldset, all visible fields minus the exclu...
def predict_compound_pairs_iterated( reactions, formulas, prior=(1, 43), max_iterations=None, element_weight=element_weight): """Predict reaction pairs using iterated method. Returns a tuple containing a dictionary of predictions keyed by the reaction IDs, and the final number of iterations...
Predict reaction pairs using iterated method. Returns a tuple containing a dictionary of predictions keyed by the reaction IDs, and the final number of iterations. Each reaction prediction entry contains a tuple with a dictionary of transfers and a dictionary of unbalanced compounds. The dictionary of ...
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Pass the correct length for list unpacking. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. """ unpack_length = UB...
Unpack a binary message into this object's attributes. Pass the correct length for list unpacking. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking.
def load(self): """Read and parse the message file.""" try: self._read() self._parse() except Exception as exc: self.failed = True params = {'path': self._path, 'exception': exc} if self.fail_silently: LOG.warning("Erro...
Read and parse the message file.
def start_login_server(self, ): """Start a server that will get a request from a user logging in. This uses the Implicit Grant Flow of OAuth2. The user is asked to login to twitch and grant PyTwitcher authorization. Once the user agrees, he is redirected to an url. This server w...
Start a server that will get a request from a user logging in. This uses the Implicit Grant Flow of OAuth2. The user is asked to login to twitch and grant PyTwitcher authorization. Once the user agrees, he is redirected to an url. This server will respond to that url and get the oauth t...
def find_element_by_name(self, name, update=False) -> Elements: '''Finds an element by name. Args: name: The name of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Rai...
Finds an element by name. Args: name: The name of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: NoSuchElementException - If the element wasn't found. ...
def project_parensemble(self,par_file=None,nsing=None, inplace=True,enforce_bounds='reset'): """ perform the null-space projection operations for null-space monte carlo Parameters ---------- par_file: str an optional file of parameter values to us...
perform the null-space projection operations for null-space monte carlo Parameters ---------- par_file: str an optional file of parameter values to use nsing: int number of singular values to in forming null subspace matrix inplace: bool overw...
def mrc_header_from_params(shape, dtype, kind, **kwargs): """Create a minimal MRC2014 header from the given parameters. Parameters ---------- shape : 3-sequence of ints 3D shape of the stored data. The values are used as ``'nx', 'ny', 'nz'`` header entries, in this order. Note that ...
Create a minimal MRC2014 header from the given parameters. Parameters ---------- shape : 3-sequence of ints 3D shape of the stored data. The values are used as ``'nx', 'ny', 'nz'`` header entries, in this order. Note that this is different from the actual data storage shape for ...
def text_iter(self, context): """ Iterates over all the elements in an iterparse context (here: <text> elements) and yields an ExportXMLDocumentGraph instance for each of them. For efficiency, the elements are removed from the DOM / main memory after processing them. If ...
Iterates over all the elements in an iterparse context (here: <text> elements) and yields an ExportXMLDocumentGraph instance for each of them. For efficiency, the elements are removed from the DOM / main memory after processing them. If ``self.debug`` is set to ``True`` (in the ``__init...
def next_non_holiday_weekday(holidays, dt): """ If a holiday falls on a Sunday, observe it on the next non-holiday weekday. Parameters ---------- holidays : list[pd.tseries.holiday.Holiday] list of holidays dt : pd.Timestamp date of holiday. """ day_of_week = dt.weekday(...
If a holiday falls on a Sunday, observe it on the next non-holiday weekday. Parameters ---------- holidays : list[pd.tseries.holiday.Holiday] list of holidays dt : pd.Timestamp date of holiday.
def _set_ospf_level12(self, v, load=False): """ Setter method for ospf_level12, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level12 (empty) If this variable is read-only (conf...
Setter method for ospf_level12, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level12 (empty) If this variable is read-only (config: false) in the source YANG file, then _set_ospf_l...
def grep(source, regex, stop_on_first=False): """Grep the constant pool of all classes in source.""" loader = ClassLoader(source, max_cache=-1) r = re.compile(regex) def _matches(constant): return r.match(constant.value) for klass in loader.classes: it = loader.search_constant_pool...
Grep the constant pool of all classes in source.
def create_pointing(self,event): """Plot the sky coverage of pointing at event.x,event.y on the canavas""" import math (ra,dec)=self.c2p((self.canvasx(event.x), self.canvasy(event.y))) this_camera=camera(camera=self.camera.get()) ccds=this_camera.getGe...
Plot the sky coverage of pointing at event.x,event.y on the canavas
def _can_process_pre_prepare(self, pre_prepare: PrePrepare, sender: str) -> Optional[int]: """ Decide whether this replica is eligible to process a PRE-PREPARE. :param pre_prepare: a PRE-PREPARE msg to process :param sender: the name of the node that sent the PRE-PREPARE msg """...
Decide whether this replica is eligible to process a PRE-PREPARE. :param pre_prepare: a PRE-PREPARE msg to process :param sender: the name of the node that sent the PRE-PREPARE msg
def cal_pth(self, v, temp): """ calculate thermal pressure :param v: unit-cell volume in A^3 :param temp: temperature in K :return: thermal pressure in GPa """ params_t = self._set_params(self.params_therm) return constq_pth(v, temp, *params_t, self.n, se...
calculate thermal pressure :param v: unit-cell volume in A^3 :param temp: temperature in K :return: thermal pressure in GPa
def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if n...
Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid.
def save_state(internal_request, state): """ Saves all necessary information needed by the UserIdHasher :type internal_request: satosa.internal_data.InternalRequest :param internal_request: The request :param state: The current state """ state_data = {"hash_type...
Saves all necessary information needed by the UserIdHasher :type internal_request: satosa.internal_data.InternalRequest :param internal_request: The request :param state: The current state
def read_leader_status(self): """Read the high availability status and current leader instance of Vault. Supported methods: GET: /sys/leader. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict """ api_path = '/v1/sys/leade...
Read the high availability status and current leader instance of Vault. Supported methods: GET: /sys/leader. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict
def OnCopyResult(self, event): """Clipboard copy results event handler""" selection = self.main_window.grid.selection data = self.main_window.actions.copy_result(selection) # Check if result is a bitmap if type(data) is wx._gdi.Bitmap: # Copy bitmap to clipboard ...
Clipboard copy results event handler
def get_filters(self): """ Returns a collection of momentjs filters """ return dict( moment_format=self.format, moment_calendar=self.calendar, moment_fromnow=self.from_now, )
Returns a collection of momentjs filters
def set_printoptions(**kwargs): """Set printing options. These options determine the way JPEG 2000 boxes are displayed. Parameters ---------- short : bool, optional When True, only the box ID, offset, and length are displayed. Useful for displaying only the basic structure or skel...
Set printing options. These options determine the way JPEG 2000 boxes are displayed. Parameters ---------- short : bool, optional When True, only the box ID, offset, and length are displayed. Useful for displaying only the basic structure or skeleton of a JPEG 2000 file. x...
def checkout(self, ref, branch=None): """Do a git checkout of `ref`.""" return git_checkout(self.repo_dir, ref, branch=branch)
Do a git checkout of `ref`.
def set(self, section, key, value, comment=None): """ Set config value with data type transformation (to str) :param str section: Section to set config for :param str key: Key to set config for :param value: Value for key. It can be any primitive type. :param str comment...
Set config value with data type transformation (to str) :param str section: Section to set config for :param str key: Key to set config for :param value: Value for key. It can be any primitive type. :param str comment: Comment for the key
def trial(log_dir=None, upload_dir=None, sync_period=None, trial_prefix="", param_map=None, init_logging=True): """ Generates a trial within a with context. """ global _trial # pylint: disable=global-statement if _trial: # TODO: would be nic...
Generates a trial within a with context.
def _init_socket(self): '''Initialises the socket used for communicating with a q service,''' try: self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._connection.connect((self.host, self.port)) self._connection.settimeout(self.timeout) ...
Initialises the socket used for communicating with a q service,
def create(cls, bucket, key, value): """Create a new tag for bucket.""" with db.session.begin_nested(): obj = cls( bucket_id=as_bucket_id(bucket), key=key, value=value ) db.session.add(obj) return obj
Create a new tag for bucket.
def cnst_AT(self, Y): r"""Compute :math:`A^T \mathbf{y}`. In this case :math:`A^T \mathbf{y} = (I \;\; \Gamma_0^T \;\; \Gamma_1^T \;\; \ldots) \mathbf{y}`. """ return self.cnst_A0T(self.block_sep0(Y)) + \ np.sum(self.cnst_A1T(self.block_sep1(Y)), axis=-1)
r"""Compute :math:`A^T \mathbf{y}`. In this case :math:`A^T \mathbf{y} = (I \;\; \Gamma_0^T \;\; \Gamma_1^T \;\; \ldots) \mathbf{y}`.
def me(self): """Get the details of the person accessing the API. Raises: ApiError: If the Webex Teams cloud returns an error. """ # API request json_data = self._session.get(API_ENDPOINT + '/me') # Return a person object created from the response JSON data...
Get the details of the person accessing the API. Raises: ApiError: If the Webex Teams cloud returns an error.
def read(self, entity=None, attrs=None, ignore=None, params=None): """Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`RepositorySet` ...
Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`RepositorySet` requires that a ``product`` be provided, so this technique will not wo...
def caption_mentions(self) -> List[str]: """List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @.""" if not self.caption: return [] # This regular expression is from jStassen, adjusted to use Python's \w to support Unicode # http://bl...
List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @.
def height_to_pressure_std(height): r"""Convert height data to pressures using the U.S. standard atmosphere. The implementation inverts the formula outlined in [Hobbs1977]_ pg.60-61. Parameters ---------- height : `pint.Quantity` Atmospheric height Returns ------- `pint.Quanti...
r"""Convert height data to pressures using the U.S. standard atmosphere. The implementation inverts the formula outlined in [Hobbs1977]_ pg.60-61. Parameters ---------- height : `pint.Quantity` Atmospheric height Returns ------- `pint.Quantity` The corresponding pressure v...
def operation(self, url, idp_entity_id, op, **opargs): """ This is the method that should be used by someone that wants to authenticate using SAML ECP :param url: The page that access is sought for :param idp_entity_id: The entity ID of the IdP that should be used fo...
This is the method that should be used by someone that wants to authenticate using SAML ECP :param url: The page that access is sought for :param idp_entity_id: The entity ID of the IdP that should be used for authentication :param op: Which HTTP operation (GET/POST/PUT/DELE...
def main(self, config_filename): """ The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred. :param str config_filename: The name of the configuration file. :rtype: int """ self._read_configuration_file(config_filename) if s...
The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred. :param str config_filename: The name of the configuration file. :rtype: int
def set_image(self, image): """ Update the current comparison (real) image """ if isinstance(image, np.ndarray): image = util.Image(image) if isinstance(image, util.NullImage): self.model_as_data = True else: self.model_as_data = False...
Update the current comparison (real) image
def rotatePoints(points, rotationDegrees, pivotx=0, pivoty=0): """ Rotates each x and y tuple in `points`` by `rotationDegrees`. The points are rotated around the origin by default, but can be rotated around another pivot point by specifying `pivotx` and `pivoty`. The points are rotated countercloc...
Rotates each x and y tuple in `points`` by `rotationDegrees`. The points are rotated around the origin by default, but can be rotated around another pivot point by specifying `pivotx` and `pivoty`. The points are rotated counterclockwise. Returns a generator that produces an x and y tuple for each poi...
def ping(self, message=_NOTSET, *, encoding=_NOTSET): """Ping the server. Accept optional echo message. """ if message is not _NOTSET: args = (message,) else: args = () return self.execute('PING', *args, encoding=encoding)
Ping the server. Accept optional echo message.
def from_name(api_url, name, dry_run=False): """ doesn't require a token config param as all of our data is currently public """ return DataSet( '/'.join([api_url, name]).rstrip('/'), token=None, dry_run=dry_run )
doesn't require a token config param as all of our data is currently public
def trigger_event(self, source, event, args): """ Trigger an event on the Entity * \a source: The source of the event * \a event: The event being triggered * \a args: A list of arguments to pass to the callback """ actions = [] for action in event.actions: if callable(action): ac = action(self, *...
Trigger an event on the Entity * \a source: The source of the event * \a event: The event being triggered * \a args: A list of arguments to pass to the callback
def set_legend(self): """Create a legend for this product """ leg = super(Coherence, self).set_legend() if leg is not None: leg.set_title('Coherence with:') return leg
Create a legend for this product
def det_residual(model, guess, start, final, shocks, diff=True, jactype='sparse'): ''' Computes the residuals, the derivatives of the stacked-time system. :param model: an fga model :param guess: the gu...
Computes the residuals, the derivatives of the stacked-time system. :param model: an fga model :param guess: the guess for the simulated values. An `(n_s.n_x) x N` array, where n_s is the number of states, n_x the number of controls, and `N` the length of the simulation. :param start: ...
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, ...
Make a confidence report and save it to disk.
def compile_protofile(proto_file_path): """Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails. """ out_file = tempfile.mkstemp...
Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails.